aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--Makefile.in10
-rw-r--r--erts/aclocal.m42
-rw-r--r--erts/configure.in61
-rw-r--r--erts/doc/src/erlang.xml8
-rw-r--r--erts/doc/src/notes.xml2
-rw-r--r--erts/emulator/beam/atom.names1
-rw-r--r--erts/emulator/beam/beam_bif_load.c4
-rw-r--r--erts/emulator/beam/beam_emu.c11
-rw-r--r--erts/emulator/beam/bif.c166
-rw-r--r--erts/emulator/beam/big.c6
-rw-r--r--erts/emulator/beam/big.h4
-rw-r--r--erts/emulator/beam/binary.c103
-rw-r--r--erts/emulator/beam/erl_alloc.c190
-rw-r--r--erts/emulator/beam/erl_alloc.types57
-rw-r--r--erts/emulator/beam/erl_alloc_util.c28
-rw-r--r--erts/emulator/beam/erl_alloc_util.h3
-rw-r--r--erts/emulator/beam/erl_async.c1
-rw-r--r--erts/emulator/beam/erl_bif_ddll.c13
-rw-r--r--erts/emulator/beam/erl_bif_info.c6
-rw-r--r--erts/emulator/beam/erl_bif_port.c9
-rw-r--r--erts/emulator/beam/erl_bif_re.c18
-rw-r--r--erts/emulator/beam/erl_db_hash.c32
-rw-r--r--erts/emulator/beam/erl_db_tree.c64
-rw-r--r--erts/emulator/beam/erl_drv_thread.c7
-rw-r--r--erts/emulator/beam/erl_lock_check.c10
-rw-r--r--erts/emulator/beam/erl_lock_check.h2
-rw-r--r--erts/emulator/beam/erl_nif.c4
-rw-r--r--erts/emulator/beam/erl_port_task.c3
-rw-r--r--erts/emulator/beam/erl_printf_term.c101
-rw-r--r--erts/emulator/beam/erl_printf_term.h4
-rw-r--r--erts/emulator/beam/erl_process.c138
-rw-r--r--erts/emulator/beam/erl_trace.c22
-rw-r--r--erts/emulator/beam/global.h21
-rw-r--r--erts/emulator/beam/io.c106
-rw-r--r--erts/emulator/beam/safe_hash.c2
-rw-r--r--erts/emulator/beam/utils.c37
-rw-r--r--erts/emulator/drivers/common/inet_drv.c18
-rw-r--r--erts/emulator/hipe/hipe_bif2.c26
-rw-r--r--erts/emulator/hipe/hipe_mkliterals.c12
-rw-r--r--erts/emulator/sys/common/erl_check_io.c5
-rw-r--r--erts/emulator/sys/common/erl_mseg.c35
-rw-r--r--erts/emulator/sys/common/erl_mseg.h11
-rw-r--r--erts/emulator/sys/common/erl_poll.c7
-rw-r--r--erts/emulator/sys/win32/erl_poll.c2
-rw-r--r--erts/emulator/test/binary_SUITE.erl123
-rw-r--r--erts/emulator/test/code_SUITE.erl2
-rw-r--r--erts/emulator/test/driver_SUITE.erl132
-rw-r--r--erts/emulator/test/driver_SUITE_data/Makefile.src3
-rw-r--r--erts/emulator/test/driver_SUITE_data/otp_9302_drv.c137
-rw-r--r--erts/etc/common/erlexec.c14
-rw-r--r--erts/etc/unix/cerl.src66
-rw-r--r--erts/include/internal/erl_printf_format.h2
-rw-r--r--erts/include/internal/libatomic_ops/ethr_atomic.h26
-rw-r--r--erts/include/internal/sparc32/atomic.h29
-rw-r--r--erts/include/internal/tile/atomic.h33
-rw-r--r--erts/lib_src/common/erl_printf_format.c29
-rw-r--r--lib/Makefile11
-rw-r--r--lib/asn1/doc/src/notes.xml2
-rw-r--r--lib/common_test/doc/src/notes.xml2
-rw-r--r--lib/compiler/doc/src/compile.xml2
-rw-r--r--lib/compiler/doc/src/notes.xml2
-rw-r--r--lib/crypto/c_src/Makefile.in8
-rw-r--r--lib/crypto/doc/src/licenses.xml2
-rw-r--r--lib/debugger/doc/src/notes.xml2
-rwxr-xr-xlib/dialyzer/doc/src/notes.xml2
-rw-r--r--lib/diameter/.gitignore58
-rw-r--r--lib/diameter/AUTHORS10
-rw-r--r--lib/diameter/Makefile.in88
-rw-r--r--lib/diameter/TAR.exclude2
-rw-r--r--lib/diameter/aclocal.m465
-rwxr-xr-xlib/diameter/autoconf/config.guess1519
-rwxr-xr-xlib/diameter/autoconf/config.sub1630
-rwxr-xr-xlib/diameter/autoconf/configure.vxworks147
-rwxr-xr-xlib/diameter/autoconf/install-sh519
-rw-r--r--lib/diameter/autoconf/vxworks/sed.general125
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_cpu3245
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_ppc3252
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_ppc60351
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_ppc603_nolongcall51
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_ppc86050
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_simlinux59
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_simso64
-rw-r--r--lib/diameter/autoconf/vxworks/sed.vxworks_sparc38
-rwxr-xr-xlib/diameter/bin/diameterc155
-rw-r--r--lib/diameter/configure.in138
-rw-r--r--lib/diameter/doc/html/.gitignore0
-rw-r--r--lib/diameter/doc/man1/.gitignore0
-rw-r--r--lib/diameter/doc/man3/.gitignore0
-rw-r--r--lib/diameter/doc/man4/.gitignore0
-rw-r--r--lib/diameter/doc/pdf/.gitignore0
-rw-r--r--lib/diameter/doc/src/Makefile199
-rw-r--r--lib/diameter/doc/src/book.xml56
-rw-r--r--lib/diameter/doc/src/diameter.xml1123
-rw-r--r--lib/diameter/doc/src/diameter_app.xml582
-rw-r--r--lib/diameter/doc/src/diameter_compile.xml124
-rw-r--r--lib/diameter/doc/src/diameter_dict.xml601
-rw-r--r--lib/diameter/doc/src/diameter_examples.xml40
-rw-r--r--lib/diameter/doc/src/diameter_intro.xml45
-rw-r--r--lib/diameter/doc/src/diameter_sctp.xml133
-rw-r--r--lib/diameter/doc/src/diameter_soc.xml110
-rw-r--r--lib/diameter/doc/src/diameter_tcp.xml110
-rw-r--r--lib/diameter/doc/src/diameter_transport.xml203
-rw-r--r--lib/diameter/doc/src/diameter_using.xml40
-rw-r--r--lib/diameter/doc/src/files.mk52
-rw-r--r--lib/diameter/doc/src/notes.gifbin0 -> 2005 bytes
-rw-r--r--lib/diameter/doc/src/notes.xml47
-rw-r--r--lib/diameter/doc/src/ref_man.xml48
-rw-r--r--lib/diameter/doc/src/user_man.xml44
-rw-r--r--lib/diameter/doc/standard/draft-ietf-dime-capablities-update-07.txt392
-rw-r--r--lib/diameter/doc/standard/draft-ietf-dime-rfc3588bis-26.txt8681
-rw-r--r--lib/diameter/doc/standard/rfc3124.txt1235
-rw-r--r--lib/diameter/doc/standard/rfc3539.txt2299
-rw-r--r--lib/diameter/doc/standard/rfc3588.txt8235
-rw-r--r--lib/diameter/doc/standard/rfc4005.txt4763
-rw-r--r--lib/diameter/doc/standard/rfc4006.txt6387
-rw-r--r--lib/diameter/doc/standard/rfc4072.txt1851
-rw-r--r--lib/diameter/doc/standard/rfc4740.txt4035
-rw-r--r--lib/diameter/doc/standard/rfc5447.txt955
-rw-r--r--lib/diameter/ebin/.gitignore5
-rw-r--r--lib/diameter/examples/.gitignore3
-rw-r--r--lib/diameter/examples/GNUmakefile35
-rw-r--r--lib/diameter/examples/client.erl125
-rw-r--r--lib/diameter/examples/client_cb.erl103
-rw-r--r--lib/diameter/examples/peer.erl139
-rw-r--r--lib/diameter/examples/redirect.erl70
-rw-r--r--lib/diameter/examples/redirect_cb.erl63
-rw-r--r--lib/diameter/examples/relay.erl92
-rw-r--r--lib/diameter/examples/relay_cb.erl69
-rw-r--r--lib/diameter/examples/sctp.erl113
-rw-r--r--lib/diameter/examples/server.erl88
-rw-r--r--lib/diameter/examples/server_cb.erl118
-rw-r--r--lib/diameter/include/diameter.hrl130
-rw-r--r--lib/diameter/include/diameter_gen.hrl431
-rw-r--r--lib/diameter/info3
-rw-r--r--lib/diameter/make/release_targets.mk92
-rw-r--r--lib/diameter/make/rules.mk.in195
-rw-r--r--lib/diameter/make/subdir.mk53
-rw-r--r--lib/diameter/make/target.mk33
-rw-r--r--lib/diameter/src/Makefile43
-rw-r--r--lib/diameter/src/app/.gitignore5
-rw-r--r--lib/diameter/src/app/Makefile199
-rw-r--r--lib/diameter/src/app/depend.sed31
-rw-r--r--lib/diameter/src/app/diameter.app.src28
-rw-r--r--lib/diameter/src/app/diameter.appup.src27
-rw-r--r--lib/diameter/src/app/diameter.erl212
-rw-r--r--lib/diameter/src/app/diameter.mk.in47
-rw-r--r--lib/diameter/src/app/diameter_app.erl36
-rw-r--r--lib/diameter/src/app/diameter_callback.erl91
-rw-r--r--lib/diameter/src/app/diameter_capx.erl388
-rw-r--r--lib/diameter/src/app/diameter_codec.erl569
-rw-r--r--lib/diameter/src/app/diameter_config.erl681
-rw-r--r--lib/diameter/src/app/diameter_dbg.erl565
-rw-r--r--lib/diameter/src/app/diameter_dict.erl153
-rw-r--r--lib/diameter/src/app/diameter_exprecs.erl301
-rw-r--r--lib/diameter/src/app/diameter_gen_base_accounting.dia68
-rw-r--r--lib/diameter/src/app/diameter_gen_base_rfc3588.dia413
-rw-r--r--lib/diameter/src/app/diameter_gen_relay.dia24
-rw-r--r--lib/diameter/src/app/diameter_info.erl869
-rw-r--r--lib/diameter/src/app/diameter_internal.hrl95
-rw-r--r--lib/diameter/src/app/diameter_lib.erl266
-rw-r--r--lib/diameter/src/app/diameter_misc_sup.erl58
-rw-r--r--lib/diameter/src/app/diameter_peer.erl230
-rw-r--r--lib/diameter/src/app/diameter_peer_fsm.erl746
-rw-r--r--lib/diameter/src/app/diameter_peer_fsm_sup.erl63
-rw-r--r--lib/diameter/src/app/diameter_reg.erl331
-rw-r--r--lib/diameter/src/app/diameter_service.erl2931
-rw-r--r--lib/diameter/src/app/diameter_service_sup.erl64
-rw-r--r--lib/diameter/src/app/diameter_session.erl172
-rw-r--r--lib/diameter/src/app/diameter_stats.erl347
-rw-r--r--lib/diameter/src/app/diameter_sup.erl101
-rw-r--r--lib/diameter/src/app/diameter_sync.erl555
-rw-r--r--lib/diameter/src/app/diameter_types.erl537
-rw-r--r--lib/diameter/src/app/diameter_types.hrl139
-rw-r--r--lib/diameter/src/app/diameter_watchdog.erl571
-rw-r--r--lib/diameter/src/app/diameter_watchdog_sup.erl60
-rw-r--r--lib/diameter/src/app/modules.mk68
-rw-r--r--lib/diameter/src/compiler/.gitignore3
-rw-r--r--lib/diameter/src/compiler/Makefile141
-rw-r--r--lib/diameter/src/compiler/diameter_codegen.erl788
-rw-r--r--lib/diameter/src/compiler/diameter_forms.hrl52
-rw-r--r--lib/diameter/src/compiler/diameter_make.erl120
-rw-r--r--lib/diameter/src/compiler/diameter_spec_scan.erl157
-rw-r--r--lib/diameter/src/compiler/diameter_spec_util.erl1052
-rw-r--r--lib/diameter/src/compiler/modules.mk27
-rw-r--r--lib/diameter/src/subdirs.mk21
-rw-r--r--lib/diameter/src/transport/.gitignore3
-rw-r--r--lib/diameter/src/transport/Makefile141
-rw-r--r--lib/diameter/src/transport/diameter_etcp.erl311
-rw-r--r--lib/diameter/src/transport/diameter_etcp_sup.erl64
-rw-r--r--lib/diameter/src/transport/diameter_sctp.erl624
-rw-r--r--lib/diameter/src/transport/diameter_sctp_sup.erl74
-rw-r--r--lib/diameter/src/transport/diameter_tcp.erl531
-rw-r--r--lib/diameter/src/transport/diameter_tcp_sup.erl78
-rw-r--r--lib/diameter/src/transport/diameter_transport_sup.erl68
-rw-r--r--lib/diameter/src/transport/modules.mk29
-rw-r--r--lib/diameter/subdirs.mk20
-rw-r--r--lib/diameter/test/Makefile408
-rw-r--r--lib/diameter/test/diameter.cover6
-rw-r--r--lib/diameter/test/diameter.spec9
-rw-r--r--lib/diameter/test/diameter_SUITE.erl108
-rw-r--r--lib/diameter/test/diameter_app_test.erl393
-rw-r--r--lib/diameter/test/diameter_appup_test.erl539
-rw-r--r--lib/diameter/test/diameter_compiler_test.erl104
-rw-r--r--lib/diameter/test/diameter_config_test.erl105
-rw-r--r--lib/diameter/test/diameter_etcp_test.beambin0 -> 1808 bytes
-rw-r--r--lib/diameter/test/diameter_peer_test.erl104
-rw-r--r--lib/diameter/test/diameter_reg_test.erl104
-rw-r--r--lib/diameter/test/diameter_session_test.erl104
-rw-r--r--lib/diameter/test/diameter_stats_test.erl104
-rw-r--r--lib/diameter/test/diameter_sync_test.erl104
-rw-r--r--lib/diameter/test/diameter_tcp_test.erl482
-rw-r--r--lib/diameter/test/diameter_test_lib.erl478
-rw-r--r--lib/diameter/test/diameter_test_lib.hrl106
-rw-r--r--lib/diameter/test/diameter_test_server.erl551
-rw-r--r--lib/diameter/test/modules.mk47
-rw-r--r--lib/diameter/test/slask/diameter_persistent_table_test.erl495
-rw-r--r--lib/diameter/vsn.mk25
-rw-r--r--lib/edoc/doc/src/notes.xml2
-rw-r--r--lib/edoc/src/edoc.hrl2
-rw-r--r--lib/edoc/src/edoc_specs.erl6
-rw-r--r--lib/edoc/src/edoc_tags.erl116
-rw-r--r--lib/erl_docgen/priv/bin/specs_gen.escript101
-rw-r--r--lib/erl_docgen/priv/xsl/db_html.xsl556
-rw-r--r--lib/erl_docgen/priv/xsl/db_man.xsl424
-rw-r--r--lib/erl_docgen/priv/xsl/db_pdf.xsl451
-rw-r--r--lib/erl_docgen/src/otp_specs.erl14
-rw-r--r--lib/erl_interface/doc/src/notes.xml2
-rw-r--r--lib/erl_interface/src/epmd/epmd_port.c7
-rw-r--r--lib/hipe/doc/src/notes.xml2
-rw-r--r--lib/inets/doc/src/httpc.xml69
-rw-r--r--lib/inets/doc/src/httpd.xml14
-rw-r--r--lib/inets/doc/src/inets.xml54
-rw-r--r--lib/inets/doc/src/mod_esi.xml29
-rw-r--r--lib/inets/doc/src/mod_security.xml4
-rw-r--r--lib/inets/doc/src/notes.xml137
-rw-r--r--lib/inets/src/ftp/ftp.erl259
-rw-r--r--lib/inets/src/http_client/httpc.erl82
-rw-r--r--lib/inets/src/http_client/httpc_handler.erl274
-rw-r--r--lib/inets/src/http_client/httpc_handler_sup.erl8
-rw-r--r--lib/inets/src/http_client/httpc_manager.erl509
-rw-r--r--lib/inets/src/http_client/httpc_request.erl104
-rw-r--r--lib/inets/src/http_lib/http_internal.hrl6
-rw-r--r--lib/inets/src/http_lib/http_transport.erl99
-rw-r--r--lib/inets/src/http_lib/http_util.erl18
-rw-r--r--lib/inets/src/http_server/httpd_file.erl17
-rw-r--r--lib/inets/src/http_server/httpd_log.erl4
-rw-r--r--lib/inets/src/http_server/httpd_request_handler.erl6
-rw-r--r--lib/inets/src/http_server/httpd_sup.erl47
-rw-r--r--lib/inets/src/http_server/httpd_util.erl38
-rw-r--r--lib/inets/src/http_server/mod_esi.erl8
-rw-r--r--lib/inets/src/inets_app/inets.appup.src16
-rw-r--r--lib/inets/test/ftp_SUITE.erl53
-rw-r--r--lib/inets/test/httpc_SUITE.erl418
-rw-r--r--lib/inets/test/httpd_basic_SUITE.erl56
-rw-r--r--lib/inets/test/httpd_mod.erl5
-rw-r--r--lib/inets/test/inets_app_test.erl14
-rw-r--r--lib/inets/test/inets_test_lib.erl11
-rw-r--r--lib/inets/test/inets_test_lib.hrl2
-rw-r--r--lib/inets/vsn.mk2
-rw-r--r--lib/jinterface/doc/src/notes.xml2
-rw-r--r--lib/kernel/doc/specs/.gitignore1
-rw-r--r--lib/kernel/doc/src/Makefile40
-rw-r--r--lib/kernel/doc/src/application.xml234
-rw-r--r--lib/kernel/doc/src/auth.xml51
-rw-r--r--lib/kernel/doc/src/code.xml6
-rw-r--r--lib/kernel/doc/src/disk_log.xml451
-rw-r--r--lib/kernel/doc/src/erl_boot_server.xml44
-rw-r--r--lib/kernel/doc/src/erl_ddll.xml129
-rw-r--r--lib/kernel/doc/src/error_handler.xml44
-rw-r--r--lib/kernel/doc/src/error_logger.xml135
-rw-r--r--lib/kernel/doc/src/file.xml895
-rw-r--r--lib/kernel/doc/src/gen_sctp.xml237
-rw-r--r--lib/kernel/doc/src/gen_tcp.xml163
-rw-r--r--lib/kernel/doc/src/gen_udp.xml101
-rw-r--r--lib/kernel/doc/src/global.xml176
-rw-r--r--lib/kernel/doc/src/global_group.xml157
-rw-r--r--lib/kernel/doc/src/heart.xml16
-rw-r--r--lib/kernel/doc/src/inet.xml193
-rw-r--r--lib/kernel/doc/src/inet_res.xml271
-rw-r--r--lib/kernel/doc/src/net_adm.xml74
-rw-r--r--lib/kernel/doc/src/net_kernel.xml90
-rw-r--r--lib/kernel/doc/src/notes.xml2
-rw-r--r--lib/kernel/doc/src/os.xml44
-rw-r--r--lib/kernel/doc/src/pg2.xml66
-rw-r--r--lib/kernel/doc/src/rpc.xml330
-rw-r--r--lib/kernel/doc/src/seq_trace.xml95
-rw-r--r--lib/kernel/doc/src/specs.xml33
-rw-r--r--lib/kernel/doc/src/wrap_log_reader.xml66
-rw-r--r--lib/kernel/include/inet.hrl15
-rw-r--r--lib/kernel/src/application.erl172
-rw-r--r--lib/kernel/src/auth.erl16
-rw-r--r--lib/kernel/src/disk_log.erl252
-rw-r--r--lib/kernel/src/disk_log.hrl24
-rw-r--r--lib/kernel/src/erl_boot_server.erl28
-rw-r--r--lib/kernel/src/erl_ddll.erl49
-rw-r--r--lib/kernel/src/error_handler.erl13
-rw-r--r--lib/kernel/src/error_logger.erl79
-rw-r--r--lib/kernel/src/file.erl375
-rw-r--r--lib/kernel/src/gen_sctp.erl148
-rw-r--r--lib/kernel/src/gen_tcp.erl82
-rw-r--r--lib/kernel/src/gen_udp.erl52
-rw-r--r--lib/kernel/src/global.erl92
-rw-r--r--lib/kernel/src/global_group.erl58
-rw-r--r--lib/kernel/src/global_search.erl5
-rw-r--r--lib/kernel/src/heart.erl10
-rw-r--r--lib/kernel/src/inet.erl96
-rw-r--r--lib/kernel/src/inet_res.erl180
-rw-r--r--lib/kernel/src/inet_udp.erl6
-rw-r--r--lib/kernel/src/net_adm.erl41
-rw-r--r--lib/kernel/src/net_kernel.erl37
-rw-r--r--lib/kernel/src/os.erl23
-rw-r--r--lib/kernel/src/pg2.erl68
-rw-r--r--lib/kernel/src/rpc.erl192
-rw-r--r--lib/kernel/src/seq_trace.erl44
-rw-r--r--lib/kernel/src/wrap_log_reader.erl35
-rw-r--r--lib/kernel/test/file_SUITE.erl77
-rw-r--r--lib/kernel/test/prim_file_SUITE.erl74
-rw-r--r--lib/mnesia/doc/src/Mnesia_chap7.xmlsrc7
-rw-r--r--lib/mnesia/doc/src/mnesia.xml32
-rw-r--r--lib/mnesia/doc/src/notes.xml2
-rw-r--r--lib/mnesia/src/mnesia.appup.src36
-rw-r--r--lib/mnesia/src/mnesia.erl11
-rw-r--r--lib/mnesia/src/mnesia.hrl1
-rw-r--r--lib/mnesia/src/mnesia_controller.erl26
-rw-r--r--lib/mnesia/src/mnesia_dumper.erl8
-rw-r--r--lib/mnesia/src/mnesia_lib.erl10
-rw-r--r--lib/mnesia/src/mnesia_loader.erl2
-rw-r--r--lib/mnesia/src/mnesia_locker.erl69
-rw-r--r--lib/mnesia/src/mnesia_schema.erl54
-rw-r--r--lib/mnesia/src/mnesia_text.erl5
-rw-r--r--lib/mnesia/src/mnesia_tm.erl66
-rw-r--r--lib/mnesia/test/Makefile1
-rw-r--r--lib/mnesia/test/mnesia_SUITE.erl2
-rw-r--r--lib/mnesia/test/mnesia_majority_test.erl186
-rw-r--r--lib/mnesia/test/mt.erl1
-rw-r--r--lib/mnesia/vsn.mk2
-rw-r--r--lib/observer/doc/src/notes.xml2
-rw-r--r--lib/odbc/doc/src/notes.xml2
-rw-r--r--lib/public_key/doc/src/Makefile3
-rw-r--r--lib/public_key/doc/src/notes.xml2
-rw-r--r--lib/public_key/doc/src/part.xml3
-rw-r--r--lib/public_key/doc/src/public_key.xml24
-rw-r--r--lib/public_key/doc/src/using_public_key.xml504
-rw-r--r--lib/reltool/src/reltool_server.erl189
-rw-r--r--lib/reltool/src/reltool_sys_win.erl26
-rw-r--r--lib/reltool/test/Makefile4
-rw-r--r--lib/reltool/test/reltool_server_SUITE.erl125
-rw-r--r--lib/reltool/test/reltool_server_SUITE_data/Makefile.src19
-rw-r--r--lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/ebin/x.app7
-rw-r--r--lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/mylib.erl4
-rw-r--r--lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/x.erl4
-rw-r--r--lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/ebin/y.app7
-rw-r--r--lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/mylib.erl4
-rw-r--r--lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/y.erl4
-rw-r--r--lib/runtime_tools/doc/src/notes.xml2
-rw-r--r--lib/sasl/Makefile4
-rw-r--r--lib/sasl/doc/src/notes.xml2
-rw-r--r--lib/sasl/examples/ebin/.gitignore0
-rw-r--r--lib/sasl/examples/src/Makefile78
-rw-r--r--lib/sasl/examples/src/target_system.erl259
-rw-r--r--lib/sasl/src/rb.erl14
-rw-r--r--lib/sasl/test/.gitignore5
-rw-r--r--lib/sasl/test/Makefile91
-rw-r--r--lib/sasl/test/alarm_handler_SUITE.erl179
-rw-r--r--lib/sasl/test/installer.erl778
-rw-r--r--lib/sasl/test/overload_SUITE.erl175
-rw-r--r--lib/sasl/test/rb_SUITE.erl606
-rw-r--r--lib/sasl/test/release_handler_SUITE.erl1651
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/Makefile.src108
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/ebin/a.app8
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a.erl47
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a_sup.erl37
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/ebin/app1.app9
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1.erl22
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_server.erl32
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_sup.erl17
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/ebin/app2.app9
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2.erl17
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_server.erl32
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_sup.erl17
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.app9
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.appup4
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1.erl22
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_server.erl35
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_sup.erl17
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/ebin/app2.app9
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2.erl17
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_server.erl32
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_sup.erl17
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/c/aa.erl41
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/c/b.erl38
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/c/c.app8
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/c/c_sup.erl40
-rwxr-xr-xlib/sasl/test/release_handler_SUITE_data/clients/start_cli138
-rwxr-xr-xlib/sasl/test/release_handler_SUITE_data/clients/start_cli237
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/ebin/a.app8
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.app8
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.erl49
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a_sup.erl37
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.app8
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.appup3
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a.erl54
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a_sup.erl37
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/ebin/installer.app6
l---------lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/src/installer.erl1
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_atom.erl26
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_list.erl26
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_numeric.erl26
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_string.erl26
-rw-r--r--lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_tuple.erl26
-rwxr-xr-xlib/sasl/test/release_handler_SUITE_data/start29
l---------lib/sasl/test/release_handler_SUITE_data/target_system.erl1
-rw-r--r--lib/sasl/test/sasl.cover2
-rw-r--r--lib/sasl/test/sasl.spec1
-rw-r--r--lib/sasl/test/sasl_SUITE.erl98
-rw-r--r--lib/sasl/test/systools_SUITE.erl2112
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.appup20
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.appup27
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.app7
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.appup27
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.appup20
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.appup27
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.appup20
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/ebin/fe.appup27
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.appup20
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.appup27
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.appup27
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-3.1/ebin/fe.app7
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/ebin/db.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/ebin/db.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.app7
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.appup20
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db1.erl13
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.app7
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.appup20
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/ebin/fe.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/ebin/fe.app8
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe1.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.app7
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.appup27
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe1.erl7
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe2.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe3.erl2
-rw-r--r--lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.app6
-rw-r--r--lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.appup12
-rw-r--r--lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.app6
-rw-r--r--lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.appup12
-rw-r--r--lib/sasl/test/systools_rc_SUITE.erl488
-rw-r--r--lib/snmp/doc/src/files.mk1
-rw-r--r--lib/snmp/doc/src/notes.xml115
-rw-r--r--lib/snmp/doc/src/snmp_agent_config_files.xml60
-rw-r--r--lib/snmp/doc/src/snmp_agent_netif.xml201
-rw-r--r--lib/snmp/doc/src/snmp_community_mib.xml26
-rw-r--r--lib/snmp/doc/src/snmp_target_mib.xml24
-rw-r--r--lib/snmp/doc/src/snmpa.xml250
-rw-r--r--lib/snmp/doc/src/snmpa_conf.xml25
-rw-r--r--lib/snmp/doc/src/snmpm.xml559
-rw-r--r--lib/snmp/mibs/Makefile.in3
-rw-r--r--lib/snmp/mibs/TRANSPORT-ADDRESS-MIB.mib417
-rw-r--r--lib/snmp/priv/conf/agent/target_addr.conf10
-rw-r--r--lib/snmp/src/agent/snmp_community_mib.erl15
-rw-r--r--lib/snmp/src/agent/snmp_notification_mib.erl7
-rw-r--r--lib/snmp/src/agent/snmp_target_mib.erl168
-rw-r--r--lib/snmp/src/agent/snmpa.erl62
-rw-r--r--lib/snmp/src/agent/snmpa_acm.erl26
-rw-r--r--lib/snmp/src/agent/snmpa_agent.erl321
-rw-r--r--lib/snmp/src/agent/snmpa_authentication_service.erl9
-rw-r--r--lib/snmp/src/agent/snmpa_conf.erl63
-rw-r--r--lib/snmp/src/agent/snmpa_internal.hrl1
-rw-r--r--lib/snmp/src/agent/snmpa_mpd.erl44
-rw-r--r--lib/snmp/src/agent/snmpa_net_if.erl79
-rw-r--r--lib/snmp/src/agent/snmpa_trap.erl229
-rw-r--r--lib/snmp/src/agent/snmpa_usm.erl17
-rw-r--r--lib/snmp/src/app/snmp.appup.src118
-rw-r--r--lib/snmp/src/manager/snmpm.erl566
-rw-r--r--lib/snmp/src/manager/snmpm_internal.hrl7
-rw-r--r--lib/snmp/src/manager/snmpm_net_if.erl18
-rw-r--r--lib/snmp/src/manager/snmpm_server.erl684
-rw-r--r--lib/snmp/src/manager/snmpm_usm.erl5
-rw-r--r--lib/snmp/src/misc/snmp_conf.erl207
-rw-r--r--lib/snmp/src/misc/snmp_config.erl20
-rw-r--r--lib/snmp/src/misc/snmp_log.erl5
-rw-r--r--lib/snmp/src/misc/snmp_misc.erl11
-rw-r--r--lib/snmp/src/misc/snmp_pdus.erl44
-rw-r--r--lib/snmp/test/Makefile7
-rw-r--r--lib/snmp/test/snmp_agent_test.erl298
-rw-r--r--lib/snmp/test/snmp_agent_test_lib.erl15
-rw-r--r--lib/snmp/test/snmp_manager_test.erl1090
-rw-r--r--lib/snmp/test/snmp_manager_user.erl135
-rw-r--r--lib/snmp/test/snmp_pdus_test.erl55
-rw-r--r--lib/snmp/vsn.mk2
-rw-r--r--lib/ssh/doc/src/notes.xml14
-rw-r--r--lib/ssh/src/ssh.appup.src2
-rw-r--r--lib/ssh/src/ssh_connection_handler.erl14
-rw-r--r--lib/ssh/test/Makefile121
-rw-r--r--lib/ssh/test/ssh.cover2
-rw-r--r--lib/ssh/test/ssh.spec7
-rw-r--r--lib/ssh/test/ssh.spec.vxworks3
-rw-r--r--lib/ssh/test/ssh_SUITE.erl72
-rw-r--r--lib/ssh/test/ssh_basic_SUITE.erl389
-rw-r--r--lib/ssh/test/ssh_sftp_SUITE.erl543
-rw-r--r--lib/ssh/test/ssh_sftp_SUITE_data/id_rsa15
-rw-r--r--lib/ssh/test/ssh_sftp_SUITE_data/id_rsa.pub1
-rw-r--r--lib/ssh/test/ssh_sftp_SUITE_data/sftp.txt252
-rw-r--r--lib/ssh/test/ssh_sftpd_SUITE.erl934
-rw-r--r--lib/ssh/test/ssh_sftpd_SUITE_data/test.txt1
-rw-r--r--lib/ssh/test/ssh_sftpd_erlclient_SUITE.erl328
-rw-r--r--lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/ssh_sftpd_file_alt.erl100
-rw-r--r--lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/test.txt1
-rw-r--r--lib/ssh/test/ssh_test_lib.erl684
-rw-r--r--lib/ssh/test/ssh_to_openssh_SUITE.erl458
-rw-r--r--lib/ssh/vsn.mk2
-rw-r--r--lib/ssl/c_src/Makefile.in8
-rw-r--r--lib/ssl/doc/src/notes.xml84
-rw-r--r--lib/ssl/src/ssl.appup.src4
-rw-r--r--lib/ssl/src/ssl.erl4
-rw-r--r--lib/ssl/src/ssl_connection.erl18
-rw-r--r--lib/ssl/src/ssl_manager.erl30
-rw-r--r--lib/stdlib/doc/specs/.gitignore1
-rw-r--r--lib/stdlib/doc/src/Makefile15
-rw-r--r--lib/stdlib/doc/src/array.xml177
-rw-r--r--lib/stdlib/doc/src/base64.xml35
-rw-r--r--lib/stdlib/doc/src/beam_lib.xml271
-rw-r--r--lib/stdlib/doc/src/binary.xml150
-rw-r--r--lib/stdlib/doc/src/c.xml127
-rw-r--r--lib/stdlib/doc/src/calendar.xml226
-rw-r--r--lib/stdlib/doc/src/dets.xml705
-rw-r--r--lib/stdlib/doc/src/dict.xml212
-rw-r--r--lib/stdlib/doc/src/digraph.xml395
-rw-r--r--lib/stdlib/doc/src/digraph_utils.xml170
-rw-r--r--lib/stdlib/doc/src/epp.xml62
-rw-r--r--lib/stdlib/doc/src/erl_eval.xml153
-rw-r--r--lib/stdlib/doc/src/erl_expand_records.xml6
-rw-r--r--lib/stdlib/doc/src/erl_id_trans.xml6
-rw-r--r--lib/stdlib/doc/src/erl_internal.xml73
-rw-r--r--lib/stdlib/doc/src/erl_lint.xml50
-rw-r--r--lib/stdlib/doc/src/erl_parse.xml122
-rw-r--r--lib/stdlib/doc/src/erl_pp.xml123
-rw-r--r--lib/stdlib/doc/src/erl_scan.xml362
-rw-r--r--lib/stdlib/doc/src/ets.xml255
-rw-r--r--lib/stdlib/doc/src/file_sorter.xml266
-rw-r--r--lib/stdlib/doc/src/filelib.xml89
-rw-r--r--lib/stdlib/doc/src/filename.xml156
-rw-r--r--lib/stdlib/doc/src/gb_sets.xml288
-rw-r--r--lib/stdlib/doc/src/gb_trees.xml216
-rw-r--r--lib/stdlib/doc/src/gen_event.xml16
-rw-r--r--lib/stdlib/doc/src/io.xml354
-rw-r--r--lib/stdlib/doc/src/io_lib.xml179
-rw-r--r--lib/stdlib/doc/src/lib.xml37
-rw-r--r--lib/stdlib/doc/src/lists.xml764
-rw-r--r--lib/stdlib/doc/src/log_mf_h.xml31
-rw-r--r--lib/stdlib/doc/src/math.xml2
-rw-r--r--lib/stdlib/doc/src/ms_transform.xml25
-rw-r--r--lib/stdlib/doc/src/notes.xml2
-rw-r--r--lib/stdlib/doc/src/orddict.xml213
-rw-r--r--lib/stdlib/doc/src/ordsets.xml153
-rw-r--r--lib/stdlib/doc/src/pg.xml55
-rw-r--r--lib/stdlib/doc/src/pool.xml46
-rw-r--r--lib/stdlib/doc/src/proc_lib.xml163
-rw-r--r--lib/stdlib/doc/src/proplists.xml210
-rw-r--r--lib/stdlib/doc/src/qlc.xml646
-rw-r--r--lib/stdlib/doc/src/queue.xml286
-rw-r--r--lib/stdlib/doc/src/random.xml50
-rw-r--r--lib/stdlib/doc/src/re.xml133
-rw-r--r--lib/stdlib/doc/src/regexp.xml152
-rw-r--r--lib/stdlib/doc/src/sets.xml153
-rw-r--r--lib/stdlib/doc/src/shell.xml37
-rw-r--r--lib/stdlib/doc/src/slave.xml60
-rw-r--r--lib/stdlib/doc/src/sofs.xml1021
-rw-r--r--lib/stdlib/doc/src/specs.xml63
-rw-r--r--lib/stdlib/doc/src/string.xml230
-rw-r--r--lib/stdlib/doc/src/supervisor.xml218
-rw-r--r--lib/stdlib/doc/src/supervisor_bridge.xml47
-rw-r--r--lib/stdlib/doc/src/sys.xml212
-rw-r--r--lib/stdlib/doc/src/timer.xml169
-rw-r--r--lib/stdlib/doc/src/unicode.xml174
-rw-r--r--lib/stdlib/doc/src/win32reg.xml98
-rw-r--r--lib/stdlib/doc/src/zip.xml281
-rw-r--r--lib/stdlib/include/zip.hrl4
-rw-r--r--lib/stdlib/src/array.erl111
-rw-r--r--lib/stdlib/src/base64.erl24
-rw-r--r--lib/stdlib/src/beam_lib.erl117
-rw-r--r--lib/stdlib/src/binary.erl37
-rw-r--r--lib/stdlib/src/c.erl66
-rw-r--r--lib/stdlib/src/calendar.erl91
-rw-r--r--lib/stdlib/src/dets.erl301
-rw-r--r--lib/stdlib/src/dict.erl99
-rw-r--r--lib/stdlib/src/digraph.erl159
-rw-r--r--lib/stdlib/src/digraph_utils.erl84
-rw-r--r--lib/stdlib/src/epp.erl43
-rw-r--r--lib/stdlib/src/erl_eval.erl134
-rw-r--r--lib/stdlib/src/erl_expand_records.erl6
-rw-r--r--lib/stdlib/src/erl_internal.erl39
-rw-r--r--lib/stdlib/src/erl_lint.erl31
-rw-r--r--lib/stdlib/src/erl_parse.yrl39
-rw-r--r--lib/stdlib/src/erl_pp.erl65
-rw-r--r--lib/stdlib/src/erl_scan.erl115
-rw-r--r--lib/stdlib/src/ets.erl148
-rw-r--r--lib/stdlib/src/file_sorter.erl119
-rw-r--r--lib/stdlib/src/filelib.erl39
-rw-r--r--lib/stdlib/src/filename.erl84
-rw-r--r--lib/stdlib/src/gb_sets.erl147
-rw-r--r--lib/stdlib/src/gb_trees.erl109
-rw-r--r--lib/stdlib/src/gen_event.erl11
-rw-r--r--lib/stdlib/src/io.erl195
-rw-r--r--lib/stdlib/src/io_lib.erl78
-rw-r--r--lib/stdlib/src/io_lib_fread.erl41
-rw-r--r--lib/stdlib/src/lib.erl20
-rw-r--r--lib/stdlib/src/lists.erl425
-rw-r--r--lib/stdlib/src/log_mf_h.erl21
-rw-r--r--lib/stdlib/src/ms_transform.erl16
-rw-r--r--lib/stdlib/src/orddict.erl98
-rw-r--r--lib/stdlib/src/ordsets.erl72
-rw-r--r--lib/stdlib/src/otp_internal.erl96
-rw-r--r--lib/stdlib/src/pg.erl28
-rw-r--r--lib/stdlib/src/pool.erl24
-rw-r--r--lib/stdlib/src/proc_lib.erl138
-rw-r--r--lib/stdlib/src/proplists.erl151
-rw-r--r--lib/stdlib/src/qlc.erl304
-rw-r--r--lib/stdlib/src/qlc_pt.erl18
-rw-r--r--lib/stdlib/src/queue.erl123
-rw-r--r--lib/stdlib/src/random.erl24
-rw-r--r--lib/stdlib/src/re.erl47
-rw-r--r--lib/stdlib/src/regexp.erl69
-rw-r--r--lib/stdlib/src/sets.erl74
-rw-r--r--lib/stdlib/src/shell.erl23
-rw-r--r--lib/stdlib/src/slave.erl52
-rw-r--r--lib/stdlib/src/sofs.erl545
-rw-r--r--lib/stdlib/src/string.erl175
-rw-r--r--lib/stdlib/src/supervisor.erl98
-rw-r--r--lib/stdlib/src/supervisor_bridge.erl18
-rw-r--r--lib/stdlib/src/sys.erl182
-rw-r--r--lib/stdlib/src/timer.erl119
-rw-r--r--lib/stdlib/src/unicode.erl51
-rw-r--r--lib/stdlib/src/win32reg.erl70
-rw-r--r--lib/stdlib/src/zip.erl185
-rw-r--r--lib/stdlib/test/dets_SUITE.erl26
-rw-r--r--lib/stdlib/test/erl_eval_SUITE.erl2
-rw-r--r--lib/stdlib/test/erl_pp_SUITE.erl2
-rw-r--r--lib/stdlib/test/sofs_SUITE.erl27
-rw-r--r--lib/test_server/doc/src/notes.xml2
-rw-r--r--lib/test_server/src/configure.in2
-rw-r--r--lib/test_server/src/ts_run.erl10
-rw-r--r--lib/tools/doc/src/notes.xml2
-rw-r--r--lib/tools/src/cover.erl1
-rw-r--r--lib/tools/test/cover_SUITE.erl4
-rw-r--r--lib/wx/doc/src/notes.xml2
-rw-r--r--lib/xmerl/doc/src/notes.xml2
-rw-r--r--lib/xmerl/src/xmerl_sax_parser.erl4
-rw-r--r--lib/xmerl/vsn.mk2
-rw-r--r--make/otp.mk.in5
-rwxr-xr-xotp_build15
693 files changed, 104573 insertions, 14610 deletions
diff --git a/.gitignore b/.gitignore
index b35a6c1c31..592ac6668b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -366,5 +366,6 @@ make/win32/
/lib/xmerl/src/xmerl_sax_parser_*.erl
/lib/xmerl/src/xmerl_b64Bin.erl
/lib/xmerl/src/xmerl_xpath_parse.erl
+/lib/xmerl/test/xmerl_test.erl
/lib/erl_interface/config.h.in
/lib/configure.in
diff --git a/Makefile.in b/Makefile.in
index b17713f182..5acd390333 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -502,6 +502,7 @@ ifeq ($(TARGET),win32)
bootstrap_setup: check_recreate_primary_bootstrap bootstrap_setup_target
@rm -f $(BOOTSTRAP_ROOT)/bootstrap/bin/erl.exe \
$(BOOTSTRAP_ROOT)/bootstrap/bin/erlc.exe \
+ $(BOOTSTRAP_ROOT)/bootstrap/bin/escript.exe \
$(BOOTSTRAP_ROOT)/bootstrap/bin/erl.ini \
$(BOOTSTRAP_ROOT)/bootstrap/bin/beam.dll
make_bootstrap_ini.sh $(BOOTSTRAP_ROOT)/bootstrap \
@@ -510,8 +511,10 @@ bootstrap_setup: check_recreate_primary_bootstrap bootstrap_setup_target
$(BOOTSTRAP_ROOT)/bootstrap/bin/erlc.exe
@cp $(ERL_TOP)/bin/$(TARGET)/erl.exe \
$(BOOTSTRAP_ROOT)/bootstrap/bin/erl.exe
+ @cp $(ERL_TOP)/bin/$(TARGET)/escript.exe \
+ $(BOOTSTRAP_ROOT)/bootstrap/bin/escript.exe
else
-bootstrap_setup: check_recreate_primary_bootstrap bootstrap_setup_target $(BOOTSTRAP_ROOT)/bootstrap/bin/erl $(BOOTSTRAP_ROOT)/bootstrap/bin/erlc
+bootstrap_setup: check_recreate_primary_bootstrap bootstrap_setup_target $(BOOTSTRAP_ROOT)/bootstrap/bin/erl $(BOOTSTRAP_ROOT)/bootstrap/bin/erlc $(BOOTSTRAP_ROOT)/bootstrap/bin/escript
$(BOOTSTRAP_ROOT)/bootstrap/bin/erl: $(ERL_TOP)/erts/etc/unix/erl.src.src $(BOOTSTRAP_ROOT)/bootstrap/target
@rm -f $(BOOTSTRAP_ROOT)/bootstrap/bin/erl
@@ -526,6 +529,11 @@ $(BOOTSTRAP_ROOT)/bootstrap/bin/erlc: $(ERL_TOP)/bin/$(TARGET)/erlc $(BOOTSTRAP_
@rm -f $(BOOTSTRAP_ROOT)/bootstrap/bin/erlc
@cp $(ERL_TOP)/bin/$(TARGET)/erlc $(BOOTSTRAP_ROOT)/bootstrap/bin/erlc
@chmod 755 $(BOOTSTRAP_ROOT)/bootstrap/bin/erlc
+
+$(BOOTSTRAP_ROOT)/bootstrap/bin/escript: $(ERL_TOP)/bin/$(TARGET)/escript $(BOOTSTRAP_ROOT)/bootstrap/target
+ @rm -f $(BOOTSTRAP_ROOT)/bootstrap/bin/escript
+ @cp $(ERL_TOP)/bin/$(TARGET)/escript $(BOOTSTRAP_ROOT)/bootstrap/bin/escript
+ @chmod 755 $(BOOTSTRAP_ROOT)/bootstrap/bin/escript
endif
bootstrap_setup_target:
diff --git a/erts/aclocal.m4 b/erts/aclocal.m4
index a1211bbf0c..f7e5c31910 100644
--- a/erts/aclocal.m4
+++ b/erts/aclocal.m4
@@ -1153,7 +1153,7 @@ case "$THR_LIB_NAME" in
AO_nop_full();
AO_store(&x, (AO_t) 0);
z = AO_load(&x);
- z = AO_compare_and_swap(&x, (AO_t) 0, (AO_t) 1);
+ z = AO_compare_and_swap_full(&x, (AO_t) 0, (AO_t) 1);
],
[ethr_have_native_atomics=yes
ethr_have_libatomic_ops=yes])
diff --git a/erts/configure.in b/erts/configure.in
index 31d1d55b8a..fac07f8b6a 100644
--- a/erts/configure.in
+++ b/erts/configure.in
@@ -769,6 +769,7 @@ if test "$enable_halfword_emulator" = "yes"; then
if test "$ARCH" = "amd64"; then
AC_DEFINE(HALFWORD_HEAP_EMULATOR, [1],
[Define if building a halfword-heap 64bit emulator])
+ ENABLE_ALLOC_TYPE_VARS="$ENABLE_ALLOC_TYPE_VARS halfword"
AC_MSG_RESULT([yes])
else
AC_MSG_ERROR(no; halfword emulator not supported on this architecture)
@@ -3523,6 +3524,8 @@ dnl use "PATH/include" and "PATH/lib".
AC_SUBST(SSL_INCLUDE)
AC_SUBST(SSL_ROOT)
AC_SUBST(SSL_LIBDIR)
+AC_SUBST(SSL_CRYPTO_LIBNAME)
+AC_SUBST(SSL_SSL_LIBNAME)
AC_SUBST(SSL_CC_RUNTIME_LIBRARY_PATH)
AC_SUBST(SSL_LD_RUNTIME_LIBRARY_PATH)
AC_SUBST(SSL_DED_LD_RUNTIME_LIBRARY_PATH)
@@ -3686,19 +3689,41 @@ case "$erl_xcomp_without_sysroot-$with_ssl" in
CRYPTO_APP=crypto
SSH_APP=ssh
- AC_MSG_CHECKING(for OpenSSL >= 0.9.7 in standard locations)
+ SSL_CRYPTO_LIBNAME=crypto
+ SSL_SSL_LIBNAME=ssl
+
+ AC_MSG_CHECKING(for OpenSSL >= 0.9.7 in standard locations)
for rdir in $extra_dir /cygdrive/c/OpenSSL $std_ssl_locations; do
dir="$erl_xcomp_sysroot$rdir"
if test -f "$erl_xcomp_isysroot$rdir/include/openssl/opensslv.h"; then
is_real_ssl=yes
SSL_ROOT="$dir"
if test "x$MIXED_CYGWIN" = "xyes" ; then
- if test -f "$dir/lib/VC/ssleay32.lib" || \
- test -f "$dir/lib/VC/openssl.lib"; then
+ if test -f "$dir/lib/VC/libeay32.lib"; then
+ SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
+ SSL_LIBDIR="$dir/lib/VC"
+ SSL_CRYPTO_LIBNAME=libeay32
+ SSL_SSL_LIBNAME=ssleay32
+ elif test -f "$dir/lib/VC/openssl.lib"; then
SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
SSL_LIBDIR="$dir/lib/VC"
- elif test -f "$dir/lib/ssleay32.lib" || \
- test -f "$dir/lib/openssl.lib"; then
+ elif test -f $dir/lib/VC/libeay32MD.lib; then
+ SSL_CRYPTO_LIBNAME=libeay32MD
+ SSL_SSL_LIBNAME=ssleay32MD
+ if test "x$enable_dynamic_ssl" = "xno" && \
+ test -f $dir/lib/VC/static/libeay32MD.lib; then
+ SSL_RUNTIME_LIBDIR="$rdir/lib/VC/static"
+ SSL_LIBDIR="$dir/lib/VC/static"
+ else
+ SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
+ SSL_LIBDIR="$dir/lib/VC"
+ fi
+ elif test -f "$dir/lib/libeay32.lib"; then
+ SSL_RUNTIME_LIBDIR="$rdir/lib"
+ SSL_LIBDIR="$dir/lib"
+ SSL_CRYPTO_LIBNAME=libeay32
+ SSL_CRYPTO_LIBNAME=ssleay32
+ elif test -f "$dir/lib/openssl.lib"; then
SSL_RUNTIME_LIBDIR="$rdir/lib"
SSL_LIBDIR="$dir/lib"
else
@@ -3858,8 +3883,32 @@ dnl so it is - be adoptable
AC_MSG_ERROR(Invalid path to option --with-ssl=PATH)
fi
SSL_ROOT="$with_ssl"
+ SSL_CRYPTO_LIBNAME=crypto
+ SSL_SSL_LIBNAME=ssl
if test "x$MIXED_CYGWIN" = "xyes" && test -d "$with_ssl/lib/VC"; then
- SSL_LIBDIR="$with_ssl/lib/VC"
+ if test -f "$with_ssl/lib/VC/libeay32.lib"; then
+ SSL_LIBDIR="$with_ssl/lib/VC"
+ SSL_CRYPTO_LIBNAME=libeay32
+ SSL_SSL_LIBNAME=ssleay32
+ elif test -f "$with_ssl/lib/VC/openssl.lib"; then
+ SSL_LIBDIR="$with_ssl/lib/VC"
+ elif test -f $with_ssl/lib/VC/libeay32MD.lib; then
+ SSL_CRYPTO_LIBNAME=libeay32MD
+ SSL_SSL_LIBNAME=ssleay32MD
+ if test "x$enable_dynamic_ssl" = "xno" && \
+ test -f $with_ssl/lib/VC/static/libeay32MD.lib; then
+ SSL_LIBDIR="$with_ssl/lib/VC/static"
+ else
+ SSL_LIBDIR="$with_ssl/lib/VC"
+ fi
+ elif test -f "$with_ssl/lib/libeay32.lib"; then
+ SSL_LIBDIR="$with_ssl/lib"
+ SSL_CRYPTO_LIBNAME=libeay32
+ SSL_CRYPTO_LIBNAME=ssleay32
+ else
+ # This probably wont work, but that's what the user said, so...
+ SSL_LIBDIR="$with_ssl/lib"
+ fi
elif test "x$ac_cv_sizeof_void_p" = "x8"; then
if test -f "$with_ssl/lib64/libcrypto.a"; then
SSL_LIBDIR="$with_ssl/lib64"
diff --git a/erts/doc/src/erlang.xml b/erts/doc/src/erlang.xml
index 19f501391f..f98e15cb52 100644
--- a/erts/doc/src/erlang.xml
+++ b/erts/doc/src/erlang.xml
@@ -2356,6 +2356,14 @@ os_prompt%</pre>
<seealso marker="tools:instrument">instrument(3)</seealso>
and/or <seealso marker="erts:erl">erl(1)</seealso>.</p>
</item>
+ <tag><c>low</c></tag>
+ <item>
+ <p>Only on 64-bit halfword emulator.</p>
+ <p>The total amount of memory allocated in low memory areas
+ that are restricted to less than 4 Gb even though
+ the system may have more physical memory.</p>
+ <p>May be removed in future releases of halfword emulator.</p>
+ </item>
</taglist>
<note>
<p>The <c>system</c> value is not complete. Some allocated
diff --git a/erts/doc/src/notes.xml b/erts/doc/src/notes.xml
index f5607945a8..7383ea381d 100644
--- a/erts/doc/src/notes.xml
+++ b/erts/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/erts/emulator/beam/atom.names b/erts/emulator/beam/atom.names
index 327620772f..de76cb9680 100644
--- a/erts/emulator/beam/atom.names
+++ b/erts/emulator/beam/atom.names
@@ -76,6 +76,7 @@ atom allocator_sizes
atom alloc_util_allocators
atom allow_passive_connect
atom already_loaded
+atom amd64
atom anchored
atom and
atom andalso
diff --git a/erts/emulator/beam/beam_bif_load.c b/erts/emulator/beam/beam_bif_load.c
index 1dbf6f9b92..d76a7d8e9f 100644
--- a/erts/emulator/beam/beam_bif_load.c
+++ b/erts/emulator/beam/beam_bif_load.c
@@ -1,7 +1,7 @@
/*
* %CopyrightBegin%
*
- * Copyright Ericsson AB 1999-2010. All Rights Reserved.
+ * Copyright Ericsson AB 1999-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
@@ -142,7 +142,7 @@ BIF_RETTYPE code_is_module_native_1(BIF_ALIST_1)
if ((modp = erts_get_module(BIF_ARG_1)) == NULL) {
return am_undefined;
}
- return (is_native(modp->code) ||
+ return ((modp->code && is_native(modp->code)) ||
(modp->old_code != 0 && is_native(modp->old_code))) ?
am_true : am_false;
}
diff --git a/erts/emulator/beam/beam_emu.c b/erts/emulator/beam/beam_emu.c
index 32ea8588d2..fb90a7d4f7 100644
--- a/erts/emulator/beam/beam_emu.c
+++ b/erts/emulator/beam/beam_emu.c
@@ -1911,13 +1911,15 @@ void process_main(void)
* Note that for the halfword emulator, the two first elements
* of the array are used.
*/
- *((BeamInstr **) (UWord) c_p->def_arg_reg) = I+3;
+ BeamInstr** pi = (BeamInstr**) c_p->def_arg_reg;
+ *pi = I+3;
set_timer(c_p, unsigned_val(timeout_value));
} else if (timeout_value == am_infinity) {
c_p->flags |= F_TIMO;
#if !defined(ARCH_64) || HALFWORD_HEAP
} else if (term_to_Uint(timeout_value, &time_val)) {
- *((BeamInstr **) (UWord) c_p->def_arg_reg) = I+3;
+ BeamInstr** pi = (BeamInstr**) c_p->def_arg_reg;
+ *pi = I+3;
set_timer(c_p, time_val);
#endif
} else { /* Wrong time */
@@ -1974,7 +1976,8 @@ void process_main(void)
* we must test the F_INSLPQUEUE flag as well as the F_TIMO flag.
*/
if ((c_p->flags & (F_INSLPQUEUE | F_TIMO)) == 0) {
- *((BeamInstr **) (UWord) c_p->def_arg_reg) = I+3;
+ BeamInstr** p = (BeamInstr **) c_p->def_arg_reg;
+ *p = I+3;
set_timer(c_p, Arg(1));
}
goto wait2;
@@ -5322,7 +5325,7 @@ void process_main(void)
ep->code[3] = (BeamInstr) OpCode(apply_bif);
ep->code[4] = (BeamInstr) bif_table[i].f;
/* XXX: set func info for bifs */
- ((BeamInstr*)ep->code + 3)[-5] = (BeamInstr) BeamOp(op_i_func_info_IaaI);
+ ep->fake_op_func_info_for_hipe[0] = (BeamInstr) BeamOp(op_i_func_info_IaaI);
}
return;
diff --git a/erts/emulator/beam/bif.c b/erts/emulator/beam/bif.c
index 8c35644125..68b3350d7f 100644
--- a/erts/emulator/beam/bif.c
+++ b/erts/emulator/beam/bif.c
@@ -2168,20 +2168,146 @@ BIF_RETTYPE tl_1(BIF_ALIST_1)
/**********************************************************************/
/* return the size of an I/O list */
-BIF_RETTYPE iolist_size_1(BIF_ALIST_1)
+static Eterm
+accumulate(Eterm acc, Uint size)
{
- Sint size = io_list_len(BIF_ARG_1);
+ if (is_non_value(acc)) {
+ /*
+ * There is no pre-existing accumulator. Allocate a
+ * bignum buffer with one extra word to be used if
+ * the bignum grows in the future.
+ */
+ Eterm* hp = (Eterm *) erts_alloc(ERTS_ALC_T_TEMP_TERM,
+ (BIG_UINT_HEAP_SIZE+1) *
+ sizeof(Eterm));
+ return uint_to_big(size, hp);
+ } else {
+ Eterm* big;
+ int need_heap;
- if (size == -1) {
- BIF_ERROR(BIF_P, BADARG);
- } else if (IS_USMALL(0, (Uint) size)) {
- BIF_RET(make_small(size));
+ /*
+ * Add 'size' to 'acc' in place. There is always one
+ * extra word allocated in case the bignum grows by one word.
+ */
+ big = big_val(acc);
+ need_heap = BIG_NEED_SIZE(BIG_SIZE(big));
+ acc = big_plus_small(acc, size, big);
+ if (BIG_NEED_SIZE(big_size(acc)) > need_heap) {
+ /*
+ * The extra word has been consumed. Grow the
+ * allocation by one word.
+ */
+ big = (Eterm *) erts_realloc(ERTS_ALC_T_TEMP_TERM,
+ big_val(acc),
+ (need_heap+1) * sizeof(Eterm));
+ acc = make_big(big);
+ }
+ return acc;
+ }
+}
+
+static Eterm
+consolidate(Process* p, Eterm acc, Uint size)
+{
+ Eterm* hp;
+
+ if (is_non_value(acc)) {
+ return erts_make_integer(size, p);
} else {
- Eterm* hp = HAlloc(BIF_P, BIG_UINT_HEAP_SIZE);
- BIF_RET(uint_to_big(size, hp));
+ Eterm* big;
+ Uint sz;
+ Eterm res;
+
+ acc = accumulate(acc, size);
+ big = big_val(acc);
+ sz = BIG_NEED_SIZE(BIG_SIZE(big));
+ hp = HAlloc(p, sz);
+ res = make_big(hp);
+ while (sz--) {
+ *hp++ = *big++;
+ }
+ erts_free(ERTS_ALC_T_TEMP_TERM, (void *) big_val(acc));
+ return res;
}
}
+BIF_RETTYPE iolist_size_1(BIF_ALIST_1)
+{
+ Eterm obj, hd;
+ Eterm* objp;
+ Uint size = 0;
+ Uint cur_size;
+ Uint new_size;
+ Eterm acc = THE_NON_VALUE;
+ DECLARE_ESTACK(s);
+
+ obj = BIF_ARG_1;
+ goto L_again;
+
+ while (!ESTACK_ISEMPTY(s)) {
+ obj = ESTACK_POP(s);
+ L_again:
+ if (is_list(obj)) {
+ L_iter_list:
+ objp = list_val(obj);
+ hd = CAR(objp);
+ obj = CDR(objp);
+ /* Head */
+ if (is_byte(hd)) {
+ size++;
+ if (size == 0) {
+ acc = accumulate(acc, (Uint) -1);
+ size = 1;
+ }
+ } else if (is_binary(hd) && binary_bitsize(hd) == 0) {
+ cur_size = binary_size(hd);
+ if ((new_size = size + cur_size) >= size) {
+ size = new_size;
+ } else {
+ acc = accumulate(acc, size);
+ size = cur_size;
+ }
+ } else if (is_list(hd)) {
+ ESTACK_PUSH(s, obj);
+ obj = hd;
+ goto L_iter_list;
+ } else if (is_not_nil(hd)) {
+ goto L_type_error;
+ }
+ /* Tail */
+ if (is_list(obj)) {
+ goto L_iter_list;
+ } else if (is_binary(obj) && binary_bitsize(obj) == 0) {
+ cur_size = binary_size(obj);
+ if ((new_size = size + cur_size) >= size) {
+ size = new_size;
+ } else {
+ acc = accumulate(acc, size);
+ size = cur_size;
+ }
+ } else if (is_not_nil(obj)) {
+ goto L_type_error;
+ }
+ } else if (is_binary(obj) && binary_bitsize(obj) == 0) {
+ cur_size = binary_size(obj);
+ if ((new_size = size + cur_size) >= size) {
+ size = new_size;
+ } else {
+ acc = accumulate(acc, size);
+ size = cur_size;
+ }
+ } else if (is_not_nil(obj)) {
+ goto L_type_error;
+ }
+ }
+
+ DESTROY_ESTACK(s);
+ BIF_RET(consolidate(BIF_P, acc, size));
+
+ L_type_error:
+ DESTROY_ESTACK(s);
+ BIF_ERROR(BIF_P, BADARG);
+}
/**********************************************************************/
@@ -3282,6 +3408,7 @@ BIF_RETTYPE ports_0(BIF_ALIST_0)
Eterm* dead_ports;
int alive, dead;
Uint32 next_ss;
+ int i;
/* To get a consistent snapshot...
* We add alive ports from start of the buffer
@@ -3293,21 +3420,18 @@ BIF_RETTYPE ports_0(BIF_ALIST_0)
erts_smp_atomic_set(&erts_dead_ports_ptr,
(erts_aint_t) (port_buf + erts_max_ports));
- next_ss = erts_smp_atomic_inctest(&erts_ports_snapshot);
+ next_ss = erts_smp_atomic32_inctest(&erts_ports_snapshot);
- if (erts_smp_atomic_read(&erts_ports_alive) > 0) {
- erts_aint_t i;
- for (i = erts_max_ports-1; i >= 0; i--) {
- Port* prt = &erts_port[i];
- erts_smp_port_state_lock(prt);
- if (!(prt->status & ERTS_PORT_SFLGS_DEAD)
- && prt->snapshot != next_ss) {
- ASSERT(prt->snapshot == next_ss - 1);
- *pp++ = prt->id;
- prt->snapshot = next_ss; /* Consumed by this snapshot */
- }
- erts_smp_port_state_unlock(prt);
+ for (i = erts_max_ports-1; i >= 0; i--) {
+ Port* prt = &erts_port[i];
+ erts_smp_port_state_lock(prt);
+ if (!(prt->status & ERTS_PORT_SFLGS_DEAD)
+ && prt->snapshot != next_ss) {
+ ASSERT(prt->snapshot == next_ss - 1);
+ *pp++ = prt->id;
+ prt->snapshot = next_ss; /* Consumed by this snapshot */
}
+ erts_smp_port_state_unlock(prt);
}
dead_ports = (Eterm*)erts_smp_atomic_xchg(&erts_dead_ports_ptr,
diff --git a/erts/emulator/beam/big.c b/erts/emulator/beam/big.c
index f47f5a9c0c..d18de9ae5d 100644
--- a/erts/emulator/beam/big.c
+++ b/erts/emulator/beam/big.c
@@ -1588,7 +1588,7 @@ big_to_double(Wterm x, double* resp)
/*
** Estimate the number of decimal digits (include sign)
*/
-int big_decimal_estimate(Eterm x)
+int big_decimal_estimate(Wterm x)
{
Eterm* xp = big_val(x);
int lg = I_lg(BIG_V(xp), BIG_SIZE(xp));
@@ -1602,7 +1602,7 @@ int big_decimal_estimate(Eterm x)
** Convert a bignum into a string of decimal numbers
*/
-static void write_big(Eterm x, void (*write_func)(void *, char), void *arg)
+static void write_big(Wterm x, void (*write_func)(void *, char), void *arg)
{
Eterm* xp = big_val(x);
ErtsDigit* dx = BIG_V(xp);
@@ -1681,7 +1681,7 @@ write_string(void *arg, char c)
*(--(*((char **) arg))) = c;
}
-char *erts_big_to_string(Eterm x, char *buf, Uint buf_sz)
+char *erts_big_to_string(Wterm x, char *buf, Uint buf_sz)
{
char *big_str = buf + buf_sz - 1;
*big_str = '\0';
diff --git a/erts/emulator/beam/big.h b/erts/emulator/beam/big.h
index f28a390aea..2afc37004f 100644
--- a/erts/emulator/beam/big.h
+++ b/erts/emulator/beam/big.h
@@ -114,9 +114,9 @@ typedef Uint dsize_t; /* Vector size type */
#endif
-int big_decimal_estimate(Eterm);
+int big_decimal_estimate(Wterm);
Eterm erts_big_to_list(Eterm, Eterm**);
-char *erts_big_to_string(Eterm x, char *buf, Uint buf_sz);
+char *erts_big_to_string(Wterm x, char *buf, Uint buf_sz);
Eterm small_times(Sint, Sint, Eterm*);
diff --git a/erts/emulator/beam/binary.c b/erts/emulator/beam/binary.c
index 9486602633..1fb39c6c67 100644
--- a/erts/emulator/beam/binary.c
+++ b/erts/emulator/beam/binary.c
@@ -32,11 +32,11 @@
#include "erl_bits.h"
#ifdef DEBUG
-static int list_to_bitstr_buf(Eterm obj, char* buf, int len);
+static int list_to_bitstr_buf(Eterm obj, char* buf, Uint len);
#else
static int list_to_bitstr_buf(Eterm obj, char* buf);
#endif
-static Sint bitstr_list_len(Eterm obj);
+static int bitstr_list_len(Eterm obj, Uint* num_bytes);
void
erts_init_binary(void)
@@ -355,21 +355,24 @@ BIF_RETTYPE bitstring_to_list_1(BIF_ALIST_1)
BIF_RETTYPE erts_list_to_binary_bif(Process *p, Eterm arg)
{
Eterm bin;
- int i;
+ Uint size;
int offset;
byte* bytes;
+
if (is_nil(arg)) {
BIF_RET(new_binary(p,(byte*)"",0));
}
if (is_not_list(arg)) {
goto error;
}
- if ((i = io_list_len(arg)) < 0) {
- goto error;
+ switch (erts_iolist_size(arg, &size)) {
+ case ERTS_IOLIST_OVERFLOW: BIF_ERROR(p, SYSTEM_LIMIT);
+ case ERTS_IOLIST_TYPE: goto error;
+ default: ;
}
- bin = new_binary(p, (byte *)NULL, i);
+ bin = new_binary(p, (byte *)NULL, size);
bytes = binary_bytes(bin);
- offset = io_list_to_buf(arg, (char*) bytes, i);
+ offset = io_list_to_buf(arg, (char*) bytes, size);
ASSERT(offset == 0);
BIF_RET(bin);
@@ -396,7 +399,8 @@ BIF_RETTYPE iolist_to_binary_1(BIF_ALIST_1)
BIF_RETTYPE list_to_bitstring_1(BIF_ALIST_1)
{
Eterm bin;
- int i,offset;
+ Uint sz;
+ int offset;
byte* bytes;
ErlSubBin* sb1;
Eterm* hp;
@@ -405,15 +409,19 @@ BIF_RETTYPE list_to_bitstring_1(BIF_ALIST_1)
BIF_RET(new_binary(BIF_P,(byte*)"",0));
}
if (is_not_list(BIF_ARG_1)) {
- goto error;
+ error:
+ BIF_ERROR(BIF_P, BADARG);
}
- if ((i = bitstr_list_len(BIF_ARG_1)) < 0) {
+ switch (bitstr_list_len(BIF_ARG_1, &sz)) {
+ case ERTS_IOLIST_TYPE:
goto error;
+ case ERTS_IOLIST_OVERFLOW:
+ BIF_ERROR(BIF_P, SYSTEM_LIMIT);
}
- bin = new_binary(BIF_P, (byte *)NULL, i);
+ bin = new_binary(BIF_P, (byte *)NULL, sz);
bytes = binary_bytes(bin);
#ifdef DEBUG
- offset = list_to_bitstr_buf(BIF_ARG_1, (char*) bytes, i);
+ offset = list_to_bitstr_buf(BIF_ARG_1, (char*) bytes, sz);
#else
offset = list_to_bitstr_buf(BIF_ARG_1, (char*) bytes);
#endif
@@ -422,20 +430,16 @@ BIF_RETTYPE list_to_bitstring_1(BIF_ALIST_1)
hp = HAlloc(BIF_P, ERL_SUB_BIN_SIZE);
sb1 = (ErlSubBin *) hp;
sb1->thing_word = HEADER_SUB_BIN;
- sb1->size = i-1;
+ sb1->size = sz-1;
sb1->offs = 0;
sb1->orig = bin;
sb1->bitoffs = 0;
sb1->bitsize = offset;
sb1->is_writable = 0;
- hp += ERL_SUB_BIN_SIZE;
bin = make_binary(sb1);
}
BIF_RET(bin);
-
- error:
- BIF_ERROR(BIF_P, BADARG);
}
BIF_RETTYPE split_binary_2(BIF_ALIST_2)
@@ -499,7 +503,7 @@ BIF_RETTYPE split_binary_2(BIF_ALIST_2)
*/
static int
#ifdef DEBUG
-list_to_bitstr_buf(Eterm obj, char* buf, int len)
+list_to_bitstr_buf(Eterm obj, char* buf, Uint len)
#else
list_to_bitstr_buf(Eterm obj, char* buf)
#endif
@@ -602,8 +606,8 @@ list_to_bitstr_buf(Eterm obj, char* buf)
return offset;
}
-static Sint
-bitstr_list_len(Eterm obj)
+static int
+bitstr_list_len(Eterm obj, Uint* num_bytes)
{
Eterm* objp;
Uint len = 0;
@@ -611,6 +615,26 @@ bitstr_list_len(Eterm obj)
DECLARE_ESTACK(s);
goto L_again;
+#define SAFE_ADD(Var, Val) \
+ do { \
+ Uint valvar = (Val); \
+ Var += valvar; \
+ if (Var < valvar) { \
+ goto L_overflow_error; \
+ } \
+ } while (0)
+
+#define SAFE_ADD_BITSIZE(Var, Bin) \
+ do { \
+ if (*binary_val(Bin) == HEADER_SUB_BIN) { \
+ Uint valvar = ((ErlSubBin *) binary_val(Bin))->bitsize; \
+ Var += valvar; \
+ if (Var < valvar) { \
+ goto L_overflow_error; \
+ } \
+ } \
+ } while (0)
+
while (!ESTACK_ISEMPTY(s)) {
obj = ESTACK_POP(s);
L_again:
@@ -621,9 +645,12 @@ bitstr_list_len(Eterm obj)
obj = CAR(objp);
if (is_byte(obj)) {
len++;
+ if (len == 0) {
+ goto L_overflow_error;
+ }
} else if (is_binary(obj)) {
- len += binary_size(obj);
- offs += binary_bitsize(obj);
+ SAFE_ADD(len, binary_size(obj));
+ SAFE_ADD_BITSIZE(offs, obj);
} else if (is_list(obj)) {
ESTACK_PUSH(s, CDR(objp));
goto L_iter_list; /* on head */
@@ -635,24 +662,44 @@ bitstr_list_len(Eterm obj)
if (is_list(obj))
goto L_iter_list; /* on tail */
else if (is_binary(obj)) {
- len += binary_size(obj);
- offs += binary_bitsize(obj);
+ SAFE_ADD(len, binary_size(obj));
+ SAFE_ADD_BITSIZE(offs, obj);
} else if (is_not_nil(obj)) {
goto L_type_error;
}
} else if (is_binary(obj)) {
- len += binary_size(obj);
- offs += binary_bitsize(obj);
+ SAFE_ADD(len, binary_size(obj));
+ SAFE_ADD_BITSIZE(offs, obj);
} else if (is_not_nil(obj)) {
goto L_type_error;
}
}
+#undef SAFE_ADD
+#undef SAFE_ADD_BITSIZE
DESTROY_ESTACK(s);
- return (Sint) (len + (offs/8) + ((offs % 8) != 0));
+
+ /*
+ * Make sure that the number of bits in the bitstring will fit
+ * in an Uint to ensure that the binary can be matched using
+ * the binary syntax.
+ */
+ if (len << 3 < len) {
+ goto L_overflow_error;
+ }
+ len += (offs >> 3) + ((offs & 7) != 0);
+ if (len << 3 < len) {
+ goto L_overflow_error;
+ }
+ *num_bytes = len;
+ return ERTS_IOLIST_OK;
L_type_error:
DESTROY_ESTACK(s);
- return (Sint) -1;
+ return ERTS_IOLIST_TYPE;
+
+ L_overflow_error:
+ DESTROY_ESTACK(s);
+ return ERTS_IOLIST_OVERFLOW;
}
diff --git a/erts/emulator/beam/erl_alloc.c b/erts/emulator/beam/erl_alloc.c
index 673eac7fea..cda404af5e 100644
--- a/erts/emulator/beam/erl_alloc.c
+++ b/erts/emulator/beam/erl_alloc.c
@@ -90,6 +90,10 @@ typedef union {
static ErtsAllocatorState_t sl_alloc_state;
static ErtsAllocatorState_t std_alloc_state;
static ErtsAllocatorState_t ll_alloc_state;
+#if HALFWORD_HEAP
+static ErtsAllocatorState_t std_alloc_low_state;
+static ErtsAllocatorState_t ll_alloc_low_state;
+#endif
static ErtsAllocatorState_t temp_alloc_state;
static ErtsAllocatorState_t eheap_alloc_state;
static ErtsAllocatorState_t binary_alloc_state;
@@ -166,6 +170,10 @@ typedef struct {
struct au_init binary_alloc;
struct au_init ets_alloc;
struct au_init driver_alloc;
+#if HALFWORD_HEAP
+ struct au_init std_alloc_low;
+ struct au_init ll_alloc_low;
+#endif
} erts_alc_hndl_args_init_t;
#define ERTS_AU_INIT__ {0, 0, GOODFIT, DEFAULT_ALLCTR_INIT, {1,1,1,1}}
@@ -193,6 +201,10 @@ set_default_sl_alloc_opts(struct au_init *ip)
#endif
ip->init.util.ts = ERTS_ALC_MTA_SHORT_LIVED;
ip->init.util.rsbcst = 80;
+#if HALFWORD_HEAP
+ ip->init.util.low_mem = 1;
+#endif
+
}
static void
@@ -256,6 +268,9 @@ set_default_temp_alloc_opts(struct au_init *ip)
ip->init.util.ts = ERTS_ALC_MTA_TEMPORARY;
ip->init.util.rsbcst = 90;
ip->init.util.rmbcmt = 100;
+#if HALFWORD_HEAP
+ ip->init.util.low_mem = 1;
+#endif
}
static void
@@ -275,6 +290,9 @@ set_default_eheap_alloc_opts(struct au_init *ip)
#endif
ip->init.util.ts = ERTS_ALC_MTA_EHEAP;
ip->init.util.rsbcst = 50;
+#if HALFWORD_HEAP
+ ip->init.util.low_mem = 1;
+#endif
}
static void
@@ -531,6 +549,20 @@ erts_alloc_init(int *argc, char **argv, ErtsAllocInitOpts *eaiop)
erts_allctrs[ERTS_ALC_A_SYSTEM].free = erts_sys_free;
erts_allctrs_info[ERTS_ALC_A_SYSTEM].enabled = 1;
+#if HALFWORD_HEAP
+ /* Init low memory variants by cloning */
+ init.std_alloc_low = init.std_alloc;
+ init.std_alloc_low.init.util.alloc_no = ERTS_ALC_A_STANDARD_LOW;
+ init.std_alloc_low.init.util.low_mem = 1;
+
+ init.ll_alloc_low = init.ll_alloc;
+ init.ll_alloc_low.init.util.alloc_no = ERTS_ALC_A_LONG_LIVED_LOW;
+ init.ll_alloc_low.init.util.low_mem = 1;
+
+ set_au_allocator(ERTS_ALC_A_STANDARD_LOW, &init.std_alloc_low);
+ set_au_allocator(ERTS_ALC_A_LONG_LIVED_LOW, &init.ll_alloc_low);
+#endif /* HALFWORD */
+
set_au_allocator(ERTS_ALC_A_TEMPORARY, &init.temp_alloc);
set_au_allocator(ERTS_ALC_A_SHORT_LIVED, &init.sl_alloc);
set_au_allocator(ERTS_ALC_A_STANDARD, &init.std_alloc);
@@ -576,7 +608,14 @@ erts_alloc_init(int *argc, char **argv, ErtsAllocInitOpts *eaiop)
start_au_allocator(ERTS_ALC_A_LONG_LIVED,
&init.ll_alloc,
&ll_alloc_state);
-
+#if HALFWORD_HEAP
+ start_au_allocator(ERTS_ALC_A_LONG_LIVED_LOW,
+ &init.ll_alloc_low,
+ &ll_alloc_low_state);
+ start_au_allocator(ERTS_ALC_A_STANDARD_LOW,
+ &init.std_alloc_low,
+ &std_alloc_low_state);
+#endif
start_au_allocator(ERTS_ALC_A_EHEAP,
&init.eheap_alloc,
&eheap_alloc_state);
@@ -612,11 +651,9 @@ erts_alloc_init(int *argc, char **argv, ErtsAllocInitOpts *eaiop)
erts_set_fix_size(ERTS_ALC_T_PROC, sizeof(Process));
erts_set_fix_size(ERTS_ALC_T_DB_TABLE, sizeof(DbTable));
erts_set_fix_size(ERTS_ALC_T_ATOM, sizeof(Atom));
- erts_set_fix_size(ERTS_ALC_T_EXPORT, sizeof(Export));
+
erts_set_fix_size(ERTS_ALC_T_MODULE, sizeof(Module));
erts_set_fix_size(ERTS_ALC_T_REG_PROC, sizeof(RegProc));
- erts_set_fix_size(ERTS_ALC_T_MONITOR_SH, ERTS_MONITOR_SH_SIZE*sizeof(Uint));
- erts_set_fix_size(ERTS_ALC_T_NLINK_SH, ERTS_LINK_SH_SIZE*sizeof(Uint));
erts_set_fix_size(ERTS_ALC_T_FUN_ENTRY, sizeof(ErlFunEntry));
#ifdef ERTS_ALC_T_DRV_EV_D_STATE
erts_set_fix_size(ERTS_ALC_T_DRV_EV_D_STATE,
@@ -626,6 +663,11 @@ erts_alloc_init(int *argc, char **argv, ErtsAllocInitOpts *eaiop)
erts_set_fix_size(ERTS_ALC_T_DRV_SEL_D_STATE,
sizeof(ErtsDrvSelectDataState));
#endif
+#if !HALFWORD_HEAP
+ erts_set_fix_size(ERTS_ALC_T_EXPORT, sizeof(Export));
+ erts_set_fix_size(ERTS_ALC_T_MONITOR_SH, ERTS_MONITOR_SH_SIZE*sizeof(Uint));
+ erts_set_fix_size(ERTS_ALC_T_NLINK_SH, ERTS_LINK_SH_SIZE*sizeof(Uint));
+#endif
#endif
#endif
@@ -638,6 +680,15 @@ set_au_allocator(ErtsAlcType_t alctr_n, struct au_init *init)
ErtsAllocatorInfo_t *ai = &erts_allctrs_info[alctr_n];
ErtsAllocatorThrSpec_t *tspec = &erts_allctr_thr_spec[alctr_n];
+#if HALFWORD_HEAP
+ /* If halfword heap, silently ignore any disabling of internal
+ * allocators for low memory
+ */
+ if (init->init.util.low_mem) {
+ init->enable = 1;
+ }
+#endif
+
if (!init->enable) {
af->alloc = erts_sys_alloc;
af->realloc = erts_sys_realloc;
@@ -1348,14 +1399,6 @@ handle_args(int *argc, char **argv, erts_alc_hndl_args_init_t *init)
argv[j++] = argv[i];
}
*argc = j;
-#if HALFWORD_HEAP
- /* If halfword heap, silently ignore any disabling of internal
- allocators */
- for (i = 0; i < aui_sz; ++i)
- aui[i]->enable = 1;
-#endif
-
-
}
static char *type_no_str(ErtsAlcType_t n)
@@ -1528,10 +1571,10 @@ erts_realloc_n_enomem(ErtsAlcType_t n, void *ptr, Uint size)
erts_alc_fatal_error(ERTS_ALC_E_NOMEM, ERTS_ALC_O_REALLOC, n, size);
}
-static ERTS_INLINE Uint
+static ERTS_INLINE UWord
alcu_size(ErtsAlcType_t ai)
{
- Uint res = 0;
+ UWord res = 0;
ASSERT(erts_allctrs_info[ai].enabled);
ASSERT(erts_allctrs_info[ai].alloc_util);
@@ -1563,6 +1606,49 @@ alcu_size(ErtsAlcType_t ai)
return res;
}
+#if HALFWORD_HEAP
+static ERTS_INLINE int
+alcu_is_low(ErtsAlcType_t ai)
+{
+ int is_low = 0;
+ ASSERT(erts_allctrs_info[ai].enabled);
+ ASSERT(erts_allctrs_info[ai].alloc_util);
+
+ if (!erts_allctrs_info[ai].thr_spec) {
+ Allctr_t *allctr = erts_allctrs_info[ai].extra;
+ is_low = allctr->mseg_opt.low_mem;
+ }
+ else {
+ ErtsAllocatorThrSpec_t *tspec = &erts_allctr_thr_spec[ai];
+ int i;
+# ifdef DEBUG
+ int found_one = 0;
+# endif
+
+ ASSERT(tspec->all_thr_safe);
+ ASSERT(tspec->enabled);
+
+ for (i = tspec->size - 1; i >= 0; i--) {
+ Allctr_t *allctr = tspec->allctr[i];
+ if (allctr) {
+# ifdef DEBUG
+ if (!found_one) {
+ is_low = allctr->mseg_opt.low_mem;
+ found_one = 1;
+ }
+ else ASSERT(is_low == allctr->mseg_opt.low_mem);
+# else
+ is_low = allctr->mseg_opt.low_mem;
+ break;
+# endif
+ }
+ }
+ ASSERT(found_one);
+ }
+ return is_low;
+}
+#endif /* HALFWORD */
+
Eterm
erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
{
@@ -1579,22 +1665,28 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
int code;
int ets;
int maximum;
+#if HALFWORD_HEAP
+ int low;
+#endif
} want = {0};
struct {
- Uint total;
- Uint processes;
- Uint processes_used;
- Uint system;
- Uint atom;
- Uint atom_used;
- Uint binary;
- Uint code;
- Uint ets;
- Uint maximum;
+ UWord total;
+ UWord processes;
+ UWord processes_used;
+ UWord system;
+ UWord atom;
+ UWord atom_used;
+ UWord binary;
+ UWord code;
+ UWord ets;
+ UWord maximum;
+#if HALFWORD_HEAP
+ UWord low;
+#endif
} size = {0};
- Eterm atoms[sizeof(size)/sizeof(Uint)];
- Uint *uintps[sizeof(size)/sizeof(Uint)];
- Eterm euints[sizeof(size)/sizeof(Uint)];
+ Eterm atoms[sizeof(size)/sizeof(UWord)];
+ UWord *uintps[sizeof(size)/sizeof(UWord)];
+ Eterm euints[sizeof(size)/sizeof(UWord)];
int want_tot_or_sys;
int length;
Eterm res = THE_NON_VALUE;
@@ -1646,7 +1738,11 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
atoms[length] = am_maximum;
uintps[length++] = &size.maximum;
}
-
+#if HALFWORD_HEAP
+ want.low = 1;
+ atoms[length] = am_low;
+ uintps[length++] = &size.low;
+#endif
}
else {
DeclareTmpHeapNoproc(tmp_heap,2);
@@ -1740,6 +1836,15 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
return am_badarg;
}
break;
+#if HALFWORD_HEAP
+ case am_low:
+ if (!want.low) {
+ want.low = 1;
+ atoms[length] = am_low;
+ uintps[length++] = &size.low;
+ }
+ break;
+#endif
default:
UnUseTmpHeapNoproc(2);
return am_badarg;
@@ -1769,7 +1874,7 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
ASSERT(length <= sizeof(atoms)/sizeof(Eterm));
ASSERT(length <= sizeof(euints)/sizeof(Eterm));
- ASSERT(length <= sizeof(uintps)/sizeof(Uint));
+ ASSERT(length <= sizeof(uintps)/sizeof(UWord));
if (proc) {
@@ -1788,8 +1893,8 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
for (ai = ERTS_ALC_A_MIN; ai <= ERTS_ALC_A_MAX; ai++) {
if (erts_allctrs_info[ai].alloc_util) {
- Uint *save;
- Uint asz;
+ UWord *save;
+ UWord asz;
switch (ai) {
case ERTS_ALC_A_TEMPORARY:
/*
@@ -1814,6 +1919,11 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
if (save)
*save = asz;
size.total += asz;
+#if HALFWORD_HEAP
+ if (alcu_is_low(ai)) {
+ size.low += asz;
+ }
+#endif
}
}
}
@@ -1821,7 +1931,7 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
if (want_tot_or_sys || want.processes || want.processes_used) {
- Uint tmp;
+ UWord tmp;
if (ERTS_MEM_NEED_ALL_ALCU)
tmp = size.processes;
@@ -1836,6 +1946,9 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
size.processes = size.processes_used = tmp;
+#if HALFWORD_HEAP
+ /* BUG: We ignore link and monitor memory */
+#else
erts_fix_info(ERTS_ALC_T_NLINK_SH, &efi);
size.processes += efi.total;
size.processes_used += efi.used;
@@ -1843,6 +1956,7 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
erts_fix_info(ERTS_ALC_T_MONITOR_SH, &efi);
size.processes += efi.total;
size.processes_used += efi.used;
+#endif
erts_fix_info(ERTS_ALC_T_PROC, &efi);
size.processes += efi.total;
@@ -1879,8 +1993,12 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
erts_fix_info(ERTS_ALC_T_MODULE, &efi);
size.code += efi.used;
size.code += export_table_sz();
+#if HALFWORD_HEAP
+ size.code += export_list_size() * sizeof(Export);
+#else
erts_fix_info(ERTS_ALC_T_EXPORT, &efi);
size.code += efi.used;
+#endif
size.code += erts_fun_table_sz();
erts_fix_info(ERTS_ALC_T_FUN_ENTRY, &efi);
size.code += efi.used;
@@ -1913,7 +2031,7 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
/* Print result... */
erts_print(to, arg, "=memory\n");
for (i = 0; i < length; i++)
- erts_print(to, arg, "%T: %beu\n", atoms[i], *uintps[i]);
+ erts_print(to, arg, "%T: %bpu\n", atoms[i], *uintps[i]);
}
if (proc) {
@@ -1926,9 +2044,9 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
if (only_one_value) {
ASSERT(length == 1);
hsz = 0;
- erts_bld_uint(NULL, &hsz, *uintps[0]);
+ erts_bld_uword(NULL, &hsz, *uintps[0]);
hp = hsz ? HAlloc((Process *) proc, hsz) : NULL;
- res = erts_bld_uint(&hp, NULL, *uintps[0]);
+ res = erts_bld_uword(&hp, NULL, *uintps[0]);
}
else {
Uint **hpp = NULL;
@@ -1938,7 +2056,7 @@ erts_memory(int *print_to_p, void *print_to_arg, void *proc, Eterm earg)
while (1) {
int i;
for (i = 0; i < length; i++)
- euints[i] = erts_bld_uint(hpp, hszp, *uintps[i]);
+ euints[i] = erts_bld_uword(hpp, hszp, *uintps[i]);
res = erts_bld_2tup_list(hpp, hszp, length, atoms, euints);
if (hpp)
break;
diff --git a/erts/emulator/beam/erl_alloc.types b/erts/emulator/beam/erl_alloc.types
index ca71798917..c6cc0e1fac 100644
--- a/erts/emulator/beam/erl_alloc.types
+++ b/erts/emulator/beam/erl_alloc.types
@@ -75,6 +75,11 @@ allocator EHEAP true eheap_alloc
allocator ETS true ets_alloc
allocator FIXED_SIZE true fix_alloc
++if halfword
+allocator LONG_LIVED_LOW true ll_alloc_low
+allocator STANDARD_LOW true std_alloc_low
++endif
+
+else # Non smp build
allocator TEMPORARY false temp_alloc
@@ -85,12 +90,18 @@ allocator EHEAP false eheap_alloc
allocator ETS false ets_alloc
allocator FIXED_SIZE false fix_alloc
++if halfword
+allocator LONG_LIVED_LOW false ll_alloc_low
+allocator STANDARD_LOW false std_alloc_low
++endif
+
+endif
allocator BINARY true binary_alloc
allocator DRIVER true driver_alloc
+
# --- Class declarations -----------------------------------------------------
#
# Syntax: class <CLASS> <DESCRIPTION>
@@ -125,14 +136,9 @@ class SYSTEM system_data
type PROC FIXED_SIZE PROCESSES proc
type ATOM FIXED_SIZE ATOM atom_entry
-type EXPORT FIXED_SIZE CODE export_entry
type MODULE FIXED_SIZE CODE module_entry
type REG_PROC FIXED_SIZE PROCESSES reg_proc
type LINK_LH STANDARD PROCESSES link_lh
-type MONITOR_SH FIXED_SIZE PROCESSES monitor_sh
-type MONITOR_LH STANDARD PROCESSES monitor_lh
-type NLINK_SH FIXED_SIZE PROCESSES nlink_sh
-type NLINK_LH STANDARD PROCESSES nlink_lh
type SUSPEND_MON STANDARD PROCESSES suspend_monitor
type PEND_SUSPEND SHORT_LIVED PROCESSES pending_suspend
type PROC_LIST SHORT_LIVED PROCESSES proc_list
@@ -175,7 +181,6 @@ type DRIVER STANDARD SYSTEM driver
type NIF DRIVER SYSTEM nif_internal
type BINARY BINARY BINARIES binary
type NBIF_TABLE SYSTEM SYSTEM nbif_tab
-type CODE LONG_LIVED CODE code
type ARG_REG STANDARD PROCESSES arg_reg
type PROC_DICT STANDARD PROCESSES proc_dict
type CALLS_BUF STANDARD PROCESSES calls_buf
@@ -193,10 +198,8 @@ type DB_FIXATION SHORT_LIVED ETS db_fixation
type DB_FIX_DEL SHORT_LIVED ETS fixed_del
type DB_TABLES LONG_LIVED ETS db_tabs
type DB_NTAB_ENT STANDARD ETS db_named_table_entry
-type DB_HEIR_DATA STANDARD ETS db_heir_data
type DB_TMP TEMPORARY ETS db_tmp
type DB_MC_STK TEMPORARY ETS db_mc_stack
-type DB_MS_PSDO_PROC LONG_LIVED ETS db_match_pseudo_proc
type DB_MS_RUN_HEAP SHORT_LIVED ETS db_match_spec_run_heap
type DB_MS_CMPL_HEAP TEMPORARY ETS db_match_spec_cmpl_heap
type DB_SEG ETS ETS db_segment
@@ -213,10 +216,8 @@ type LOGGER_DSBUF TEMPORARY SYSTEM logger_dsbuf
type TMP_DSBUF TEMPORARY SYSTEM tmp_dsbuf
type INFO_DSBUF SYSTEM SYSTEM info_dsbuf
# INFO_DSBUF have to use the SYSTEM allocator; otherwise, a deadlock might occur
-type SCHDLR_DATA LONG_LIVED SYSTEM scheduler_data
type SCHDLR_SLP_INFO LONG_LIVED SYSTEM scheduler_sleep_info
type RUNQS LONG_LIVED SYSTEM run_queues
-type DDLL_PROCESS STANDARD SYSTEM ddll_processes
type DDLL_HANDLE STANDARD SYSTEM ddll_handle
type DDLL_ERRCODES LONG_LIVED SYSTEM ddll_errcodes
type DDLL_TMP_BUF TEMPORARY SYSTEM ddll_tmp_buf
@@ -327,13 +328,45 @@ type SSB SHORT_LIVED PROCESSES ssb
+endif
++if halfword
+
+type DDLL_PROCESS STANDARD_LOW SYSTEM ddll_processes
+type MONITOR_LH STANDARD_LOW PROCESSES monitor_lh
+type NLINK_LH STANDARD_LOW PROCESSES nlink_lh
+type CODE LONG_LIVED_LOW CODE code
+type DB_HEIR_DATA STANDARD_LOW ETS db_heir_data
+type DB_MS_PSDO_PROC LONG_LIVED_LOW ETS db_match_pseudo_proc
+type SCHDLR_DATA LONG_LIVED_LOW SYSTEM scheduler_data
+type LL_TEMP_TERM LONG_LIVED_LOW SYSTEM ll_temp_term
+
+# no FIXED_SIZE for low memory
+type EXPORT STANDARD_LOW CODE export_entry
+type MONITOR_SH STANDARD_LOW PROCESSES monitor_sh
+type NLINK_SH STANDARD_LOW PROCESSES nlink_sh
+
++else # "fullword"
+
+type DDLL_PROCESS STANDARD SYSTEM ddll_processes
+type MONITOR_LH STANDARD PROCESSES monitor_lh
+type NLINK_LH STANDARD PROCESSES nlink_lh
+type CODE LONG_LIVED CODE code
+type DB_HEIR_DATA STANDARD ETS db_heir_data
+type DB_MS_PSDO_PROC LONG_LIVED ETS db_match_pseudo_proc
+type SCHDLR_DATA LONG_LIVED SYSTEM scheduler_data
+type LL_TEMP_TERM LONG_LIVED SYSTEM ll_temp_term
+
+type EXPORT FIXED_SIZE CODE export_entry
+type MONITOR_SH FIXED_SIZE PROCESSES monitor_sh
+type NLINK_SH FIXED_SIZE PROCESSES nlink_sh
+
++endif
+
+
#
# Types used by system specific code
#
type TEMP_TERM TEMPORARY SYSTEM temp_term
-type LL_TEMP_TERM LONG_LIVED SYSTEM ll_temp_term
-
type DRV_TAB LONG_LIVED SYSTEM drv_tab
type DRV_EV_STATE LONG_LIVED SYSTEM driver_event_state
type DRV_EV_D_STATE FIXED_SIZE SYSTEM driver_event_data_state
diff --git a/erts/emulator/beam/erl_alloc_util.c b/erts/emulator/beam/erl_alloc_util.c
index 84c72439a3..cc04ef65bf 100644
--- a/erts/emulator/beam/erl_alloc_util.c
+++ b/erts/emulator/beam/erl_alloc_util.c
@@ -1639,6 +1639,9 @@ static struct {
Eterm e;
Eterm t;
Eterm ramv;
+#if HALFWORD_HEAP
+ Eterm low;
+#endif
Eterm sbct;
#if HAVE_ERTS_MSEG
Eterm asbcst;
@@ -1724,6 +1727,9 @@ init_atoms(Allctr_t *allctr)
AM_INIT(e);
AM_INIT(t);
AM_INIT(ramv);
+#if HALFWORD_HEAP
+ AM_INIT(low);
+#endif
AM_INIT(sbct);
#if HAVE_ERTS_MSEG
AM_INIT(asbcst);
@@ -2168,6 +2174,9 @@ info_options(Allctr_t *allctr,
"option e: true\n"
"option t: %s\n"
"option ramv: %s\n"
+#if HALFWORD_HEAP
+ "option low: %s\n"
+#endif
"option sbct: %beu\n"
#if HAVE_ERTS_MSEG
"option asbcst: %bpu\n"
@@ -2185,6 +2194,9 @@ info_options(Allctr_t *allctr,
"option mbcgs: %beu\n",
topt,
allctr->ramv ? "true" : "false",
+#if HALFWORD_HEAP
+ allctr->mseg_opt.low_mem ? "true" : "false",
+#endif
allctr->sbc_threshold,
#if HAVE_ERTS_MSEG
allctr->mseg_opt.abs_shrink_th,
@@ -2243,6 +2255,9 @@ info_options(Allctr_t *allctr,
add_2tup(hpp, szp, &res,
am.sbct,
bld_uint(hpp, szp, allctr->sbc_threshold));
+#if HALFWORD_HEAP
+ add_2tup(hpp, szp, &res, am.low, allctr->mseg_opt.low_mem ? am_true : am_false);
+#endif
add_2tup(hpp, szp, &res, am.ramv, allctr->ramv ? am_true : am_false);
add_2tup(hpp, szp, &res, am.t, (allctr->t
? bld_uint(hpp, szp, (Uint) allctr->t)
@@ -3105,13 +3120,12 @@ erts_alcu_start(Allctr_t *allctr, AllctrInit_t *init)
goto error;
#if HAVE_ERTS_MSEG
- {
- ErtsMsegOpt_t mseg_opt = ERTS_MSEG_DEFAULT_OPT_INITIALIZER;
-
- sys_memcpy((void *) &allctr->mseg_opt,
- (void *) &mseg_opt,
- sizeof(ErtsMsegOpt_t));
- }
+ sys_memcpy((void *) &allctr->mseg_opt,
+ (void *) &erts_mseg_default_opt,
+ sizeof(ErtsMsegOpt_t));
+# if HALFWORD_HEAP
+ allctr->mseg_opt.low_mem = init->low_mem;
+# endif
#endif
allctr->name_prefix = init->name_prefix;
diff --git a/erts/emulator/beam/erl_alloc_util.h b/erts/emulator/beam/erl_alloc_util.h
index d296081714..ddf84c086c 100644
--- a/erts/emulator/beam/erl_alloc_util.h
+++ b/erts/emulator/beam/erl_alloc_util.h
@@ -38,6 +38,7 @@ typedef struct {
int tspec;
int tpref;
int ramv;
+ int low_mem; /* HALFWORD only */
UWord sbct;
UWord asbcst;
UWord rsbcst;
@@ -70,6 +71,7 @@ typedef struct {
0, /* (bool) tspec: thread specific */\
0, /* (bool) tpref: thread preferred */\
0, /* (bool) ramv: realloc always moves */\
+ 0, /* (bool) low_mem: HALFWORD only */\
512*1024, /* (bytes) sbct: sbc threshold */\
2*1024*2024, /* (amount) asbcst: abs sbc shrink threshold */\
20, /* (%) rsbcst: rel sbc shrink threshold */\
@@ -97,6 +99,7 @@ typedef struct {
0, /* (bool) tspec: thread specific */\
0, /* (bool) tpref: thread preferred */\
0, /* (bool) ramv: realloc always moves */\
+ 0, /* (bool) low_mem: HALFWORD only */\
64*1024, /* (bytes) sbct: sbc threshold */\
2*1024*2024, /* (amount) asbcst: abs sbc shrink threshold */\
20, /* (%) rsbcst: rel sbc shrink threshold */\
diff --git a/erts/emulator/beam/erl_async.c b/erts/emulator/beam/erl_async.c
index 12c7631448..a920bd2c8c 100644
--- a/erts/emulator/beam/erl_async.c
+++ b/erts/emulator/beam/erl_async.c
@@ -251,6 +251,7 @@ static int async_del(long id)
erts_free(ERTS_ALC_T_ASYNC, a);
return 1;
}
+ a = a->next;
}
erts_mtx_unlock(&async_q[i].mtx);
}
diff --git a/erts/emulator/beam/erl_bif_ddll.c b/erts/emulator/beam/erl_bif_ddll.c
index c9cdcb87a6..9631fb50db 100644
--- a/erts/emulator/beam/erl_bif_ddll.c
+++ b/erts/emulator/beam/erl_bif_ddll.c
@@ -1,7 +1,7 @@
/*
* %CopyrightBegin%
*
- * Copyright Ericsson AB 2006-2010. All Rights Reserved.
+ * 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
@@ -146,7 +146,7 @@ BIF_RETTYPE erl_ddll_try_load_3(Process *p, Eterm path_term,
Eterm name_term, Eterm options)
{
char *path = NULL;
- int path_len;
+ Uint path_len;
char *name = NULL;
DE_Handle *dh;
erts_driver_t *drv;
@@ -221,9 +221,7 @@ BIF_RETTYPE erl_ddll_try_load_3(Process *p, Eterm path_term,
goto error;
}
- path_len = io_list_len(path_term);
-
- if (path_len <= 0) {
+ if (erts_iolist_size(path_term, &path_len)) {
goto error;
}
path = erts_alloc(ERTS_ALC_T_DDLL_TMP_BUF, path_len + 1 /* might need path separator */ + sys_strlen(name) + 1);
@@ -1878,7 +1876,7 @@ static Eterm mkatom(char *str)
static char *pick_list_or_atom(Eterm name_term)
{
char *name = NULL;
- int name_len;
+ Uint name_len;
if (is_atom(name_term)) {
Atom *ap = atom_tab(atom_val(name_term));
if (ap->len == 0) {
@@ -1890,8 +1888,7 @@ static char *pick_list_or_atom(Eterm name_term)
memcpy(name,ap->name,ap->len);
name[ap->len] = '\0';
} else {
- name_len = io_list_len(name_term);
- if (name_len <= 0) {
+ if (erts_iolist_size(name_term, &name_len)) {
goto error;
}
name = erts_alloc(ERTS_ALC_T_DDLL_TMP_BUF, name_len + 1);
diff --git a/erts/emulator/beam/erl_bif_info.c b/erts/emulator/beam/erl_bif_info.c
index e50fc18e64..f264bf44df 100644
--- a/erts/emulator/beam/erl_bif_info.c
+++ b/erts/emulator/beam/erl_bif_info.c
@@ -1732,14 +1732,14 @@ info_1_tuple(Process* BIF_P, /* Pointer to current process. */
# define ERTS_ERROR_CHECKER_PRINTF_XML VALGRIND_PRINTF_XML
# endif
#endif
- int buf_size = 8*1024; /* Try with 8KB first */
+ Uint buf_size = 8*1024; /* Try with 8KB first */
char *buf = erts_alloc(ERTS_ALC_T_TMP, buf_size);
int r = io_list_to_buf(*tp, (char*) buf, buf_size - 1);
if (r < 0) {
erts_free(ERTS_ALC_T_TMP, (void *) buf);
- buf_size = io_list_len(*tp);
- if (buf_size < 0)
+ if (erts_iolist_size(*tp, &buf_size)) {
goto badarg;
+ }
buf_size++;
buf = erts_alloc(ERTS_ALC_T_TMP, buf_size);
r = io_list_to_buf(*tp, (char*) buf, buf_size - 1);
diff --git a/erts/emulator/beam/erl_bif_port.c b/erts/emulator/beam/erl_bif_port.c
index fbc92b9730..3fd35dd963 100644
--- a/erts/emulator/beam/erl_bif_port.c
+++ b/erts/emulator/beam/erl_bif_port.c
@@ -1,7 +1,7 @@
/*
* %CopyrightBegin%
*
- * Copyright Ericsson AB 2001-2010. All Rights Reserved.
+ * Copyright Ericsson AB 2001-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
@@ -996,6 +996,7 @@ static byte* convert_environment(Process* p, Eterm env)
Eterm* hp;
Uint heap_size;
int n;
+ Uint size;
byte* bytes;
if ((n = list_length(env)) < 0) {
@@ -1039,15 +1040,15 @@ static byte* convert_environment(Process* p, Eterm env)
if (is_not_nil(env)) {
goto done;
}
- if ((n = io_list_len(all)) < 0) {
+ if (erts_iolist_size(all, &size)) {
goto done;
}
/*
* Put the result in a binary (no risk for a memory leak that way).
*/
- (void) erts_new_heap_binary(p, NULL, n, &bytes);
- io_list_to_buf(all, (char*)bytes, n);
+ (void) erts_new_heap_binary(p, NULL, size, &bytes);
+ io_list_to_buf(all, (char*)bytes, size);
done:
erts_free(ERTS_ALC_T_TMP, temp_heap);
diff --git a/erts/emulator/beam/erl_bif_re.c b/erts/emulator/beam/erl_bif_re.c
index d4a8a3aaa7..26891c4348 100644
--- a/erts/emulator/beam/erl_bif_re.c
+++ b/erts/emulator/beam/erl_bif_re.c
@@ -1,7 +1,7 @@
/*
* %CopyrightBegin%
*
- * Copyright Ericsson AB 2008-2010. All Rights Reserved.
+ * 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
@@ -417,7 +417,7 @@ build_compile_result(Process *p, Eterm error_tag, pcre *result, int errcode, con
BIF_RETTYPE
re_compile_2(BIF_ALIST_2)
{
- int slen;
+ Uint slen;
char *expr;
pcre *result;
int errcode = 0;
@@ -444,7 +444,7 @@ re_compile_2(BIF_ALIST_2)
BIF_TRAP2(ucompile_trap_exportp, BIF_P, BIF_ARG_1, BIF_ARG_2);
}
- if ((slen = io_list_len(BIF_ARG_1)) < 0) {
+ if (erts_iolist_size(BIF_ARG_1, &slen)) {
BIF_ERROR(BIF_P,BADARG);
}
expr = erts_alloc(ERTS_ALC_T_RE_TMP_BUF, slen + 1);
@@ -795,8 +795,8 @@ build_capture(Eterm capture_spec[CAPSPEC_SIZE], const pcre *code)
memcpy(tmpb,ap->name,ap->len);
tmpb[ap->len] = '\0';
} else {
- int slen = io_list_len(val);
- if (slen < 0) {
+ Uint slen;
+ if (erts_iolist_size(val, &slen)) {
goto error;
}
if ((slen + 1) > tmpbsiz) {
@@ -851,7 +851,7 @@ re_run_3(BIF_ALIST_3)
const pcre *code_tmp;
RestartContext restart;
byte *temp_alloc = NULL;
- int slength;
+ Uint slength;
int startoffset = 0;
int options = 0, comp_options = 0;
int ovsize;
@@ -875,7 +875,7 @@ re_run_3(BIF_ALIST_3)
if (is_not_tuple(BIF_ARG_2) || (arityval(*tuple_val(BIF_ARG_2)) != 4)) {
if (is_binary(BIF_ARG_2) || is_list(BIF_ARG_2) || is_nil(BIF_ARG_2)) {
/* Compile from textual RE */
- int slen;
+ Uint slen;
char *expr;
pcre *result;
int errcode = 0;
@@ -889,7 +889,7 @@ re_run_3(BIF_ALIST_3)
BIF_TRAP3(urun_trap_exportp, BIF_P, BIF_ARG_1, BIF_ARG_2, BIF_ARG_3);
}
- if ((slen = io_list_len(BIF_ARG_2)) < 0) {
+ if (erts_iolist_size(BIF_ARG_2, &slen)) {
BIF_ERROR(BIF_P,BADARG);
}
@@ -1027,7 +1027,7 @@ re_run_3(BIF_ALIST_3)
restart.flags |= RESTART_FLAG_SUBJECT_IN_BINARY;
} else {
handle_iolist:
- if ((slength = io_list_len(BIF_ARG_1)) < 0) {
+ if (erts_iolist_size(BIF_ARG_1, &slength)) {
erts_free(ERTS_ALC_T_RE_SUBJECT, restart.ovector);
erts_free(ERTS_ALC_T_RE_SUBJECT, restart.code);
if (restart.ret_info != NULL) {
diff --git a/erts/emulator/beam/erl_db_hash.c b/erts/emulator/beam/erl_db_hash.c
index 9ef990cc4f..fdc82c8b88 100644
--- a/erts/emulator/beam/erl_db_hash.c
+++ b/erts/emulator/beam/erl_db_hash.c
@@ -105,7 +105,7 @@
#define NSEG_2 256 /* Size of second segment table */
#define NSEG_INC 128 /* Number of segments to grow after that */
-#define SEGTAB(tb) ((struct segment**)erts_smp_atomic_read(&(tb)->segtab))
+#define SEGTAB(tb) ((struct segment**)erts_smp_atomic_read_acqb(&(tb)->segtab))
#define NACTIVE(tb) ((int)erts_smp_atomic_read(&(tb)->nactive))
#define NITEMS(tb) ((int)erts_smp_atomic_read(&(tb)->common.nitems))
@@ -122,8 +122,8 @@
*/
static ERTS_INLINE Uint hash_to_ix(DbTableHash* tb, HashValue hval)
{
- Uint mask = erts_smp_atomic_read(&tb->szm);
- Uint ix = hval & mask;
+ Uint mask = erts_smp_atomic_read_acqb(&tb->szm);
+ Uint ix = hval & mask;
if (ix >= erts_smp_atomic_read(&tb->nactive)) {
ix &= mask>>1;
ASSERT(ix < erts_smp_atomic_read(&tb->nactive));
@@ -668,6 +668,7 @@ int db_create_hash(Process *p, DbTable *tbl)
else { /* coarse locking */
tb->locks = NULL;
}
+ ERTS_THR_MEMORY_BARRIER;
#endif /* ERST_SMP */
return DB_ERROR_NONE;
}
@@ -2085,7 +2086,14 @@ static void db_print_hash(int to, void *to_arg, int show, DbTable *tbl)
while(list != 0) {
if (list->hvalue == INVALID_HASH)
erts_print(to, to_arg, "*");
- erts_print(to, to_arg, "%T", make_tuple(list->dbterm.tpl));
+ if (tb->common.compress) {
+ Eterm key = GETKEY(tb, list->dbterm.tpl);
+ erts_print(to, to_arg, "key=%R", key, list->dbterm.tpl);
+ }
+ else {
+ Eterm obj = make_tuple_rel(list->dbterm.tpl,list->dbterm.tpl);
+ erts_print(to, to_arg, "%R", obj, list->dbterm.tpl);
+ }
if (list->next != 0)
erts_print(to, to_arg, ",");
list = list->next;
@@ -2342,7 +2350,7 @@ static int alloc_seg(DbTableHash *tb)
struct ext_segment* eseg;
eseg = (struct ext_segment*) SEGTAB(tb)[seg_ix-1];
MY_ASSERT(eseg!=NULL && eseg->s.is_ext_segment);
- erts_smp_atomic_set(&tb->segtab, (erts_aint_t) eseg->segtab);
+ erts_smp_atomic_set_relb(&tb->segtab, (erts_aint_t) eseg->segtab);
tb->nsegs = eseg->nsegs;
}
ASSERT(seg_ix < tb->nsegs);
@@ -2414,7 +2422,7 @@ static int free_seg(DbTableHash *tb, int free_records)
MY_ASSERT(newtop->s.is_ext_segment);
if (newtop->prev_segtab != NULL) {
/* Time to use a smaller segtab */
- erts_smp_atomic_set(&tb->segtab, (erts_aint_t)newtop->prev_segtab);
+ erts_smp_atomic_set_relb(&tb->segtab, (erts_aint_t)newtop->prev_segtab);
tb->nsegs = seg_ix;
ASSERT(tb->nsegs == EXTSEG(SEGTAB(tb))->nsegs);
}
@@ -2431,7 +2439,7 @@ static int free_seg(DbTableHash *tb, int free_records)
if (seg_ix > 0) {
if (seg_ix < tb->nsegs) SEGTAB(tb)[seg_ix] = NULL;
} else {
- erts_smp_atomic_set(&tb->segtab, (erts_aint_t)NULL);
+ erts_smp_atomic_set_relb(&tb->segtab, (erts_aint_t)NULL);
}
#endif
tb->nslots -= SEGSZ;
@@ -2526,9 +2534,9 @@ static void grow(DbTableHash* tb, int nactive)
}
erts_smp_atomic_inc(&tb->nactive);
if (from_ix == 0) {
- erts_smp_atomic_set(&tb->szm, szm);
+ erts_smp_atomic_set_relb(&tb->szm, szm);
}
- erts_smp_atomic_set(&tb->is_resizing, 0);
+ erts_smp_atomic_set_relb(&tb->is_resizing, 0);
/* Finally, let's split the bucket. We try to do it in a smart way
to keep link order and avoid unnecessary updates of next-pointers */
@@ -2560,7 +2568,7 @@ static void grow(DbTableHash* tb, int nactive)
return;
abort:
- erts_smp_atomic_set(&tb->is_resizing, 0);
+ erts_smp_atomic_set_relb(&tb->is_resizing, 0);
}
@@ -2604,7 +2612,7 @@ static void shrink(DbTableHash* tb, int nactive)
erts_smp_atomic_set(&tb->nactive, src_ix);
if (dst_ix == 0) {
- erts_smp_atomic_set(&tb->szm, low_szm);
+ erts_smp_atomic_set_relb(&tb->szm, low_szm);
}
WUNLOCK_HASH(lck);
@@ -2618,7 +2626,7 @@ static void shrink(DbTableHash* tb, int nactive)
}
/*else already done */
- erts_smp_atomic_set(&tb->is_resizing, 0);
+ erts_smp_atomic_set_relb(&tb->is_resizing, 0);
}
diff --git a/erts/emulator/beam/erl_db_tree.c b/erts/emulator/beam/erl_db_tree.c
index a59c0c258d..9a0ba3a418 100644
--- a/erts/emulator/beam/erl_db_tree.c
+++ b/erts/emulator/beam/erl_db_tree.c
@@ -111,7 +111,7 @@ static void release_stack(DbTableTree* tb, DbTreeStack* stack)
{
if (stack == &tb->static_stack) {
ASSERT(erts_smp_atomic_read(&tb->is_stack_busy) == 1);
- erts_smp_atomic_set(&tb->is_stack_busy, 0);
+ erts_smp_atomic_set_relb(&tb->is_stack_busy, 0);
}
else {
erts_db_free(ERTS_ALC_T_DB_STK, (DbTable *) tb,
@@ -179,7 +179,7 @@ static ERTS_INLINE TreeDbTerm* replace_dbterm(DbTableTree *tb, TreeDbTerm* old,
static TreeDbTerm *traverse_until(TreeDbTerm *t, int *current, int to);
static void check_slot_pos(DbTableTree *tb);
static void check_saved_stack(DbTableTree *tb);
-static int check_table_tree(TreeDbTerm *t);
+static int check_table_tree(DbTableTree* tb, TreeDbTerm *t);
#define TREE_DEBUG
#endif
@@ -194,8 +194,8 @@ static int check_table_tree(TreeDbTerm *t);
** Debugging dump
*/
-static void do_dump_tree2(int to, void *to_arg, int show, TreeDbTerm *t,
- int offset);
+static void do_dump_tree2(DbTableTree*, int to, void *to_arg, int show,
+ TreeDbTerm *t, int offset);
#else
@@ -1730,6 +1730,7 @@ static int db_select_delete_tree(Process *p, DbTable *tbl,
** Other interface routines (not directly coupled to one bif)
*/
+
/* Display tree contents (for dump) */
static void db_print_tree(int to, void *to_arg,
int show,
@@ -1740,7 +1741,7 @@ static void db_print_tree(int to, void *to_arg,
if (show)
erts_print(to, to_arg, "\nTree data dump:\n"
"------------------------------------------------\n");
- do_dump_tree2(to, to_arg, show, tb->root, 0);
+ do_dump_tree2(&tbl->tree, to, to_arg, show, tb->root, 0);
if (show)
erts_print(to, to_arg, "\n"
"------------------------------------------------\n");
@@ -2694,7 +2695,7 @@ static Sint do_cmp_partly_bound(Eterm a, Eterm b, Eterm* b_base, int *done)
while (1) {
if ((j = do_cmp_partly_bound(*aa++, *bb++, b_base, done)) != 0 || *done)
return j;
- if (*aa==*bb)
+ if (is_same(*aa, NULL, *bb, b_base))
return 0;
if (is_not_list(*aa) || is_not_list(*bb))
return do_cmp_partly_bound(*aa, *bb, b_base, done);
@@ -2742,7 +2743,7 @@ static Sint cmp_partly_bound(Eterm partly_bound_key, Eterm bound_key, Eterm* bk_
erts_fprintf(stderr," > ");
else
erts_fprintf(stderr," == ");
- erts_fprintf(stderr,"%T\n",bound_key); // HALFWORD BUG: printing rterm
+ erts_fprintf(stderr,"%R\n", bound_key, bk_base);
#endif
return ret;
}
@@ -3084,19 +3085,28 @@ static int doit_select_delete(DbTableTree *tb, TreeDbTerm *this, void *ptr,
}
#ifdef TREE_DEBUG
-static void do_dump_tree2(int to, void *to_arg, int show, TreeDbTerm *t,
- int offset)
+static void do_dump_tree2(DbTableTree* tb, int to, void *to_arg, int show,
+ TreeDbTerm *t, int offset)
{
if (t == NULL)
- return 0;
- do_dump_tree2(to, to_arg, show, t->right, offset + 4);
+ return;
+ do_dump_tree2(tb, to, to_arg, show, t->right, offset + 4);
if (show) {
- erts_print(to, to_arg, "%*s%T (addr = %p, bal = %d)\n"
- offset, "", make_tuple(t->dbterm.tpl),
+ const char* prefix;
+ Eterm term;
+ if (tb->common.compress) {
+ prefix = "key=";
+ term = GETKEY(tb, t->dbterm.tpl);
+ }
+ else {
+ prefix = "";
+ term = make_tuple_rel(t->dbterm.tpl,t->dbterm.tpl);
+ }
+ erts_print(to, to_arg, "%*s%s%R (addr = %p, bal = %d)\n",
+ offset, "", prefix, term, t->dbterm.tpl,
t, t->balance);
}
- do_dump_tree2(to, to_arg, show, t->left, offset + 4);
- return sum;
+ do_dump_tree2(tb, to, to_arg, show, t->left, offset + 4);
}
#endif
@@ -3106,7 +3116,7 @@ static void do_dump_tree2(int to, void *to_arg, int show, TreeDbTerm *t,
void db_check_table_tree(DbTable *tbl)
{
DbTableTree *tb = &tbl->tree;
- check_table_tree(tb->root);
+ check_table_tree(tb, tb->root);
check_saved_stack(tb);
check_slot_pos(tb);
}
@@ -3137,7 +3147,7 @@ static void check_slot_pos(DbTableTree *tb)
"element position %d is really 0x%08X, when stack says "
"it's 0x%08X\n", tb->stack.slot, t,
tb->stack.array[tb->stack.pos - 1]);
- do_dump_tree2(ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
+ do_dump_tree2(tb, ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
}
}
@@ -3152,14 +3162,14 @@ static void check_saved_stack(DbTableTree *tb)
if (t != stack->array[0]) {
erts_fprintf(stderr,"tb->stack[0] is 0x%08X, should be 0x%08X\n",
stack->array[0], t);
- do_dump_tree2(ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
+ do_dump_tree2(tb, ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
return;
}
while (n < stack->pos) {
if (t == NULL) {
erts_fprintf(stderr, "NULL pointer in tree when stack not empty,"
" stack depth is %d\n", n);
- do_dump_tree2(ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
+ do_dump_tree2(tb, ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
return;
}
n++;
@@ -3173,28 +3183,26 @@ static void check_saved_stack(DbTableTree *tb)
"represent child pointer in tree!"
"(left == 0x%08X, right == 0x%08X\n",
n, tb->stack[n], t->left, t->right);
- do_dump_tree2(ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
+ do_dump_tree2(tb, ERTS_PRINT_STDERR, NULL, 1, tb->root, 0);
return;
}
}
}
}
-static int check_table_tree(TreeDbTerm *t)
+static int check_table_tree(DbTableTree* tb, TreeDbTerm *t)
{
int lh, rh;
if (t == NULL)
return 0;
- lh = check_table_tree(t->left);
- rh = check_table_tree(t->right);
+ lh = check_table_tree(tb, t->left);
+ rh = check_table_tree(tb, t->right);
if ((rh - lh) != t->balance) {
erts_fprintf(stderr, "Invalid tree balance for this node:\n");
- erts_fprintf(stderr,"balance = %d, left = 0x%08X, right = 0x%08X\n"
- "data = %T",
- t->balance, t->left, t->right,
- make_tuple(t->dbterm.tpl));
+ erts_fprintf(stderr,"balance = %d, left = 0x%08X, right = 0x%08X\n",
+ t->balance, t->left, t->right);
erts_fprintf(stderr,"\nDump:\n---------------------------------\n");
- do_dump_tree2(ERTS_PRINT_STDERR, NULL, 1, t, 0);
+ do_dump_tree2(tb, ERTS_PRINT_STDERR, NULL, 1, t, 0);
erts_fprintf(stderr,"\n---------------------------------\n");
}
return ((rh > lh) ? rh : lh) + 1;
diff --git a/erts/emulator/beam/erl_drv_thread.c b/erts/emulator/beam/erl_drv_thread.c
index 39bbe9633b..dc578f6d2a 100644
--- a/erts/emulator/beam/erl_drv_thread.c
+++ b/erts/emulator/beam/erl_drv_thread.c
@@ -700,6 +700,13 @@ erl_drv_thread_join(ErlDrvTid tid, void **respp)
extern int erts_darwin_main_thread_pipe[2];
extern int erts_darwin_main_thread_result_pipe[2];
+int erl_drv_stolen_main_thread_join(ErlDrvTid tid, void **respp);
+int erl_drv_steal_main_thread(char *name,
+ ErlDrvTid *dtid,
+ void* (*func)(void*),
+ void* arg,
+ ErlDrvThreadOpts *opts);
+
int
erl_drv_stolen_main_thread_join(ErlDrvTid tid, void **respp)
diff --git a/erts/emulator/beam/erl_lock_check.c b/erts/emulator/beam/erl_lock_check.c
index 9e18997890..9180508a49 100644
--- a/erts/emulator/beam/erl_lock_check.c
+++ b/erts/emulator/beam/erl_lock_check.c
@@ -240,7 +240,7 @@ typedef struct erts_lc_locked_lock_t_ erts_lc_locked_lock_t;
struct erts_lc_locked_lock_t_ {
erts_lc_locked_lock_t *next;
erts_lc_locked_lock_t *prev;
- Eterm extra;
+ UWord extra;
Sint16 id;
Uint16 flags;
};
@@ -441,12 +441,12 @@ new_locked_lock(erts_lc_lock_t *lck, Uint16 op_flags)
}
static void
-print_lock2(char *prefix, Sint16 id, Eterm extra, Uint16 flags, char *suffix)
+print_lock2(char *prefix, Sint16 id, Wterm extra, Uint16 flags, char *suffix)
{
char *lname = (0 <= id && id < ERTS_LOCK_ORDER_SIZE
? erts_lock_order[id].name
: "unknown");
- if (is_boxed(extra))
+ if (is_not_immed(extra))
erts_fprintf(stderr,
"%s'%s:%p%s'%s%s",
prefix,
@@ -1260,7 +1260,8 @@ erts_lc_init_lock(erts_lc_lock_t *lck, char *name, Uint16 flags)
{
lck->id = erts_lc_get_lock_order_id(name);
- lck->extra = make_boxed(&lck->extra);
+ lck->extra = &lck->extra;
+ ASSERT(is_not_immed(lck->extra));
lck->flags = flags;
lck->inited = ERTS_LC_INITITALIZED;
}
@@ -1270,6 +1271,7 @@ erts_lc_init_lock_x(erts_lc_lock_t *lck, char *name, Uint16 flags, Eterm extra)
{
lck->id = erts_lc_get_lock_order_id(name);
lck->extra = extra;
+ ASSERT(is_immed(lck->extra));
lck->flags = flags;
lck->inited = ERTS_LC_INITITALIZED;
}
diff --git a/erts/emulator/beam/erl_lock_check.h b/erts/emulator/beam/erl_lock_check.h
index cdb06d4458..b67f36fa06 100644
--- a/erts/emulator/beam/erl_lock_check.h
+++ b/erts/emulator/beam/erl_lock_check.h
@@ -39,7 +39,7 @@ typedef struct {
int inited;
Sint16 id;
Uint16 flags;
- Eterm extra;
+ UWord extra;
} erts_lc_lock_t;
#define ERTS_LC_INITITALIZED 0x7f7f7f7f
diff --git a/erts/emulator/beam/erl_nif.c b/erts/emulator/beam/erl_nif.c
index 8b48444904..68421b4387 100644
--- a/erts/emulator/beam/erl_nif.c
+++ b/erts/emulator/beam/erl_nif.c
@@ -472,7 +472,7 @@ static void tmp_alloc_dtor(struct enif_tmp_obj_t* obj)
int enif_inspect_iolist_as_binary(ErlNifEnv* env, Eterm term, ErlNifBinary* bin)
{
struct enif_tmp_obj_t* tobj;
- int sz;
+ Uint sz;
if (is_binary(term)) {
return enif_inspect_binary(env,term,bin);
}
@@ -483,7 +483,7 @@ int enif_inspect_iolist_as_binary(ErlNifEnv* env, Eterm term, ErlNifBinary* bin)
bin->ref_bin = NULL;
return 1;
}
- if ((sz = io_list_len(term)) < 0) {
+ if (erts_iolist_size(term, &sz)) {
return 0;
}
diff --git a/erts/emulator/beam/erl_port_task.c b/erts/emulator/beam/erl_port_task.c
index 1b07024ca1..326021643f 100644
--- a/erts/emulator/beam/erl_port_task.c
+++ b/erts/emulator/beam/erl_port_task.c
@@ -658,8 +658,6 @@ erts_port_task_free_port(Port *pp)
when scheduled out... */
ErtsPortTask *ptp = port_task_alloc();
erts_smp_port_state_lock(pp);
- ASSERT(erts_smp_atomic_read(&erts_ports_alive) > 0);
- erts_smp_atomic_dec(&erts_ports_alive);
pp->status &= ~ERTS_PORT_SFLG_CLOSING;
pp->status |= ERTS_PORT_SFLG_FREE_SCHEDULED;
erts_may_save_closed_port(pp);
@@ -681,7 +679,6 @@ erts_port_task_free_port(Port *pp)
port_is_dequeued = 1;
}
erts_smp_port_state_lock(pp);
- erts_smp_atomic_dec(&erts_ports_alive);
pp->status &= ~ERTS_PORT_SFLG_CLOSING;
pp->status |= ERTS_PORT_SFLG_FREE_SCHEDULED;
erts_may_save_closed_port(pp);
diff --git a/erts/emulator/beam/erl_printf_term.c b/erts/emulator/beam/erl_printf_term.c
index b71404fd27..34da9cab84 100644
--- a/erts/emulator/beam/erl_printf_term.c
+++ b/erts/emulator/beam/erl_printf_term.c
@@ -114,13 +114,13 @@ do { \
/* return 0 if list is not a non-empty flat list of printable characters */
static int
-is_printable_string(Eterm list)
+is_printable_string(Eterm list, Eterm* base)
{
int len = 0;
int c;
while(is_list(list)) {
- Eterm* consp = list_val(list);
+ Eterm* consp = list_val_rel(list, base);
Eterm hd = CAR(consp);
if (!is_byte(hd))
@@ -226,17 +226,20 @@ static int print_atom_name(fmtfn_t fn, void* arg, Eterm atom, long *dcount)
#define PRT_LAST_ARRAY_ELEMENT ((Eterm) 7) /* Note! Must be last... */
static int
-print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
+print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount,
+ Eterm* obj_base) /* ignored if !HALFWORD_HEAP */
{
DECLARE_WSTACK(s);
int res;
int i;
Eterm val;
Uint32 *ref_num;
+ union {
+ UWord word;
+ Eterm* ptr;
+ }popped;
Eterm* nobj;
-#if HALFWORD_HEAP
- UWord wobj;
-#endif
+ Wterm wobj;
res = 0;
@@ -258,18 +261,17 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
PRINT_CHAR(res, fn, arg, '}');
goto L_outer_loop;
default:
-#if HALFWORD_HEAP
- obj = (Eterm) (wobj = WSTACK_POP(s));
-#else
- obj = WSTACK_POP(s);
-#endif
+ popped.word = WSTACK_POP(s);
+
switch (val) {
case PRT_TERM:
+ obj = (Eterm) popped.word;
break;
case PRT_ONE_CONS:
+ obj = (Eterm) popped.word;
L_print_one_cons:
{
- Eterm* cons = list_val(obj);
+ Eterm* cons = list_val_rel(obj, obj_base);
Eterm tl;
obj = CAR(cons);
@@ -288,27 +290,13 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
}
break;
case PRT_LAST_ARRAY_ELEMENT:
- {
-#if HALFWORD_HEAP
- Eterm* ptr = (Eterm *) wobj;
-#else
- Eterm* ptr = (Eterm *) obj;
-#endif
- obj = *ptr;
- }
+ obj = *popped.ptr;
break;
default: /* PRT_LAST_ARRAY_ELEMENT+1 and upwards */
- {
-#if HALFWORD_HEAP
- Eterm* ptr = (Eterm *) wobj;
-#else
- Eterm* ptr = (Eterm *) obj;
-#endif
- obj = *ptr++;
- WSTACK_PUSH(s, (UWord) ptr);
- WSTACK_PUSH(s, val-1);
- WSTACK_PUSH(s, PRT_COMMA);
- }
+ obj = *popped.ptr;
+ WSTACK_PUSH(s, (UWord) (popped.ptr + 1));
+ WSTACK_PUSH(s, val-1);
+ WSTACK_PUSH(s, PRT_COMMA);
break;
}
break;
@@ -325,8 +313,12 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
PRINT_CHAR(res, fn, arg, '>');
goto L_done;
}
-
- switch (tag_val_def(obj)) {
+#if HALFWORD_HEAP
+ wobj = is_immed(obj) ? (Wterm)obj : rterm2wterm(obj, obj_base);
+#else
+ wobj = (Wterm)obj;
+#endif
+ switch (tag_val_def(wobj)) {
case NIL_DEF:
PRINT_STRING(res, fn, arg, "[]");
break;
@@ -348,13 +340,13 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
int print_res;
char def_buf[64];
char *buf, *big_str;
- Uint sz = (Uint) big_decimal_estimate(obj);
+ Uint sz = (Uint) big_decimal_estimate(wobj);
sz++;
if (sz <= 64)
buf = &def_buf[0];
else
buf = erts_alloc(ERTS_ALC_T_TMP, sz);
- big_str = erts_big_to_string(obj, buf, sz);
+ big_str = erts_big_to_string(wobj, buf, sz);
print_res = erts_printf_string(fn, arg, big_str);
if (buf != &def_buf[0])
erts_free(ERTS_ALC_T_TMP, (void *) buf);
@@ -369,9 +361,9 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
case EXTERNAL_REF_DEF:
PRINT_STRING(res, fn, arg, "#Ref<");
PRINT_ULONG(res, fn, arg, 'u', 0, 1,
- (unsigned long) ref_channel_no(obj));
- ref_num = ref_numbers(obj);
- for (i = ref_no_of_numbers(obj)-1; i >= 0; i--) {
+ (unsigned long) ref_channel_no(wobj));
+ ref_num = ref_numbers(wobj);
+ for (i = ref_no_of_numbers(wobj)-1; i >= 0; i--) {
PRINT_CHAR(res, fn, arg, '.');
PRINT_ULONG(res, fn, arg, 'u', 0, 1, (unsigned long) ref_num[i]);
}
@@ -381,30 +373,30 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
case EXTERNAL_PID_DEF:
PRINT_CHAR(res, fn, arg, '<');
PRINT_ULONG(res, fn, arg, 'u', 0, 1,
- (unsigned long) pid_channel_no(obj));
+ (unsigned long) pid_channel_no(wobj));
PRINT_CHAR(res, fn, arg, '.');
PRINT_ULONG(res, fn, arg, 'u', 0, 1,
- (unsigned long) pid_number(obj));
+ (unsigned long) pid_number(wobj));
PRINT_CHAR(res, fn, arg, '.');
PRINT_ULONG(res, fn, arg, 'u', 0, 1,
- (unsigned long) pid_serial(obj));
+ (unsigned long) pid_serial(wobj));
PRINT_CHAR(res, fn, arg, '>');
break;
case PORT_DEF:
case EXTERNAL_PORT_DEF:
PRINT_STRING(res, fn, arg, "#Port<");
PRINT_ULONG(res, fn, arg, 'u', 0, 1,
- (unsigned long) port_channel_no(obj));
+ (unsigned long) port_channel_no(wobj));
PRINT_CHAR(res, fn, arg, '.');
PRINT_ULONG(res, fn, arg, 'u', 0, 1,
- (unsigned long) port_number(obj));
+ (unsigned long) port_number(wobj));
PRINT_CHAR(res, fn, arg, '>');
break;
case LIST_DEF:
- if (is_printable_string(obj)) {
+ if (is_printable_string(obj, obj_base)) {
int c;
PRINT_CHAR(res, fn, arg, '"');
- nobj = list_val(obj);
+ nobj = list_val_rel(obj, obj_base);
while (1) {
if ((*dcount)-- <= 0)
goto L_done;
@@ -418,7 +410,7 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
}
if (is_not_list(*nobj))
break;
- nobj = list_val(*nobj);
+ nobj = list_val_rel(*nobj, obj_base);
}
PRINT_CHAR(res, fn, arg, '"');
} else {
@@ -428,7 +420,7 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
}
break;
case TUPLE_DEF:
- nobj = tuple_val(obj); /* pointer to arity */
+ nobj = tuple_val(wobj); /* pointer to arity */
i = arityval(*nobj); /* arity */
PRINT_CHAR(res, fn, arg, '{');
WSTACK_PUSH(s,PRT_CLOSE_TUPLE);
@@ -440,13 +432,13 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
break;
case FLOAT_DEF: {
FloatDef ff;
- GET_DOUBLE(obj, ff);
+ GET_DOUBLE(wobj, ff);
PRINT_DOUBLE(res, fn, arg, 'e', 6, 0, ff.fd);
}
break;
case BINARY_DEF:
{
- ProcBin* pb = (ProcBin *) binary_val(obj);
+ ProcBin* pb = (ProcBin *) binary_val(wobj);
if (pb->size == 1)
PRINT_STRING(res, fn, arg, "<<1 byte>>");
else {
@@ -458,7 +450,7 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
break;
case EXPORT_DEF:
{
- Export* ep = *((Export **) (export_val(obj) + 1));
+ Export* ep = *((Export **) (export_val(wobj) + 1));
Atom* module = atom_tab(atom_val(ep->code[0]));
Atom* name = atom_tab(atom_val(ep->code[1]));
@@ -474,7 +466,7 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
break;
case FUN_DEF:
{
- ErlFunThing *funp = (ErlFunThing *) fun_val(obj);
+ ErlFunThing *funp = (ErlFunThing *) fun_val(wobj);
Atom *ap = atom_tab(atom_val(funp->fe->module));
PRINT_STRING(res, fn, arg, "#Fun<");
@@ -490,7 +482,7 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
break;
default:
PRINT_STRING(res, fn, arg, "<unknown:");
- PRINT_POINTER(res, fn, arg, (UWord) obj);
+ PRINT_POINTER(res, fn, arg, wobj);
PRINT_CHAR(res, fn, arg, '>');
break;
}
@@ -503,9 +495,10 @@ print_term(fmtfn_t fn, void* arg, Eterm obj, long *dcount)
}
int
-erts_printf_term(fmtfn_t fn, void* arg, unsigned long term, long precision)
+erts_printf_term(fmtfn_t fn, void* arg, unsigned long term, long precision,
+ unsigned long* term_base)
{
- int res = print_term(fn, arg, (Uint) term, &precision);
+ int res = print_term(fn, arg, (Eterm)term, &precision, (Eterm*)term_base);
if (res < 0)
return res;
if (precision <= 0)
diff --git a/erts/emulator/beam/erl_printf_term.h b/erts/emulator/beam/erl_printf_term.h
index 4f76028396..4ba22f12de 100644
--- a/erts/emulator/beam/erl_printf_term.h
+++ b/erts/emulator/beam/erl_printf_term.h
@@ -21,6 +21,6 @@
#define ERL_PRINTF_TERM_H__
#include "erl_printf_format.h"
-int erts_printf_term(fmtfn_t fn, void* arg, unsigned long term, long precision);
-
+int erts_printf_term(fmtfn_t fn, void* arg, unsigned long term, long precision,
+ unsigned long* term_base);
#endif
diff --git a/erts/emulator/beam/erl_process.c b/erts/emulator/beam/erl_process.c
index 8a56976905..2704359a8f 100644
--- a/erts/emulator/beam/erl_process.c
+++ b/erts/emulator/beam/erl_process.c
@@ -166,9 +166,8 @@ static struct {
static struct {
erts_smp_mtx_t update_mtx;
- erts_smp_atomic32_t active_runqs;
+ erts_smp_atomic32_t no_runqs;
int last_active_runqs;
- erts_smp_atomic32_t used_runqs;
int forced_check_balance;
erts_smp_atomic32_t checking_balance;
int halftime;
@@ -965,7 +964,7 @@ sched_spin_wait(ErtsSchedulerSleepInfo *ssi, int spincount)
erts_aint32_t flgs;
do {
- flgs = erts_smp_atomic32_read(&ssi->flags);
+ flgs = erts_smp_atomic32_read_acqb(&ssi->flags);
if ((flgs & (ERTS_SSI_FLG_SLEEPING|ERTS_SSI_FLG_WAITING))
!= (ERTS_SSI_FLG_SLEEPING|ERTS_SSI_FLG_WAITING)) {
break;
@@ -1114,7 +1113,7 @@ scheduler_wait(int *fcalls, ErtsSchedulerData *esdp, ErtsRunQueue *rq)
else {
erts_aint_t dt;
- erts_smp_atomic32_set(&function_calls, 0);
+ erts_smp_atomic32_set_relb(&function_calls, 0);
*fcalls = 0;
sched_waiting_sys(esdp->no, rq);
@@ -1147,7 +1146,7 @@ scheduler_wait(int *fcalls, ErtsSchedulerData *esdp, ErtsRunQueue *rq)
nonblockable_aux_work(esdp, ssi, aux_work);
#endif
- flgs = erts_smp_atomic32_read(&ssi->flags);
+ flgs = erts_smp_atomic32_read_acqb(&ssi->flags);
if (!(flgs & ERTS_SSI_FLG_WAITING)) {
ASSERT(!(flgs & ERTS_SSI_FLG_SLEEPING));
goto sys_woken;
@@ -1333,6 +1332,76 @@ wake_all_schedulers(void)
}
}
+#define ERTS_NO_USED_RUNQS_SHIFT 16
+#define ERTS_NO_RUNQS_MASK 0xffff
+
+#if ERTS_MAX_NO_OF_SCHEDULERS > ERTS_NO_RUNQS_MASK
+# error "Too large amount of schedulers allowed"
+#endif
+
+static ERTS_INLINE void
+init_no_runqs(int active, int used)
+{
+ erts_aint32_t no_runqs = (erts_aint32_t) (active & ERTS_NO_RUNQS_MASK);
+ no_runqs |= (erts_aint32_t) ((used & ERTS_NO_RUNQS_MASK) << ERTS_NO_USED_RUNQS_SHIFT);
+ erts_smp_atomic32_init(&balance_info.no_runqs, no_runqs);
+}
+
+static ERTS_INLINE void
+get_no_runqs(int *active, int *used)
+{
+ erts_aint32_t no_runqs = erts_smp_atomic32_read(&balance_info.no_runqs);
+ if (active)
+ *active = (int) (no_runqs & ERTS_NO_RUNQS_MASK);
+ if (used)
+ *used = (int) ((no_runqs >> ERTS_NO_USED_RUNQS_SHIFT) & ERTS_NO_RUNQS_MASK);
+}
+
+static ERTS_INLINE void
+set_no_used_runqs(int used)
+{
+ erts_aint32_t exp = erts_smp_atomic32_read(&balance_info.no_runqs);
+ while (1) {
+ erts_aint32_t act, new;
+ new = (used << ERTS_NO_USED_RUNQS_SHIFT) | (exp & ERTS_NO_RUNQS_MASK);
+ act = erts_smp_atomic32_cmpxchg(&balance_info.no_runqs, new, exp);
+ if (act == exp)
+ break;
+ exp = act;
+ }
+}
+
+static ERTS_INLINE void
+set_no_active_runqs(int active)
+{
+ erts_aint32_t exp = erts_smp_atomic32_read(&balance_info.no_runqs);
+ while (1) {
+ erts_aint32_t act, new;
+ new = (exp & (ERTS_NO_RUNQS_MASK << ERTS_NO_USED_RUNQS_SHIFT)) | active;
+ act = erts_smp_atomic32_cmpxchg(&balance_info.no_runqs, new, exp);
+ if (act == exp)
+ break;
+ exp = act;
+ }
+}
+
+static ERTS_INLINE int
+try_inc_no_active_runqs(int active)
+{
+ erts_aint32_t exp = erts_smp_atomic32_read(&balance_info.no_runqs);
+ if (((exp >> ERTS_NO_USED_RUNQS_SHIFT) & ERTS_NO_RUNQS_MASK) < active)
+ return 0;
+ if ((exp & ERTS_NO_RUNQS_MASK) + 1 == active) {
+ erts_aint32_t new, act;
+ new = (exp & ~ERTS_NO_RUNQS_MASK) | active;
+ act = erts_smp_atomic32_cmpxchg(&balance_info.no_runqs, new, exp);
+ if (act == exp)
+ return 1;
+ }
+ return 0;
+}
+
+
static ERTS_INLINE int
chk_wake_sched(ErtsRunQueue *crq, int ix, int activate)
{
@@ -1344,9 +1413,7 @@ chk_wake_sched(ErtsRunQueue *crq, int ix, int activate)
iflgs = erts_smp_atomic32_read(&wrq->info_flags);
if (!(iflgs & (ERTS_RUNQ_IFLG_SUSPENDED|ERTS_RUNQ_IFLG_NONEMPTY))) {
if (activate) {
- if (ix == erts_smp_atomic32_cmpxchg(&balance_info.active_runqs,
- ix+1,
- ix)) {
+ if (try_inc_no_active_runqs(ix+1)) {
erts_smp_xrunq_lock(crq, wrq);
wrq->flags &= ~ERTS_RUNQ_FLG_INACTIVE;
erts_smp_xrunq_unlock(crq, wrq);
@@ -1363,8 +1430,9 @@ wake_scheduler_on_empty_runq(ErtsRunQueue *crq)
{
int ix = crq->ix;
int stop_ix = ix;
- int active_ix = erts_smp_atomic32_read(&balance_info.active_runqs);
- int balance_ix = erts_smp_atomic32_read(&balance_info.used_runqs);
+ int active_ix, balance_ix;
+
+ get_no_runqs(&active_ix, &balance_ix);
if (active_ix > balance_ix)
active_ix = balance_ix;
@@ -1416,7 +1484,7 @@ erts_sched_notify_check_cpu_bind(void)
int ix;
if (erts_common_run_queue) {
for (ix = 0; ix < erts_no_schedulers; ix++)
- erts_smp_atomic32_set(&ERTS_SCHEDULER_IX(ix)->chk_cpu_bind, 1);
+ erts_smp_atomic32_set_relb(&ERTS_SCHEDULER_IX(ix)->chk_cpu_bind, 1);
wake_all_schedulers();
}
else {
@@ -1871,8 +1939,7 @@ try_steal_task(ErtsRunQueue *rq)
ERTS_SMP_LC_CHK_RUNQ_LOCK(rq, rq_locked);
- active_rqs = erts_smp_atomic32_read(&balance_info.active_runqs);
- blnc_rqs = erts_smp_atomic32_read(&balance_info.used_runqs);
+ get_no_runqs(&active_rqs, &blnc_rqs);
if (active_rqs > blnc_rqs)
active_rqs = blnc_rqs;
@@ -1883,7 +1950,7 @@ try_steal_task(ErtsRunQueue *rq)
if (active_rqs < blnc_rqs) {
int no = blnc_rqs - active_rqs;
int stop_ix = vix = active_rqs + rq->ix % no;
- while (erts_smp_atomic32_read(&no_empty_run_queues) < blnc_rqs) {
+ while (erts_smp_atomic32_read_acqb(&no_empty_run_queues) < blnc_rqs) {
res = check_possible_steal_victim(rq, &rq_locked, vix);
if (res)
goto done;
@@ -1898,7 +1965,7 @@ try_steal_task(ErtsRunQueue *rq)
vix = rq->ix;
/* ... then try to steal a job from another active queue... */
- while (erts_smp_atomic32_read(&no_empty_run_queues) < blnc_rqs) {
+ while (erts_smp_atomic32_read_acqb(&no_empty_run_queues) < blnc_rqs) {
vix++;
if (vix >= active_rqs)
vix = 0;
@@ -1999,7 +2066,7 @@ check_balance(ErtsRunQueue *c_rq)
return;
}
- blnc_no_rqs = (int) erts_smp_atomic32_read(&balance_info.used_runqs);
+ get_no_runqs(NULL, &blnc_no_rqs);
if (blnc_no_rqs == 1) {
c_rq->check_balance_reds = INT_MAX;
erts_smp_atomic32_set(&balance_info.checking_balance, 0);
@@ -2038,7 +2105,8 @@ check_balance(ErtsRunQueue *c_rq)
forced = balance_info.forced_check_balance;
balance_info.forced_check_balance = 0;
- blnc_no_rqs = (int) erts_smp_atomic32_read(&balance_info.used_runqs);
+ get_no_runqs(&current_active, &blnc_no_rqs);
+
if (blnc_no_rqs == 1) {
erts_smp_mtx_unlock(&balance_info.update_mtx);
erts_smp_runq_lock(c_rq);
@@ -2052,8 +2120,6 @@ check_balance(ErtsRunQueue *c_rq)
if (balance_info.full_reds_history_index >= ERTS_FULL_REDS_HISTORY_SIZE)
balance_info.full_reds_history_index = 0;
- current_active = erts_smp_atomic32_read(&balance_info.active_runqs);
-
/* Read balance information for all run queues */
for (qix = 0; qix < blnc_no_rqs; qix++) {
ErtsRunQueue *rq = ERTS_RUNQ_IX(qix);
@@ -2387,7 +2453,7 @@ erts_fprintf(stderr, "--------------------------------\n");
}
balance_info.last_active_runqs = active;
- erts_smp_atomic32_set(&balance_info.active_runqs, active);
+ set_no_active_runqs(active);
balance_info.halftime = 1;
erts_smp_atomic32_set(&balance_info.checking_balance, 0);
@@ -2695,9 +2761,8 @@ erts_init_scheduling(int mrq, int no_schedulers, int no_schedulers_online)
erts_smp_atomic32_init(&schdlr_sspnd.msb.ongoing, 0);
erts_smp_atomic32_init(&schdlr_sspnd.active, no_schedulers);
schdlr_sspnd.msb.procs = NULL;
- erts_smp_atomic32_set(&balance_info.used_runqs,
- erts_common_run_queue ? 1 : no_schedulers_online);
- erts_smp_atomic32_init(&balance_info.active_runqs, no_schedulers);
+ init_no_runqs(no_schedulers,
+ erts_common_run_queue ? 1 : no_schedulers_online);
balance_info.last_active_runqs = no_schedulers;
erts_smp_mtx_init(&balance_info.update_mtx, "migration_info_update");
balance_info.forced_check_balance = 0;
@@ -2939,7 +3004,7 @@ sched_spin_suspended(ErtsSchedulerSleepInfo *ssi, int spincount)
erts_aint32_t flgs;
do {
- flgs = erts_smp_atomic32_read(&ssi->flags);
+ flgs = erts_smp_atomic32_read_acqb(&ssi->flags);
if ((flgs & (ERTS_SSI_FLG_SLEEPING
| ERTS_SSI_FLG_WAITING
| ERTS_SSI_FLG_SUSPENDED))
@@ -3068,7 +3133,7 @@ suspend_scheduler(ErtsSchedulerData *esdp)
wake = 0;
}
- flgs = erts_smp_atomic32_read(&ssi->flags);
+ flgs = erts_smp_atomic32_read_acqb(&ssi->flags);
if (!(flgs & ERTS_SSI_FLG_SUSPENDED))
break;
erts_smp_mtx_unlock(&schdlr_sspnd.mtx);
@@ -3292,7 +3357,7 @@ erts_set_schedulers_online(Process *p,
ErtsRunQueue *to_rq = ERTS_RUNQ_IX(ix % no);
evacuate_run_queue(from_rq, to_rq);
}
- erts_smp_atomic32_set(&balance_info.used_runqs, no);
+ set_no_used_runqs(no);
erts_smp_mtx_unlock(&balance_info.update_mtx);
erts_smp_mtx_lock(&schdlr_sspnd.mtx);
}
@@ -3346,7 +3411,7 @@ erts_set_schedulers_online(Process *p,
for (ix = erts_no_run_queues-1; ix >= no; ix--)
evacuate_run_queue(ERTS_RUNQ_IX(ix),
ERTS_RUNQ_IX(ix % no));
- erts_smp_atomic32_set(&balance_info.used_runqs, no);
+ set_no_used_runqs(no);
erts_smp_mtx_unlock(&balance_info.update_mtx);
erts_smp_mtx_lock(&schdlr_sspnd.mtx);
for (ix = no; ix < online; ix++) {
@@ -3443,7 +3508,7 @@ erts_block_multi_scheduling(Process *p, ErtsProcLocks plocks, int on, int all)
else {
erts_smp_mtx_unlock(&schdlr_sspnd.mtx);
erts_smp_mtx_lock(&balance_info.update_mtx);
- erts_smp_atomic32_set(&balance_info.used_runqs, 1);
+ set_no_used_runqs(1);
for (ix = 0; ix < online; ix++) {
ErtsRunQueue *rq = ERTS_RUNQ_IX(ix);
erts_smp_runq_lock(rq);
@@ -3580,7 +3645,7 @@ erts_block_multi_scheduling(Process *p, ErtsProcLocks plocks, int on, int all)
evacuate_run_queue(ERTS_RUNQ_IX(ix),
ERTS_RUNQ_IX(ix % online));
- erts_smp_atomic32_set(&balance_info.used_runqs, online);
+ set_no_used_runqs(online);
/* Make sure that we balance soon... */
balance_info.forced_check_balance = 1;
erts_smp_runq_lock(ERTS_RUNQ_IX(0));
@@ -5131,7 +5196,7 @@ Process *schedule(Process *p, int calls)
esdp = erts_get_scheduler_data();
rq = erts_get_runq_current(esdp);
ASSERT(esdp);
- fcalls = (int) erts_smp_atomic32_read(&function_calls);
+ fcalls = (int) erts_smp_atomic32_read_acqb(&function_calls);
actual_reds = reds = 0;
erts_smp_runq_lock(rq);
} else {
@@ -5282,14 +5347,14 @@ Process *schedule(Process *p, int calls)
| ERTS_RUNQ_FLG_CHK_CPU_BIND
| ERTS_RUNQ_FLG_SUSPENDED)) {
if ((rq->flags & ERTS_RUNQ_FLG_SUSPENDED)
- || (erts_smp_atomic32_read(&esdp->ssi->flags)
+ || (erts_smp_atomic32_read_acqb(&esdp->ssi->flags)
& ERTS_SSI_FLG_SUSPENDED)) {
ASSERT(erts_smp_atomic32_read(&esdp->ssi->flags)
& ERTS_SSI_FLG_SUSPENDED);
suspend_scheduler(esdp);
}
if ((rq->flags & ERTS_RUNQ_FLG_CHK_CPU_BIND)
- || erts_smp_atomic32_read(&esdp->chk_cpu_bind)) {
+ || erts_smp_atomic32_read_acqb(&esdp->chk_cpu_bind)) {
erts_sched_check_cpu_bind(esdp);
}
}
@@ -5340,7 +5405,7 @@ Process *schedule(Process *p, int calls)
if (rq->flags & (ERTS_RUNQ_FLG_SHARED_RUNQ
| ERTS_RUNQ_FLG_SUSPENDED)) {
if ((rq->flags & ERTS_RUNQ_FLG_SUSPENDED)
- || (erts_smp_atomic32_read(&esdp->ssi->flags)
+ || (erts_smp_atomic32_read_acqb(&esdp->ssi->flags)
& ERTS_SSI_FLG_SUSPENDED)) {
ASSERT(erts_smp_atomic32_read(&esdp->ssi->flags)
& ERTS_SSI_FLG_SUSPENDED);
@@ -5384,7 +5449,7 @@ Process *schedule(Process *p, int calls)
* Schedule system-level activities.
*/
- erts_smp_atomic32_set(&function_calls, 0);
+ erts_smp_atomic32_set_relb(&function_calls, 0);
fcalls = 0;
ASSERT(!erts_port_task_have_outstanding_io_tasks());
@@ -5426,7 +5491,7 @@ Process *schedule(Process *p, int calls)
if (erts_common_run_queue->waiting)
wake_scheduler(erts_common_run_queue, 0, 1);
}
- else if (erts_smp_atomic32_read(&no_empty_run_queues) != 0) {
+ else if (erts_smp_atomic32_read_acqb(&no_empty_run_queues) != 0) {
wake_scheduler_on_empty_runq(rq);
rq->wakeup_other = 0;
}
@@ -7637,7 +7702,8 @@ continue_exit_process(Process *p
static void
timeout_proc(Process* p)
{
- p->i = *((BeamInstr **) (UWord) p->def_arg_reg);
+ BeamInstr** pi = (BeamInstr **) p->def_arg_reg;
+ p->i = *pi;
p->flags |= F_TIMO;
p->flags &= ~F_INSLPQUEUE;
diff --git a/erts/emulator/beam/erl_trace.c b/erts/emulator/beam/erl_trace.c
index c0397ca6c3..8833137112 100644
--- a/erts/emulator/beam/erl_trace.c
+++ b/erts/emulator/beam/erl_trace.c
@@ -1538,8 +1538,7 @@ erts_call_trace(Process* p, BeamInstr mfa[3], Binary *match_spec,
Eterm tracee;
#endif
Eterm transformed_args[MAX_ARG];
- DeclareTmpHeap(sub_bin_heap_et,ERL_SUB_BIN_SIZE,p);
- ErlSubBin *sub_bin_heap = (ErlSubBin *) sub_bin_heap_et;
+ DeclareTypedTmpHeap(ErlSubBin,sub_bin_heap,p);
ASSERT(tracer_pid);
if (*tracer_pid == am_true) {
@@ -1600,21 +1599,20 @@ erts_call_trace(Process* p, BeamInstr mfa[3], Binary *match_spec,
if (is_boxed(arg) && header_is_bin_matchstate(*boxed_val(arg))) {
ErlBinMatchState* ms = (ErlBinMatchState *) boxed_val(arg);
ErlBinMatchBuffer* mb = &ms->mb;
- ErlSubBin* sb = sub_bin_heap;
Uint bit_size;
ASSERT(sub_bin_heap->thing_word == 0); /* At most one of match context */
bit_size = mb->size - mb->offset;
- sb->thing_word = HEADER_SUB_BIN;
- sb->size = BYTE_OFFSET(bit_size);
- sb->bitsize = BIT_OFFSET(bit_size);
- sb->offs = BYTE_OFFSET(mb->offset);
- sb->bitoffs = BIT_OFFSET(mb->offset);
- sb->is_writable = 0;
- sb->orig = mb->orig;
-
- arg = make_binary(sb);
+ sub_bin_heap->thing_word = HEADER_SUB_BIN;
+ sub_bin_heap->size = BYTE_OFFSET(bit_size);
+ sub_bin_heap->bitsize = BIT_OFFSET(bit_size);
+ sub_bin_heap->offs = BYTE_OFFSET(mb->offset);
+ sub_bin_heap->bitoffs = BIT_OFFSET(mb->offset);
+ sub_bin_heap->is_writable = 0;
+ sub_bin_heap->orig = mb->orig;
+
+ arg = make_binary(sub_bin_heap);
}
transformed_args[i] = arg;
}
diff --git a/erts/emulator/beam/global.h b/erts/emulator/beam/global.h
index 96da894d90..499bdd77ba 100644
--- a/erts/emulator/beam/global.h
+++ b/erts/emulator/beam/global.h
@@ -183,7 +183,7 @@ struct port {
process to get (line oriented I/O)*/
Uint32 status; /* Status and type flags */
int control_flags; /* Flags for port_control() */
- Uint32 snapshot; /* Next snapshot that port should be part of */
+ erts_aint32_t snapshot; /* Next snapshot that port should be part of */
struct reg_proc *reg;
ErlDrvPDL port_data_lock;
@@ -527,11 +527,10 @@ union erl_off_heap_ptr {
/* arrays that get malloced at startup */
extern Port* erts_port;
-extern erts_smp_atomic_t erts_ports_alive;
extern Uint erts_max_ports;
extern Uint erts_port_tab_index_mask;
-extern erts_smp_atomic_t erts_ports_snapshot;
+extern erts_smp_atomic32_t erts_ports_snapshot;
extern erts_smp_atomic_t erts_dead_ports_ptr;
ERTS_GLB_INLINE void erts_may_save_closed_port(Port *prt);
@@ -541,12 +540,12 @@ ERTS_GLB_INLINE void erts_may_save_closed_port(Port *prt);
ERTS_GLB_INLINE void erts_may_save_closed_port(Port *prt)
{
ERTS_SMP_LC_ASSERT(erts_smp_lc_spinlock_is_locked(&prt->state_lck));
- if (prt->snapshot != erts_smp_atomic_read(&erts_ports_snapshot)) {
+ if (prt->snapshot != erts_smp_atomic32_read_acqb(&erts_ports_snapshot)) {
/* Dead ports are added from the end of the snapshot buffer */
Eterm* tombstone = (Eterm*) erts_smp_atomic_addtest(&erts_dead_ports_ptr,
-(erts_aint_t)sizeof(Eterm));
ASSERT(tombstone+1 != NULL);
- ASSERT(prt->snapshot == (Uint32) erts_smp_atomic_read(&erts_ports_snapshot) - 1);
+ ASSERT(prt->snapshot == erts_smp_atomic32_read(&erts_ports_snapshot) - 1);
*tombstone = prt->id;
}
/*else no ongoing snapshot or port was already included or created after snapshot */
@@ -1653,10 +1652,14 @@ struct Sint_buf {
};
char* Sint_to_buf(Sint, struct Sint_buf*);
+#define ERTS_IOLIST_OK 0
+#define ERTS_IOLIST_OVERFLOW 1
+#define ERTS_IOLIST_TYPE 2
+
Eterm buf_to_intlist(Eterm**, char*, int, Eterm); /* most callers pass plain char*'s */
int io_list_to_buf(Eterm, char*, int);
int io_list_to_buf2(Eterm, char*, int);
-int io_list_len(Eterm);
+int erts_iolist_size(Eterm, Uint *);
int is_string(Eterm);
void erl_at_exit(void (*) (void*), void*);
Eterm collect_memory(Process *);
@@ -1890,6 +1893,8 @@ erts_alloc_message_heap(Uint size,
# if defined(DEBUG)
# define DeclareTmpHeap(VariableName,Size,Process) \
Eterm *VariableName = erts_debug_allocate_tmp_heap(Size,Process)
+# define DeclareTypedTmpHeap(Type,VariableName,Process) \
+ Type *VariableName = (Type *) erts_debug_allocate_tmp_heap(sizeof(Type)/sizeof(Eterm),Process)
# define DeclareTmpHeapNoproc(VariableName,Size) \
Eterm *VariableName = erts_debug_allocate_tmp_heap(Size,NULL)
# define UseTmpHeap(Size,Proc) \
@@ -1911,6 +1916,8 @@ erts_alloc_message_heap(Uint size,
# else
# define DeclareTmpHeap(VariableName,Size,Process) \
Eterm *VariableName = (ERTS_PROC_GET_SCHDATA(Process)->tmp_heap)+(ERTS_PROC_GET_SCHDATA(Process)->num_tmp_heap_used)
+# define DeclareTypedTmpHeap(Type,VariableName,Process) \
+ Type *VariableName = (Type *) (ERTS_PROC_GET_SCHDATA(Process)->tmp_heap)+(ERTS_PROC_GET_SCHDATA(Process)->num_tmp_heap_used)
# define DeclareTmpHeapNoproc(VariableName,Size) \
Eterm *VariableName = (erts_get_scheduler_data()->tmp_heap)+(erts_get_scheduler_data()->num_tmp_heap_used)
# define UseTmpHeap(Size,Proc) \
@@ -1936,6 +1943,8 @@ erts_alloc_message_heap(Uint size,
#else
# define DeclareTmpHeap(VariableName,Size,Process) \
Eterm VariableName[Size]
+# define DeclareTypedTmpHeap(Type,VariableName,Process) \
+ Type VariableName[1]
# define DeclareTmpHeapNoproc(VariableName,Size) \
Eterm VariableName[Size]
# define UseTmpHeap(Size,Proc) /* Nothing */
diff --git a/erts/emulator/beam/io.c b/erts/emulator/beam/io.c
index f619c6f88b..df5f8b22a3 100644
--- a/erts/emulator/beam/io.c
+++ b/erts/emulator/beam/io.c
@@ -56,7 +56,6 @@ static erts_smp_tsd_key_t driver_list_last_error_key; /* Save last DDLL error o
per thread basis (for BC interfaces) */
Port* erts_port; /* The port table */
-erts_smp_atomic_t erts_ports_alive;
erts_smp_atomic_t erts_bytes_out; /* No bytes sent out of the system */
erts_smp_atomic_t erts_bytes_in; /* No bytes gotten into the system */
@@ -82,6 +81,9 @@ static void driver_monitor_unlock_pdl(Port *p);
#define DRV_MONITOR_UNLOCK_PDL(Port) /* nothing */
#endif
+#define ERL_SMALL_IO_BIN_LIMIT (4*ERL_ONHEAP_BIN_LIMIT)
+#define SMALL_WRITE_VEC 16
+
static ERTS_INLINE ErlIOQueue*
drvport2ioq(ErlDrvPort drvport)
{
@@ -190,7 +192,7 @@ typedef struct line_buf_context {
static erts_smp_spinlock_t get_free_port_lck;
static Uint last_port_num;
static Uint port_num_mask;
-erts_smp_atomic_t erts_ports_snapshot; /* Identifies the _next_ snapshot (not the ongoing) */
+erts_smp_atomic32_t erts_ports_snapshot; /* Identifies the _next_ snapshot (not the ongoing) */
static ERTS_INLINE void
@@ -421,10 +423,9 @@ setup_port(Port* prt, Eterm pid, erts_driver_t *driver,
new_name = (char*) erts_alloc(ERTS_ALC_T_PORT_NAME, sys_strlen(name)+1);
sys_strcpy(new_name, name);
erts_smp_runq_lock(runq);
- erts_smp_atomic_inc(&erts_ports_alive);
erts_smp_port_state_lock(prt);
prt->status = ERTS_PORT_SFLG_CONNECTED | xstatus;
- prt->snapshot = (Uint32) erts_smp_atomic_read(&erts_ports_snapshot);
+ prt->snapshot = erts_smp_atomic32_read(&erts_ports_snapshot);
old_name = prt->name;
prt->name = new_name;
#ifdef ERTS_SMP
@@ -954,13 +955,14 @@ do { \
int _bitoffs; \
int _bitsize; \
ERTS_GET_REAL_BIN(obj, _real, _offset, _bitoffs, _bitsize); \
- ASSERT(_bitsize == 0); \
+ if (_bitsize != 0) goto L_type_error; \
if (thing_subtag(*binary_val(_real)) == REFC_BINARY_SUBTAG && \
_bitoffs == 0) { \
b_size += _size; \
+ if (b_size < _size) goto L_overflow_error; \
in_clist = 0; \
v_size++; \
- if (_size >= bin_limit) { \
+ if (_size >= ERL_SMALL_IO_BIN_LIMIT) { \
p_in_clist = 0; \
p_v_size++; \
} else { \
@@ -972,6 +974,7 @@ do { \
} \
} else { \
c_size += _size; \
+ if (c_size < _size) goto L_overflow_error; \
if (!in_clist) { \
in_clist = 1; \
v_size++; \
@@ -986,29 +989,30 @@ do { \
/*
-** Size of a io list in bytes
-** return -1 if error
-** returns: - Total size of io list
-** vsize - SysIOVec size needed for a writev
-** csize - Number of bytes not in binary (in the common binary)
-** pvsize - SysIOVec size needed if packing small binaries
-** pcsize - Number of bytes in the common binary if packing
-*/
+ * Returns 0 if successful and a non-zero value otherwise.
+ *
+ * Return values through pointers:
+ * *vsize - SysIOVec size needed for a writev
+ * *csize - Number of bytes not in binary (in the common binary)
+ * *pvsize - SysIOVec size needed if packing small binaries
+ * *pcsize - Number of bytes in the common binary if packing
+ * *total_size - Total size of iolist in bytes
+ */
static int
-io_list_vec_len(Eterm obj, int* vsize, int* csize,
- int bin_limit, /* small binaries limit */
- int * pvsize, int * pcsize)
+io_list_vec_len(Eterm obj, Uint* vsize, Uint* csize,
+ Uint* pvsize, Uint* pcsize, Uint* total_size)
{
DECLARE_ESTACK(s);
Eterm* objp;
- int v_size = 0;
- int c_size = 0;
- int b_size = 0;
- int in_clist = 0;
- int p_v_size = 0;
- int p_c_size = 0;
- int p_in_clist = 0;
+ Uint v_size = 0;
+ Uint c_size = 0;
+ Uint b_size = 0;
+ Uint in_clist = 0;
+ Uint p_v_size = 0;
+ Uint p_c_size = 0;
+ Uint p_in_clist = 0;
+ Uint total;
goto L_jump_start; /* avoid a push */
@@ -1022,6 +1026,9 @@ io_list_vec_len(Eterm obj, int* vsize, int* csize,
if (is_byte(obj)) {
c_size++;
+ if (c_size == 0) {
+ goto L_overflow_error;
+ }
if (!in_clist) {
in_clist = 1;
v_size++;
@@ -1061,32 +1068,31 @@ io_list_vec_len(Eterm obj, int* vsize, int* csize,
}
}
+ total = c_size + b_size;
+ if (total < c_size) {
+ goto L_overflow_error;
+ }
+ *total_size = total;
+
DESTROY_ESTACK(s);
- if (vsize != NULL)
- *vsize = v_size;
- if (csize != NULL)
- *csize = c_size;
- if (pvsize != NULL)
- *pvsize = p_v_size;
- if (pcsize != NULL)
- *pcsize = p_c_size;
- return c_size + b_size;
+ *vsize = v_size;
+ *csize = c_size;
+ *pvsize = p_v_size;
+ *pcsize = p_c_size;
+ return 0;
L_type_error:
+ L_overflow_error:
DESTROY_ESTACK(s);
- return -1;
+ return 1;
}
-#define ERL_SMALL_IO_BIN_LIMIT (4*ERL_ONHEAP_BIN_LIMIT)
-#define SMALL_WRITE_VEC 16
-
-
/* write data to a port */
int erts_write_to_port(Eterm caller_id, Port *p, Eterm list)
{
char *buf;
erts_driver_t *drv = p->drv_ptr;
- int size;
+ Uint size;
int fpe_was_unmasked;
ERTS_SMP_LC_ASSERT(erts_lc_is_port_locked(p));
@@ -1094,10 +1100,10 @@ int erts_write_to_port(Eterm caller_id, Port *p, Eterm list)
p->caller = caller_id;
if (drv->outputv != NULL) {
- int vsize;
- int csize;
- int pvsize;
- int pcsize;
+ Uint vsize;
+ Uint csize;
+ Uint pvsize;
+ Uint pcsize;
int blimit;
SysIOVec iv[SMALL_WRITE_VEC];
ErlDrvBinary* bv[SMALL_WRITE_VEC];
@@ -1106,9 +1112,8 @@ int erts_write_to_port(Eterm caller_id, Port *p, Eterm list)
ErlDrvBinary* cbin;
ErlIOVec ev;
- if ((size = io_list_vec_len(list, &vsize, &csize,
- ERL_SMALL_IO_BIN_LIMIT,
- &pvsize, &pcsize)) < 0) {
+ if (io_list_vec_len(list, &vsize, &csize,
+ &pvsize, &pcsize, &size)) {
goto bad_value;
}
/* To pack or not to pack (small binaries) ...? */
@@ -1183,7 +1188,7 @@ int erts_write_to_port(Eterm caller_id, Port *p, Eterm list)
else {
ASSERT(r == -1); /* Overflow */
erts_free(ERTS_ALC_T_TMP, buf);
- if ((size = io_list_len(list)) < 0) {
+ if (erts_iolist_size(list, &size)) {
goto bad_value;
}
@@ -1274,7 +1279,6 @@ void init_io(void)
erts_smp_atomic_init(&erts_bytes_out, 0);
erts_smp_atomic_init(&erts_bytes_in, 0);
- erts_smp_atomic_init(&erts_ports_alive, 0);
for (i = 0; i < erts_max_ports; i++) {
erts_port_task_init_sched(&erts_port[i].sched);
@@ -1296,7 +1300,7 @@ void init_io(void)
erts_port[i].port_data_lock = NULL;
}
- erts_smp_atomic_init(&erts_ports_snapshot, (erts_aint_t) 0);
+ erts_smp_atomic32_init(&erts_ports_snapshot, (erts_aint32_t) 0);
last_port_num = 0;
erts_smp_spinlock_init(&get_free_port_lck, "get_free_port");
@@ -2147,7 +2151,7 @@ erts_port_control(Process* p, Port* prt, Uint command, Eterm iolist)
byte* to_port = NULL; /* Buffer to write to port. */
/* Initialization is for shutting up
warning about use before set. */
- int to_len = 0; /* Length of buffer. */
+ Uint to_len = 0; /* Length of buffer. */
int must_free = 0; /* True if the buffer should be freed. */
char port_result[ERL_ONHEAP_BIN_LIMIT]; /* Default buffer for result from port. */
char* port_resp; /* Pointer to result buffer. */
@@ -2192,7 +2196,7 @@ erts_port_control(Process* p, Port* prt, Uint command, Eterm iolist)
} else {
ASSERT(r == -1); /* Overflow */
erts_free(ERTS_ALC_T_TMP, (void *) to_port);
- if ((to_len = io_list_len(iolist)) < 0) { /* Type error */
+ if (erts_iolist_size(iolist, &to_len)) { /* Type error */
return THE_NON_VALUE;
}
must_free = 1;
diff --git a/erts/emulator/beam/safe_hash.c b/erts/emulator/beam/safe_hash.c
index 21d6ce9304..3e9243c77d 100644
--- a/erts/emulator/beam/safe_hash.c
+++ b/erts/emulator/beam/safe_hash.c
@@ -99,7 +99,7 @@ static void rehash(SafeHash* h, int grow_limit)
erts_free(h->type, (void *) old_tab);
}
/*else already done */
- erts_smp_atomic_set(&h->is_rehashing, 0);
+ erts_smp_atomic_set_relb(&h->is_rehashing, 0);
}
diff --git a/erts/emulator/beam/utils.c b/erts/emulator/beam/utils.c
index 6b4f3b3b36..a17de717bc 100644
--- a/erts/emulator/beam/utils.c
+++ b/erts/emulator/beam/utils.c
@@ -3021,13 +3021,25 @@ int io_list_to_buf(Eterm obj, char* buf, int len)
return -1;
}
-int io_list_len(Eterm obj)
+/*
+ * Return 0 if successful, and non-zero if unsuccessful.
+ */
+int erts_iolist_size(Eterm obj, Uint* sizep)
{
Eterm* objp;
- Sint len = 0;
+ Uint size = 0;
DECLARE_ESTACK(s);
goto L_again;
+#define SAFE_ADD(Var, Val) \
+ do { \
+ Uint valvar = (Val); \
+ Var += valvar; \
+ if (Var < valvar) { \
+ goto L_overflow_error; \
+ } \
+ } while (0)
+
while (!ESTACK_ISEMPTY(s)) {
obj = ESTACK_POP(s);
L_again:
@@ -3037,9 +3049,12 @@ int io_list_len(Eterm obj)
/* Head */
obj = CAR(objp);
if (is_byte(obj)) {
- len++;
+ size++;
+ if (size == 0) {
+ goto L_overflow_error;
+ }
} else if (is_binary(obj) && binary_bitsize(obj) == 0) {
- len += binary_size(obj);
+ SAFE_ADD(size, binary_size(obj));
} else if (is_list(obj)) {
ESTACK_PUSH(s, CDR(objp));
goto L_iter_list; /* on head */
@@ -3051,23 +3066,29 @@ int io_list_len(Eterm obj)
if (is_list(obj))
goto L_iter_list; /* on tail */
else if (is_binary(obj) && binary_bitsize(obj) == 0) {
- len += binary_size(obj);
+ SAFE_ADD(size, binary_size(obj));
} else if (is_not_nil(obj)) {
goto L_type_error;
}
} else if (is_binary(obj) && binary_bitsize(obj) == 0) { /* Tail was binary */
- len += binary_size(obj);
+ SAFE_ADD(size, binary_size(obj));
} else if (is_not_nil(obj)) {
goto L_type_error;
}
}
+#undef SAFE_ADD
DESTROY_ESTACK(s);
- return len;
+ *sizep = size;
+ return ERTS_IOLIST_OK;
+
+ L_overflow_error:
+ DESTROY_ESTACK(s);
+ return ERTS_IOLIST_OVERFLOW;
L_type_error:
DESTROY_ESTACK(s);
- return -1;
+ return ERTS_IOLIST_TYPE;
}
/* return 0 if item is not a non-empty flat list of bytes */
diff --git a/erts/emulator/drivers/common/inet_drv.c b/erts/emulator/drivers/common/inet_drv.c
index aec456151c..40c4a0df08 100644
--- a/erts/emulator/drivers/common/inet_drv.c
+++ b/erts/emulator/drivers/common/inet_drv.c
@@ -1948,7 +1948,7 @@ static int http_response_inetdrv(void *arg, int major, int minor,
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[27];
- ErlDrvTermData caller;
+ ErlDrvTermData caller = ERL_DRV_NIL;
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async,S,Ref,{ok,{http_response,Version,Status,Phrase}}} */
@@ -2041,7 +2041,7 @@ http_request_inetdrv(void* arg, const http_atom_t* meth, const char* meth_ptr,
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[43];
- ErlDrvTermData caller;
+ ErlDrvTermData caller = ERL_DRV_NIL;
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async, S, Ref, {ok,{http_request,Meth,Uri,Version}}} */
@@ -2092,7 +2092,7 @@ http_header_inetdrv(void* arg, const http_atom_t* name, const char* name_ptr,
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[26];
- ErlDrvTermData caller;
+ ErlDrvTermData caller = ERL_DRV_NIL;
if (desc->inet.active == INET_PASSIVE) {
/* {inet_async,S,Ref,{ok,{http_header,Bit,Name,IValue,Value}} */
@@ -2221,7 +2221,7 @@ int ssl_tls_inetdrv(void* arg, unsigned type, unsigned major, unsigned minor,
tcp_descriptor* desc = (tcp_descriptor*) arg;
int i = 0;
ErlDrvTermData spec[28];
- ErlDrvTermData caller;
+ ErlDrvTermData caller = ERL_DRV_NIL;
ErlDrvBinary* bin;
int ret;
@@ -7980,11 +7980,11 @@ static int tcp_inet_ctl(ErlDrvData e, unsigned int cmd, char* buf, int len,
timeout = get_int32(buf);
if (desc->inet.state == TCP_STATE_ACCEPTING) {
- unsigned long time_left;
- int oid;
- ErlDrvTermData ocaller;
- int oreq;
- unsigned otimeout;
+ unsigned long time_left = 0;
+ int oid = 0;
+ ErlDrvTermData ocaller = ERL_DRV_NIL;
+ int oreq = 0;
+ unsigned otimeout = 0;
ErlDrvTermData caller = driver_caller(desc->inet.port);
MultiTimerData *mtd = NULL,*omtd = NULL;
ErlDrvMonitor monitor, omonitor;
diff --git a/erts/emulator/hipe/hipe_bif2.c b/erts/emulator/hipe/hipe_bif2.c
index 19cd32c68f..2660f74a82 100644
--- a/erts/emulator/hipe/hipe_bif2.c
+++ b/erts/emulator/hipe/hipe_bif2.c
@@ -1,9 +1,8 @@
/*
* %CopyrightBegin%
-
- *
+ *
* Copyright Ericsson AB 2001-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
@@ -37,14 +36,25 @@
#include "hipe_arch.h"
#include "hipe_stack.h"
-BIF_RETTYPE hipe_bifs_show_estack_1(BIF_ALIST_1)
+static void proc_unlock(Process* c_p, Process* rp)
{
+ ErtsProcLocks locks = ERTS_PROC_LOCKS_ALL;
+ if (rp == c_p) {
+ locks &= ~ERTS_PROC_LOCK_MAIN;
+ }
+ if (rp && locks) {
+ erts_smp_proc_unlock(rp, locks);
+ }
+}
+
+BIF_RETTYPE hipe_bifs_show_estack_1(BIF_ALIST_1)
+{
Process *rp = erts_pid2proc(BIF_P, ERTS_PROC_LOCK_MAIN,
BIF_ARG_1, ERTS_PROC_LOCKS_ALL);
if (!rp)
BIF_ERROR(BIF_P, BADARG);
hipe_print_estack(rp);
- erts_smp_proc_unlock(rp, ERTS_PROC_LOCKS_ALL);
+ proc_unlock(BIF_P, rp);
BIF_RET(am_true);
}
@@ -55,7 +65,7 @@ BIF_RETTYPE hipe_bifs_show_heap_1(BIF_ALIST_1)
if (!rp)
BIF_ERROR(BIF_P, BADARG);
hipe_print_heap(rp);
- erts_smp_proc_unlock(rp, ERTS_PROC_LOCKS_ALL);
+ proc_unlock(BIF_P, rp);
BIF_RET(am_true);
}
@@ -66,7 +76,7 @@ BIF_RETTYPE hipe_bifs_show_nstack_1(BIF_ALIST_1)
if (!rp)
BIF_ERROR(BIF_P, BADARG);
hipe_print_nstack(rp);
- erts_smp_proc_unlock(rp, ERTS_PROC_LOCKS_ALL);
+ proc_unlock(BIF_P, rp);
BIF_RET(am_true);
}
@@ -82,7 +92,7 @@ BIF_RETTYPE hipe_bifs_show_pcb_1(BIF_ALIST_1)
if (!rp)
BIF_ERROR(BIF_P, BADARG);
hipe_print_pcb(rp);
- erts_smp_proc_unlock(rp, ERTS_PROC_LOCKS_ALL);
+ proc_unlock(BIF_P, rp);
BIF_RET(am_true);
}
diff --git a/erts/emulator/hipe/hipe_mkliterals.c b/erts/emulator/hipe/hipe_mkliterals.c
index 650861b54b..bced90785d 100644
--- a/erts/emulator/hipe/hipe_mkliterals.c
+++ b/erts/emulator/hipe/hipe_mkliterals.c
@@ -587,9 +587,9 @@ static void print_params(FILE *fp, void (*print_param)(FILE*,const struct rts_pa
(*print_param)(fp, &rts_params[i]);
}
-static int do_c(FILE *fp)
+static int do_c(FILE *fp, const char* this_exe)
{
- fprintf(fp, "/* File: hipe_literals.h, generated by hipe_mkliterals */\n");
+ fprintf(fp, "/* File: hipe_literals.h, generated by %s */\n", this_exe);
fprintf(fp, "#ifndef __HIPE_LITERALS_H__\n");
fprintf(fp, "#define __HIPE_LITERALS_H__\n\n");
print_literals(fp, c_define_literal);
@@ -603,9 +603,9 @@ static int do_c(FILE *fp)
return 0;
}
-static int do_e(FILE *fp)
+static int do_e(FILE *fp, const char* this_exe)
{
- fprintf(fp, "%%%% File: hipe_literals.hrl, generated by hipe_mkliterals");
+ fprintf(fp, "%%%% File: hipe_literals.hrl, generated by %s", this_exe);
fprintf(fp, "\n\n");
print_literals(fp, e_define_literal);
fprintf(fp, "\n");
@@ -622,9 +622,9 @@ int main(int argc, const char **argv)
compute_crc();
if (argc == 2) {
if (strcmp(argv[1], "-c") == 0)
- return do_c(stdout);
+ return do_c(stdout, argv[0]);
if (strcmp(argv[1], "-e") == 0)
- return do_e(stdout);
+ return do_e(stdout, argv[0]);
}
fprintf(stderr, "usage: %s [-c | -e] > output-file\n", argv[0]);
return 1;
diff --git a/erts/emulator/sys/common/erl_check_io.c b/erts/emulator/sys/common/erl_check_io.c
index 218bd79584..71b374527e 100644
--- a/erts/emulator/sys/common/erl_check_io.c
+++ b/erts/emulator/sys/common/erl_check_io.c
@@ -1137,6 +1137,11 @@ ERTS_CIO_EXPORT(erts_check_io)(int do_wait)
restart:
+#ifdef ERTS_BREAK_REQUESTED
+ if (ERTS_BREAK_REQUESTED)
+ erts_do_break_handling();
+#endif
+
/* Figure out timeout value */
if (do_wait) {
erts_time_remaining(&wait_time);
diff --git a/erts/emulator/sys/common/erl_mseg.c b/erts/emulator/sys/common/erl_mseg.c
index ffa3a6328c..eaef6680dd 100644
--- a/erts/emulator/sys/common/erl_mseg.c
+++ b/erts/emulator/sys/common/erl_mseg.c
@@ -134,7 +134,16 @@ static int mmap_fd;
#define CAN_PARTLY_DESTROY 0
#endif
-static const ErtsMsegOpt_t default_opt = ERTS_MSEG_DEFAULT_OPT_INITIALIZER;
+const ErtsMsegOpt_t erts_mseg_default_opt = {
+ 1, /* Use cache */
+ 1, /* Preserv data */
+ 0, /* Absolute shrink threshold */
+ 0 /* Relative shrink threshold */
+#if HALFWORD_HEAP
+ ,0 /* need low memory */
+#endif
+};
+
typedef struct cache_desc_t_ {
void *seg;
@@ -605,18 +614,10 @@ mseg_clear_cache(MemKind* mk)
INC_CC(clear_cache);
}
-static ERTS_INLINE MemKind* type2mk(ErtsAlcType_t atype)
+static ERTS_INLINE MemKind* memkind(const ErtsMsegOpt_t *opt)
{
#if HALFWORD_HEAP
- switch (atype) {
- case ERTS_ALC_A_ETS:
- case ERTS_ALC_A_BINARY:
- case ERTS_ALC_A_FIXED_SIZE:
- case ERTS_ALC_A_DRIVER:
- return &hi_mem;
- default:
- return &low_mem;
- }
+ return opt->low_mem ? &low_mem : &hi_mem;
#else
return &the_mem;
#endif
@@ -628,7 +629,7 @@ mseg_alloc(ErtsAlcType_t atype, Uint *size_p, const ErtsMsegOpt_t *opt)
Uint max, min, diff_size, size;
cache_desc_t *cd, *cand_cd;
void *seg;
- MemKind* mk = type2mk(atype);
+ MemKind* mk = memkind(opt);
INC_CC(alloc);
@@ -742,7 +743,7 @@ static void
mseg_dealloc(ErtsAlcType_t atype, void *seg, Uint size,
const ErtsMsegOpt_t *opt)
{
- MemKind* mk = type2mk(atype);
+ MemKind* mk = memkind(opt);
cache_desc_t *cd;
ERTS_MSEG_DEALLOC_STAT(mk,size);
@@ -800,7 +801,7 @@ static void *
mseg_realloc(ErtsAlcType_t atype, void *seg, Uint old_size, Uint *new_size_p,
const ErtsMsegOpt_t *opt)
{
- MemKind* mk = type2mk(atype);
+ MemKind* mk = memkind(opt);
void *new_seg;
Uint new_size;
@@ -1372,7 +1373,7 @@ erts_mseg_alloc_opt(ErtsAlcType_t atype, Uint *size_p, const ErtsMsegOpt_t *opt)
void *
erts_mseg_alloc(ErtsAlcType_t atype, Uint *size_p)
{
- return erts_mseg_alloc_opt(atype, size_p, &default_opt);
+ return erts_mseg_alloc_opt(atype, size_p, &erts_mseg_default_opt);
}
void
@@ -1387,7 +1388,7 @@ erts_mseg_dealloc_opt(ErtsAlcType_t atype, void *seg, Uint size,
void
erts_mseg_dealloc(ErtsAlcType_t atype, void *seg, Uint size)
{
- erts_mseg_dealloc_opt(atype, seg, size, &default_opt);
+ erts_mseg_dealloc_opt(atype, seg, size, &erts_mseg_default_opt);
}
void *
@@ -1405,7 +1406,7 @@ void *
erts_mseg_realloc(ErtsAlcType_t atype, void *seg, Uint old_size,
Uint *new_size_p)
{
- return erts_mseg_realloc_opt(atype, seg, old_size, new_size_p, &default_opt);
+ return erts_mseg_realloc_opt(atype, seg, old_size, new_size_p, &erts_mseg_default_opt);
}
void
diff --git a/erts/emulator/sys/common/erl_mseg.h b/erts/emulator/sys/common/erl_mseg.h
index d8053eb0d9..fbb66ee33b 100644
--- a/erts/emulator/sys/common/erl_mseg.h
+++ b/erts/emulator/sys/common/erl_mseg.h
@@ -60,15 +60,12 @@ typedef struct {
int preserv;
UWord abs_shrink_th;
UWord rel_shrink_th;
+#if HALFWORD_HEAP
+ int low_mem;
+#endif
} ErtsMsegOpt_t;
-#define ERTS_MSEG_DEFAULT_OPT_INITIALIZER \
-{ \
- 1, /* Use cache */ \
- 1, /* Preserv data */ \
- 0, /* Absolute shrink threshold */ \
- 0 /* Relative shrink threshold */ \
-}
+extern const ErtsMsegOpt_t erts_mseg_default_opt;
void *erts_mseg_alloc(ErtsAlcType_t, Uint *);
void *erts_mseg_alloc_opt(ErtsAlcType_t, Uint *, const ErtsMsegOpt_t *);
diff --git a/erts/emulator/sys/common/erl_poll.c b/erts/emulator/sys/common/erl_poll.c
index 3ae5b8d747..f5c785d683 100644
--- a/erts/emulator/sys/common/erl_poll.c
+++ b/erts/emulator/sys/common/erl_poll.c
@@ -766,7 +766,7 @@ write_batch_buf(ErtsPollSet ps, ErtsPollBatchBuf *bbp)
short filter;
int fd = (int) ebuf[i].ident;
- switch ((int) ebuf[i].udata) {
+ switch ((int) (long) ebuf[i].udata) {
/*
* Since we use a lazy update approach EV_DELETE will
@@ -805,7 +805,7 @@ write_batch_buf(ErtsPollSet ps, ErtsPollBatchBuf *bbp)
if (fd == (int) ebuf[j].ident) {
ebuf[j].udata = (void *) ERTS_POLL_KQ_OP_HANDLED;
if (!(ebuf[j].flags & EV_ERROR)) {
- switch ((int) ebuf[j].udata) {
+ switch ((int) (long) ebuf[j].udata) {
case ERTS_POLL_KQ_OP_ADD2_W:
filter = EVFILT_WRITE;
goto rm_add_fb;
@@ -823,7 +823,8 @@ write_batch_buf(ErtsPollSet ps, ErtsPollBatchBuf *bbp)
}
}
/* The other add succeded... */
- filter = (((int) ebuf[i].udata == ERTS_POLL_KQ_OP_ADD2_W)
+ filter = ((((int) (long) ebuf[i].udata)
+ == ERTS_POLL_KQ_OP_ADD2_W)
? EVFILT_READ
: EVFILT_WRITE);
rm_add_fb:
diff --git a/erts/emulator/sys/win32/erl_poll.c b/erts/emulator/sys/win32/erl_poll.c
index 7662f190ef..074e2e247f 100644
--- a/erts/emulator/sys/win32/erl_poll.c
+++ b/erts/emulator/sys/win32/erl_poll.c
@@ -693,6 +693,7 @@ static void *break_waiter(void *param)
ResetEvent(harr[0]);
erts_mtx_lock(&break_waiter_lock);
erts_atomic32_set(&break_waiter_state,BREAK_WAITER_GOT_BREAK);
+ ERTS_THR_MEMORY_BARRIER;
SetEvent(break_happened_event);
erts_mtx_unlock(&break_waiter_lock);
break;
@@ -700,6 +701,7 @@ static void *break_waiter(void *param)
ResetEvent(harr[1]);
erts_mtx_lock(&break_waiter_lock);
erts_atomic32_set(&break_waiter_state,BREAK_WAITER_GOT_HALT);
+ ERTS_THR_MEMORY_BARRIER;
SetEvent(break_happened_event);
erts_mtx_unlock(&break_waiter_lock);
break;
diff --git a/erts/emulator/test/binary_SUITE.erl b/erts/emulator/test/binary_SUITE.erl
index 7e409f053e..4e82381fba 100644
--- a/erts/emulator/test/binary_SUITE.erl
+++ b/erts/emulator/test/binary_SUITE.erl
@@ -23,12 +23,12 @@
%% Tests binaries and the BIFs:
%% list_to_binary/1
%% iolist_to_binary/1
-%% bitstr_to_list/1
+%% list_to_bitstring/1
%% binary_to_list/1
%% binary_to_list/3
%% binary_to_term/1
%% binary_to_term/2
-%% bitstr_to_list/1
+%% bitstring_to_list/1
%% term_to_binary/1
%% erlang:external_size/1
%% size(Binary)
@@ -275,12 +275,33 @@ bad_list_to_binary(Config) when is_list(Config) ->
?line test_bad_bin(fun(X, Y) -> X*Y end),
?line test_bad_bin([1,fun(X) -> X + 1 end,2|fun() -> 0 end]),
?line test_bad_bin([fun(X) -> X + 1 end]),
+
+ %% Test iolists that do not fit in the address space.
+ %% Unfortunately, it would be too slow to test in a 64-bit emulator.
+ case erlang:system_info(wordsize) of
+ 4 -> huge_iolists();
+ _ -> ok
+ end.
+
+huge_iolists() ->
+ FourGigs = 1 bsl 32,
+ ?line Sizes = [FourGigs+N || N <- lists:seq(0, 64)] ++
+ [1 bsl N || N <- lists:seq(33, 37)],
+ ?line Base = <<0:(1 bsl 20)/unit:8>>,
+ [begin
+ L = build_iolist(Sz, Base),
+ ?line {'EXIT',{system_limit,_}} = (catch list_to_binary([L])),
+ ?line {'EXIT',{system_limit,_}} = (catch list_to_bitstring([L])),
+ ?line {'EXIT',{system_limit,_}} = (catch binary:list_to_bin([L])),
+ ?line {'EXIT',{system_limit,_}} = (catch iolist_to_binary(L))
+ end || Sz <- Sizes],
ok.
test_bad_bin(List) ->
{'EXIT',{badarg,_}} = (catch list_to_binary(List)),
{'EXIT',{badarg,_}} = (catch iolist_to_binary(List)),
- {'EXIT',{badarg,_}} = (catch list_to_bitstring(List)).
+ {'EXIT',{badarg,_}} = (catch list_to_bitstring(List)),
+ {'EXIT',{badarg,_}} = (catch iolist_size(List)).
bad_binary_to_list(doc) -> "Tries binary_to_list/1,3 with bad arguments.";
bad_binary_to_list(Config) when is_list(Config) ->
@@ -516,18 +537,65 @@ external_size_1(Term, Size0, Limit) when Size0 < Limit ->
external_size_1(_, _, _) -> ok.
t_iolist_size(Config) when is_list(Config) ->
- %% Build a term whose external size only fits in a big num (on 32-bit CPU).
- Bin = iolist_to_binary(lists:seq(0, 254)),
- ?line ok = t_iolist_size_1(Bin, 0, 16#7FFFFFFF),
- ?line ok = t_iolist_size_1(make_unaligned_sub_binary(Bin), 0, 16#7FFFFFFF).
+ ?line Seed = now(),
+ ?line io:format("Seed: ~p", [Seed]),
+ ?line random:seed(Seed),
+ ?line Base = <<0:(1 bsl 20)/unit:8>>,
+ ?line Powers = [1 bsl N || N <- lists:seq(2, 37)],
+ ?line Sizes0 = [[N - random:uniform(N div 2),
+ lists:seq(N-2, N+2),
+ N+N div 2,
+ N + random:uniform(N div 2)] ||
+ N <- Powers],
+ %% Test sizes around 1^32 more thoroughly.
+ FourGigs = 1 bsl 32,
+ ?line Sizes1 = [FourGigs+N || N <- lists:seq(-8, 40)] ++ Sizes0,
+ ?line Sizes2 = lists:flatten(Sizes1),
+ ?line Sizes = lists:usort(Sizes2),
+ io:format("~p sizes:", [length(Sizes)]),
+ io:format("~p\n", [Sizes]),
+ ?line [Sz = iolist_size(build_iolist(Sz, Base)) || Sz <- Sizes],
+ ok.
-t_iolist_size_1(IOList, Size0, Limit) when Size0 < Limit ->
- case iolist_size(IOList) of
- Size when is_integer(Size), Size0 < Size ->
- io:format("~p", [Size]),
- t_iolist_size_1([IOList|IOList], Size, Limit)
+build_iolist(N, Base) when N < 16 ->
+ case random:uniform(3) of
+ 1 ->
+ <<Bin:N/binary,_/binary>> = Base,
+ Bin;
+ _ ->
+ lists:seq(1, N)
+ end;
+build_iolist(N, Base) when N =< byte_size(Base) ->
+ case random:uniform(3) of
+ 1 ->
+ <<Bin:N/binary,_/binary>> = Base,
+ Bin;
+ 2 ->
+ <<Bin:N/binary,_/binary>> = Base,
+ [Bin];
+ 3 ->
+ case N rem 2 of
+ 0 ->
+ L = build_iolist(N div 2, Base),
+ [L,L];
+ 1 ->
+ L = build_iolist(N div 2, Base),
+ [L,L,45]
+ end
end;
-t_iolist_size_1(_, _, _) -> ok.
+build_iolist(N0, Base) ->
+ Small = random:uniform(15),
+ Seq = lists:seq(1, Small),
+ N = N0 - Small,
+ case N rem 2 of
+ 0 ->
+ L = build_iolist(N div 2, Base),
+ [L,L|Seq];
+ 1 ->
+ L = build_iolist(N div 2, Base),
+ [47,L,L|Seq]
+ end.
+
bad_binary_to_term_2(doc) -> "OTP-4053.";
bad_binary_to_term_2(suite) -> [];
@@ -1183,34 +1251,7 @@ deep(Config) when is_list(Config) ->
deep_roundtrip(T) ->
B = term_to_binary(T),
- true = deep_eq(T, binary_to_term(B)).
-
-%%
-%% FIXME: =:= runs out of stack.
-%%
-deep_eq([H1|T1], [H2|T2]) ->
- deep_eq(H1, H2) andalso deep_eq(T1, T2);
-deep_eq(T1, T2) when tuple_size(T1) =:= tuple_size(T2) ->
- deep_eq_tup(T1, T2, tuple_size(T1));
-deep_eq(T1, T2) when is_function(T1), is_function(T2) ->
- {uniq,U1} = erlang:fun_info(T1, uniq),
- {index,I1} = erlang:fun_info(T1, index),
- {arity,A1} = erlang:fun_info(T1, arity),
- {env,E1} = erlang:fun_info(T1, env),
- {uniq,U2} = erlang:fun_info(T2, uniq),
- {index,I2} = erlang:fun_info(T2, index),
- {arity,A2} = erlang:fun_info(T2, arity),
- {env,E2} = erlang:fun_info(T2, env),
- U1 =:= U2 andalso I1 =:= I2 andalso A1 =:= A2 andalso
- deep_eq(E1, E2);
-deep_eq(T1, T2) ->
- T1 =:= T2.
-
-deep_eq_tup(_T1, _T2, 0) ->
- true;
-deep_eq_tup(T1, T2, N) ->
- deep_eq(element(N, T1), element(N, T2)) andalso
- deep_eq_tup(T1, T2, N-1).
+ T = binary_to_term(B).
obsolete_funs(Config) when is_list(Config) ->
erts_debug:set_internal_state(available_internal_state, true),
diff --git a/erts/emulator/test/code_SUITE.erl b/erts/emulator/test/code_SUITE.erl
index c1a048be75..a062cea117 100644
--- a/erts/emulator/test/code_SUITE.erl
+++ b/erts/emulator/test/code_SUITE.erl
@@ -498,7 +498,9 @@ do_false_dependency(Init, Code) ->
?line unlink(Pid), exit(Pid, kill),
?line true = erlang:purge_module(cpbugx),
?line true = erlang:delete_module(cpbugx),
+ ?line code:is_module_native(cpbugx), % test is_module_native on deleted code
?line true = erlang:purge_module(cpbugx),
+ ?line code:is_module_native(cpbugx), % test is_module_native on purged code
ok.
false_dependency_loop(Parent, Init, SendInitAck) ->
diff --git a/erts/emulator/test/driver_SUITE.erl b/erts/emulator/test/driver_SUITE.erl
index 7600a44988..f6cf01ce16 100644
--- a/erts/emulator/test/driver_SUITE.erl
+++ b/erts/emulator/test/driver_SUITE.erl
@@ -38,7 +38,7 @@
timer_change/1,
timer_delay/1,
queue_echo/1,
- fun_to_port/1,
+ outputv_errors/1,
driver_unloaded/1,
io_ready_exit/1,
use_fallback_pollset/1,
@@ -74,7 +74,8 @@
missing_callbacks/1,
smp_select/1,
driver_select_use/1,
- thread_mseg_alloc_cache_clean/1]).
+ thread_mseg_alloc_cache_clean/1,
+ otp_9302/1]).
-export([bin_prefix/2]).
@@ -129,7 +130,7 @@ end_per_testcase(Case, Config) ->
suite() -> [{ct_hooks,[ts_install_cth]}].
all() ->
- [fun_to_port, outputv_echo, queue_echo, {group, timer},
+ [outputv_errors, outputv_echo, queue_echo, {group, timer},
driver_unloaded, io_ready_exit, use_fallback_pollset,
bad_fd_in_pollset, driver_event, fd_change,
steal_control, otp_6602, 'driver_system_info_ver1.0',
@@ -141,7 +142,8 @@ all() ->
smaller_minor_vsn_drv, peek_non_existing_queue,
otp_6879, caller, many_events, missing_callbacks,
smp_select, driver_select_use,
- thread_mseg_alloc_cache_clean].
+ thread_mseg_alloc_cache_clean,
+ otp_9302].
groups() ->
[{timer, [],
@@ -165,37 +167,89 @@ init_per_group(_GroupName, Config) ->
end_per_group(_GroupName, Config) ->
Config.
-
-fun_to_port(doc) -> "Test sending a fun to port with an outputv-capable driver.";
-fun_to_port(Config) when is_list(Config) ->
+outputv_errors(doc) -> "Test sending bad types to port with an outputv-capable driver.";
+outputv_errors(Config) when is_list(Config) ->
?line Path = ?config(data_dir, Config),
?line erl_ddll:start(),
?line ok = load_driver(Path, outputv_drv),
- ?line fun_to_port_1(fun() -> 33 end),
- ?line fun_to_port_1([fun() -> 42 end]),
- ?line fun_to_port_1([1|fun() -> 42 end]),
- L = build_io_list(65536),
- ?line fun_to_port_1([L,fun() -> 42 end]),
- ?line fun_to_port_1([L|fun() -> 42 end]),
+ outputv_bad_types(fun(T) ->
+ ?line outputv_errors_1(T),
+ ?line outputv_errors_1([1|T]),
+ ?line L = [1,2,3],
+ ?line outputv_errors_1([L,T]),
+ ?line outputv_errors_1([L|T])
+ end),
+ outputv_errors_1(42),
+
+ %% Test iolists that do not fit in the address space.
+ %% Unfortunately, it would be too slow to test in a 64-bit emulator.
+ case erlang:system_info(wordsize) of
+ 4 -> outputv_huge_iolists();
+ _ -> ok
+ end.
+
+outputv_bad_types(Test) ->
+ Types = [-1,256,atom,42.0,{a,b,c},make_ref(),fun() -> 42 end,
+ [1|2],<<1:1>>,<<1:9>>,<<1:15>>],
+ _ = [Test(Type) || Type <- Types],
+ ok.
+
+outputv_huge_iolists() ->
+ FourGigs = 1 bsl 32,
+ ?line Sizes = [FourGigs+N || N <- lists:seq(0, 64)] ++
+ [1 bsl N || N <- lists:seq(33, 37)],
+ ?line Base = <<0:(1 bsl 20)/unit:8>>,
+ [begin
+ ?line L = build_iolist(Sz, Base),
+ ?line outputv_errors_1(L)
+ end || Sz <- Sizes],
ok.
-fun_to_port_1(Term) ->
- Port = open_port({spawn,outputv_drv}, []),
+outputv_errors_1(Term) ->
+ Port = open_port({spawn_driver,outputv_drv}, []),
{'EXIT',{badarg,_}} = (catch port_command(Port, Term)),
port_close(Port).
-build_io_list(0) -> [];
-build_io_list(1) -> [7];
-build_io_list(N) ->
- L = build_io_list(N div 2),
+build_iolist(N, Base) when N < 16 ->
+ case random:uniform(3) of
+ 1 ->
+ <<Bin:N/binary,_/binary>> = Base,
+ Bin;
+ _ ->
+ lists:seq(1, N)
+ end;
+build_iolist(N, Base) when N =< byte_size(Base) ->
+ case random:uniform(3) of
+ 1 ->
+ <<Bin:N/binary,_/binary>> = Base,
+ Bin;
+ 2 ->
+ <<Bin:N/binary,_/binary>> = Base,
+ [Bin];
+ 3 ->
+ case N rem 2 of
+ 0 ->
+ L = build_iolist(N div 2, Base),
+ [L,L];
+ 1 ->
+ L = build_iolist(N div 2, Base),
+ [L,L,45]
+ end
+ end;
+build_iolist(N0, Base) ->
+ Small = random:uniform(15),
+ Seq = lists:seq(1, Small),
+ N = N0 - Small,
case N rem 2 of
- 0 -> [L|L];
- 1 -> [7,L|L]
+ 0 ->
+ L = build_iolist(N div 2, Base),
+ [L,L|Seq];
+ 1 ->
+ L = build_iolist(N div 2, Base),
+ [47,L,L|Seq]
end.
-
-
outputv_echo(doc) -> ["Test echoing data with a driver that supports outputv."];
outputv_echo(Config) when is_list(Config) ->
?line Dog = test_server:timetrap(test_server:minutes(10)),
@@ -1838,13 +1892,39 @@ thread_mseg_alloc_cache_clean_test(Port, N, CCI, Size) ->
?line ?t:format("CCC = ~p~n", [CCC]),
?line true = CCC > OCCC,
?line thread_mseg_alloc_cache_clean_test(Port, N-1, CCI, Size).
-
-
+
+otp_9302(Config) when is_list(Config) ->
+ ?line Path = ?config(data_dir, Config),
+ ?line erl_ddll:start(),
+ ?line ok = load_driver(Path, otp_9302_drv),
+ ?line Port = open_port({spawn, otp_9302_drv}, []),
+ ?line true = is_port(Port),
+ ?line port_command(Port, ""),
+ ?line {msg, block} = get_port_msg(Port, infinity),
+ ?line {msg, job} = get_port_msg(Port, infinity),
+ ?line case erlang:system_info(thread_pool_size) of
+ 0 ->
+ {msg, cancel} = get_port_msg(Port, infinity);
+ _ ->
+ ok
+ end,
+ ?line {msg, job} = get_port_msg(Port, infinity),
+ ?line {msg, end_of_jobs} = get_port_msg(Port, infinity),
+ ?line no_msg = get_port_msg(Port, 2000),
+ ?line port_close(Port),
+ ?line ok.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Utilities
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
+
+get_port_msg(Port, Timeout) ->
+ receive
+ {Port, What} ->
+ {msg, What}
+ after Timeout ->
+ no_msg
+ end.
wait_until(Fun) ->
case Fun() of
diff --git a/erts/emulator/test/driver_SUITE_data/Makefile.src b/erts/emulator/test/driver_SUITE_data/Makefile.src
index 4ac7987d2f..5b3ba1557e 100644
--- a/erts/emulator/test/driver_SUITE_data/Makefile.src
+++ b/erts/emulator/test/driver_SUITE_data/Makefile.src
@@ -11,7 +11,8 @@ MISC_DRVS = outputv_drv@dll@ \
caller_drv@dll@ \
many_events_drv@dll@ \
missing_callback_drv@dll@ \
- thr_alloc_drv@dll@
+ thr_alloc_drv@dll@ \
+ otp_9302_drv@dll@
SYS_INFO_DRVS = sys_info_1_0_drv@dll@ \
sys_info_1_1_drv@dll@ \
diff --git a/erts/emulator/test/driver_SUITE_data/otp_9302_drv.c b/erts/emulator/test/driver_SUITE_data/otp_9302_drv.c
new file mode 100644
index 0000000000..1147549135
--- /dev/null
+++ b/erts/emulator/test/driver_SUITE_data/otp_9302_drv.c
@@ -0,0 +1,137 @@
+/*
+ * %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%
+ */
+#ifdef __WIN32__
+#include <windows.h>
+#endif
+#include "erl_driver.h"
+
+static ErlDrvData start(ErlDrvPort port,
+ char *command);
+static void output(ErlDrvData drv_data,
+ char *buf, int len);
+static void ready_async(ErlDrvData drv_data,
+ ErlDrvThreadData thread_data);
+
+static ErlDrvEntry otp_9302_drv_entry = {
+ NULL /* init */,
+ start,
+ NULL /* stop */,
+ output,
+ NULL /* ready_input */,
+ NULL /* ready_output */,
+ "otp_9302_drv",
+ NULL /* finish */,
+ NULL /* handle */,
+ NULL /* control */,
+ NULL /* timeout */,
+ NULL /* outputv */,
+ ready_async,
+ NULL /* flush */,
+ NULL /* call */,
+ NULL /* event */,
+ ERL_DRV_EXTENDED_MARKER,
+ ERL_DRV_EXTENDED_MAJOR_VERSION,
+ ERL_DRV_EXTENDED_MINOR_VERSION,
+ ERL_DRV_FLAG_USE_PORT_LOCKING,
+ NULL /* handle2 */,
+ NULL /* handle_monitor */
+};
+
+DRIVER_INIT(otp_9302_drv)
+{
+ return &otp_9302_drv_entry;
+}
+
+static ErlDrvData start(ErlDrvPort port,
+ char *command)
+{
+ return (ErlDrvData) port;
+}
+
+typedef struct {
+ ErlDrvPort port;
+ ErlDrvTermData receiver;
+ int block;
+ int cancel;
+ int eoj;
+} Otp9302AsyncData;
+
+static void async_invoke(void *data)
+{
+ Otp9302AsyncData *adata = (Otp9302AsyncData *) data;
+ char *what = (adata->block
+ ? "block"
+ : (adata->cancel
+ ? "cancel"
+ : (adata->eoj
+ ? "end_of_jobs"
+ : "job")));
+ ErlDrvTermData spec[] = {
+ ERL_DRV_PORT, driver_mk_port(adata->port),
+ ERL_DRV_ATOM, driver_mk_atom(what),
+ ERL_DRV_TUPLE, 2
+ };
+ driver_send_term(adata->port, adata->receiver,
+ spec, sizeof(spec)/sizeof(spec[0]));
+ if (adata->block) {
+#ifdef __WIN32__
+ Sleep((DWORD) 2000);
+#else
+ sleep(2);
+#endif
+ }
+}
+
+static void output(ErlDrvData drv_data,
+ char *buf, int len)
+{
+ ErlDrvPort port = (ErlDrvPort) drv_data;
+ ErlDrvTermData caller = driver_caller(port);
+ unsigned int key = (unsigned int) port;
+ long id[5];
+ Otp9302AsyncData *ad[5];
+ int i;
+
+ for (i = 0; i < sizeof(ad)/sizeof(ad[0]); i++) {
+ ad[i] = driver_alloc(sizeof(Otp9302AsyncData));
+ if (!ad[i])
+ abort();
+
+ ad[i]->port = port;
+ ad[i]->receiver = caller;
+ ad[i]->block = 0;
+ ad[i]->eoj = 0;
+ ad[i]->cancel = 0;
+ }
+ ad[0]->block = 1;
+ ad[2]->cancel = 1;
+ ad[4]->eoj = 1;
+ for (i = 0; i < sizeof(id)/sizeof(id[0]); i++)
+ id[i] = driver_async(port, &key, async_invoke, ad[i], driver_free);
+ if (id[2] > 0)
+ driver_async_cancel(id[2]);
+}
+
+static void ready_async(ErlDrvData drv_data,
+ ErlDrvThreadData thread_data)
+{
+ if ((void *) thread_data)
+ driver_free((void *) thread_data);
+}
+
diff --git a/erts/etc/common/erlexec.c b/erts/etc/common/erlexec.c
index 60b3af7db7..90d3be9448 100644
--- a/erts/etc/common/erlexec.c
+++ b/erts/etc/common/erlexec.c
@@ -394,6 +394,7 @@ int main(int argc, char **argv)
int print_args_exit = 0;
int print_qouted_cmd_exit = 0;
erts_cpu_info_t *cpuinfo = NULL;
+ char* emu_name;
#ifdef __WIN32__
this_module_handle = module;
@@ -566,6 +567,7 @@ int main(int argc, char **argv)
usage("+MYm");
}
emu = add_extra_suffixes(emu, emu_type);
+ emu_name = strsave(emu);
erts_snprintf(tmpStr, sizeof(tmpStr), "%s" DIRSEP "%s" BINARY_EXT, bindir, emu);
emu = strsave(tmpStr);
@@ -682,6 +684,9 @@ int main(int argc, char **argv)
verbose = 1;
} else if (strcmp(argv[i], "-emu_args_exit") == 0) {
print_args_exit = 1;
+ } else if (strcmp(argv[i], "-emu_name_exit") == 0) {
+ printf("%s\n", emu_name);
+ exit(0);
} else if (strcmp(argv[i], "-emu_qouted_cmd_exit") == 0) {
print_qouted_cmd_exit = 1;
} else if (strcmp(argv[i], "-env") == 0) { /* -env VARNAME VARVALUE */
@@ -1970,6 +1975,11 @@ initial_argv_massage(int *argc, char ***argv)
*/
vix = 0;
+
+ av = build_args_from_env("ERL_" OTP_SYSTEM_VERSION "_FLAGS");
+ if (av)
+ avv[vix++].argv = av;
+
av = build_args_from_env("ERL_AFLAGS");
if (av)
avv[vix++].argv = av;
@@ -1984,10 +1994,6 @@ initial_argv_massage(int *argc, char ***argv)
if (av)
avv[vix++].argv = av;
- av = build_args_from_env("ERL_" OTP_SYSTEM_VERSION "_FLAGS");
- if (av)
- avv[vix++].argv = av;
-
av = build_args_from_env("ERL_ZFLAGS");
if (av)
avv[vix++].argv = av;
diff --git a/erts/etc/unix/cerl.src b/erts/etc/unix/cerl.src
index 0355f2629f..0b2d6512ea 100644
--- a/erts/etc/unix/cerl.src
+++ b/erts/etc/unix/cerl.src
@@ -62,13 +62,21 @@ cxargs_add() {
done
}
+eeargs=
+eeargs_add() {
+ while [ $# -gt 0 ]; do
+ cargs="$cargs $1"
+ eeargs="$eeargs $1"
+ shift
+ done
+}
+
core=
GDB=
GDBBP=
GDBARGS=
TYPE=
-EMU_TYPE=
debug=
run_valgrind=no
@@ -127,34 +135,37 @@ while [ $# -gt 0 ]; do
;;
"-smp")
shift
- cargs="$cargs -smp"
- EMU_TYPE=.smp
+ if [ $# -le 0 ]; then
+ eeargs_add -smp
+ else
+ case $1 in
+ disable)
+ shift
+ eeargs_add -smpdisable
+ ;;
+ enable)
+ shift
+ eeargs_add -smp
+ ;;
+ *)
+ eeargs_add -smp
+ esac
+ fi
+ ;;
+ "-smpdisable")
+ shift
+ eeargs_add -smpdisable
;;
"-lcnt")
shift
cargs="$cargs -lcnt"
TYPE=.lcnt
;;
- "-frag")
- shift
- cargs="$cargs -frag"
- EMU_TYPE=.frag
- ;;
- "-smp_frag")
- shift
- cargs="$cargs -smp_frag"
- EMU_TYPE=.smp_frag
- ;;
"-gprof")
shift
cargs="$cargs -gprof"
TYPE=.gprof
;;
- "-hybrid")
- shift
- cargs="$cargs -hybrid"
- EMU_TYPE=.hybrid
- ;;
"-debug")
shift
cargs="$cargs -debug"
@@ -180,11 +191,6 @@ while [ $# -gt 0 ]; do
# shift
# GDB=xxgdb
# ;;
- "-shared")
- shift
- cargs="$cargs -shared"
- TYPE=.shared
- ;;
"-purify")
shift
cargs="$cargs -purify"
@@ -222,7 +228,9 @@ PATH=$BINDIR:$ROOTDIR/bin:$PATH
EXEC=$BINDIR/erlexec
PROGNAME="$PROGNAME $cargs"
-EMU=$EMU$TYPE$EMU_TYPE
+EMU="$EMU$TYPE"
+EMU_NAME=`$EXEC -emu_name_exit $eeargs`
+
if [ $run_valgrind != yes ]; then
xargs="$xargs -pz $PRELOADED --"
fi
@@ -248,9 +256,9 @@ if [ "x$GDB" = "x" ]; then
valgrind_log=
else
if [ $valmajor -gt 2 -a $valminor -gt 4 ]; then
- valgrind_log="$log_file_prefix$VALGRIND_LOG_DIR/$VALGRIND_LOGFILE_PREFIX$VALGRIND_LOGFILE_INFIX$EMU.log.$$"
+ valgrind_log="$log_file_prefix$VALGRIND_LOG_DIR/$VALGRIND_LOGFILE_PREFIX$VALGRIND_LOGFILE_INFIX$EMU_NAME.log.$$"
else
- valgrind_log="$log_file_prefix$VALGRIND_LOG_DIR/$VALGRIND_LOGFILE_PREFIX$VALGRIND_LOGFILE_INFIX$EMU.log"
+ valgrind_log="$log_file_prefix$VALGRIND_LOG_DIR/$VALGRIND_LOGFILE_PREFIX$VALGRIND_LOGFILE_INFIX$EMU_NAME.log"
fi
fi
if [ "x$VALGRIND_MISC_FLAGS" = "x" ]; then
@@ -263,9 +271,9 @@ if [ "x$GDB" = "x" ]; then
early_beam_args=`echo $beam_args | sed "s|^\(.*-progname\).*$|\1|g"`
late_beam_args=`echo $beam_args | sed "s|^$pre_beam_args.*\(-- -home.*\)$|\1|g"`
- exec valgrind $valgrind_xml $valgrind_log $valgrind_misc_flags $BINDIR/$EMU $emu_xargs $early_beam_args "$PROGNAME" $late_beam_args -pz $PRELOADED
+ exec valgrind $valgrind_xml $valgrind_log $valgrind_misc_flags $BINDIR/$EMU_NAME $emu_xargs $early_beam_args "$PROGNAME" $late_beam_args -pz $PRELOADED
else
- exec $EXEC $xargs ${1+"$@"}
+ exec $EXEC $eeargs $xargs ${1+"$@"}
fi
else
if [ "x$EMACS" = "x" ]; then
@@ -300,5 +308,5 @@ else
(insert-string \"source $ROOTDIR/erts/etc/unix/etp-commands\") \
(comint-send-input)"
# Fire up gdb in emacs...
- exec $EMACS --eval "(progn (gdb \"gdb $GDBARGS$EMU\") $gdbcmd)"
+ exec $EMACS --eval "(progn (gdb \"gdb $GDBARGS$EMU_NAME\") $gdbcmd)"
fi
diff --git a/erts/include/internal/erl_printf_format.h b/erts/include/internal/erl_printf_format.h
index 45818079ea..400cc7dafd 100644
--- a/erts/include/internal/erl_printf_format.h
+++ b/erts/include/internal/erl_printf_format.h
@@ -40,7 +40,7 @@ extern int erts_printf_ulong(fmtfn_t, void*, char, int, int, unsigned long);
extern int erts_printf_slong(fmtfn_t, void*, char, int, int, signed long);
extern int erts_printf_double(fmtfn_t, void *, char, int, int, double);
-extern int (*erts_printf_eterm_func)(fmtfn_t, void*, unsigned long, long);
+extern int (*erts_printf_eterm_func)(fmtfn_t, void*, unsigned long, long, unsigned long*);
#endif
diff --git a/erts/include/internal/libatomic_ops/ethr_atomic.h b/erts/include/internal/libatomic_ops/ethr_atomic.h
index d56693dbf8..2fc82c99a8 100644
--- a/erts/include/internal/libatomic_ops/ethr_atomic.h
+++ b/erts/include/internal/libatomic_ops/ethr_atomic.h
@@ -146,13 +146,13 @@ ETHR_NATMC_FUNC__(read)(ETHR_ATMC_T__ *var)
static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(add_return)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ incr)
{
-#ifdef AO_HAVE_fetch_and_add
- return ((ETHR_AINT_T__) AO_fetch_and_add(&var->counter, (AO_t) incr)) + incr;
+#ifdef AO_HAVE_fetch_and_add_full
+ return ((ETHR_AINT_T__) AO_fetch_and_add_full(&var->counter, (AO_t) incr)) + incr;
#else
while (1) {
AO_t exp = AO_load(&var->counter);
AO_t new = exp + (AO_t) incr;
- if (AO_compare_and_swap(&var->counter, exp, new))
+ if (AO_compare_and_swap_full(&var->counter, exp, new))
return (ETHR_AINT_T__) new;
}
#endif
@@ -167,8 +167,8 @@ ETHR_NATMC_FUNC__(add)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ incr)
static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(inc_return)(ETHR_ATMC_T__ *var)
{
-#ifdef AO_HAVE_fetch_and_add1
- return ((ETHR_AINT_T__) AO_fetch_and_add1(&var->counter)) + 1;
+#ifdef AO_HAVE_fetch_and_add1_full
+ return ((ETHR_AINT_T__) AO_fetch_and_add1_full(&var->counter)) + 1;
#else
return ETHR_NATMC_FUNC__(add_return)(var, 1);
#endif
@@ -183,8 +183,8 @@ ETHR_NATMC_FUNC__(inc)(ETHR_ATMC_T__ *var)
static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(dec_return)(ETHR_ATMC_T__ *var)
{
-#ifdef AO_HAVE_fetch_and_sub1
- return ((ETHR_AINT_T__) AO_fetch_and_sub1(&var->counter)) - 1;
+#ifdef AO_HAVE_fetch_and_sub1_full
+ return ((ETHR_AINT_T__) AO_fetch_and_sub1_full(&var->counter)) - 1;
#else
return ETHR_NATMC_FUNC__(add_return)(var, -1);
#endif
@@ -202,7 +202,7 @@ ETHR_NATMC_FUNC__(and_retold)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ mask)
while (1) {
AO_t exp = AO_load(&var->counter);
AO_t new = exp & ((AO_t) mask);
- if (AO_compare_and_swap(&var->counter, exp, new))
+ if (AO_compare_and_swap_full(&var->counter, exp, new))
return (ETHR_AINT_T__) exp;
}
}
@@ -213,7 +213,7 @@ ETHR_NATMC_FUNC__(or_retold)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ mask)
while (1) {
AO_t exp = AO_load(&var->counter);
AO_t new = exp | ((AO_t) mask);
- if (AO_compare_and_swap(&var->counter, exp, new))
+ if (AO_compare_and_swap_full(&var->counter, exp, new))
return (ETHR_AINT_T__) exp;
}
}
@@ -225,7 +225,7 @@ ETHR_NATMC_FUNC__(cmpxchg)(ETHR_ATMC_T__ *var,
{
ETHR_AINT_T__ act;
do {
- if (AO_compare_and_swap(&var->counter, (AO_t) exp, (AO_t) new))
+ if (AO_compare_and_swap_full(&var->counter, (AO_t) exp, (AO_t) new))
return exp;
act = (ETHR_AINT_T__) AO_load(&var->counter);
} while (act == exp);
@@ -237,7 +237,7 @@ ETHR_NATMC_FUNC__(xchg)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ new)
{
while (1) {
AO_t exp = AO_load(&var->counter);
- if (AO_compare_and_swap(&var->counter, exp, (AO_t) new))
+ if (AO_compare_and_swap_full(&var->counter, exp, (AO_t) new))
return (ETHR_AINT_T__) exp;
}
}
@@ -265,7 +265,6 @@ ETHR_NATMC_FUNC__(inc_return_acqb)(ETHR_ATMC_T__ *var)
return ((ETHR_AINT_T__) AO_fetch_and_add1_acquire(&var->counter)) + 1;
#else
ETHR_AINT_T__ res = ETHR_NATMC_FUNC__(add_return)(var, 1);
- ETHR_MEMORY_BARRIER;
return res;
#endif
}
@@ -287,7 +286,6 @@ ETHR_NATMC_FUNC__(dec_return_relb)(ETHR_ATMC_T__ *var)
#ifdef AO_HAVE_fetch_and_sub1_release
return ((ETHR_AINT_T__) AO_fetch_and_sub1_release(&var->counter)) - 1;
#else
- ETHR_MEMORY_BARRIER;
return ETHR_NATMC_FUNC__(dec_return)(var);
#endif
}
@@ -314,7 +312,6 @@ ETHR_NATMC_FUNC__(cmpxchg_acqb)(ETHR_ATMC_T__ *var,
return act;
#else
ETHR_AINT_T__ act = ETHR_NATMC_FUNC__(cmpxchg)(var, new, exp);
- ETHR_MEMORY_BARRIER;
return act;
#endif
}
@@ -333,7 +330,6 @@ ETHR_NATMC_FUNC__(cmpxchg_relb)(ETHR_ATMC_T__ *var,
} while (act == exp);
return act;
#else
- ETHR_MEMORY_BARRIER;
return ETHR_NATMC_FUNC__(cmpxchg)(var, new, exp);
#endif
}
diff --git a/erts/include/internal/sparc32/atomic.h b/erts/include/internal/sparc32/atomic.h
index 00380dbf07..16182f8b01 100644
--- a/erts/include/internal/sparc32/atomic.h
+++ b/erts/include/internal/sparc32/atomic.h
@@ -95,7 +95,7 @@ ETHR_NATMC_FUNC__(add_return)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ incr)
{
ETHR_AINT_T__ old, tmp;
- __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n");
+ __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n" : : : "memory");
do {
old = var->counter;
tmp = old+incr;
@@ -105,7 +105,7 @@ ETHR_NATMC_FUNC__(add_return)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ incr)
: "r"(old), "r"(&var->counter), "0"(tmp)
: "memory");
} while (__builtin_expect(old != tmp, 0));
- __asm__ __volatile__("membar #StoreLoad|#StoreStore");
+ __asm__ __volatile__("membar #StoreLoad|#StoreStore" : : : "memory");
return old+incr;
}
@@ -144,7 +144,7 @@ ETHR_NATMC_FUNC__(and_retold)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ mask)
{
ETHR_AINT_T__ old, tmp;
- __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n");
+ __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n" : : : "memory");
do {
old = var->counter;
tmp = old & mask;
@@ -154,7 +154,7 @@ ETHR_NATMC_FUNC__(and_retold)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ mask)
: "r"(old), "r"(&var->counter), "0"(tmp)
: "memory");
} while (__builtin_expect(old != tmp, 0));
- __asm__ __volatile__("membar #StoreLoad|#StoreStore");
+ __asm__ __volatile__("membar #StoreLoad|#StoreStore" : : : "memory");
return old;
}
@@ -163,7 +163,7 @@ ETHR_NATMC_FUNC__(or_retold)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ mask)
{
ETHR_AINT_T__ old, tmp;
- __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n");
+ __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n" : : : "memory");
do {
old = var->counter;
tmp = old | mask;
@@ -173,7 +173,7 @@ ETHR_NATMC_FUNC__(or_retold)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ mask)
: "r"(old), "r"(&var->counter), "0"(tmp)
: "memory");
} while (__builtin_expect(old != tmp, 0));
- __asm__ __volatile__("membar #StoreLoad|#StoreStore");
+ __asm__ __volatile__("membar #StoreLoad|#StoreStore" : : : "memory");
return old;
}
@@ -182,7 +182,7 @@ ETHR_NATMC_FUNC__(xchg)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ val)
{
ETHR_AINT_T__ old, new;
- __asm__ __volatile__("membar #LoadLoad|#StoreLoad");
+ __asm__ __volatile__("membar #LoadLoad|#StoreLoad" : : : "memory");
do {
old = var->counter;
new = val;
@@ -192,20 +192,20 @@ ETHR_NATMC_FUNC__(xchg)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ val)
: "r"(old), "r"(&var->counter), "0"(new)
: "memory");
} while (__builtin_expect(old != new, 0));
- __asm__ __volatile__("membar #StoreLoad|#StoreStore");
+ __asm__ __volatile__("membar #StoreLoad|#StoreStore" : : : "memory");
return old;
}
static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(cmpxchg)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ new, ETHR_AINT_T__ old)
{
- __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n");
+ __asm__ __volatile__("membar #LoadLoad|#StoreLoad\n" : : : "memory");
__asm__ __volatile__(
ETHR_CAS__ " [%2], %1, %0"
: "=&r"(new)
: "r"(old), "r"(&var->counter), "0"(new)
: "memory");
- __asm__ __volatile__("membar #StoreLoad|#StoreStore");
+ __asm__ __volatile__("membar #StoreLoad|#StoreStore" : : : "memory");
return new;
}
@@ -213,13 +213,11 @@ ETHR_NATMC_FUNC__(cmpxchg)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ new, ETHR_AINT_T__
* Atomic ops with at least specified barriers.
*/
-/* TODO: relax acquire barriers */
-
static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(read_acqb)(ETHR_ATMC_T__ *var)
{
ETHR_AINT_T__ res = ETHR_NATMC_FUNC__(read)(var);
- __asm__ __volatile__("membar #LoadLoad|#LoadStore|#StoreLoad|#StoreStore" : : : "memory");
+ __asm__ __volatile__("membar #LoadLoad|#LoadStore" : : : "memory");
return res;
}
@@ -234,21 +232,18 @@ static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(inc_return_acqb)(ETHR_ATMC_T__ *var)
{
ETHR_AINT_T__ res = ETHR_NATMC_FUNC__(inc_return)(var);
- __asm__ __volatile__("membar #LoadLoad|#LoadStore" : : : "memory");
return res;
}
static ETHR_INLINE void
ETHR_NATMC_FUNC__(dec_relb)(ETHR_ATMC_T__ *var)
{
- __asm__ __volatile__("membar #LoadStore|#StoreStore" : : : "memory");
ETHR_NATMC_FUNC__(dec)(var);
}
static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(dec_return_relb)(ETHR_ATMC_T__ *var)
{
- __asm__ __volatile__("membar #LoadStore|#StoreStore" : : : "memory");
return ETHR_NATMC_FUNC__(dec_return)(var);
}
@@ -256,14 +251,12 @@ static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(cmpxchg_acqb)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ new, ETHR_AINT_T__ old)
{
ETHR_AINT_T__ res = ETHR_NATMC_FUNC__(cmpxchg)(var, new, old);
- __asm__ __volatile__("membar #LoadLoad|#LoadStore" : : : "memory");
return res;
}
static ETHR_INLINE ETHR_AINT_T__
ETHR_NATMC_FUNC__(cmpxchg_relb)(ETHR_ATMC_T__ *var, ETHR_AINT_T__ new, ETHR_AINT_T__ old)
{
- __asm__ __volatile__("membar #LoadStore|#StoreStore" : : : "memory");
return ETHR_NATMC_FUNC__(cmpxchg)(var, new, old);
}
diff --git a/erts/include/internal/tile/atomic.h b/erts/include/internal/tile/atomic.h
index 48e4c0c6c8..0c7b597a6b 100644
--- a/erts/include/internal/tile/atomic.h
+++ b/erts/include/internal/tile/atomic.h
@@ -65,25 +65,35 @@ ethr_native_atomic32_read(ethr_native_atomic32_t *var)
static ETHR_INLINE void
ethr_native_atomic32_add(ethr_native_atomic32_t *var, ethr_sint32_t incr)
{
+ ETHR_MEMORY_BARRIER;
atomic_add(&var->counter, incr);
+ ETHR_MEMORY_BARRIER;
}
static ETHR_INLINE void
ethr_native_atomic32_inc(ethr_native_atomic32_t *var)
{
+ ETHR_MEMORY_BARRIER;
atomic_increment(&var->counter);
+ ETHR_MEMORY_BARRIER;
}
static ETHR_INLINE void
ethr_native_atomic32_dec(ethr_native_atomic32_t *var)
{
+ ETHR_MEMORY_BARRIER;
atomic_decrement(&var->counter);
+ ETHR_MEMORY_BARRIER;
}
static ETHR_INLINE ethr_sint32_t
ethr_native_atomic32_add_return(ethr_native_atomic32_t *var, ethr_sint32_t incr)
{
- return atomic_exchange_and_add(&var->counter, incr) + incr;
+ ethr_sint32_t res;
+ ETHR_MEMORY_BARRIER;
+ res = atomic_exchange_and_add(&var->counter, incr) + incr;
+ ETHR_MEMORY_BARRIER;
+ return res;
}
static ETHR_INLINE ethr_sint32_t
@@ -101,18 +111,27 @@ ethr_native_atomic32_dec_return(ethr_native_atomic32_t *var)
static ETHR_INLINE ethr_sint32_t
ethr_native_atomic32_and_retold(ethr_native_atomic32_t *var, ethr_sint32_t mask)
{
- return atomic_and_val(&var->counter, mask);
+ ethr_sint32_t res;
+ ETHR_MEMORY_BARRIER;
+ res = atomic_and_val(&var->counter, mask);
+ ETHR_MEMORY_BARRIER;
+ return res;
}
static ETHR_INLINE ethr_sint32_t
ethr_native_atomic32_or_retold(ethr_native_atomic32_t *var, ethr_sint32_t mask)
{
- return atomic_or_val(&var->counter, mask);
+ ethr_sint32_t res;
+ ETHR_MEMORY_BARRIER;
+ res = atomic_or_val(&var->counter, mask);
+ ETHR_MEMORY_BARRIER;
+ return res;
}
static ETHR_INLINE ethr_sint32_t
ethr_native_atomic32_xchg(ethr_native_atomic32_t *var, ethr_sint32_t val)
{
+ ETHR_MEMORY_BARRIER;
return atomic_exchange_acq(&var->counter, val);
}
@@ -121,6 +140,7 @@ ethr_native_atomic32_cmpxchg(ethr_native_atomic32_t *var,
ethr_sint32_t new,
ethr_sint32_t expected)
{
+ ETHR_MEMORY_BARRIER;
return atomic_compare_and_exchange_val_acq(&var->counter, new, expected);
}
@@ -139,9 +159,7 @@ ethr_native_atomic32_read_acqb(ethr_native_atomic32_t *var)
static ETHR_INLINE ethr_sint32_t
ethr_native_atomic32_inc_return_acqb(ethr_native_atomic32_t *var)
{
- ethr_sint32_t res = ethr_native_atomic32_inc_return(var);
- ETHR_MEMORY_BARRIER;
- return res;
+ return ethr_native_atomic32_inc_return(var);
}
static ETHR_INLINE void
@@ -154,14 +172,12 @@ ethr_native_atomic32_set_relb(ethr_native_atomic32_t *var, ethr_sint32_t val)
static ETHR_INLINE void
ethr_native_atomic32_dec_relb(ethr_native_atomic32_t *var)
{
- ETHR_MEMORY_BARRIER;
ethr_native_atomic32_dec(var);
}
static ETHR_INLINE ethr_sint32_t
ethr_native_atomic32_dec_return_relb(ethr_native_atomic32_t *var)
{
- ETHR_MEMORY_BARRIER;
return ethr_native_atomic32_dec_return(var);
}
@@ -178,7 +194,6 @@ ethr_native_atomic32_cmpxchg_relb(ethr_native_atomic32_t *var,
ethr_sint32_t new,
ethr_sint32_t exp)
{
- ETHR_MEMORY_BARRIER;
return ethr_native_atomic32_cmpxchg(var, new, exp);
}
diff --git a/erts/lib_src/common/erl_printf_format.c b/erts/lib_src/common/erl_printf_format.c
index 968d563325..fba3fd723c 100644
--- a/erts/lib_src/common/erl_printf_format.c
+++ b/erts/lib_src/common/erl_printf_format.c
@@ -25,7 +25,7 @@
* width: [0-9]+ | '*'
* precision: [0-9]+ | '*'
* length: hh | h | l | ll | L | j | t | b<sz>
- * conversion: d,i | o,u,x,X | e,E | f,F | g,G | a,A | c | s | T |
+ * conversion: d,i | o,u,x,X | e,E | f,F | g,G | a,A | c | s | T | R |
* p | n | %
* sz: 8 | 16 | 32 | 64 | p | e
*/
@@ -101,7 +101,7 @@
#endif
#define FMTC_d 0x0000
-#define FMTC_i 0x0001
+#define FMTC_R 0x0001
#define FMTC_o 0x0002
#define FMTC_u 0x0003
#define FMTC_x 0x0004
@@ -165,7 +165,7 @@ static char heX[] = "0123456789ABCDEF";
#define SIGN(X) ((X) > 0 ? 1 : ((X) < 0 ? -1 : 0))
#define USIGN(X) ((X) == 0 ? 0 : 1)
-int (*erts_printf_eterm_func)(fmtfn_t, void*, unsigned long, long) = NULL;
+int (*erts_printf_eterm_func)(fmtfn_t, void*, unsigned long, long, unsigned long*) = NULL;
static int
noop_fn(void *vfp, char* buf, size_t len)
@@ -183,8 +183,8 @@ static int fmt_fld(fmtfn_t fn,void* arg,
int len;
/* format the prefix */
- if ((sign || (fmt & (FMTF_sgn|FMTF_blk))) &&
- (((fmt & FMTC_MASK) == FMTC_d) || ((fmt & FMTC_MASK) == FMTC_i))) {
+ if ((sign || (fmt & (FMTF_sgn|FMTF_blk)))
+ && (fmt & FMTC_MASK) == FMTC_d) {
if (sign < 0)
*pp++ = '-';
else if ((fmt & FMTF_sgn))
@@ -245,7 +245,6 @@ static int fmt_long(fmtfn_t fn,void* arg,int sign,unsigned long uval,
switch(fmt & FMTC_MASK) {
case FMTC_d:
- case FMTC_i:
case FMTC_u:
break;
case FMTC_o:
@@ -298,7 +297,6 @@ static int fmt_long_long(fmtfn_t fn,void* arg,int sign,
switch(fmt & FMTC_MASK) {
case FMTC_d:
- case FMTC_i:
case FMTC_u:
break;
case FMTC_o:
@@ -622,7 +620,7 @@ int erts_printf_format(fmtfn_t fn, void* arg, char* fmt, va_list ap)
/* specifier */
switch(*ptr) {
case 'd': ptr++; fmt |= FMTC_d; break;
- case 'i': ptr++; fmt |= FMTC_i; break;
+ case 'i': ptr++; fmt |= FMTC_d; break;
case 'o': ptr++; fmt |= FMTC_o; break;
case 'u': ptr++; fmt |= FMTC_u; break;
case 'x': ptr++; fmt |= FMTC_x; break;
@@ -637,6 +635,7 @@ int erts_printf_format(fmtfn_t fn, void* arg, char* fmt, va_list ap)
case 'p': ptr++; fmt |= FMTC_p; break;
case 'n': ptr++; fmt |= FMTC_n; break;
case 'T': ptr++; fmt |= FMTC_T; break;
+ case 'R': ptr++; fmt |= FMTC_R; break;
case '%':
FMT(fn,arg,ptr,1,count);
ptr++;
@@ -650,7 +649,6 @@ int erts_printf_format(fmtfn_t fn, void* arg, char* fmt, va_list ap)
switch(fmt & FMTC_MASK) {
case FMTC_d:
- case FMTC_i:
switch(fmt & FMTL_MASK) {
case FMTL_hh: {
signed char tval = (signed char) va_arg(ap,int);
@@ -814,9 +812,12 @@ int erts_printf_format(fmtfn_t fn, void* arg, char* fmt, va_list ap)
default: *va_arg(ap,int*) = count; break;
}
break;
- case FMTC_T: {
+ case FMTC_T: /* Eterm */
+ case FMTC_R: { /* Eterm, Eterm* base (base ignored if !HALFWORD_HEAP) */
long prec;
unsigned long eterm;
+ unsigned long* eterm_base;
+
if (!erts_printf_eterm_func)
return -EINVAL;
if (precision < 0)
@@ -826,14 +827,16 @@ int erts_printf_format(fmtfn_t fn, void* arg, char* fmt, va_list ap)
else
prec = (long) precision;
eterm = va_arg(ap, unsigned long);
+ eterm_base = ((fmt & FMTC_MASK) == FMTC_R) ?
+ va_arg(ap, unsigned long*) : NULL;
if (width > 0 && !(fmt & FMTF_adj)) {
- res = (*erts_printf_eterm_func)(noop_fn, NULL, eterm, prec);
+ res = (*erts_printf_eterm_func)(noop_fn, NULL, eterm, prec, eterm_base);
if (res < 0)
return res;
if (width > res)
BLANKS(fn, arg, width - res, count);
}
- res = (*erts_printf_eterm_func)(fn, arg, eterm, prec);
+ res = (*erts_printf_eterm_func)(fn, arg, eterm, prec, eterm_base);
if (res < 0)
return res;
count += res;
@@ -924,7 +927,7 @@ erts_printf_slong(fmtfn_t fn, void *arg, char conv, int pad, int width,
unsigned long ul_val;
switch (conv) {
case 'd': fmt |= FMTC_d; break;
- case 'i': fmt |= FMTC_i; break;
+ case 'i': fmt |= FMTC_d; break;
case 'o': fmt |= FMTC_o; break;
case 'x': fmt |= FMTC_x; break;
case 'X': fmt |= FMTC_X; break;
diff --git a/lib/Makefile b/lib/Makefile
index 5faf0c8714..7f4c309da9 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -28,8 +28,9 @@ ifeq ($(findstring vxworks,$(TARGET)),vxworks)
snmp otp_mibs appmon erl_interface os_mon tools runtime_tools
ifdef BUILD_ALL
OTHER_SUB_DIRECTORIES += mnesia jinterface ic asn1 debugger \
- inets mnesia_session orber pman tv observer cosTransactions cosEvent \
- cosTime cosNotification cosProperty cosFileTransfer cosEventDomain
+ inets mnesia_session diameter orber pman tv observer \
+ cosTransactions cosEvent cosTime cosNotification cosProperty
+ cosFileTransfer cosEventDomain
endif
else
ifeq ($(findstring ose,$(TARGET)),ose)
@@ -57,7 +58,8 @@ else
OTHER_SUB_DIRECTORIES += \
snmp otp_mibs appmon erl_interface asn1 jinterface gs wx inets ic \
mnesia crypto orber os_mon parsetools syntax_tools pman \
- public_key ssl toolbar tv observer debugger reltool odbc runtime_tools \
+ public_key ssl toolbar tv observer debugger reltool odbc \
+ runtime_tools diameter \
cosTransactions cosEvent cosTime cosNotification cosProperty \
cosFileTransfer cosEventDomain et megaco webtool \
xmerl edoc eunit ssh inviso typer docbuilder erl_docgen common_test percept
@@ -68,7 +70,8 @@ else
snmp otp_mibs appmon erl_interface asn1 jinterface wx debugger reltool gs inets \
ic mnesia crypto orber os_mon parsetools syntax_tools \
pman public_key ssl toolbar tv observer odbc \
- runtime_tools cosTransactions cosEvent cosTime cosNotification \
+ runtime_tools diameter \
+ cosTransactions cosEvent cosTime cosNotification \
cosProperty cosFileTransfer cosEventDomain et megaco webtool \
xmerl edoc eunit ssh inviso typer docbuilder erl_docgen common_test percept
# dialyzer
diff --git a/lib/asn1/doc/src/notes.xml b/lib/asn1/doc/src/notes.xml
index 77769afcd4..ccff9892c6 100644
--- a/lib/asn1/doc/src/notes.xml
+++ b/lib/asn1/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/common_test/doc/src/notes.xml b/lib/common_test/doc/src/notes.xml
index fef1222fcb..15c7e2a9f2 100644
--- a/lib/common_test/doc/src/notes.xml
+++ b/lib/common_test/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/compiler/doc/src/compile.xml b/lib/compiler/doc/src/compile.xml
index f2af932aef..830c89ae84 100644
--- a/lib/compiler/doc/src/compile.xml
+++ b/lib/compiler/doc/src/compile.xml
@@ -68,7 +68,7 @@
to be an error if the module name in the source code is
not the same as the basename of the output file.</p>
- <p>Here follows first all elements of <c>Options</c> that in
+ <p><marker id="type-option"/>Here follows first all elements of <c>Options</c> that in
some way control the behavior of the compiler.</p>
<taglist>
<tag><c>basic_validation</c></tag>
diff --git a/lib/compiler/doc/src/notes.xml b/lib/compiler/doc/src/notes.xml
index 25a6db4ce0..5757d0c1cb 100644
--- a/lib/compiler/doc/src/notes.xml
+++ b/lib/compiler/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/crypto/c_src/Makefile.in b/lib/crypto/c_src/Makefile.in
index 040adcfd09..3ace10403e 100644
--- a/lib/crypto/c_src/Makefile.in
+++ b/lib/crypto/c_src/Makefile.in
@@ -40,7 +40,7 @@ CFLAGS = $(DED_CFLAGS)
# From erts/configure
SSL_LIBDIR = @SSL_LIBDIR@
SSL_INCLUDE = @SSL_INCLUDE@
-
+SSL_CRYPTO_LIBNAME = @SSL_CRYPTO_LIBNAME@
INCLUDES = $(SSL_INCLUDE) $(DED_INCLUDES)
@@ -84,10 +84,10 @@ DYNAMIC_CRYPTO_LIB=@SSL_DYNAMIC_ONLY@
ifeq ($(DYNAMIC_CRYPTO_LIB),yes)
SSL_DED_LD_RUNTIME_LIBRARY_PATH = @SSL_DED_LD_RUNTIME_LIBRARY_PATH@
-CRYPTO_LINK_LIB=$(SSL_DED_LD_RUNTIME_LIBRARY_PATH) -L$(SSL_LIBDIR) -lcrypto
+CRYPTO_LINK_LIB=$(SSL_DED_LD_RUNTIME_LIBRARY_PATH) -L$(SSL_LIBDIR) -l$(SSL_CRYPTO_LIBNAME)
else
SSL_DED_LD_RUNTIME_LIBRARY_PATH=
-CRYPTO_LINK_LIB=$(SSL_LIBDIR)/libcrypto.a
+CRYPTO_LINK_LIB=$(SSL_LIBDIR)/lib$(SSL_CRYPTO_LIBNAME).a
endif
# ----------------------------------------------------
@@ -112,7 +112,7 @@ $(LIBDIR)/crypto$(TYPEMARKER).so: $(OBJS)
$(LIBDIR)/crypto$(TYPEMARKER).dll: $(OBJS)
$(INSTALL_DIR) $(LIBDIR)
- $(LD) $(LDFLAGS) -o $@ $(SSL_DED_LD_RUNTIME_LIBRARY_PATH) -L$(SSL_LIBDIR) $(OBJS) -llibeay32
+ $(LD) $(LDFLAGS) -o $@ $(SSL_DED_LD_RUNTIME_LIBRARY_PATH) -L$(SSL_LIBDIR) $(OBJS) -l$(SSL_CRYPTO_LIBNAME)
clean:
ifeq ($(findstring win32,$(TARGET)), win32)
diff --git a/lib/crypto/doc/src/licenses.xml b/lib/crypto/doc/src/licenses.xml
index bae87a373e..e851655aa5 100644
--- a/lib/crypto/doc/src/licenses.xml
+++ b/lib/crypto/doc/src/licenses.xml
@@ -37,7 +37,7 @@ This chapter contains in extenso versions
<title>OpenSSL License</title>
<code type="none">
/* ====================================================================
- * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
+ * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
diff --git a/lib/debugger/doc/src/notes.xml b/lib/debugger/doc/src/notes.xml
index 3aa169a135..93e447848a 100644
--- a/lib/debugger/doc/src/notes.xml
+++ b/lib/debugger/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/dialyzer/doc/src/notes.xml b/lib/dialyzer/doc/src/notes.xml
index f132a50e0d..0dadf647c3 100755
--- a/lib/dialyzer/doc/src/notes.xml
+++ b/lib/dialyzer/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2006</year><year>2010</year>
+ <year>2006</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/diameter/.gitignore b/lib/diameter/.gitignore
new file mode 100644
index 0000000000..5afcbedc23
--- /dev/null
+++ b/lib/diameter/.gitignore
@@ -0,0 +1,58 @@
+
+# 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/AUTHORS b/lib/diameter/AUTHORS
new file mode 100644
index 0000000000..40bd970276
--- /dev/null
+++ b/lib/diameter/AUTHORS
@@ -0,0 +1,10 @@
+Original Authors:
+
+ Anders Svensson
+ Ulf Wiger
+
+Contributors:
+
+
+
+
diff --git a/lib/diameter/Makefile.in b/lib/diameter/Makefile.in
new file mode 100644
index 0000000000..cf38c26045
--- /dev/null
+++ b/lib/diameter/Makefile.in
@@ -0,0 +1,88 @@
+#
+# %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/TAR.exclude b/lib/diameter/TAR.exclude
new file mode 100644
index 0000000000..4a2b3192c5
--- /dev/null
+++ b/lib/diameter/TAR.exclude
@@ -0,0 +1,2 @@
+diameter/doc/standard
+
diff --git a/lib/diameter/aclocal.m4 b/lib/diameter/aclocal.m4
new file mode 100644
index 0000000000..fcefdb7679
--- /dev/null
+++ b/lib/diameter/aclocal.m4
@@ -0,0 +1,65 @@
+dnl
+dnl %CopyrightBegin%
+dnl
+dnl Copyright Ericsson AB 1998-2010. 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
new file mode 100755
index 0000000000..38a833903b
--- /dev/null
+++ b/lib/diameter/autoconf/config.guess
@@ -0,0 +1,1519 @@
+#! /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
+ 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*)
+ echo i860-stratus-sysv4
+ exit ;;
+ i*86:VOS:*:*)
+ echo ${UNAME_MACHINE}-stratus-vos
+ exit ;;
+ *:VOS:*:*)
+ 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
new file mode 100755
index 0000000000..f43233b104
--- /dev/null
+++ b/lib/diameter/autoconf/config.sub
@@ -0,0 +1,1630 @@
+#! /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
new file mode 100755
index 0000000000..70d7bdbaf2
--- /dev/null
+++ b/lib/diameter/autoconf/configure.vxworks
@@ -0,0 +1,147 @@
+#!/bin/sh
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2009. 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
new file mode 100755
index 0000000000..a5897de6ea
--- /dev/null
+++ b/lib/diameter/autoconf/install-sh
@@ -0,0 +1,519 @@
+#!/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
new file mode 100644
index 0000000000..f725a6f9ca
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.general
@@ -0,0 +1,125 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2009. 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
new file mode 100644
index 0000000000..163dd78897
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_cpu32
@@ -0,0 +1,45 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2010. 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
new file mode 100644
index 0000000000..5db28337c0
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc32
@@ -0,0 +1,52 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2006-2010. 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
new file mode 100644
index 0000000000..40296b8f07
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603
@@ -0,0 +1,51 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2000-2010. 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
new file mode 100644
index 0000000000..2550432d1e
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603_nolongcall
@@ -0,0 +1,51 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2010. 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
new file mode 100644
index 0000000000..cd7c9ff797
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc860
@@ -0,0 +1,50 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2010. 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
new file mode 100644
index 0000000000..6eb6f8ea92
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_simlinux
@@ -0,0 +1,59 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2008-2010. 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
new file mode 100644
index 0000000000..1d7413b484
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_simso
@@ -0,0 +1,64 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2005-2010. 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
new file mode 100644
index 0000000000..ae26f234d2
--- /dev/null
+++ b/lib/diameter/autoconf/vxworks/sed.vxworks_sparc
@@ -0,0 +1,38 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2009. 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
new file mode 100755
index 0000000000..cba664bfad
--- /dev/null
+++ b/lib/diameter/bin/diameterc
@@ -0,0 +1,155 @@
+#!/usr/bin/env escript
+%% Use -*- erlang -*- mode in Erlang
+
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2010. 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(diameterc).
+
+-mode(compile).
+
+-include_lib("kernel/include/file.hrl").
+
+%% The parsed command line.
+-record(argv, {file,
+ options = [{outdir, "."}],
+ output = [erl, hrl]}).
+
+usage() ->
+ io:format(
+ "~w [options] file~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",
+ [?MODULE]).
+
+main(Args) ->
+ %% Add the ebin directory relative to the script path.
+ BinDir = filename:dirname(escript:script_name()),
+ code:add_path(filename:join([BinDir, "..", "ebin"])),
+ halt(gen(Args)).
+
+gen(Args) ->
+ try parse_args(Args) of
+ #argv{} = A ->
+ compile(A)
+ catch
+ throw: usage ->
+ usage(),
+ 0;
+ throw: Reason ->
+ error_msg(norm(Reason)),
+ 1
+ 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
+ catch
+ error: Reason ->
+ 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).
+
+error_msg({Fmt, Args}) ->
+ io:format(standard_error, Fmt ++ "~n", Args).
+
+norm({_,_} = T) ->
+ T;
+norm(Str) ->
+ {Str, []}.
+
+%% parse_args/1
+
+parse_args(Args)
+ when is_list(Args) ->
+ arg(Args, #argv{}).
+
+arg(["-h" | _], _) ->
+ throw(usage);
+
+arg(["-v" | Args], #argv{options = Opts} = A) ->
+ arg(Args, A#argv{options = [verbose | Opts]});
+
+arg(["-o", Dir | Args], #argv{options = Opts} = A) ->
+ true = dir_exists(Dir),
+ arg(Args, A#argv{options = [{outdir, Dir} | Opts]});
+
+arg(["-i", Dir | Args], #argv{options = Opts} = A) ->
+ true = dir_exists(Dir),
+ arg(Args, A#argv{options = Opts ++ [{include, Dir}]});
+
+arg(["-E" | Args], #argv{output = Output} = A) ->
+ arg(Args, A#argv{output = lists:delete(erl, Output)});
+
+arg(["-H" | Args], #argv{output = Output} = A) ->
+ arg(Args, A#argv{output = lists:delete(hrl, Output)});
+
+arg(["-d" | Args], #argv{options = Opts, output = Output} = A) ->
+ arg(Args, A#argv{options = [debug | Opts],
+ output = [spec | Output]});
+
+arg([[$- = M, C, H | T] | Args], A) %% clustered options
+ when C /= $i, C /= $o ->
+ arg([[M,C], [M,H|T] | Args], A);
+
+arg([File], A) ->
+ true = file_exists(File),
+ A#argv{file = File};
+
+arg([], _) ->
+ throw("No input file");
+
+arg([Bad | _], _) ->
+ throw({"Unknown option: ~p", [Bad]}).
+
+%% path_exists/2
+
+path_exists(File, Type) ->
+ case file:read_file_info(File) of
+ {ok, #file_info{type = Type}} ->
+ true;
+ {ok, #file_info{type = WrongType}} ->
+ throw({"Invalid type for file: ~p, ~p", [WrongType, File]});
+ _ ->
+ throw({"No such file: ~p", [File]})
+ end.
+
+file_exists(File) ->
+ path_exists(File, regular).
+
+dir_exists(File) ->
+ path_exists(File, directory).
diff --git a/lib/diameter/configure.in b/lib/diameter/configure.in
new file mode 100644
index 0000000000..76b15ced9b
--- /dev/null
+++ b/lib/diameter/configure.in
@@ -0,0 +1,138 @@
+dnl Process this file with autoconf to produce a configure script.
+
+dnl %CopyrightBegin%
+dnl
+dnl Copyright Ericsson AB 1998-2010. 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/html/.gitignore b/lib/diameter/doc/html/.gitignore
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/lib/diameter/doc/html/.gitignore
diff --git a/lib/diameter/doc/man1/.gitignore b/lib/diameter/doc/man1/.gitignore
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/lib/diameter/doc/man1/.gitignore
diff --git a/lib/diameter/doc/man3/.gitignore b/lib/diameter/doc/man3/.gitignore
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/lib/diameter/doc/man3/.gitignore
diff --git a/lib/diameter/doc/man4/.gitignore b/lib/diameter/doc/man4/.gitignore
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/lib/diameter/doc/man4/.gitignore
diff --git a/lib/diameter/doc/pdf/.gitignore b/lib/diameter/doc/pdf/.gitignore
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/lib/diameter/doc/pdf/.gitignore
diff --git a/lib/diameter/doc/src/Makefile b/lib/diameter/doc/src/Makefile
new file mode 100644
index 0000000000..f2a91a88b7
--- /dev/null
+++ b/lib/diameter/doc/src/Makefile
@@ -0,0 +1,199 @@
+#
+# %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
+
+include ../../vsn.mk
+
+VSN = $(DIAMETER_VSN)
+
+RELSYSDIR = $(RELEASE_PATH)/lib/$(APPLICATION)-$(VSN)
+
+# ----------------------------------------------------
+# Target Specs
+# ----------------------------------------------------
+include files.mk
+
+XML_FILES = $(BOOK_FILES) $(XML_APPLICATION_FILES) \
+ $(XML_REF1_FILES) $(XML_REF3_FILES) $(XML_REF4_FILES) \
+ $(XML_PART_FILES) $(XML_CHAPTER_FILES)
+
+INTERNAL_HTML_FILES = $(TECHNICAL_DESCR_FILES:%.xml=$(HTMLDIR)/%.html)
+
+HTML_APP_FILES = $(XML_APPLICATION_FILES:%.xml=$(HTMLDIR)/%.html)
+HTML_EXTRA_FILES = $(XML_EXTRA_FILES:%.xml=$(HTMLDIR)/%.html)
+HTML_PART_FILES = $(XML_PART_FILES:%.xml=$(HTMLDIR)/%.html)
+
+HTML_FILES = $(HTML_APP_FILES) $(HTML_EXTRA_FILES) $(HTML_PART_FILES)
+
+INFO_FILE = ../../info
+
+HTML_REF_FILES = $(XML_REF1_FILES:%.xml=$(HTMLDIR)/%.html) \
+ $(XML_REF3_FILES:%.xml=$(HTMLDIR)/%.html) \
+ $(XML_REF4_FILES:%.xml=$(HTMLDIR)/%.html)
+
+HTML_CHAPTER_FILES = $(XML_CHAPTER_FILES:%.xml=$(HTMLDIR)/%.html)
+
+EXTRA_FILES = \
+ $(DEFAULT_GIF_FILES) \
+ $(DEFAULT_HTML_FILES) \
+ $(HTML_REF_FILES) \
+ $(HTML_CHAPTER_FILES)
+
+MAN1_FILES = $(XML_REF1_FILES:%.xml=$(MAN1DIR)/%.1)
+MAN3_FILES = $(XML_REF3_FILES:%.xml=$(MAN3DIR)/%.3)
+MAN4_FILES = $(XML_REF4_FILES:%.xml=$(MAN4DIR)/%.4)
+
+HTML_REF_MAN_FILE = $(HTMLDIR)/index.html
+
+TOP_PDF_FILE = $(PDFDIR)/$(APPLICATION)-$(VSN).pdf
+
+STANDARD_DIR = ../standard
+STANDARDS =
+
+# ----------------------------------------------------
+# FLAGS
+# ----------------------------------------------------
+
+XML_FLAGS +=
+DVIPS_FLAGS +=
+
+# ----------------------------------------------------
+# Targets
+# ----------------------------------------------------
+
+$(HTMLDIR)/%.gif: %.gif
+ $(INSTALL_DATA) $< $@
+
+docs: pdf html man
+
+ldocs: local_docs $(INDEX_TARGET)
+
+$(TOP_PDF_FILE): $(XML_FILES)
+
+pdf: $(TOP_PDF_FILE)
+
+html: gifs $(HTML_REF_MAN_FILE)
+
+clean clean_docs: clean_pdf clean_html clean_man
+ rm -f errs core *~
+
+clean_pdf:
+ rm -f $(PDFDIR)/*
+
+clean_man:
+ rm -f $(MAN1DIR)/* $(MAN3DIR)/* $(MAN4DIR)/*
+
+clean_html:
+ rm -rf $(HTMLDIR)/*
+
+gifs: $(GIF_FILES:%=$(HTMLDIR)/%)
+
+man: $(MAN1_FILES) $(MAN3_FILES) $(MAN4_FILES)
+
+$(INDEX_TARGET): $(INDEX_SRC) $(APP_FILE)
+ sed -e 's/%VSN%/$(VSN)/; \
+ s/%ERLANG_SITE%/www\.erlang\.se\//; \
+ s/%UP_ONE_LEVEL%/..\/..\/..\/doc\/index.html/; \
+ s/%OFF_PRINT%/pdf\/diameter-$(VSN).pdf/' $< > $@
+
+depend 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)"
+ @echo ""
+ @echo "XML_APPLICATION_FILES = $(XML_APPLICATION_FILES)"
+ @echo "XML_PART_FILES = $(XML_PART_FILES)"
+ @echo "XML_REF1_FILES = $(XML_REF1_FILES)"
+ @echo "XML_REF3_FILES = $(XML_REF3_FILES)"
+ @echo "XML_REF4_FILES = $(XML_REF4_FILES)"
+ @echo "XML_CHAPTER_FILES = $(XML_CHAPTER_FILES)"
+ @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)"
+ @echo ""
+ @echo "HTML_FILES = $(HTML_FILES)"
+ @echo "TOP_HTML_FILES = $(TOP_HTML_FILES)"
+ @echo ""
+ @echo "DEFAULT_HTML_FILES = $(DEFAULT_HTML_FILES)"
+ @echo "DEFAULT_GIF_FILES = $(DEFAULT_GIF_FILES)"
+ @echo ""
+ @echo ""
+
+
+# ----------------------------------------------------
+# 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
+ echo $(LOCAL)
+
+release_spec:
+
+$(HTMLDIR)/diameter_app.html: diameter_app.xml
+$(HTMLDIR)/diameter_compile.html: diameter_compile.xml
+$(HTMLDIR)/diameter_debug.html: diameter_debug.xml
+$(HTMLDIR)/diameter_dict.html: diameter_dict.xml
+$(HTMLDIR)/diameter_intro.html: diameter_intro.xml
+$(HTMLDIR)/diameter_run.html: diameter_run.xml
+$(HTMLDIR)/diameter.html: diameter.xml
+$(HTMLDIR)/diameter_tcp.html: diameter_tcp.xml
+$(HTMLDIR)/diameter_transport.html: diameter_transport.xml
+$(HTMLDIR)/diameter_soc.html: diameter_soc.xml
+$(HTMLDIR)/diameter_sctp.html: diameter_sctp.xml
+
+.PHONY: clean clean_html clean_man clean_pdf \
+ depend debug opt info \
+ docs gifs html ldocs man pdf \
+ release_docs_spec release_spec
diff --git a/lib/diameter/doc/src/book.xml b/lib/diameter/doc/src/book.xml
new file mode 100644
index 0000000000..960296528b
--- /dev/null
+++ b/lib/diameter/doc/src/book.xml
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE book SYSTEM "book.dtd">
+
+<book xmlns:xi="http://www.w3.org/2001/XInclude">
+
+<header titlestyle="normal">
+<copyright>
+<year>2011</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</title>
+<prepared></prepared>
+<docno></docno>
+<date></date>
+<rev></rev>
+<file>book.xml</file>
+</header>
+
+<insidecover>
+</insidecover>
+
+<pagetext>Diameter</pagetext>
+
+<preamble>
+<contents level="2"></contents>
+</preamble>
+
+<parts lift="no">
+<xi:include href="user_man.xml"/>
+</parts>
+
+<applications>
+<xi:include href="ref_man.xml"/>
+</applications>
+
+<releasenotes>
+<xi:include href="notes.xml"/>
+</releasenotes>
+
+<index></index>
+
+</book>
diff --git a/lib/diameter/doc/src/diameter.xml b/lib/diameter/doc/src/diameter.xml
new file mode 100644
index 0000000000..9774183a2a
--- /dev/null
+++ b/lib/diameter/doc/src/diameter.xml
@@ -0,0 +1,1123 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE erlref SYSTEM "erlref.dtd">
+
+<erlref>
+<header>
+
+<copyright>
+<year>2011</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(3)</title>
+
+<prepared>Anders Svensson</prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev>%VSN%</rev>
+<file>diameter.xml</file>
+
+</header>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+
+<module>diameter</module>
+<modulesummary>Main API of the diameter application.</modulesummary>
+
+<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>
+
+<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>.
+Incoming Diameter requests are communicated as callbacks to a
+<seealso
+marker="diameter_app">diameter_app(3)</seealso> callback modules as
+specified in the service configuration.</p>
+
+<p>
+Beware the difference between <em>diameter application</em> and
+<em>Diameter application</em>.
+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>
+
+<p>
+The diameter application must be started before calling functions in
+this module.</p>
+
+</description>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+<section>
+<title>DATA TYPES</title>
+
+<taglist>
+
+<tag><c>Address()</c></tag>
+<tag><c>DiameterIdentity()</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>
+
+<marker id="application_alias"/>
+</item>
+
+<tag><c>application_alias() = term()</c></tag>
+<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>
+
+<marker id="application_module"/>
+</item>
+
+<tag><c>application_module() = Mod | [Mod | ExtraArgs]</c></tag>
+<item>
+<code>
+Mod = atom()
+ExtraArgs = list()
+</code>
+
+<p>
+A module implementing the callback interface defined in <seealso
+marker="diameter_app">diameter_app(3)</seealso>, 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>
+
+<marker id="application_opt"/>
+</item>
+
+<tag><c>application_opt()</c></tag>
+<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>
+
+<taglist>
+
+<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>
+</item>
+
+<tag><c>{dictionary, atom()}</c></tag>
+<item>
+<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>
+</item>
+
+<tag><c>{module, application_module()}</c></tag>
+<item>
+<p>
+A 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>
+</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>
+</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,
+Defaults to <c>false</c> if unspecified.</p>
+
+<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
+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>
+</item>
+
+<tag><c>{answer_errors, callback|report|discard}</c></tag>
+<item>
+<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>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
+question is as if a callback had taken place and returned
+<c>{error, failure}</c>.</p>
+
+<p>
+Defaults to <c>report</c> if unspecified.</p>
+</item>
+
+</taglist>
+
+<marker id="call_opt"/>
+</item>
+
+<tag><c>call_opt()</c></tag>
+<item>
+
+<p>
+Options available to <seealso marker="#call">call/4</seealso> when
+sending an outgoing Diameter request.</p>
+
+<taglist>
+
+<tag><c>{extra, list()}</c></tag>
+<item>
+<p>
+Extra arguments to append to callbacks to the callback
+module in question.
+These are appended to any extra arguments configured with the callback
+itself.
+Multiple options append to the argument list.</p>
+</item>
+
+<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>
+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>
+<item>
+<p>
+The number of milliseconds after which the request should
+timeout.
+Defaults to 5000.</p>
+</item>
+
+<tag><c>detach</c></tag>
+<item>
+<p>
+Causes <seealso marker="#call">call/4</seealso> 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>
+</item>
+
+</taglist>
+
+<marker id="capability"/>
+</item>
+
+<tag><c>capability()</c></tag>
+<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>
+
+<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>
+<item>
+<p>
+Value of the Origin-Realm AVP in outgoing messages.</p>
+</item>
+
+<tag><c>{'Host-IP-Address', [Address()]}</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>
+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
+application is started.</p>
+</item>
+
+<tag><c>{'Supported-Vendor-Id', [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>
+</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>
+
+</taglist>
+
+<p>
+Note that each tuple communicates one or more AVP values.
+It is an error to specify duplicate tuples.</p>
+
+<marker id="evaluable"/>
+</item>
+
+<tag><c>evaluable() = {M,F,A} | fun() | [evaluable() | A]</c></tag>
+<item>
+<p>
+An expression that can be evaluated as a function in the following
+sense.</p>
+
+<code>
+eval([{M,F,A} | T]) ->
+ apply(M, F, T ++ A);
+eval([F|A]) ->
+ apply(F, A);
+eval(F) ->
+ eval([F]).
+</code>
+
+<p>
+Evaluating an evaluable() <c>E</c> on an argument list <c>A</c>
+is meant in the sense of <c>eval([E|A])</c>.</p>
+
+<marker id="peer_filter"/>
+</item>
+
+<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.
+Has one of the following types.</p>
+
+<taglist>
+
+<tag><c>none</c></tag>
+<item>
+<p>
+Matches any peer.
+This is a convenience that provides a filter equivalent to no
+filter at all.</p>
+</item>
+
+<tag><c>host</c></tag>
+<item>
+<p>
+Matches only those peers whose <c>Origin-Host</c> has the same value
+as <c>Destination-Host</c> in the outgoing request in question,
+or any peer if the request does not contain
+a <c>Destination-Host</c> AVP.</p>
+</item>
+
+<tag><c>realm</c></tag>
+<item>
+<p>
+Matches only those peers whose <c>Origin-Realm</c> has the same value
+as <c>Destination-Realm</c> in the outgoing request in question,
+or any peer if the request does not contain
+a <c>Destination-Realm</c> AVP.</p>
+</item>
+
+<tag><c>{host, any|UTF8String()}</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|UTF8String()</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>
+</item>
+
+<tag><c>{eval, evaluable()}</c></tag>
+<item>
+<p>
+Matches only those peers for which the specified evaluable() evaluates
+to true on the peer's <c>diameter_caps</c> record.</p>
+</item>
+
+<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>
+<item>
+<p>
+Matches only those peers matched by each filter of the specified list.</p>
+</item>
+
+<tag><c>{any, [peer_filter()]}</c></tag>
+<item>
+<p>
+Matches only those peers matched by at least one filter of the
+specified list.</p>
+</item>
+
+</taglist>
+
+<marker id="service_event"/>
+</item>
+
+<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>
+
+<p>
+The <c>info</c> field of the event record can be one of the
+following.</p>
+
+<taglist>
+
+<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()]}
+Pkt = #diameter_packet{}
+</code>
+
+<p>
+Reports that the RFC 3539 watchdog state machine has
+transitioned into (<c>up</c>) or out of (<c>down</c>) the open
+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
+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.
+That is, the event communicates connectivity with the
+peer as a whole while the callbacks communicate connectivity with
+respect to individual Diameter applications.</p>
+</item>
+
+<tag><c>{reconnect, Ref, Opts}</c></tag>
+<item>
+<code>
+Ref = transport_ref()
+Opts = [transport_opt()]
+</code>
+
+<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>
+</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>
+
+<marker id="service_name"/>
+</item>
+
+<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
+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>
+
+<marker id="service_opt"/>
+</item>
+
+<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>
+
+<taglist>
+
+<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
+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>
+</item>
+
+</taglist>
+
+<marker id="transport_opt"/>
+</item>
+
+<tag><c>transport_opt()</c></tag>
+<item>
+<p>
+Options accepted by <seealso
+marker="#add_transport">add_transport/2</seealso>.</p>
+
+<taglist>
+<tag><c>{transport_module, atom()}</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>
+
+<p>
+The interface required of a transport module is documented in <seealso
+marker="diameter_transport">diameter_transport(3)</seealso>.</p>
+</item>
+
+<tag><c>{transport_config, term()}</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>
+</item>
+
+<tag><c>{applications, [application_alias()]}</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>
+</item>
+
+<tag><c>{capabilities, [capability()]}</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>
+</item>
+
+<tag><c>{watchdog_timer, TwInit}</c></tag>
+<item>
+<code>
+TwInit = Unsigned32()
+ | {M,F,A}
+</code>
+
+<p>
+The RFC 3539 watchdog timer.
+An integer value is interpreted as the RFC's TwInit in milliseconds,
+a jitter of &plusmn; 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>
+
+<tag><c>{reconnect_timer, Tc}</c></tag>
+<item>
+<code>
+Tc = Unsigned32()
+</code>
+
+<p>
+For a connecting transport, the RFC 3588 Tc timer, in milliseconds.
+Note that this timer determines the frequency with which the transport
+will attempt to establish a connection with its peer only <em>before</em>
+an initial connection is established: once there is an initial
+connection it's watchdog_timer that determines the frequency of
+reconnection attempts, as required by RFC 3539.</p>
+
+<p>
+For a listening transport, the timer specifies the time after which a
+previously connected peer will be forgotten: a connection after this time is
+regarded as an initial connection rather than a reestablishment,
+causing the RFC 3539 state machine to pass to state OPEN 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>
+
+<p>
+Defaults to 30000 for a connecting transport and 60000 for a listening
+transport.</p>
+</item>
+
+</taglist>
+
+<p>
+Unrecognized options are silently ignored but are returned unmodified
+by <seealso
+marker="#service_info_1">service_info/1,2</seealso> and can be referred to
+in predicate functions passed to <seealso
+marker="#remove_transport">remove_transport/2</seealso>.</p>
+
+</item>
+
+</taglist>
+
+</section>
+
+<marker id="add_transport"/>
+<funcs>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>add_transport(SvcName, {connect|listen, Options})
+ -> {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>Reason = term()</v>
+</type>
+<desc>
+<p>
+Add transport capability to a service.
+The service will start a transport process(es) 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
+one peer, an listening transport potentially with many.</p>
+
+<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
+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>
+
+<p>
+The returned reference uniquely identifies the transport within the
+scope of the service.
+Not that the function returns before a transport connection has been
+established.</p>
+
+<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>
+
+<marker id="call"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>call(SvcName, App, Request, Options) -> Answer | {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()</v>
+<v>Answer = term()</v>
+<v>Options = [call_opt()]</v>
+</type>
+<desc>
+<p>
+Send a Diameter request message and possibly return the answer or error.</p>
+
+<p>
+<c>App</c> identifies 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>.
+The call returns either when an answer message is received from the
+peer or an error occurs, unless the <c>detach</c> option has been
+specified.
+If <c>detach</c> is not specified then the form of an <c>Answer</c> is
+as returned from a <seealso
+marker="diameter_app#handle_answer">handle_answer/4</seealso> or
+<seealso
+marker="diameter_app#handle_error">handle_error/4</seealso>
+callback.</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>
+is returned.
+If <seealso marker="diameter_app#pick_peer">pick_peer/4</seealso>
+selects a candidate peer then a request process is spawned for the
+outgoing request, in which there is a
+<seealso
+marker="diameter_app#prepare_request">prepare_request/3</seealso>
+callback, the message is encoded and 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>
+
+<list>
+
+<item>
+<p>
+If the initial encode of the outgoing request
+fails, then the request process fails and <c>{error, encode}</c>
+is returned.</p>
+</item>
+
+<item>
+<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>
+</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>
+</item>
+
+<item>
+<p>
+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>
+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>
+</item>
+
+<item>
+<p>
+If an encode error takes place during
+retransmission then the request process fails and
+<c>{error, failure}</c> is returned.</p>
+</item>
+
+<item>
+<p>
+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>
+is returned depending on whether or not there has been an
+attempt to send the request over the transport.</p>
+</item>
+
+</list>
+
+<p>
+Note that <c>{error, encode}</c> is the only return value which
+guarantees that the request has not been sent over the transport.</p>
+
+<marker id="origin_state_id"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>origin_state_id() -> Unsigned32()</name>
+<fsummary>Returns a reasonable Origin-State-Id.</fsummary>
+<desc>
+<p>
+Return a reasonable value for use as Origin-State-Id in
+outgoing messages.
+The value returned is the number of seconds since 19680120T031408Z
+(the first value that can be encoded as a Time())
+at the time the diameter application was started.</p>
+
+<marker id="remove_transport"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>remove_transport(SvcName, Pred) -> ok</name>
+<fsummary>Remove previously added transports.</fsummary>
+<type>
+<v>SvcName = service_name()</v>
+<v>Pred = Fun | MFA | ref() | list() | true | false</v>
+<v></v>
+<v>Fun = fun((reference(), connect|listen, list()) -> boolean())</v>
+<v>&nbsp;&nbsp;&nbsp; | fun((reference(), list()) -> boolean())</v>
+<v>&nbsp;&nbsp;&nbsp; | fun((list()) -> boolean())</v>
+<v>MFA = {atom(), atom(), list()}</v>
+</type>
+<desc>
+<p>
+Remove previously added transports.</p>
+
+<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.
+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
+Pred = {M,F,A}: fun(Ref, Type, Opts) -> apply(M, F, [Ref, Type, Opts | A]) end
+</code>
+
+<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. -->
+
+<marker id="service_info_1"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>service_info(SvcName) -> Info</name>
+<fsummary>Return information about a started service.</fsummary>
+<type>
+<v>SvcName = service_name()</v>
+<v>Info = [{Item, Value}]</v>
+</type>
+<desc>
+<p>
+Return information about a started service.
+Equivalent to <c>service_info(SvcName, all)</c>.</p>
+
+<marker id="service_info_2"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>service_info(SvcName, Item) -> Value</name>
+<fsummary>Return specific information about a started service.</fsummary>
+<type>
+<v>SvcName = service_name()</v>
+<v>Value = term()</v>
+</type>
+<desc>
+<p>
+Return specific information about a started service.</p>
+
+<marker id="services"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>services() -> [SvcName]</name>
+<fsummary>Return the list of started services.</fsummary>
+<type>
+<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>
+<fsummary>Return a value for a Session-Id AVP</fsummary>
+<type>
+<v>Ident = DiameterIdentity()</v>
+</type>
+<desc>
+<p>
+Return a value for a Session-Id AVP.
+The value has the form required by section 8.8 of RFC 3588.
+Ident should be the Origin-Host of the peer from which
+the message containing the returned value will be sent.</p>
+
+<marker id="start_service"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+<func>
+<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>Reason = term()</v>
+</type>
+<desc>
+<p>
+Start a diameter service.
+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>
+
+<marker id="stop_service"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+<func>
+<name>stop_service(SvcName) -> ok | {error, Reason}</name>
+<fsummary>Stops a Diameter service.</fsummary>
+<type>
+<v>SvcName = service_name()</v>
+<v>Reason = term()</v>
+</type>
+<desc>
+<p>
+Stop a diameter service.</p>
+
+<marker id="subscribe"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>subscribe(SvcName) -> true</name>
+<fsummary>Subscribe to event messages from a service.</fsummary>
+<type>
+<v>SvcName = service_name()</v>
+</type>
+<desc>
+<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>
+
+<marker id="unsubscribe"/>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>unsubscribe(SvcName) -> true</name>
+<fsummary></fsummary>
+<type>
+<v>SvcName = service_name()</v>
+</type>
+<desc>
+<p>
+Unsubscribe to event messages from a service.</p>
+
+</desc>
+</func>
+
+</funcs>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+<section>
+<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>
+
+</section>
+
+</erlref>
diff --git a/lib/diameter/doc/src/diameter_app.xml b/lib/diameter/doc/src/diameter_app.xml
new file mode 100644
index 0000000000..c2fecce768
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_app.xml
@@ -0,0 +1,582 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE erlref SYSTEM "erlref.dtd">
+
+<erlref>
+<header>
+
+<copyright>
+<year>2011</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_app(3)</title>
+<prepared>Anders Svensson</prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev>%REV%</rev>
+<file>diameter_app.xml</file>
+
+</header>
+
+<module>diameter_app</module>
+<modulesummary>
+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>
+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
+specification file whose format is documented in
+<seealso marker="diameter_dict">diameter_dict(4)</seealso>
+while the callback module is documented here.
+The callback module implements the Diameter application-specific
+functionality of a service.</p>
+
+<note>
+<p>
+The arities of the callback functions below 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>
+and, except for peer_up, peer_down and handle_request, any extra
+arguments passed to <seealso
+marker="diameter#call">diameter:call/4</seealso>.</p>
+</note>
+
+<p>
+A callback module must export all of the functions documented below.
+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 attainment
+or loss of communicativity 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
+Diameter request message.</p>
+</item>
+
+<item>
+<p>
+<seealso marker="#handle_request">handle_request/3</seealso>
+is called in response to an incoming Diameter request message.</p>
+</item>
+
+</list>
+
+</description>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+
+<section>
+<title>DATA TYPES</title>
+
+<taglist>
+
+<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
+connection, as well as the capabilities as
+determined by capabilities exchange.
+Each field of the record is a 2-tuple consisting of
+values for the (local) host and (remote) peer.
+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>
+<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 in the 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: messages are sent exactly as specified.</p>
+
+</item>
+
+<tag><c>packet() = #diameter_packet{}</c></tag>
+<item>
+<p>
+A container for incoming and outgoing Diameters message that's passed
+through encode/decode and transport.
+Defined in diameter.hrl.
+Fields should not be altered except as documented.</p>
+</item>
+
+<tag><c>peer_ref() = term()</c></tag>
+<item>
+<p>
+A term identifying a transport connection with a Diameter peer.
+Should be treated opaquely.</p>
+</item>
+
+<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>
+
+<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>.
+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.
+Callback functions returning a state are evaluated in a common
+service-specific process while
+those not returning state are evaluated in a request-specific
+process.</p>
+</item>
+
+</taglist>
+
+<marker id="peer_up"/>
+</section>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+
+<funcs>
+
+<func>
+<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>
+</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>
+
+<marker id="peer_down"/>
+</desc>
+</func>
+
+<func>
+<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>
+</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>
+
+<marker id="pick_peer"/>
+</desc>
+</func>
+
+<func>
+<name>Mod:pick_peer(Cands, Reserved, SvcName, State)
+ -> {ok, Peer} | {Peer, NewState} | false</name>
+<fsummary>Select a target peer for an outgoing request.</fsummary>
+<type>
+<v>Cands = [Peer]</v>
+<v>Peer = peer() | false</v>
+<v>SvcName = service_name()</v>
+<v>State = NewState = state()</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>.</p>
+<!--
+The local candidates are those whose transport process is executing on
+the local Erlang node, the remote list those that are available on
+other nodes.</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
+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
+retransmission to an alternate peer is abandoned if an answer is
+received from a previously selected peer.</p>
+
+<marker id="prepare_request"/>
+</desc>
+
+</func>
+
+<func>
+<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>
+</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.
+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
+<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.</p>
+
+<p>
+Any returned packet() can 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.
+A specified <c>message_length</c> 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
+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>
+<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>
+</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
+a peer connection is lost an an alternate peer selected but the
+Packet passed to <c>prepare_retransmit/3</c> is as returned by
+<c>prepare_request/3</c>.</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
+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>
+
+<func>
+<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>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.</p>
+
+<p>
+The decoded answer record is in the <c>msg</c> field of <c>Packet</c>,
+the undecoded binary in the <c>packet</c> field.
+<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>
+
+<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
+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>
+
+<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}</c>.
+There is no <c>handle_error/4</c> callback in this case.
+Application configuration may change this behaviour as described for
+<seealso
+marker="diameter#start_service">diameter:start_service/2</seealso>.</p>
+
+<marker id="handle_error"/>
+</desc>
+</func>
+
+<func>
+<name>Mod:handle_error(Reason, Request, SvcName, Peer) -> Result</name>
+<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>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.</p>
+
+<p>
+Reason <c>timeout</c> indicates that an answer message has not been
+received within the required time.
+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>
+
+<marker id="handle_request"/>
+</desc>
+</func>
+
+<func>
+<name>Mod:handle_request(Packet, SvcName, Peer) -> Action</name>
+<fsummary>Receive an incoming request.</fsummary>
+<type>
+<v>Packet = packet()</v>
+<v>SvcName = term()</v>
+<v>Peer = peer()</v>
+<v>Action = Reply | NoReply | Relay | {eval, Action, ContF}</v>
+<v>Reply = {reply, message()}
+ | {protocol_error, ResultCode}</v>
+<v>NoReply = discard</v>
+<v>Relay = {relay, Opts}</v>
+<v>Opts = list()</v>
+<v>ContF = diameter:evaluable()</v>
+<v>ResultCode = 3000..3999</v>
+</type>
+<desc>
+<p>
+Invoked when a request message is received from a peer.</p>
+
+<p>
+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>)
+is determined by the Application Identifier in the header of the
+incoming Diameter request message, the selected module being the one
+whose corresponding <seealso
+marker="diameter_dict#MESSAGE_RECORDS">dictionary</seealso> declares
+itself as defining the application in question, or the RFC 3588 relay
+application if the specific application is unsupported but the relay
+application has been advertised.</p>
+
+<p>
+The packet() in which the incoming request is communicated has the
+following signature.</p>
+
+<code>
+#diameter_packet{header = #diameter_header{},
+ avps = [#diameter_avp{}],
+ msg = record() | undefined,
+ errors = [integer() | {integer(), #diameter_avp{}}],
+ bin = binary(),
+ transport_data = term()}
+</code>
+
+<p>
+The <c>msg</c> field will be <c>undefined</c> only 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>
+
+<p>
+The <c>errors</c> field specifies any non-protocol errors that were
+encountered in decoding the request and can be returned in a
+<c>reply</c> tuple to have diameter set the Result-Code and Failed-AVP
+AVP's appropriately.
+The list is empty if the request has been received in the relay
+application.</p>
+
+<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>
+
+<p>
+The semantics of each of the possible return values are as follows.
+(TODO: more.)</p>
+
+<taglist>
+
+<tag><c>{reply, Answer}</c></tag>
+<item>
+<p>
+Send the specified answer message to the peer.</p>
+</item>
+
+<tag><c>{relay, Opts}</c></tag>
+<item>
+<p>
+Relay a request to another peer.</p>
+</item>
+
+<tag><c>{protocol_error, ResultCode}</c></tag>
+<item>
+<p>
+Send an answer message to the peer containing the specified 3xxx
+protocol error.</p>
+
+<p>
+RFC 3588 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, ResultCode}</c>
+tuple will cause the request process in question to fail.</p>
+</item>
+
+<tag><c>discard</c></tag>
+<item>
+<p>
+Discard the request.</p>
+</item>
+
+<tag><c>{eval, Action, ContF}</c></tag>
+<item>
+<p>
+Handle the request as if <c>Action</c> has been returned and then
+evaluate the evaluable() <c>ContF</c> in the request process.</p>
+</item>
+
+</taglist>
+
+<p>
+Note that diameter will respond to protocol errors in an incoming
+request without invoking the a <c>handle_request/3</c> callback.</p>
+
+</desc>
+</func>
+
+</funcs>
+
+</erlref>
diff --git a/lib/diameter/doc/src/diameter_compile.xml b/lib/diameter/doc/src/diameter_compile.xml
new file mode 100644
index 0000000000..72bac30709
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_compile.xml
@@ -0,0 +1,124 @@
+<?xml version="1.0" encoding="iso-8859-1" ?>
+<!DOCTYPE comref SYSTEM "comref.dtd">
+
+<comref>
+<header>
+<copyright>
+<year>2011</year>
+<holder>Ericsson AB. All Rights Reserved.</holder>
+</copyright>
+<legalnotice>
+
+The program may be used and/or copied only with the written permission
+from Ericsson AB, or in accordance with the terms and conditions
+stipulated in the agreement/contract under which the program has been
+supplied.
+
+</legalnotice>
+
+<title>diameterc(1)</title>
+
+<prepared></prepared>
+<docno></docno>
+<date></date>
+<rev></rev>
+<file>diameter_compile.xml</file>
+</header>
+
+<com>diameterc</com>
+<comsummary><![CDATA[diameterc [<options>] <file>]]></comsummary>
+
+<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
+to encode and decode the dictionary's messages and AVP's.</p>
+
+</description>
+
+<section>
+<title>USAGE</title>
+
+<taglist>
+
+<tag><![CDATA[diameterc [<options>] <file>]]></tag>
+<item>
+<p>
+Transforms a single dictionary file. Valid options are as follows.</p>
+
+<!-- Leave -h/d/v undocumented, except for the usage message from the
+ utility itself. -->
+
+<taglist>
+<tag><![CDATA[-o <dir>]]></tag>
+<item>
+<p>
+Specifies the directory into which the generated source should be written.
+Defaults to the current working directory.</p>
+</item>
+
+<tag><![CDATA[-i <dir>]]></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>
+</item>
+
+<tag><![CDATA[-E]]></tag>
+<item>
+<p>
+Supresses erl generation.</p>
+</item>
+
+<tag><![CDATA[-H]]></tag>
+<item>
+<p>
+Supresses hrl generation.</p>
+</item>
+
+</taglist>
+
+</item>
+</taglist>
+
+</section>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>EXIT STATUS</title>
+
+<p>
+Returns 0 on success, non-zero on failure.</p>
+
+</section>
+
+<!-- ===================================================================== -->
+
+<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>
+
+</section>
+
+</comref>
diff --git a/lib/diameter/doc/src/diameter_dict.xml b/lib/diameter/doc/src/diameter_dict.xml
new file mode 100644
index 0000000000..5bc3cab9e4
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_dict.xml
@@ -0,0 +1,601 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE erlref SYSTEM "fileref.dtd">
+
+<fileref>
+<header>
+
+<copyright>
+<year>2011</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_dict(4)</title>
+<prepared>Anders Svensson</prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev>%VSN%</rev>
+<file>diameter_dict.xml</file>
+</header>
+
+<!-- ===================================================================== -->
+
+<file>diameter_dict</file>
+<filesummary>Dictionary inteface of the diameter application.</filesummary>
+
+<description>
+<p>
+A diameter service as configured with <seealso
+marker="diameter#start_service">diameter:start_service/2</seealso>
+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.
+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.</p>
+
+<p>
+The codec generation also results in an hrl 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.
+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.</p>
+
+<!-- TODO: Need some reserved dictionary for agents that shouldn't -->
+<!-- know about specific applications. -->
+
+<p>
+The diameter application defines the base application of RFC 3588 in
+the file diameter_gen_base_rfc3588.dia, and
+this is the only application that diameter itself has any specific
+knowledge of.
+Other applications are callback modules configured for an application
+as far as diameter is concerned.</p>
+
+<p>
+A generated hrl also contains defines for the values of defined for
+AVPs of type Enumerated.</p>
+
+<p>
+See <seealso marker="diameter_compile">diameterc</seealso> for a
+utility that transforms dictionary files into codec modules needed
+at runtime.</p>
+
+<marker id="FILE_FORMAT"/>
+</description>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>FILE FORMAT</title>
+
+<p>
+A specification 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.
+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>
+
+<p>
+The tags, their arguments and the contents of each corresponding
+section are as follows.
+Each section can occur only once unless otherwise specified.
+The order in which sections are specified is unimportant.</p>
+
+<taglist>
+
+<tag><c>@id Number</c></tag>
+<item>
+<p>
+Defines the integer Number as the Diameter Application Id of the
+application in question.
+The section has empty content.</p>
+
+<p>
+The Application Id is set in the Diameter Header of outgoing messages
+of the application, and the value in the header of an incoming message
+is used to identify the relevant dictionary module.</p>
+
+<p>
+Example:</p>
+
+<code>
+@id 16777231
+</code>
+
+</item>
+
+<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>
+
+<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>
+
+<p>
+Example:</p>
+
+<code>
+@name etsi_e2
+</code>
+
+</item>
+
+<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>
+
+<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>
+
+<p>
+Example:</p>
+
+<code>
+@prefix etsi_e2_
+</code>
+
+</item>
+
+<tag><c>@vendor Number Name</c></tag>
+<item>
+<p>
+Defines the integer Number as the the default Vendor-ID of AVP's for
+which the V flag is set.
+Name documents the owner of the application
+but is otherwise unused.
+The section has empty content.</p>
+
+<p>
+Example:</p>
+
+<code>
+@vendor 13019 ETSI
+</code>
+
+</item>
+
+<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
+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>
+
+<p>
+Example:</p>
+
+<code>
+@avp_vendor_id 2937
+
+WWW-Auth
+Domain-Index
+Region-Set
+</code>
+
+</item>
+
+<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>
+
+<p>
+Can occur 0 or more times (with different values of Mod) but all
+dictionaries should typically inherit RFC3588 AVPs from
+diameter_gen_base_rfc3588.</p>
+
+<p>
+Example:</p>
+
+<code>
+@inherits diameter_gen_base_rfc3588
+</code>
+
+</item>
+
+<tag><c>@avp_types</c></tag>
+<item>
+<p>
+Defines the name, code, type and flags of individual AVPs.
+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>
+
+<p>
+Example:</p>
+
+<code>
+@avp_types
+
+Location-Information 350 Grouped VM
+Requested-Information 353 Enumerated V
+</code>
+
+<p>
+Note that the P flag has been deprecated by the Diameter Maintenance
+and Extensions Working Group of the IETF.</p>
+
+</item>
+
+<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>
+
+<p>
+Can occur 0 or more times (with different values of Mod).</p>
+
+<p>
+Example:</p>
+
+<code>
+@custom_types rfc4005_types
+
+Framed-IP-Address
+</code>
+</item>
+
+<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>
+
+<!-- RFC 4740 RTR/RTA -->
+<code>
+@messages
+
+RTR ::= &lt; Diameter Header: 287, REQ, PXY >
+ &lt; 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 ]
+
+RTA ::= &lt; Diameter Header: 287, PXY >
+ &lt; 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 ]
+</code>
+
+</item>
+
+<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>
+
+<p>
+Example:</p>
+
+<code>
+@grouped
+
+SIP-Deregistration-Reason ::= &lt; AVP Header: 383 >
+ { SIP-Reason-Code }
+ [ SIP-Reason-Info ]
+ * [ AVP ]
+</code>
+</item>
+
+<tag><c>@enum Name</c></tag>
+<item>
+<p>
+Defines values of AVP Name having type Enumerated.
+Section content consists of names and corresponding integer values.
+Integer values can be prefixed with 0x to be interpreted as
+hexidecimal.</p>
+
+<p>
+Can occur 0 or more times (with different values of Name).</p>
+
+<p>
+Example:</p>
+
+<code>
+@enum SIP-Reason-Code
+
+PERMANENT_TERMINATION 0
+NEW_SIP_SERVER_ASSIGNED 1
+SIP_SERVER_CHANGE 2
+REMOVE_SIP_SERVER 3
+</code>
+</item>
+
+</taglist>
+
+<p>
+Comments can be included in a dictionary file using semicolon:
+text from a semicolon to end of line is ignored.</p>
+
+<marker id="MESSAGE_RECORDS"/>
+</section>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>MESSAGE RECORDS</title>
+
+<p>
+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
+contained in the message or grouped AVP in the order specified in the
+definition in question.
+For example, the grouped AVP</p>
+
+<code>
+SIP-Deregistration-Reason ::= &lt; AVP Header: 383 >
+ { SIP-Reason-Code }
+ [ SIP-Reason-Info ]
+ * [ AVP ]
+</code>
+
+<p>
+will result in the following record definition given an empty
+prefix.</p>
+
+<code>
+-record('SIP-Deregistration-Reason' {'SIP-Reason-Code',
+ 'SIP-Reason-Info',
+ 'AVP'}).
+</code>
+
+<p>
+The values encoded in the fields of generated records depends on the
+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
+types being described below.</p>
+
+<marker id="DATA_TYPES"/>
+</section>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>DATA TYPES</title>
+
+<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
+as values of the types defined here.
+Values are passed to <seealso
+marker="diameter#call">diameter:call/4</seealso>
+in a request record when sending a request, returned in a resulting
+answer record and passed to a diameter_app(3) <seealso
+marker="diameter_app#handle_request">handle_request</seealso>
+callback upon reception of an incoming request.</p>
+
+<p>
+<em>Basic AVP Data Formats</em></p>
+
+<marker id="OctetString"/>
+<marker id="Integer32"/>
+<marker id="Integer64"/>
+<marker id="Unsigned32"/>
+<marker id="Unsigned64"/>
+<marker id="Float32"/>
+<marker id="Float64"/>
+<marker id="Grouped"/>
+
+<code>
+OctetString() = [0..255]
+Integer32() = -2147483647..2147483647
+Integer64() = -9223372036854775807..9223372036854775807
+Unsigned32() = 0..4294967295
+Unsigned64() = 0..18446744073709551615
+Float32() = '-infinity' | float() | infinity
+Float64() = '-infinity' | float() | infinity
+Grouped() = record()
+</code>
+
+<p>
+On encode, an OctetString() can be specified as an iolist(),
+excessively large floats (in absolute value) are equivalent to
+infinity or '-infinity' and excessively large integers result in
+encode failure.
+The records for grouped AVPs are as discussed in the previous
+section.</p>
+
+<p>
+<em>Derived AVP Data Formats</em></p>
+
+<marker id="Address"/>
+<code>
+Address() = OctetString()
+ | tuple()
+</code>
+
+<p>
+On encode, an OctetString() IPv4 address is parsed in the usual
+x.x.x.x format while an IPv6 address is parsed in any of the formats
+specified by section 2.2 of RFC 2373, "Text Representation of
+Addresses".
+An IPv4 tuple() has length 4 and contains values of type 0..255.
+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>
+Time() = {date(), time()}
+
+where
+
+ date() = {Year, Month, Day}
+ time() = {Hour, Minute, Second}
+
+ Year = integer()
+ Month = 1..12
+ Day = 1..31
+ Hour = 0..23
+ Minute = 0..59
+ Second = 0..59
+</code>
+
+<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.
+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>
+UTF8String() = [integer()]
+</code>
+
+<p>
+List elements are the UTF-8 encodings of the individual characters
+in the string.
+Invalid codepoints will result in encode/decode failure.</p>
+
+<marker id="DiameterIdentity"/>
+<code>
+DiameterIdentity() = OctetString()
+</code>
+
+<p>
+A value must have length at least 1.</p>
+
+<marker id="DiameterURI"/>
+<code>
+DiameterURI() = OctetString()
+ | #diameter_URI{type = Type,
+ fqdn = FQDN,
+ port = Port,
+ transport = Transport,
+ protocol = Protocol}
+
+where
+
+ Type = aaa | aaas
+ FQDN = OctetString()
+ Port = integer()
+ Transport = sctp | tcp
+ Protocol = diameter | radius | 'tacacs+'
+</code>
+
+<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.
+The record representation is used on decode.</p>
+
+<marker id="Enumerated"/>
+<code>
+Enumerated() = Integer32()
+</code>
+
+<p>
+On encode, values can be specified using the macros defined in a
+dictionary's hrl file.</p>
+
+<marker id="IPFilterRule"/>
+<marker id="QoSFilterRule"/>
+<code>
+IPFilterRule() = OctetString()
+QoSFilterRule() = OctetString()
+</code>
+
+<p>
+Values of these types are not parsed by diameter.</p>
+
+</section>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+
+<section>
+<title>SEE ALSO</title>
+
+<p>
+<seealso marker="diameter_util">diameterc(1)</seealso></p>
+
+</section>
+
+</fileref>
diff --git a/lib/diameter/doc/src/diameter_examples.xml b/lib/diameter/doc/src/diameter_examples.xml
new file mode 100644
index 0000000000..344b237866
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_examples.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE chapter SYSTEM "chapter.dtd">
+
+<chapter>
+<header>
+
+<copyright>
+<year>2011</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>Examples</title>
+<prepared></prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev></rev>
+<file>diameter_examples.xml</file>
+</header>
+
+<!-- ===================================================================== -->
+
+</chapter>
+
diff --git a/lib/diameter/doc/src/diameter_intro.xml b/lib/diameter/doc/src/diameter_intro.xml
new file mode 100644
index 0000000000..0009b2b77d
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_intro.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE chapter SYSTEM "chapter.dtd">
+
+<chapter>
+<header>
+<copyright>
+<year>2011</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>Introduction</title>
+<prepared></prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev></rev>
+<file>diameter_intro.xml</file>
+</header>
+
+<p>
+The diameter application is an implementation of the Diameter protocol
+as defined by RFC 3588.
+It supports arbitrary Diameter applications by allowing a client to
+specify the commands and AVP's to be supported and has support for
+implementing all roles defined in the RFC: client, server and agent.
+</p>
+
+</chapter>
+
diff --git a/lib/diameter/doc/src/diameter_sctp.xml b/lib/diameter/doc/src/diameter_sctp.xml
new file mode 100644
index 0000000000..d0377f4b38
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_sctp.xml
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE erlref SYSTEM "erlref.dtd">
+
+<erlref>
+<header>
+<copyright>
+<year>2011</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_sctp(3)</title>
+<prepared>Anders Svensson</prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev></rev>
+<file>diameter_sctp.xml</file>
+</header>
+
+<module>diameter_sctp</module>
+<modulesummary>Diameter transport over SCTP.</modulesummary>
+
+<description>
+
+<p>
+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>
+and implements the behaviour documented in
+<seealso marker="diameter_transport">diameter_transport(3)</seealso>.</p>
+
+<marker id="start"/>
+</description>
+
+<!-- ===================================================================== -->
+
+<funcs>
+
+<func>
+<name>start({Type, Ref}, Svc, [Opt])
+ -> {ok, Pid, [LAddr]} | {error, Reason}</name>
+<fsummary>Start a transport process.</fsummary>
+<type>
+<v>Type = connect | accept</v>
+<v>Ref = reference()</v>
+<v>Svc = #diameter_service{}</v>
+<v>Opt = {raddr, ip_address()} | {rport, integer()} | term()</v>
+<v>Pid = pid()</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>
+
+<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 connector and not valid for a listener.
+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
+connector in question attempts each in sequence until an association
+is established.
+Remaining options are any accepted by gen_sctp:open/1, 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
+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.)
+Option <c>port</c> defaults to 3868 for a listener and 0 for a connector.</p>
+
+<p>
+diameter_sctp uses the <c>transport_data</c> field of
+the <c>diameter_packet</c> record to communicate the stream on which an
+inbound message has been received, or on which an outbound message
+should be sent: the value will be of the form <c>{stream, Id}</c>
+on an inbound message passed to a <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>
+(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>
+
+<!-- TODO: Some way of getting at the number of available outbound -->
+<!-- streams. -->
+
+</desc>
+</func>
+
+</funcs>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+
+<section>
+<title>SEE ALSO</title>
+
+<p>
+<seealso marker="diameter_transport">diameter_transport(3)</seealso></p>
+
+</section>
+
+</erlref>
diff --git a/lib/diameter/doc/src/diameter_soc.xml b/lib/diameter/doc/src/diameter_soc.xml
new file mode 100644
index 0000000000..4f8581a904
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_soc.xml
@@ -0,0 +1,110 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE chapter SYSTEM "chapter.dtd">
+
+<chapter>
+
+<header>
+<copyright>
+<year>2011</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>Standards Compliance</title>
+<prepared></prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev></rev>
+<file>diameter_soc.xml</file>
+
+</header>
+
+<p>
+Known points of questionable or non-compliance.</p>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>RFC 3588</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>
+</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>
+</item>
+
+<item>
+<p>
+The peer state machine's election process (section 5.6.4) isn't
+implemented as specified since it assumes knowledge of a
+peer's Origin-Host before sending it a CER. (The identity becoming known
+upon reception of CEA.)
+The possibility of configuring
+the peer's Origin-Host could be added, along with handling of the case
+that it sends something else, but for many applications this will
+just be unnecessary configuration of a value that it has no control over.</p>
+</item>
+<!-- Transport protocol plus address/port, which we do know when
+ sending and receiving CER, is enough to definitely identify
+ the peer. However, there's nothing stopping a peer from using
+ different identities on different transport protocols, even
+ if it's maybe a bit far-fetched. -->
+
+</list>
+
+</section>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>RFC 3539</title>
+
+<p>
+RFC 3539 is more difficult to comply to since it discusses
+problems as much as it requires functionality but all the MUST's are
+covered, the watchdog state machine being the primary one.
+Of the optional functionality, load balancing is left to the
+diameter user (since it's the one deciding who to send to) and
+there is no Congestion Manager.</p>
+
+</section>
+
+</chapter>
diff --git a/lib/diameter/doc/src/diameter_tcp.xml b/lib/diameter/doc/src/diameter_tcp.xml
new file mode 100644
index 0000000000..5d6e07b1b8
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_tcp.xml
@@ -0,0 +1,110 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE erlref SYSTEM "erlref.dtd">
+
+<erlref>
+<header>
+<copyright>
+<year>2011</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_tcp(3)</title>
+<prepared>Anders Svensson</prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev></rev>
+<file>diameter_tcp.xml</file>
+</header>
+
+<module>diameter_tcp</module>
+<modulesummary>Diameter transport over TCP.</modulesummary>
+
+<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>
+and implements the behaviour documented in
+<seealso marker="diameter_transport">diameter_transport(3)</seealso>.</p>
+
+<marker id="start"/>
+</description>
+
+<!-- ===================================================================== -->
+
+<funcs>
+
+<func>
+<name>start({Type, Ref}, Svc, [Opt])
+ -> {ok, Pid, [LAddr]} | {error, Reason}</name>
+<fsummary>Start a transport process.</fsummary>
+<type>
+<v>Type = connect | accept</v>
+<v>Ref = reference()</v>
+<v>Svc = #diameter_service{}</v>
+<v>Opt = {raddr, ip_address()} | {rport, integer()} | term()</v>
+<v>Pid = pid()</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>
+
+<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 connector and not valid for a listener.
+Remaining options are any accepted by gen_tcp:connect/3 for
+a connector, or gen_tcp:listen/2 for a listener, with the exception
+of <c>binary</c>, <c>packet</c> and <c>active</c>.
+Also, option <c>port</c> can be specified for a listener 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>
+
+<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>
+
+<p>
+The returned local address list has length one.</p>
+
+</desc>
+</func>
+
+</funcs>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+
+<section>
+<title>SEE ALSO</title>
+
+<p>
+<seealso marker="diameter_transport">diameter_transport(3)</seealso></p>
+
+</section>
+
+</erlref>
diff --git a/lib/diameter/doc/src/diameter_transport.xml b/lib/diameter/doc/src/diameter_transport.xml
new file mode 100644
index 0000000000..be1bb2c56e
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_transport.xml
@@ -0,0 +1,203 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE erlref SYSTEM "erlref.dtd">
+
+<erlref>
+<header>
+<copyright>
+<year>2011</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_transport(3)</title>
+<prepared>Anders Svensson</prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev></rev>
+<file>diameter_transport.xml</file>
+</header>
+
+<module>diameter_transport</module>
+<modulesummary>Diameter transport behaviour.</modulesummary>
+
+<description>
+
+<p>
+A module specified as a <c>transport_module</c> to <seealso
+marker="diameter#add_transport">diameter:add_transport/2</seealso>
+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>
+
+<!-- ===================================================================== -->
+
+<funcs>
+
+<func>
+<name>Mod:start({Type, Ref}, Svc, Opts)
+ -> {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>Svc = #diameter_service{}</v>
+<v>Opts = term()</v>
+<v>Pid = pid()</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
+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.
+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>
+that has lead to starting of a transport process.</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>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>MESSAGES</title>
+
+<p>
+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>
+
+<taglist>
+
+<tag><c>{diameter, {send, Packet}}</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>
+</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>
+</item>
+
+</taglist>
+
+<p>
+A transport process should send the following messages
+to its parent.</p>
+
+<taglist>
+
+<tag><c>{diameter, {self(), connected}}</c></tag>
+<item>
+<p>
+Inform the parent that the transport process with Type = accept has
+established a connection with the peer.
+Not sent if the transport process has Type = connect.</p>
+</item>
+
+<tag><c>{diameter, {self(), connected, Remote}}</c></tag>
+<item>
+<p>
+Inform the parent that the transport process with Type = connect
+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
+endpoint to which the transport has connected.</p>
+</item>
+
+<tag><c>{diameter, {recv, Packet}}</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>
+</item>
+
+</taglist>
+
+</section>
+
+<!-- ===================================================================== -->
+<!-- ===================================================================== -->
+
+<section>
+<title>SEE ALSO</title>
+
+<p>
+<seealso marker="diameter_tcp">diameter_tcp(3)</seealso>,
+<seealso marker="diameter_sctp">diameter_sctp(3)</seealso></p>
+
+</section>
+
+</erlref>
diff --git a/lib/diameter/doc/src/diameter_using.xml b/lib/diameter/doc/src/diameter_using.xml
new file mode 100644
index 0000000000..737a0a3941
--- /dev/null
+++ b/lib/diameter/doc/src/diameter_using.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE chapter SYSTEM "chapter.dtd">
+
+<chapter>
+
+<header>
+<copyright>
+<year>2011</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>Using the stack</title>
+<prepared></prepared>
+<responsible></responsible>
+<docno></docno>
+<approved></approved>
+<checked></checked>
+<date></date>
+<rev></rev>
+<file>diameter_using.xml</file>
+
+</header>
+
+<!-- ===================================================================== -->
+
+</chapter>
diff --git a/lib/diameter/doc/src/files.mk b/lib/diameter/doc/src/files.mk
new file mode 100644
index 0000000000..23558e394f
--- /dev/null
+++ b/lib/diameter/doc/src/files.mk
@@ -0,0 +1,52 @@
+#-*-makefile-*- ; force emacs to enter makefile-mode
+
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2010. 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%
+
+XML_APPLICATION_FILES = \
+ ref_man.xml
+
+XML_REF1_FILES = \
+ diameter_compile.xml
+
+XML_REF3_FILES = \
+ diameter.xml \
+ diameter_app.xml \
+ diameter_transport.xml \
+ diameter_tcp.xml \
+ diameter_sctp.xml
+
+XML_REF4_FILES = \
+ diameter_dict.xml
+
+XML_PART_FILES = \
+ user_man.xml
+
+XML_EXTRA_FILES =
+
+XML_CHAPTER_FILES = \
+ diameter_intro.xml \
+ diameter_using.xml \
+ diameter_examples.xml \
+ diameter_soc.xml \
+ notes.xml
+
+BOOK_FILES = \
+ book.xml
+
+GIF_FILES = \
+ notes.gif
diff --git a/lib/diameter/doc/src/notes.gif b/lib/diameter/doc/src/notes.gif
new file mode 100644
index 0000000000..e000cca26a
--- /dev/null
+++ b/lib/diameter/doc/src/notes.gif
Binary files differ
diff --git a/lib/diameter/doc/src/notes.xml b/lib/diameter/doc/src/notes.xml
new file mode 100644
index 0000000000..8fdb88749e
--- /dev/null
+++ b/lib/diameter/doc/src/notes.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE chapter SYSTEM "chapter.dtd">
+
+<chapter>
+
+<header>
+<copyright>
+<year>2011</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>Release Notes</title>
+<prepared></prepared>
+<docno></docno>
+<date></date>
+<rev></rev>
+<file>notes.xml</file>
+</header>
+
+<p>
+Releases are listed in reverse chronological order, most recent
+first.</p>
+
+<!-- ===================================================================== -->
+
+<section>
+<title>diameter 0.9</title>
+
+<p>
+First OTP release.</p>
+
+</section>
+
+</chapter>
diff --git a/lib/diameter/doc/src/ref_man.xml b/lib/diameter/doc/src/ref_man.xml
new file mode 100644
index 0000000000..137ce79094
--- /dev/null
+++ b/lib/diameter/doc/src/ref_man.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE application SYSTEM "application.dtd">
+
+<application xmlns:xi="http://www.w3.org/2001/XInclude">
+
+<header>
+<copyright>
+<year>2011</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 Reference Manual</title>
+<prepared></prepared>
+<docno></docno>
+<date></date>
+<rev></rev>
+<file>ref_man.xml</file>
+</header>
+
+<description>
+<p>
+The Diameter application is a framework for building
+applications on top of the Diameter protocol. </p>
+
+</description>
+
+<xi:include href="diameter.xml"/>
+<xi:include href="diameter_compile.xml"/>
+<xi:include href="diameter_app.xml"/>
+<xi:include href="diameter_dict.xml"/>
+<xi:include href="diameter_transport.xml"/>
+<xi:include href="diameter_tcp.xml"/>
+<xi:include href="diameter_sctp.xml"/>
+
+</application>
diff --git a/lib/diameter/doc/src/user_man.xml b/lib/diameter/doc/src/user_man.xml
new file mode 100644
index 0000000000..a6416c7e23
--- /dev/null
+++ b/lib/diameter/doc/src/user_man.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="latin1" ?>
+<!DOCTYPE part SYSTEM "part.dtd">
+
+<part xmlns:xi="http://www.w3.org/2001/XInclude">
+
+<header>
+<copyright>
+<year>2011</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 Users Guide</title>
+<prepared></prepared>
+<docno></docno>
+<date></date>
+<rev></rev>
+<file>user_man.xml</file>
+</header>
+<description>
+
+<p>
+The diameter application is a framework for building
+applications on top of the Diameter protocol. </p>
+</description>
+
+<xi:include href="diameter_intro.xml"/>
+<xi:include href="diameter_using.xml"/>
+<xi:include href="diameter_examples.xml"/>
+<xi:include href="diameter_soc.xml"/>
+
+</part>
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
new file mode 100644
index 0000000000..bb7ec2d08c
--- /dev/null
+++ b/lib/diameter/doc/standard/draft-ietf-dime-capablities-update-07.txt
@@ -0,0 +1,392 @@
+
+
+
+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
+
+
+ Glen Zorn
+ Network Zen
+ 227/358 Thanon Sanphawut
+ Bang Na, Bangkok 10260
+ Thailand
+
+ Phone: +66 (0) 87-040-4617
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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/draft-ietf-dime-rfc3588bis-26.txt
new file mode 100644
index 0000000000..87b9562f93
--- /dev/null
+++ b/lib/diameter/doc/standard/draft-ietf-dime-rfc3588bis-26.txt
@@ -0,0 +1,8681 @@
+
+
+
+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
+ Nokia Research Center
+ G. Zorn
+ Network Zen
+ January 20, 2011
+
+
+ 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.
+
+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 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ (http://trustee.ietf.org/license-info) in effect on the date of
+ publication of this document. Please review these documents
+ carefully, as they describe your rights and restrictions with respect
+ to this document. Code Components extracted from this document must
+ include Simplified BSD License text as described in Section 4.e of
+ the Trust Legal Provisions and are provided without warranty as
+ described in the Simplified BSD License.
+
+
+Table of Contents
+
+ 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 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
+
+ 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.
+
+ Network access requirements for AAA protocols are summarized in
+ [RFC2989]. These include:
+
+
+ Failover
+
+ [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].
+
+ Transmission-level security
+
+ [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.
+
+ While [RFC3162] defines the use of IPsec with RADIUS, support for
+ IPsec is not required. In order to provide universal support for
+ transmission-level security, and enable both intra- and inter-
+ 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
+
+
+
+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].
+
+
+ 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.
+
+
+ Server-initiated messages
+
+ While RADIUS server-initiated messages are defined in [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
+ 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
+ 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
+ devices and Diameter agents. This capability enables Diameter
+ 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:
+
+
+ Capability negotiation
+
+ RADIUS does not support error messages, capability negotiation, or
+ 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
+ service has been implemented. Diameter includes support for error
+
+
+
+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).
+
+
+ Peer discovery and configuration
+
+ 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
+ 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
+ enables dynamic discovery of peers (see Section 5.2). Derivation
+ 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
+ feasible to implement it within embedded devices.
+
+1.1. Diameter Protocol
+
+ The Diameter base protocol provides the following facilities:
+
+ o Ability to exchange messages and deliver AVPs
+
+ o Capabilities negotiation
+
+ o Error notification
+
+ o Extensibility, through addition of new applications, commands and
+ AVPs (required in [RFC2989]).
+
+ o Basic services necessary for applications, such as 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:
+
+
+
+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.
+
+ 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.
+
+ The Diameter base protocol satisfies the minimum requirements for an
+ 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
+ access [RFC4005]. It is also possible for the base protocol to be
+ extended for use in new applications, via the addition of new
+ commands or AVPs. The initial focus of Diameter was network access
+ and accounting applications. A truly generic AAA protocol used by
+ 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.
+
+ 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
+ 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
+ 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.
+
+ The Diameter protocol also supports server-initiated messages, such
+ as a request to abort service to a particular user.
+
+1.1.1. Description of the Document Set
+
+ 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
+
+
+ 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.
+ These application documents specify how to use the Diameter protocol
+ within the context of their application.
+
+ 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).
+
+1.1.2. Conventions Used in This Document
+
+ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+ "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+ document are to be interpreted as described in [RFC2119].
+
+1.1.3. Changes from RFC3588
+
+ 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.
+
+ 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
+ document. As work on this document progressed, it became clear
+ that the multiplicity of meaning and use of Application Id AVPs in
+ the CER/CEA messages (and the messages themselves) is seen as an
+
+
+
+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.
+
+ 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
+ deprecated.
+
+ o Diameter Extensibility Changes. 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
+ 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).
+
+ o Simplification of 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.
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 11]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+1.2. Terminology
+
+ AAA
+
+ Authentication, Authorization and Accounting.
+
+
+ ABNF
+
+ Augmented Backus-Naur Form [RFC5234]. A metalanguage with its own
+ formal syntax and rules. It is based on the Backus-Naur Form and
+ 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
+ allocation.
+
+
+ Accounting Record
+
+ An accounting record represents a summary of the resource
+ consumption of a user over the entire session. Accounting servers
+ creating the accounting record may do so by processing interim
+ 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
+
+ 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
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 12]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ accounting information.
+
+
+ Diameter Agent
+
+ A Diameter Agent is a Diameter Node that provides either relay,
+ proxy, redirect or translation services.
+
+
+ Diameter Client
+
+ 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
+ (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.
+
+
+ Diameter Peer
+
+ If a Diameter Node shares a direct transport connection with
+ another Diameter Node, it is a Diameter Peer to that Diameter
+ Node.
+
+
+ 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
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ Multi-session
+
+ A multi-session represents a logical linking of several sessions.
+ Multi-sessions are tracked by using the Acct-Multi-Session-Id. An
+ example of a multi-session would be a Multi-link PPP bundle. Each
+ 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
+ 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
+ applications.
+
+
+ Realm
+
+ The string in the NAI that immediately follows the '@' character.
+ 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
+ routed or redirected. In RADIUS, realm names are not necessarily
+ piggybacked on the DNS namespace but may be independent of it.
+
+
+ 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
+ application that defines real-time accounting functionality.
+
+
+ Relay Agent or Relay
+
+ Relays forward requests and responses based on routing-related
+ AVPs and routing table entries. Since relays do not make policy
+ decisions, they do not examine or alter non-routing AVPs. As a
+ result, relays never originate messages, do not need to understand
+ 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
+ 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
+ servers, redirect agents refer clients to servers and allow them
+ to communicate directly. Since redirect agents do not sit in the
+ forwarding path, they do not alter any AVPs transiting between
+ 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
+ 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
+ particular activity. Diameter application documents provide
+ guidelines as to when a session begins and ends. All Diameter
+ 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.
+
+
+ Sub-session
+
+ A sub-session represents a distinct service (e.g., QoS or data
+ characteristics) provided to a given session. These services may
+ happen concurrently (e.g., simultaneous voice and data transfer
+ during the same session) or serially. These changes in sessions
+ are tracked with the Accounting-Sub-Session-Id.
+
+
+ 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
+ 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.
+
+
+ Upstream
+
+ Upstream is used to identify the direction of a particular
+ 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
+ mechanisms, including:
+
+ o Defining new AVP values
+
+ o Creating new AVPs
+
+ o Creating new commands
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Note: Protocol designers should try to re-use 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
+ useful in a Diameter application.
+
+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
+ AVP value. IANA considerations for these AVP values are discussed in
+ Section 11.4.
+
+ 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.
+
+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.
+
+ 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.
+
+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
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ A change to the ABNF 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
+ 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
+ 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
+ then a failure is generated (see Section 7).
+
+ It is the decision of the protocol designer when to develop a new
+ Diameter application rather than extending Diameter in other ways.
+ However, a new Diameter application MUST be created when one or more
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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 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
+ 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
+ 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
+ connections to peers, capabilities negotiation, how messages are sent
+ and routed through peers, and how the connections are eventually torn
+ down. The base protocol also defines certain rules that apply to all
+ message exchanges between Diameter nodes.
+
+ Communication between Diameter peers begins with one peer sending a
+ message to another Diameter peer. The set of AVPs included in the
+ message is determined by a particular Diameter application. One AVP
+ that is included to reference a user's session is the Session-Id.
+
+ 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
+ Diameter server or client receiving a request depends on the Diameter
+ application employed.
+
+ Session state (associated with a Session-Id) MUST be freed upon
+ receipt of the Session-Termination-Request, Session-Termination-
+ Answer, expiration of authorized service time in the Session-Timeout
+ AVP, and according to rules established in a particular Diameter
+ application.
+
+ The base Diameter protocol may be used by itself for accounting
+ applications. For authentication and authorization, it is always
+ extended for a particular application.
+
+ 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".
+
+ 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
+ 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
+
+
+ includes accounting, and all Diameter applications.
+
+ Diameter proxies MUST support the base protocol, which includes
+ accounting. In addition, they MUST fully support each Diameter
+ application that is needed to implement proxied services, e.g.,
+ NASREQ and/or Mobile IPv4. A Diameter proxy MUST be referred to as
+ "Diameter X Proxy" where X is the application which it supports, and
+ not a "Diameter Proxy".
+
+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.
+
+ 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).
+
+ Diameter clients MUST support either TCP or SCTP, while 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.
+
+ When no transport connection exists with a peer, an attempt to
+ connect SHOULD be periodically made. 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
+
+
+
+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.
+
+ Diameter implementations SHOULD be able to interpret ICMP protocol
+ port unreachable messages as explicit indications that the server is
+ not reachable, subject to security policy on trusting such messages.
+ Further guidance regarding the treatment of ICMP errors can be found
+ in [RFC5927] and [RFC5461]. Diameter implementations SHOULD also be
+ able to interpret a reset from the transport and timed-out connection
+ attempts. If Diameter receives data from the lower layer that cannot
+ be parsed or identified as a Diameter error made by the peer, the
+ stream is compromised and cannot be recovered. The transport
+ connection MUST be closed using a RESET call (send a TCP RST bit) or
+ an SCTP ABORT message (graceful closure is compromised).
+
+2.1.1. SCTP Guidelines
+
+ 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.
+
+ Out-of-order delivery has special concerns during a connection
+ establishment and termination. When a connection is established, the
+ responder side sends a CEA message and moves to R-Open state as
+ specified in Section 5.6. If an application message is sent shortly
+ after the CEA and delivered out-of-order, the initiator side, still
+ in Wait-I-CEA state, will discard the application message and close
+ 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.
+
+ Another race condition may occur when DPR and DPA messages are used.
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 23]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+2.2. Securing Diameter Messages
+
+ Connections between Diameter peers SHOULD be protected by TLS/TCP and
+ DTLS/SCTP. All Diameter base protocol implementations MUST support
+ 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.
+
+2.3. Diameter Application Compliance
+
+ Application Ids are advertised during the capabilities exchange phase
+ (see Section 5.3). Advertising support of an application implies
+ that the sender supports the functionality specified in the
+ respective Diameter application specification.
+
+ 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
+ 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.
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+ Diameter relay and proxy agents are responsible for finding an
+ upstream server that supports the application of a particular
+ message. If none can be found, an error message is returned with the
+ Result-Code AVP set to DIAMETER_UNABLE_TO_DELIVER.
+
+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.
+
+ 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
+ Diameter client and the Diameter server; it is identified via the
+ Session-Id AVP.
+
+
+ +--------+ +-------+ +--------+
+ | Client | | Relay | | Server |
+ +--------+ +-------+ +--------+
+ <----------> <---------->
+ peer connection A peer connection B
+
+ <----------------------------->
+ User session x
+
+ 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
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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:
+
+ Host identity
+
+ Following the conventions described for the DiameterIdentity
+ derived AVP data format in Section 4.3. 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
+ values listed in Section 5.6.
+
+
+ Static or Dynamic
+
+ Specifies whether a peer entry was statically configured or
+ dynamically discovered.
+
+
+ Expiration time
+
+ Specifies the time at which dynamically discovered peer table
+ entries are to be either refreshed, or expired.
+
+
+ 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)
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 26]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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:
+
+ Realm Name
+
+ This is the field that is 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
+ can have a different destination based on the Application Id in
+ 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.
+
+ 2. RELAY - All Diameter messages that fall within this category
+ 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
+
+ 3. PROXY - All Diameter messages that fall within this category
+ MUST be routed to a next Diameter entity that is indicated by
+ the identifier described below. The local server MAY apply
+ its local policies to the message by including new AVPs to the
+ message prior to routing. See Section 6.1.9 for proxying
+ guidelines.
+
+ 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.
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 27]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ Action field is set to REDIRECT, this field contains the identity
+ of one or more servers the message MUST be redirected to.
+
+ Static or Dynamic
+
+ Specifies whether a route entry was statically configured or
+ dynamically discovered.
+
+ Expiration time
+
+ Specifies the time at which a dynamically discovered route table
+ entry expires.
+
+ It is important to note that Diameter agents MUST support at least
+ 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.
+
+ 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
+ advertised itself as a relay or proxy agent. Otherwise, an error is
+ returned with the Result-Code AVP set to DIAMETER_UNABLE_TO_DELIVER.
+
+2.8. Role of Diameter Agents
+
+ 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
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ o They can do value-added processing to the requests or responses.
+
+ o They can be used for load balancing.
+
+ o A complex network will have multiple authentication sources, they
+ can sort requests and forward towards the correct target.
+
+ 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
+ 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
+ answer. A stateless agent is one that only maintains transaction
+ state.
+
+ The Proxy-Info AVP allows stateless agents to add local state to a
+ Diameter request, with the guarantee that the same state will be
+ present in the answer. However, the protocol's failover procedures
+ require that agents maintain a copy of pending requests.
+
+ 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
+ expires. Each authorized session has an expiration, which is
+ communicated by Diameter servers via the Session-Timeout AVP.
+
+ Maintaining session state may be useful in certain applications, such
+ as:
+
+ o Protocol translation (e.g., RADIUS <-> Diameter)
+
+ o Limiting resources authorized to a particular user
+
+ o Per user or 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
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+ Relays modify Diameter messages by inserting and removing routing
+ information, but do not modify any other portion of a message.
+ Relays SHOULD NOT maintain session state but MUST maintain
+ transaction state.
+
+ +------+ ---------> +------+ ---------> +------+
+ | | 1. Request | | 2. Request | |
+ | NAS | | DRL | | HMS |
+ | | 4. Answer | | 3. Answer | |
+ +------+ <--------- +------+ <--------- +------+
+ example.net example.net example.com
+
+ Figure 2: Relaying of Diameter messages
+
+ The example provided in Figure 2 depicts a request issued from NAS,
+ which is an access device, for the user [email protected]. Prior to
+ issuing the request, 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
+ 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.
+
+2.8.2. Proxy Agents
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+ Since enforcing policies requires an understanding of the service
+ being provided, Proxies MUST only advertise the Diameter applications
+ they support.
+
+2.8.3. Redirect Agents
+
+ Redirect agents are useful in scenarios where the Diameter routing
+ configuration needs to be centralized. An example is a redirect
+ agent that provides services to all members of a consortium, but does
+ not wish to be burdened with relaying all messages between realms.
+ This scenario is advantageous since it does not require that the
+ consortium provide routing updates to its members when changes are
+ made to a member's infrastructure.
+
+ Since redirect agents do not relay messages, and only return an
+ answer with the information necessary for Diameter agents to
+ communicate directly, they do not modify messages. Since redirect
+ agents do not receive answer messages, they cannot maintain session
+ state.
+
+ 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
+ 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.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 31]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ +------+
+ | |
+ | DRD |
+ | |
+ +------+
+ ^ |
+ 2. Request | | 3. Redirection
+ | | Notification
+ | v
+ +------+ ---------> +------+ ---------> +------+
+ | | 1. Request | | 4. Request | |
+ | NAS | | DRL | | HMS |
+ | | 6. Answer | | 5. Answer | |
+ +------+ <--------- +------+ <--------- +------+
+ example.net example.net example.com
+
+ Figure 3: Redirecting a Diameter Message
+
+ 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.
+
+2.8.4. Translation Agents
+
+ A translation agent is a device that provides translation between two
+ protocols (e.g., RADIUS<->Diameter, TACACS+<->Diameter). Translation
+ agents are likely to be used as aggregation servers to communicate
+ with a Diameter infrastructure, while allowing for the embedded
+ systems to be migrated at a slower pace.
+
+ Given that the Diameter protocol introduces the concept of long-lived
+ authorized sessions, translation agents MUST be session stateful and
+ MUST maintain transaction state.
+
+ Translation of messages can only occur if the agent recognizes the
+ application of a particular request, and therefore translation agents
+ MUST only advertise their locally supported applications.
+
+ +------+ ---------> +------+ ---------> +------+
+ | | RADIUS Request | | Diameter Request | |
+ | NAS | | TLA | | HMS |
+ | | RADIUS Answer | | Diameter Answer | |
+ +------+ <--------- +------+ <--------- +------+
+ example.net example.net example.com
+
+ Figure 4: Translation of RADIUS to Diameter
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 32]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+2.9. Diameter Path Authorization
+
+ 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.
+
+ 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.
+
+ Prior to bringing up a connection, authorization checks are performed
+ at each connection along the path. Diameter capabilities negotiation
+ (CER/CEA) also MUST be carried out, in order to determine what
+ Diameter applications are supported by each peer. Diameter sessions
+ MUST be routed only through authorized nodes that have advertised
+ support for the Diameter application required by the session.
+
+ 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.
+
+ The home Diameter server, prior to authorizing a session, MUST check
+ the Route-Record AVPs to make sure that the route traversed by the
+ request is acceptable. For example, administrators within the home
+ 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
+ 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.
+
+ A home realm may also wish to check that each accounting request
+ message corresponds to a Diameter response authorizing the session.
+ Accounting requests without corresponding authorization responses
+ SHOULD be subjected to further scrutiny, as should accounting
+ requests indicating a difference between the requested and provided
+ service.
+
+ Forwarding of an authorization response is considered evidence of a
+ 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
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 33]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ 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
+ are transmitted in network byte order.
+
+ 0 1 2 3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Version | Message Length |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | command flags | Command-Code |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Application-ID |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Hop-by-Hop Identifier |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | End-to-End Identifier |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | AVPs ...
+ +-+-+-+-+-+-+-+-+-+-+-+-+-
+
+ Version
+
+ This Version field MUST be set to 1 to indicate Diameter Version
+ 1.
+
+ Message Length
+
+ 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.
+
+ Command Flags
+
+ The Command Flags field is eight bits. The following bits are
+ assigned:
+
+ 0 1 2 3 4 5 6 7
+ +-+-+-+-+-+-+-+-+
+ |R P E T r r r r|
+ +-+-+-+-+-+-+-+-+
+
+ R(equest)
+
+ 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
+ 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.
+ 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.
+
+
+ T(Potentially re-transmitted 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.
+
+
+ r(eserved)
+
+ These flag bits are reserved for future use, and 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+ 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.
+
+
+ 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
+ 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
+ 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
+ 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.
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 37]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ AVPs
+
+ AVPs are a method of encapsulating information relevant to the
+ Diameter message. See Section 4 for more information on AVPs.
+
+3.1. Command Codes
+
+ 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
+ be taken for a particular message. The following Command Codes are
+ defined in the Diameter base protocol:
+
+ Command-Name Abbrev. Code Reference
+ --------------------------------------------------------
+ Abort-Session-Request ASR 274 8.5.1
+ Abort-Session-Answer ASA 274 8.5.2
+ Accounting-Request ACR 271 9.7.1
+ Accounting-Answer ACA 271 9.7.2
+ Capabilities-Exchange- CER 257 5.3.1
+ Request
+ Capabilities-Exchange- CEA 257 5.3.2
+ Answer
+ Device-Watchdog-Request DWR 280 5.5.1
+ Device-Watchdog-Answer DWA 280 5.5.2
+ Disconnect-Peer-Request DPR 282 5.4.1
+ Disconnect-Peer-Answer DPA 282 5.4.2
+ Re-Auth-Request RAR 258 8.3.1
+ Re-Auth-Answer RAA 258 8.3.2
+ Session-Termination- STR 275 8.4.1
+ Request
+ 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 / "-")
+
+ diameter-message = header [ *fixed] [ *required] [ *optional]
+
+ header = "<" "Diameter Header:" command-id
+ [r-bit] [p-bit] [e-bit] [application-id] ">"
+
+ 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.
+
+ 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'.
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 39]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+
+
+ The following is a definition of a fictitious command code:
+
+ Example-Request ::= < Diameter Header: 9999999, REQ, PXY >
+ { User-Name }
+ * { Origin-Host }
+ * [ AVP ]
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 40]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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.
+
+ An example is a message set used to terminate a session. The command
+ name is Session-Terminate-Request and Session-Terminate-Answer, while
+ 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
+ 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
+ answer, which includes a result code that communicates one of the
+ following:
+
+ o The request was successful
+
+ o The request failed
+
+ o An additional request has to be sent to provide information the
+ peer requires prior to returning a successful or failed answer.
+
+ o The receiver could not process the request, but provides
+ information about a Diameter peer that is able to satisfy the
+ request, known as redirect.
+
+ Additional information, encoded within AVPs, may also be included in
+ answer messages.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 41]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+4. Diameter AVPs
+
+ 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
+ boundary is reached. The length of the padding is not reflected in
+ the AVP Length field.
+
+4.1. AVP Header
+
+ The fields in the AVP header MUST be sent in network byte order. The
+ format of the header is:
+
+ 0 1 2 3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | AVP Code |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ |V M P r r r r r| AVP Length |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Vendor-ID (opt) |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Data ...
+ +-+-+-+-+-+-+-+-+
+
+ AVP Code
+
+ 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.
+ AVP numbers 256 and above are used for Diameter, which are
+ allocated by IANA (see Section 11.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.
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 42]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ 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.
+
+ 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.
+
+ 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
+ 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.
+
+4.1.1. Optional Header Elements
+
+ 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
+
+
+
+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.
+
+4.2. Basic AVP Data Formats
+
+ The Data field is zero or more octets and contains information
+ specific to the Attribute. The format and length of the Data field
+ is determined by the AVP Code and AVP Length fields. The format of
+ the Data field MUST be one of the following base data types or a data
+ 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.
+
+
+ Integer32
+
+ 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
+ MUST be set to 16 (20 if the 'V' bit is enabled).
+
+
+ Unsigned32
+
+ 32 bit unsigned value, in network byte order. The AVP Length
+ field MUST be set to 12 (16 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).
+
+
+ Float32
+
+ This represents floating point values of single precision as
+ described by [FLOATPOINT]. The 32-bit value is transmitted in
+ 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
+ described by [FLOATPOINT]. The 64-bit value is transmitted in
+ 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.
+
+
+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
+ 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
+
+ The following are commonly used Derived AVP Data Formats.
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 45]
+
+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.
+
+
+ Time
+
+ The Time format is derived from the OctetString AVP Base 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].
+
+ 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.
+
+
+ UTF8String
+
+ The UTF8String format is derived from the OctetString AVP Base
+ 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.
+
+ Since additional code points are added by amendments to the 10646
+ standard from time to time, implementations MUST be prepared to
+ encounter any code point from 0x00000001 to 0x7fffffff. Byte
+ sequences that do not correspond to the valid encoding of a code
+ point into UTF-8 charset or are outside this range are prohibited.
+
+ The use of control codes SHOULD be avoided. When it is necessary
+ to represent a new line, the control code sequence CR LF SHOULD be
+ used.
+
+ The use of leading or trailing white space SHOULD be avoided.
+
+ For code points not directly supported by user interface hardware
+ 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
+ different from the number of characters encoded.
+
+ Note that the AVP Length field of an UTF8String is measured in
+ octets, not characters.
+
+ DiameterIdentity
+
+ The DiameterIdentity format is derived from the OctetString AVP
+ Base Format.
+
+ DiameterIdentity = FQDN/Realm
+
+
+ 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,
+ or whether they must be routed or redirected.
+
+
+ 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 (URI)
+ syntax [RFC3986] rules specified below:
+
+
+
+
+
+
+
+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
+
+ port = ":" 1*DIGIT
+
+ ; One of the ports used to listen for
+ ; incoming connections.
+ ; If absent, the default Diameter port
+ ; (3868) is assumed if no transport
+ ; security is used and port (TBD) when
+ ; transport security (TLS/TCP and DTLS/SCTP) is used.
+
+ transport = ";transport=" transport-protocol
+
+ ; One of the transports used to listen
+ ; for incoming connections. If absent,
+ ; the default protocol is assumed to be TCP.
+ ; UDP MUST NOT be used when the aaa-protocol
+ ; field is set to diameter.
+
+ transport-protocol = ( "tcp" / "sctp" / "udp" )
+
+ protocol = ";protocol=" aaa-protocol
+
+ ; If absent, the default AAA protocol
+ ; is Diameter.
+
+ aaa-protocol = ( "diameter" / "radius" / "tacacs+" )
+
+ 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
+
+
+
+
+
+
+
+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.
+
+
+ IPFilterRule
+
+ The IPFilterRule format is derived from the OctetString AVP Base
+ 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:
+
+ Direction (in or out)
+ Source and destination IP address (possibly masked)
+ Protocol
+ Source and destination port (lists or ranges)
+ TCP flags
+ IP fragment flag
+ 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.
+
+ IPFilterRule filters MUST follow the format:
+
+ action dir proto from src to dst [options]
+
+ action permit - Allow packets that match the rule.
+ deny - Drop packets that match the rule.
+
+ dir "in" is from the terminal, "out" is to the
+ terminal.
+
+ proto An IP protocol specified by number. The "ip"
+ keyword means any protocol will match.
+
+ src and dst <address/mask> [ports]
+
+ The <address/mask> may be specified as:
+ ipno An IPv4 or IPv6 number in dotted-
+ quad or canonical IPv6 form. Only
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 49]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ NOT have bits set beyond the mask.
+ For a match to occur, the same IP
+ version must be present in the
+ packet that was used in describing
+ the IP address. To test for a
+ particular IP version, the bits part
+ can be set to zero. The keyword
+ "any" is 0.0.0.0/0 or the IPv6
+ equivalent. The keyword "assigned"
+ is the address or set of addresses
+ assigned to the terminal. For IPv4,
+ a typical first rule is often "deny
+ in ip! assigned"
+
+ The sense of the match can be inverted by
+ preceding an address with the not modifier (!),
+ causing all other addresses to be matched
+ instead. This does not affect the selection of
+ port numbers.
+
+ With the TCP, UDP and SCTP protocols, optional
+ ports may be specified as:
+
+ {port/port-port}[,ports[,...]]
+
+ The '-' notation specifies a range of ports
+ (including boundaries).
+
+ Fragmented packets that have a non-zero offset
+ (i.e., not the first fragment) will never match
+ a rule that has one or more port
+ specifications. See the frag option for
+ details on matching fragmented packets.
+
+ options:
+ frag Match if the packet is a fragment and this is not
+ the first fragment of the datagram. frag may not
+ be used in conjunction with either tcpflags or
+ TCP/UDP port specifications.
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 50]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ (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
+ supported TCP options are:
+
+ mss (maximum segment size), window (tcp window
+ advertisement), sack (selective ack), ts (rfc1323
+ timestamp) and cc (rfc1644 t/tcp connection
+ count). The absence of a particular option may
+ be denoted with a '!'.
+
+ established
+ TCP packets only. Match packets that have the RST
+ or ACK bits set.
+
+ setup TCP packets only. Match packets that have the SYN
+ bit set but no ACK bit.
+
+
+ tcpflags spec
+ TCP packets only. Match if the TCP header
+ 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
+ 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
+ offset. See the frag option for details on
+ matching fragmented packets.
+
+ icmptypes types
+ ICMP packets only. Match if the ICMP type is in
+ the list types. The list may be specified as any
+ combination of ranges or individual types
+ separated by commas. Both the numeric values and
+ the symbolic values listed below can be used. The
+ supported ICMP types are:
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 51]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ echo reply (0), destination unreachable (3),
+ source quench (4), redirect (5), echo request
+ (8), router advertisement (9), router
+ 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)
+ 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.
+
+
+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.
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 52]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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]
+
+ 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.
+
+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:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 53]
+
+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".
+
+
+ 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>
+ 2163bc1d0ad82371f6bc09484133c3f09ad74a0dd5346d54195a7cf0b35
+ 2cabc881839a4fdcfbc1769e2677a4c1fb499284c5f70b48f58503a45c5
+ c2d6943f82d5930f2b7c1da640f476f0e9c9572a50db8ea6e51e1c2c7bd
+ f8bb43dc995144b8dbe297ac739493946803e1cee3e15d9b765008a1b2a
+ cf4ac777c80041d72c01e691cf751dbf86e85f509f3988e5875dc905119
+ 26841f00f0e29a6d1ddc1a842289d440268681e052b30fb638045f7779c
+ 1d873c784f054f688f5001559ecff64865ef975f3e60d2fd7966b8c7f92
+
+ Futuristic-Acct-Record = <binary>
+ fe19da5802acd98b07a5b86cb4d5d03f0314ab9ef1ad0b67111ff3b90a0
+ 57fe29620bf3585fd2dd9fcc38ce62f6cc208c6163c008f4258d1bc88b8
+ 17694a74ccad3ec69269461b14b2e7a4c111fb239e33714da207983f58c
+ 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
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 54]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ size.
+
+
+ This AVP would be encoded as follows:
+
+ 0 1 2 3 4 5 6 7
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 0 | Example AVP Header (AVP Code = 999999), Length = 496 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 8 | Origin-Host AVP Header (AVP Code = 264), Length = 19 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 16 | 'e' | 'x' | 'a' | 'm' | 'p' | 'l' | 'e' | '.' |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 24 | 'c' | 'o' | 'm' |Padding| Session-Id AVP Header |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 32 | (AVP Code = 263), Length = 49 | 'g' | 'r' | 'u' | 'm' |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 72 | 'F' | '3' | 'B' | '8' | '1' |Padding|Padding|Padding|
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 80 | Session-Id AVP Header (AVP Code = 263), Length = 50 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 88 | 'g' | 'r' | 'u' | 'm' | 'p' | '.' | 'e' | 'x' |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 120| '5' | '8' | ';' | '0' | 'A' | 'F' | '3' | 'B' |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 128| '8' | '2' |Padding|Padding| Recovery-Policy Header (AVP |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 136| Code = 8341), Length = 223 | 0x21 | 0x63 | 0xbc | 0x1d |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 144| 0x0a | 0xd8 | 0x23 | 0x71 | 0xf6 | 0xbc | 0x09 | 0x48 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 352| 0x8c | 0x7f | 0x92 |Padding| Futuristic-Acct-Record Header |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 328|(AVP Code = 15930),Length = 137| 0xfe | 0x19 | 0xda | 0x58 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 336| 0x02 | 0xac | 0xd9 | 0x8b | 0x07 | 0xa5 | 0xb8 | 0xc6 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 488| 0xe4 | 0x99 | 0x68 | 0xf8 | 0x41 |Padding|Padding|Padding|
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 55]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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.
+
+ Due to space constraints, the short form DiamIdent is used to
+ represent DiameterIdentity.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 56]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ +----------+
+ | AVP Flag |
+ | rules |
+ |----+-----|
+ AVP Section | |MUST |
+ Attribute Name Code Defined Data Type |MUST| NOT |
+ -----------------------------------------|----+-----|
+ Acct- 85 9.8.2 Unsigned32 | M | V |
+ Interim-Interval | | |
+ Accounting- 483 9.8.7 Enumerated | M | V |
+ Realtime-Required | | |
+ Acct- 50 9.8.5 UTF8String | M | V |
+ Multi-Session-Id | | |
+ Accounting- 485 9.8.3 Unsigned32 | M | V |
+ Record-Number | | |
+ Accounting- 480 9.8.1 Enumerated | M | V |
+ Record-Type | | |
+ Accounting- 44 9.8.4 OctetString| M | V |
+ Session-Id | | |
+ Accounting- 287 9.8.6 Unsigned64 | M | V |
+ Sub-Session-Id | | |
+ Acct- 259 6.9 Unsigned32 | M | V |
+ Application-Id | | |
+ Auth- 258 6.8 Unsigned32 | M | V |
+ Application-Id | | |
+ Auth-Request- 274 8.7 Enumerated | M | V |
+ Type | | |
+ Authorization- 291 8.9 Unsigned32 | M | V |
+ Lifetime | | |
+ Auth-Grace- 276 8.10 Unsigned32 | M | V |
+ Period | | |
+ Auth-Session- 277 8.11 Enumerated | M | V |
+ State | | |
+ Re-Auth-Request- 285 8.12 Enumerated | M | V |
+ Type | | |
+ Class 25 8.20 OctetString| M | V |
+ Destination-Host 293 6.5 DiamIdent | M | V |
+ Destination- 283 6.6 DiamIdent | M | V |
+ Realm | | |
+ Disconnect-Cause 273 5.4.3 Enumerated | M | V |
+ Error-Message 281 7.3 UTF8String | | V,M |
+ Error-Reporting- 294 7.4 DiamIdent | | V,M |
+ Host | | |
+ Event-Timestamp 55 8.21 Time | M | V |
+ Experimental- 297 7.6 Grouped | M | V |
+ Result | | |
+ -----------------------------------------|----+-----|
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 57]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ +----------+
+ | AVP Flag |
+ | rules |
+ |----+-----|
+ AVP Section | |MUST |
+ Attribute Name Code Defined Data Type |MUST| NOT |
+ -----------------------------------------|----+-----|
+ Experimental- 298 7.7 Unsigned32 | M | V |
+ Result-Code | | |
+ Failed-AVP 279 7.5 Grouped | M | V |
+ Firmware- 267 5.3.4 Unsigned32 | | V,M |
+ Revision | | |
+ Host-IP-Address 257 5.3.5 Address | M | V |
+ Inband-Security | M | V |
+ -Id 299 6.10 Unsigned32 | | |
+ Multi-Round- 272 8.19 Unsigned32 | M | V |
+ Time-Out | | |
+ Origin-Host 264 6.3 DiamIdent | M | V |
+ Origin-Realm 296 6.4 DiamIdent | M | V |
+ Origin-State-Id 278 8.16 Unsigned32 | M | V |
+ Product-Name 269 5.3.7 UTF8String | | V,M |
+ Proxy-Host 280 6.7.3 DiamIdent | M | V |
+ Proxy-Info 284 6.7.2 Grouped | M | V |
+ Proxy-State 33 6.7.4 OctetString| M | V |
+ Redirect-Host 292 6.12 DiamURI | M | V |
+ Redirect-Host- 261 6.13 Enumerated | M | V |
+ Usage | | |
+ Redirect-Max- 262 6.14 Unsigned32 | M | V |
+ Cache-Time | | |
+ Result-Code 268 7.1 Unsigned32 | M | V |
+ Route-Record 282 6.7.1 DiamIdent | M | V |
+ Session-Id 263 8.8 UTF8String | M | V |
+ Session-Timeout 27 8.13 Unsigned32 | M | V |
+ Session-Binding 270 8.17 Unsigned32 | M | V |
+ Session-Server- 271 8.18 Enumerated | M | V |
+ Failover | | |
+ Supported- 265 5.3.6 Unsigned32 | M | V |
+ Vendor-Id | | |
+ Termination- 295 8.15 Enumerated | M | V |
+ Cause | | |
+ User-Name 1 8.14 UTF8String | M | V |
+ Vendor-Id 266 5.3.3 Unsigned32 | M | V |
+ Vendor-Specific- 260 6.11 Grouped | M | V |
+ Application-Id | | |
+ -----------------------------------------|----+-----|
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 58]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+5. Diameter Peers
+
+ This section describes how Diameter nodes establish connections and
+ communicate with peers.
+
+5.1. Peer Connections
+
+ 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
+ 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
+ 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
+ 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
+ of active connections exists.
+
+ 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.
+
+ 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
+ assume the role of either primary or secondary.
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 59]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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.
+
+ 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:
+
+
+ 1. The Diameter implementation consults its list of static
+ (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.
+
+ 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'.
+
+ The client can follow the resolution process defined by the
+ 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
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 60]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ and/or AAAA RR's) for the target hostname specified in the SRV
+ records. 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
+ 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
+ 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.
+
+5.3. Capabilities Exchange
+
+ When two Diameter peers establish a transport connection, they MUST
+ 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 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ layer connection. Note that receiving a CER or CEA from a peer
+ 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
+ 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
+ the receiver regarding all of its application capabilities.
+
+ Diameter implementations SHOULD first attempt to establish a TLS/TCP
+ 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.
+
+ 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.
+ In both cases, the transport connection is closed. If the local
+ policy permits receiving CERs from unknown hosts, a successful CEA
+ MAY be returned. If a CER from an unknown peer is answered with a
+ successful CEA, the lifetime of the peer entry is equal to the
+ lifetime of the transport connection. In case of a transport
+ 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.
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ 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-
+ 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.
+
+ 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
+ locally used when transmitting Diameter messages.
+
+ Message Format
+
+ <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 ]
+
+5.3.2. Capabilities-Exchange-Answer
+
+ 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.
+
+ When Diameter is run over SCTP [RFC4960] or DTLS/SCTP [RFC6083],
+ which allow connections to span multiple interfaces, hence, multiple
+ IP addresses, the Capabilities-Exchange-Answer message MUST contain
+ 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 >
+ { 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 ]
+
+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
+ envisioned that the combination of the Vendor-Id, Product-Name
+ (Section 5.3.7) and the 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
+ indicates that this field is ignored.
+
+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
+ computers running Diameter software modules, for instance), the
+ revision of the Diameter software module may be reported instead.
+
+5.3.5. Host-IP-Address AVP
+
+ The Host-IP-Address AVP (AVP Code 257) is of type Address and is used
+ 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
+ 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
+ AVP SHOULD remain constant across firmware revisions for the same
+ product.
+
+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
+ 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.
+
+ 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. Expires July 24, 2011 [Page 65]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+5.4.1. Disconnect-Peer-Request
+
+ 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.
+
+ Message Format
+
+ <DPR> ::= < Diameter Header: 282, REQ >
+ { Origin-Host }
+ { Origin-Realm }
+ { Disconnect-Cause }
+ * [ AVP ]
+
+5.4.2. Disconnect-Peer-Answer
+
+ 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 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:
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 66]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ REBOOTING 0
+ A scheduled reboot is imminent. Receiver of 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.
+
+ 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.
+
+5.5. Transport Failure Detection
+
+ Given the nature of the Diameter protocol, it is recommended that
+ transport failures be detected as soon as possible. Detecting such
+ failures will minimize the occurrence of messages sent to unavailable
+ agents, resulting in unnecessary delays, and will provide better
+ failover performance. The Device-Watchdog-Request and Device-
+ Watchdog-Answer messages, defined in this section, are used to pro-
+ actively detect transport failures.
+
+5.5.1. Device-Watchdog-Request
+
+ 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
+ to an alternate peer.
+
+ Message Format
+
+ <DWR> ::= < Diameter Header: 280, REQ >
+ { Origin-Host }
+ { Origin-Realm }
+ [ Origin-State-Id ]
+ * [ AVP ]
+
+5.5.2. Device-Watchdog-Answer
+
+ 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 >
+ { Result-Code }
+ { Origin-Host }
+ { Origin-Realm }
+ [ Error-Message ]
+ [ Failed-AVP ]
+ [ Origin-State-Id ]
+ * [ AVP ]
+
+5.5.3. Transport Failure Algorithm
+
+ The transport failure algorithm is defined in [RFC3539]. All
+ Diameter implementations MUST support the algorithm defined in the
+ specification in order to be compliant to the Diameter base protocol.
+
+5.5.4. Failover and Failback Procedures
+
+ 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.
+
+ In order for a Diameter node to perform failover procedures, it is
+ necessary for the node to maintain a pending message queue for a
+ given peer. When an answer message is received, the corresponding
+ 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.
+
+ 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
+ field in the Diameter header along with the Origin-Host AVP MUST be
+ used to identify duplicate messages.
+
+ 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.
+
+5.6. Peer State Machine
+
+ This section contains a finite state machine that MUST be observed by
+ all Diameter implementations. Each Diameter node MUST follow the
+ state machine described below when communicating with each peer.
+ Multiple actions are separated by commas, and may continue on
+ succeeding lines, as space requires. Similarly, state and next state
+ may also span multiple lines, as space requires.
+
+ 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
+ [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 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.
+
+ A CER message is always sent on the initiating connection immediately
+ after the connection request is successfully completed. In the case
+ of an election, one of the two connections will shut down. The
+ responder connection will survive if the Origin-Host of the local
+ Diameter entity is higher than that of the peer; the initiator
+ connection will survive if the peer's Origin-Host is higher. All
+ subsequent messages are sent on the surviving connection. Note that
+ 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
+ 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
+ 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
+ handshake when both ends are in the open state. If the 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.
+
+ The state machine constrains only the behavior of a Diameter
+ implementation as seen by Diameter peers through events on the wire.
+
+ Any implementation that produces equivalent results is considered
+ compliant.
+
+ state event action next state
+ -----------------------------------------------------------------
+ Closed Start I-Snd-Conn-Req Wait-Conn-Ack
+ R-Conn-CER R-Accept, R-Open
+ Process-CER,
+ R-Snd-CEA
+
+ Wait-Conn-Ack I-Rcv-Conn-Ack I-Snd-CER Wait-I-CEA
+ I-Rcv-Conn-Nack Cleanup Closed
+ R-Conn-CER R-Accept, Wait-Conn-Ack/
+ Process-CER Elect
+ Timeout Error Closed
+
+ Wait-I-CEA I-Rcv-CEA Process-CEA I-Open
+ R-Conn-CER R-Accept, Wait-Returns
+ Process-CER,
+ Elect
+ I-Peer-Disc I-Disc Closed
+ I-Rcv-Non-CEA Error Closed
+ Timeout Error Closed
+
+ Wait-Conn-Ack/ I-Rcv-Conn-Ack I-Snd-CER,Elect Wait-Returns
+ Elect I-Rcv-Conn-Nack R-Snd-CEA R-Open
+ R-Peer-Disc R-Disc Wait-Conn-Ack
+ R-Conn-CER R-Reject Wait-Conn-Ack/
+ Elect
+ Timeout Error Closed
+
+ Wait-Returns Win-Election I-Disc,R-Snd-CEA R-Open
+ I-Peer-Disc I-Disc, R-Open
+ R-Snd-CEA
+ I-Rcv-CEA R-Disc I-Open
+ R-Peer-Disc R-Disc Wait-I-CEA
+ 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
+ R-Snd-DWA
+ 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-Peer-Disc R-Disc Closed
+
+ I-Open Send-Message I-Snd-Message I-Open
+ I-Rcv-Message Process I-Open
+ I-Rcv-DWR Process-DWR, I-Open
+ I-Snd-DWA
+ 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-Peer-Disc I-Disc Closed
+
+ Closing I-Rcv-DPA I-Disc Closed
+ R-Rcv-DPA R-Disc Closed
+ Timeout Error Closed
+ I-Peer-Disc I-Disc Closed
+ R-Peer-Disc R-Disc Closed
+
+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.
+
+ 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 logic that handles incoming connections SHOULD close and discard
+ the connection if any message other than 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
+ 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
+ connections.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 72]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Start The Diameter application has signaled that a
+ connection should be initiated with the peer.
+
+ R-Conn-CER An acknowledgement is received stating that the
+ transport connection has been established, and the
+ associated CER has arrived.
+
+ Rcv-Conn-Ack A positive acknowledgement is received confirming that
+ the transport connection is established.
+
+ Rcv-Conn-Nack A negative acknowledgement was received stating that
+ the transport connection was not established.
+
+ Timeout An application-defined timer has expired while waiting
+ for some event.
+
+ Rcv-CER A CER message from the peer was received.
+
+ Rcv-CEA A CEA message from the peer was received.
+
+ Rcv-Non-CEA A message other than CEA from the peer was received.
+
+ Peer-Disc A disconnection indication from the peer was received.
+
+ Rcv-DPR A DPR message from the peer was received.
+
+ Rcv-DPA A DPA message from the peer was received.
+
+ Win-Election An election was held, and the local node was the
+ winner.
+
+ Send-Message A message is to be sent.
+
+ Rcv-Message A message other than CER, CEA, DPR, DPA, DWR or DWA
+ was received.
+
+ Stop The Diameter application has signaled that a
+ connection should be terminated (e.g., on system
+ shutdown).
+
+5.6.3. Actions
+
+ 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.
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 73]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Snd-Conn-Req A transport connection is initiated with the peer.
+
+ Accept The incoming connection associated with the R-Conn-CER
+ is accepted as the responder connection.
+
+ Reject The incoming connection associated with the R-Conn-CER
+ 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
+ local resources are freed.
+
+ Error The transport layer connection is disconnected,
+ either politely or abortively, in response to
+ an error condition. Local resources are freed.
+
+ Process-CEA A received CEA is processed.
+
+ Snd-DPR A DPR message is sent to the peer.
+
+ Snd-DPA A DPA message is sent to the peer.
+
+ Disc The transport layer connection is disconnected,
+ and local resources are freed.
+
+ Elect An election occurs (see Section 5.6.4 for more
+ information).
+
+ Snd-Message A message is sent.
+
+ Snd-DWR A DWR message is sent.
+
+ Snd-DWA A DWA message is sent.
+
+ Process-DWR The DWR message is serviced.
+
+ Process-DWA The DWA message is serviced.
+
+ Process A message is serviced.
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 74]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+5.6.4. The Election Process
+
+ 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).
+
+ 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
+
+ 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:
+
+ o a request that is not able to be proxied (such as 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
+ 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
+ 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
+ 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 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
+ 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).
+
+ 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.
+
+ o The procedures listed in Section 6.1.6 are 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.
+
+ 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.
+
+6.1.1. Originating a Request
+
+ When creating a request, in addition to any other procedures
+ 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.
+
+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.
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 77]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ o The message SHOULD be saved in the list of pending requests.
+
+ Other actions to perform on the message based on the particular role
+ the agent is playing are described in the following sections.
+
+6.1.3. Receiving Requests
+
+ A relay or proxy agent MUST check for forwarding loops when receiving
+ requests. A loop is detected if the server finds its own identity in
+ a Route-Record AVP. When such an event occurs, the agent MUST answer
+ with the Result-Code AVP set to DIAMETER_LOOP_DETECTED.
+
+6.1.4. Processing Local Requests
+
+ A request is known to be for local consumption when one of the
+ following conditions occur:
+
+ 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
+
+ o Both the Destination-Host and the Destination-Realm are not
+ present.
+
+ 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.
+
+ 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
+ be forwarded to the peer.
+
+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
+ 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
+ and/or application that is not locally supported, the message is
+ 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
+ semantics.
+
+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.
+
+6.1.8. Redirecting Requests
+
+ When a redirect agent receives a request whose routing entry is set
+ 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
+ Redirect-Host AVP.
+
+ +------------------+
+ | Diameter |
+ | Redirect Agent |
+ +------------------+
+ ^ | 2. command + 'E' bit
+ 1. Request | | Result-Code =
+ [email protected] | | DIAMETER_REDIRECT_INDICATION +
+ | | Redirect-Host AVP(s)
+ | v
+ +-------------+ 3. Request +-------------+
+ | example.com |------------->| example.net |
+ | Relay | | Diameter |
+ | 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,
+ and the request is sent directly to it.
+
+ Multiple Redirect-Host AVPs are allowed. The receiver of the answer
+ message with the 'E' bit set selects exactly one of these hosts as
+ the destination of the redirected message.
+
+ 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.
+
+ 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)
+ 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
+ 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
+ rule MUST be used against the redirect usage value to resolve the
+ contention. The precedence rule can be found in Section 6.13.
+
+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.
+
+ 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:
+
+ o The keys should be generated securely following the randomness
+ recommendations in [RFC4086].
+
+ o The keys and cryptographic protection algorithms should be at
+ least 128 bits in strength.
+
+ o The keys should not be used for any other purpose than generating
+ and verifying tickets.
+
+ o The keys should be changed regularly.
+
+ o The keys should be changed if the ticket format or cryptographic
+ protection algorithms change.
+
+ The message is then forwarded to the next hop, as identified in the
+ Routing Table.
+
+ 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)
+ (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)
+
+ Figure 6: Routing of Diameter messages
+
+ Relay and proxy agents are not required to perform full inspection of
+ 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
+
+
+6.2. Diameter Answer Processing
+
+ When a request is locally processed, the following procedures MUST be
+ applied to create the associated answer, in addition to any
+ 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
+ answer.
+
+ o The local host's identity is encoded in the Origin-Host AVP.
+
+ o The Destination-Host and Destination-Realm AVPs MUST NOT be
+ present in the answer message.
+
+ o The Result-Code AVP is added with its value indicating success or
+ failure.
+
+ o If the Session-Id is present in the request, it MUST be included
+ in the answer.
+
+ 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.
+
+ 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
+ the above processing rules.
+
+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
+ corresponding message should be removed from the list of pending
+ requests. It SHOULD ignore answers received that do not match a
+ known Hop-by-Hop Identifier.
+
+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 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
+ 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
+ Diameter server.
+
+ The agent MUST then send the answer to the host that it received the
+ original request from.
+
+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
+ endpoint that originated the Diameter message. Relay agents MUST NOT
+ modify this AVP.
+
+ The value of the Origin-Host AVP is guaranteed to be unique within a
+ single host.
+
+ Note that the Origin-Host AVP may resolve to more than one address as
+ the Diameter peer may support more than one address.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+6.4. Origin-Realm AVP
+
+ The Origin-Realm AVP (AVP Code 296) is of type DiameterIdentity.
+ This AVP contains the Realm of the originator of any Diameter message
+ and MUST be present in all messages.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+6.5. Destination-Host AVP
+
+ 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
+ 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.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+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.
+ 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
+ SHOULD list the Destination-Realm AVP as a required AVP (an AVP
+ indicated as {AVP}) otherwise the message is inherently a non-
+ routable message.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+6.7. Routing AVPs
+
+ The AVPs defined in this section are Diameter AVPs used for routing
+ purposes. These AVPs change as Diameter messages are processed by
+ agents.
+
+6.7.1. Route-Record AVP
+
+ The Route-Record AVP (AVP Code 282) is of type DiameterIdentity. The
+ identity added in this AVP MUST be the same as the one received in
+ the Origin-Host of the Capabilities Exchange message.
+
+6.7.2. Proxy-Info AVP
+
+ 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:
+
+ 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
+
+ The Proxy-Host AVP (AVP Code 280) is of type DiameterIdentity. This
+ AVP contains the identity of the host that added the Proxy-Info AVP.
+
+6.7.4. Proxy-State AVP
+
+ The Proxy-State AVP (AVP Code 33) is of type OctetString. It
+ contains state information that would otherwise be stored at the
+ Diameter entity that created it. As such, this AVP MUST be treated
+ as opaque data by other Diameter entities.
+
+6.8. Auth-Application-Id AVP
+
+ The Auth-Application-Id AVP (AVP Code 258) is of type Unsigned32 and
+ is used in order to advertise support of the Authentication and
+ Authorization portion of an application (see Section 2.4). If
+ present in a message other than CER and CEA, the value of the Auth-
+ Application-Id AVP MUST match the Application Id present in the
+ Diameter message header.
+
+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
+ 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.
+
+6.10. Inband-Security-Id AVP
+
+ 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.
+
+ The following values are supported:
+
+
+ NO_INBAND_SECURITY 0
+
+ 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].
+
+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-
+ 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.
+
+ 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.
+
+ The Vendor-Specific-Application-Id AVP SHOULD be placed as close to
+ the Diameter header as possible.
+
+ AVP Format
+
+ <Vendor-Specific-Application-Id> ::= < AVP Header: 260 >
+ { Vendor-Id }
+ [ Auth-Application-Id ]
+ [ Acct-Application-Id ]
+
+ 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,
+ then the recipient SHOULD issue an answer with a Result-Code set to
+ 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.
+
+ If a Vendor-Specific-Application-Id is received that contains both
+ 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
+ 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
+ 'E' bit is set and the Result-Code AVP is set to
+ DIAMETER_REDIRECT_INDICATION.
+
+ Upon receiving the above, the receiving Diameter node SHOULD forward
+ the request directly to one of the hosts identified in these AVPs.
+ The server contained in the selected Redirect-Host AVP SHOULD be used
+ for all messages matching the criteria set by the Redirect-Host-Usage
+ AVP.
+
+6.13. Redirect-Host-Usage AVP
+
+ The Redirect-Host-Usage AVP (AVP Code 261) is of type Enumerated.
+ 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
+ resulting from the Redirect-Host is to be used. The following values
+ are supported:
+
+
+ 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.
+
+
+ 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
+ redirect usage values of the cached routes during normal routing to
+ resolve contentions that may occur. The precedence rule is the order
+ that dictate which redirect usage should be considered before any
+ other as they appear. The order is as follows:
+
+
+ 1. ALL_SESSION
+
+ 2. ALL_USER
+
+ 3. REALM_AND_APPLICATION
+
+ 4. ALL_REALM
+
+ 5. ALL_APPLICATION
+
+ 6. ALL_HOST
+
+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 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.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 89]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+7. Error Handling
+
+ 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 |----///----+
+ | +---------------------| | v
+ +------+--+ | 2. answer + 'E' set | Relay 2 | +--------+
+ |Diameter |<-+ (Unable to Forward) +---------+ |Diameter|
+ | | | Home |
+ | Relay 1 |--+ +---------+ | Server |
+ +---------+ | 3. Request |Diameter | +--------+
+ +-------------------->| | ^
+ | Relay 3 |-----------+
+ +---------+
+
+ 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
+ detects that it cannot forward the request to the home server, an
+ answer message is returned with the 'E' bit set and the Result-Code
+ AVP set to DIAMETER_UNABLE_TO_DELIVER. Given that this error falls
+ within the protocol error category, Relay 1 would take special
+ action, and given the error, attempt to route the message through its
+ alternate Relay 3.
+
+ +---------+ 1. Request +---------+ 2. Request +---------+
+ | Access |------------>|Diameter |------------>|Diameter |
+ | | | | | Home |
+ | Device |<------------| Relay |<------------| Server |
+ +---------+ 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 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,
+ 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
+ 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.
+
+ 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:
+
+ 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
+ containing the offending AVP.
+
+ o A request with an AVP that is received with an unrecognized value
+ causes an answer to be returned with the Result-Code AVP set to
+ 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
+ {AVP}. The receiver issues an answer with the Result-Code set to
+ 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.
+
+ 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
+ specific errors that can be described by this AVP are described in
+ the following section.
+
+
+
+
+
+
+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.
+
+
+ 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)
+
+ o 2xxx (Success)
+
+ o 3xxx (Protocol Errors)
+
+ o 4xxx (Transient Failures)
+
+ o 5xxx (Permanent Failure)
+
+ A non-recognized class (one whose first digit is not defined in this
+ section) MUST be handled as a permanent failure.
+
+7.1.1. Informational
+
+ Errors that fall within this category are used to inform the
+ 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
+ inform the access device that the authentication mechanism being
+ 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.
+
+ DIAMETER_LIMITED_SUCCESS 2002
+
+ When returned, the request was successfully completed, but
+ additional processing is required by the application in order to
+ provide service to the user.
+
+7.1.3. Protocol Errors
+
+ 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.
+
+
+ DIAMETER_UNABLE_TO_DELIVER 3002
+
+ This error is given when Diameter can not 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
+ 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
+ to an alternate peer. This error MUST only be used when a
+ 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
+ intended recipient. The message MAY be sent to an alternate peer,
+ 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
+ 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_BIT_IN_HEADER 3011
+
+ 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
+
+ This error is returned when a request is received with an invalid
+ message length.
+
+
+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.
+ 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
+ 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.
+
+ 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.
+
+
+ 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
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 95]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ Code definition. If this value is sent in the Result-Code AVP, a
+ Failed-AVP AVP SHOULD be included in the message. The Failed-AVP
+ AVP MUST contain an example of the missing AVP complete with the
+ Vendor-Id if applicable. The value field of the missing AVP
+ should be of correct minimum length and contain zeroes.
+
+
+ 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.
+
+
+ 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.
+
+
+ DIAMETER_AVP_NOT_ALLOWED 5008
+
+ A message was received with an AVP that MUST NOT be present. The
+ 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
+
+
+ DIAMETER_NO_COMMON_APPLICATION 5010
+
+ This error is returned by a Diameter node that receives a CER
+ 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_AVP_LENGTH 5014
+
+ The request contained an AVP with an invalid length. A Diameter
+ message indicating this error MUST include the offending AVPs
+ within a Failed-AVP AVP. In cases where the erroneous AVP length
+ value exceeds the message length or is less than the minimum AVP
+ header length, it is sufficient to include the offending AVP
+ header and a zero filled payload of the minimum required length
+ for the payloads data type. If the AVP is a grouped AVP, the
+ grouped AVP header with an empty payload would be sufficient to
+ indicate the offending AVP. In the case where the offending AVP
+ header cannot be fully decoded when the AVP length is less than
+ the minimum AVP header length, it is sufficient to include an
+ offending AVP header that is formulated by padding the incomplete
+ AVP header with zero up to the minimum AVP header length.
+
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+
+ DIAMETER_INVALID_HDR_BITS 5020
+
+ 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 5021
+
+ 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.
+
+
+7.2. Error Bit
+
+ The 'E' (Error Bit) in the Diameter header is set when the request
+ caused a protocol-related error (see Section 7.1.3). A message with
+ 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 Format
+
+ <answer-message> ::= < Diameter Header: code, ERR [PXY] >
+ 0*1< Session-Id >
+ { Origin-Host }
+ { Origin-Realm }
+ { Result-Code }
+ [ Origin-State-Id ]
+ [ Error-Message ]
+ [ Error-Reporting-Host ]
+ [ Failed-AVP ]
+ [ Experimental-Result ]
+ * [ Proxy-Info ]
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 98]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ * [ 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
+ found in the request message.
+
+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
+ 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.
+
+7.4. Error-Reporting-Host AVP
+
+ The Error-Reporting-Host AVP (AVP Code 294) is of type
+ DiameterIdentity. This AVP contains the identity of the Diameter
+ 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.
+
+7.5. Failed-AVP AVP
+
+ The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
+ 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.
+
+ 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
+ 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
+ required length for the omitted AVP will be added. If the failure
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 99]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ 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.
+
+ AVP Format
+
+ <Failed-AVP> ::= < AVP Header: 279 >
+ 1* {AVP}
+
+7.6. Experimental-Result AVP
+
+ The Experimental-Result AVP (AVP Code 297) is of type Grouped, and
+ indicates whether a particular vendor-specific request was completed
+ successfully or whether an error occurred. This AVP has the
+ following structure:
+
+ AVP Format
+
+ Experimental-Result ::= < AVP Header: 297 >
+ { Vendor-Id }
+ { 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
+ follows. All Diameter answer messages defined in vendor-specific
+ applications MUST include either one Result-Code AVP or one
+ Experimental-Result AVP.
+
+7.7. Experimental-Result-Code AVP
+
+ The Experimental-Result-Code AVP (AVP Code 298) is of type Unsigned32
+ and contains a vendor-assigned value representing the result of
+ processing the request.
+
+ 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
+ values).
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 100]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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.
+
+ When a service makes use of the authentication and/or authorization
+ portion of an application, and a user requests access to the network,
+ the Diameter client issues an auth request to its local server. The
+ 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
+ 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.
+
+ An access device that does not expect to send a re-authorization or a
+ session termination request to the server MAY include the Auth-
+ Session-State AVP with the value set to NO_STATE_MAINTAINED as a hint
+ to the server. If the server accepts the hint, it agrees that since
+ no session termination message will be received once service to the
+ user is terminated, it cannot maintain state for the session. If the
+ answer message from the server contains a different value in the
+ Auth-Session-State AVP (or the default value if the AVP is absent),
+ the access device MUST follow the server's directives. Note that the
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ 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
+ machine defined in subsequent sections may not be applicable.
+ Therefore, the applications 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,
+ ASR/ASA messages for stateful sessions.
+
+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).
+
+ There are four different authorization session state machines
+ supported in the Diameter base protocol. The first two describe a
+ session in which the server is maintaining session state, indicated
+ by the value of the Auth-Session-State AVP (or its absence). One
+ describes the session from a client perspective, the other from a
+ server perspective. The second two state machines are used when the
+ server does not maintain session state. Here again, one describes
+ the session from a client perspective, the other from a server
+ perspective.
+
+ 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.
+
+ In the case that an application does not support re-auth, the state
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 102]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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 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
+ 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
+ successfully sent' is the complement of 'Failure to send X'.
+
+ The following state machine is observed by a client when state is
+ maintained on the server:
+
+ CLIENT, STATEFUL
+ State Event Action New State
+ ---------------------------------------------------------------
+ Idle Client or Device Requests Send Pending
+ access service
+ specific
+ auth req
+
+ Idle ASR Received Send ASA Idle
+ for unknown session with
+ Result-Code =
+ UNKNOWN_
+ SESSION_ID
+
+ Idle RAR Received Send RAA Idle
+ for unknown session with
+ Result-Code =
+ UNKNOWN_
+ SESSION_ID
+
+ 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
+ but service not provided
+
+ Pending Error processing successful Sent STR Discon
+ Service-specific authorization
+ answer
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 103]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Pending Failed Service-specific Cleanup Idle
+ authorization answer received
+
+ Open User or client device Send Open
+ requests access to service service
+ specific
+ auth req
+
+ Open Successful Service-specific Provide Open
+ authorization answer received Service
+
+ Open Failed Service-specific Discon. Idle
+ authorization answer user/device
+ received.
+
+ Open RAR received and client will Send RAA Open
+ perform subsequent re-auth with
+ Result-Code =
+ SUCCESS
+
+ Open RAR received and client will Send RAA Idle
+ not perform subsequent with
+ re-auth Result-Code !=
+ SUCCESS,
+ Discon.
+ user/device
+
+ Open Session-Timeout Expires on Send STR Discon
+ Access Device
+
+ Open ASR Received, Send ASA Discon
+ client will comply with
+ with request to end the Result-Code =
+ session = SUCCESS,
+ Send STR.
+
+ Open ASR Received, Send ASA Open
+ client will not comply with
+ with request to end the Result-Code !=
+ session != SUCCESS
+
+ Open Authorization-Lifetime + Send STR Discon
+ Auth-Grace-Period expires on
+ access device
+
+ Discon ASR Received Send ASA Discon
+
+ Discon STA Received Discon. Idle
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 104]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ user/device
+
+ The following state machine is observed by a server when it is
+ maintaining state for the session:
+
+ SERVER, STATEFUL
+ State Event Action New State
+ ---------------------------------------------------------------
+ Idle Service-specific authorization Send Open
+ request received, and successful
+ user is authorized serv.
+ specific
+ answer
+
+ Idle Service-specific authorization Send Idle
+ request received, and failed serv.
+ user is not authorized specific
+ answer
+
+ Open Service-specific authorization Send Open
+ request received, and user successful
+ is authorized serv. specific
+ answer
+
+ Open Service-specific authorization Send Idle
+ request received, and user failed serv.
+ is not authorized specific
+ answer,
+ Cleanup
+
+ Open Home server wants to confirm Send RAR Pending
+ authentication and/or
+ authorization of the user
+
+ Pending Received RAA with a failed Cleanup Idle
+ Result-Code
+
+ Pending Received RAA with Result-Code Update Open
+ = SUCCESS session
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ home server
+
+ Discon Failure to send ASR Wait, Discon
+ resend ASR
+
+ Discon ASR successfully sent and Cleanup Idle
+ ASA Received with Result-Code
+
+ Not ASA Received None No Change.
+ Discon
+
+ Any STR Received Send STA, Idle
+ Cleanup.
+
+ The following state machine is observed by a client when state is not
+ maintained on the server:
+
+ CLIENT, STATELESS
+ State Event Action New State
+ ---------------------------------------------------------------
+ Idle Client or Device Requests Send Pending
+ access service
+ specific
+ auth req
+
+ 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
+ authorization answer
+ received
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ SERVER, STATELESS
+ State Event Action New State
+ ---------------------------------------------------------------
+ Idle Service-specific authorization Send serv. Idle
+ request received, and specific
+ successfully processed answer
+
+8.2. Accounting Session State Machine
+
+ The following state machines MUST be supported for applications that
+ have an accounting portion or that require only accounting services.
+ The first state machine is to be observed by clients.
+
+ See Section 9.7 for Accounting Command Codes and Section 9.8 for
+ Accounting AVPs.
+
+ The server side in the accounting state machine depends in some cases
+ on the particular application. The Diameter base protocol defines a
+ default state machine that MUST be followed by all applications that
+ have not specified other state machines. This is the second state
+ 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.
+ 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
+ can happen either immediately after record reception or in a post-
+ processing phase. However, as these tasks are typically application
+ 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.
+
+ However, the Diameter base protocol defines one optional server side
+ state machine that MAY be followed by applications that require
+ keeping track of the session state at the accounting server. Note
+ 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 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ 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
+ notification DIAMETER_OUT_OF_SPACE, DIAMETER_TOO_BUSY, or
+ DIAMETER_LOOP_DETECTED in the Result-Code AVP of the Accounting
+ Answer command.
+
+ 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
+ to be sent, if the given application has both authentication/
+ authorization and accounting portions.
+
+ 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,
+ respectively.
+
+ CLIENT, ACCOUNTING
+ State Event Action New State
+ ---------------------------------------------------------------
+ Idle Client or device requests Send PendingS
+ access accounting
+ start req.
+
+ Idle Client or device requests Send PendingE
+ a one-time service accounting
+ event req
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ space available and realtime Start
+ not equal to DELIVER_AND_GRANT Record
+
+ PendingS Failure to send and no buffer Open
+ space available and realtime
+ equal to GRANT_AND_LOSE
+
+ PendingS Failure to send and no Disconnect Idle
+ buffer space available and user/dev
+ realtime not equal to
+ GRANT_AND_LOSE
+
+ PendingS Failed accounting start answer Open
+ received and realtime equal
+ to GRANT_AND_LOSE
+
+ PendingS Failed accounting start answer Disconnect Idle
+ received and realtime not user/dev
+ equal to GRANT_AND_LOSE
+
+ PendingS User service terminated Store PendingS
+ stop
+ record
+
+ Open Interim interval elapses Send PendingI
+ accounting
+ interim
+ record
+ Open User service terminated Send PendingL
+ accounting
+ stop req.
+
+ PendingI Successful accounting interim Open
+ answer received
+
+ PendingI Failure to send and (buffer Store Open
+ space available or old interim
+ record can be overwritten) record
+ and realtime 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ realtime not equal to
+ GRANT_AND_LOSE
+
+ PendingI Failed accounting interim Open
+ answer received and realtime
+ equal to GRANT_AND_LOSE
+
+ PendingI Failed accounting interim Disconnect Idle
+ answer received and user/dev
+ realtime not equal to
+ GRANT_AND_LOSE
+
+ PendingI User service terminated Store PendingI
+ stop
+ record
+ PendingE Successful accounting Idle
+ event answer received
+
+ PendingE Failure to send and buffer Store Idle
+ space available event
+ record
+
+ PendingE Failure to send and no buffer Idle
+ space available
+
+ PendingE Failed accounting event answer Idle
+ received
+
+ PendingB Successful accounting answer Delete Idle
+ received record
+
+ PendingB Failure to send Idle
+
+ PendingB Failed accounting answer Delete Idle
+ received record
+
+ PendingL Successful accounting Idle
+ stop answer received
+
+ PendingL Failure to send and buffer Store Idle
+ space available stop
+ record
+
+ PendingL Failure to send and no buffer Idle
+ space available
+
+ PendingL Failed accounting stop answer Idle
+ 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
+ processed. start
+ answer
+
+ Idle Accounting event request Send Idle
+ received, and successfully accounting
+ processed. event
+ answer
+
+ Idle Interim record received, Send Idle
+ and successfully processed. accounting
+ interim
+ answer
+
+ Idle Accounting stop request Send Idle
+ received, and successfully accounting
+ processed stop answer
+
+ Idle Accounting request received, Send Idle
+ no space left to store accounting
+ records answer,
+ Result-Code =
+ OUT_OF_
+ SPACE
+
+ SERVER, STATEFUL ACCOUNTING
+ State Event Action New State
+ ---------------------------------------------------------------
+
+ Idle Accounting start request Send Open
+ received, and successfully accounting
+ processed. start
+ answer,
+ Start Ts
+
+ Idle Accounting event request Send Idle
+ received, and successfully accounting
+ processed. event
+ answer
+
+ 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
+
+
+ Result-Code =
+ OUT_OF_
+ SPACE
+
+ Open Interim record received, Send Open
+ and successfully processed. accounting
+ interim
+ answer,
+ Restart Ts
+
+ Open Accounting stop request Send Idle
+ received, and successfully accounting
+ processed stop answer,
+ Stop Ts
+
+ Open Accounting request received, Send Idle
+ no space left to store accounting
+ records answer,
+ Result-Code =
+ OUT_OF_
+ SPACE,
+ Stop Ts
+
+ Open Session supervision timer Ts Stop Ts Idle
+ expired
+
+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
+ 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.
+
+8.3.1. Re-Auth-Request
+
+ 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.
+
+
+ Message Format
+
+ <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 ]
+
+8.3.2. Re-Auth-Answer
+
+ 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.
+
+ A successful RAA message MUST be followed by an application-specific
+ authentication and/or authorization message.
+
+
+ Message Format
+
+ <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 ]
+
+
+
+
+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
+ which it is maintaining state, to be notified when that session is no
+ longer active, both for tracking purposes as well as to allow
+ stateful agents to release any resources that they may have provided
+ for the user's session. For sessions whose state is not being
+ maintained, this section is not used.
+
+ When a user session that required Diameter authorization terminates,
+ the access device that provided the service MUST issue a Session-
+ Termination-Request (STR) message to the Diameter server that
+ authorized the service, to notify it that the session is no longer
+ active. An STR MUST be issued when a user session terminates for any
+ reason, including user logoff, expiration of Session-Timeout,
+ administrative action, termination upon receipt of an Abort-Session-
+ Request (see below), orderly shutdown of the access device, etc.
+
+ The access device also MUST issue an STR for a session that was
+ authorized but never actually started. This could occur, for
+ example, due to a sudden resource shortage in the access device, or
+ because the access device is unwilling to provide the type of service
+ requested in the authorization, or because the access device does not
+ support a mandatory AVP returned in the authorization, etc.
+
+ 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
+ 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
+ NO_STATE_MAINTAINED, a proxy that causes an authorized session not to
+ be started MUST issue an STR to the Diameter server that authorized
+ the session, since the access device has no way of knowing that the
+ session had been authorized.
+
+ 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.
+
+ 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
+ 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
+ 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
+ authenticated and/or authorized session is being terminated.
+
+
+ Message Format
+
+ <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 ]
+
+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. Expires July 24, 2011 [Page 115]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Message Format
+
+ <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 ]
+
+8.5. Aborting a Session
+
+ A Diameter server may request that the access device stop providing
+ service for a particular session by issuing an Abort-Session-Request
+ (ASR).
+
+ For example, the Diameter server that originally authorized the
+ session may be required to cause that session to be stopped for lack
+ of credit or other reasons that were not anticipated when the session
+ was first authorized.
+
+ 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
+ ASRs from certain agents only. In any case, the access device MUST
+ 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
+ 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
+
+ <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 ]
+
+8.5.2. Abort-Session-Answer
+
+ 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
+ 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
+ DIAMETER_UNKNOWN_SESSION_ID. If the access device does not stop the
+ session for any other reason, Result-Code is set to
+ DIAMETER_UNABLE_TO_COMPLY.
+
+
+ Message Format
+
+ <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 ]
+
+
+
+
+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
+ for which no STR would have been issued, due to unanticipated
+ 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 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
+ 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
+ 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.
+
+ 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
+ that were authorized on upstream servers, to allow session state to
+ be cleaned up globally.
+
+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.
+ 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
+ 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.
+
+
+ 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
+ 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).
+
+ 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.
+
+ 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>;<high 32 bits>;<low 32 bits>[;<optional value>]
+
+ <high 32 bits> and <low 32 bits> are decimal representations of the
+ high and low 32 bits of a monotonically increasing 64-bit value. The
+ 64-bit value is rendered in two part to simplify formatting by 32-bit
+ 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.
+
+ Example, in which there is no optional value:
+
+ accesspoint7.example.com;1876543210;523
+
+ Example, in which there is an optional value:
+
+ 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.
+
+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
+ 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-
+ auth is expected.
+
+ 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.
+
+ 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
+ client.
+
+8.10. Auth-Grace-Period AVP
+
+ The Auth-Grace-Period AVP (AVP Code 276) is of type Unsigned32 and
+ contains the number of seconds the Diameter server will wait
+ following the expiration of the Authorization-Lifetime AVP before
+ cleaning up resources for the session.
+
+8.11. Auth-Session-State AVP
+
+ The Auth-Session-State AVP (AVP Code 277) is of type Enumerated and
+ specifies whether state is maintained for a particular session. The
+ client MAY include this AVP in requests as a hint to the server, but
+ 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
+ maintained, and the access device MUST issue a session termination
+ 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. Expires July 24, 2011 [Page 121]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ and contains the maximum number of seconds of service to be provided
+ to the user before termination of the session. When both the
+ Session-Timeout and the Authorization-Lifetime AVPs are present in an
+ answer message, the former MUST be equal to or greater than the value
+ of the latter.
+
+ 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).
+
+ A Session-Timeout AVP MAY be present in a re-authorization answer
+ message, and 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
+ has an unlimited number of seconds before termination.
+
+ 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
+ client.
+
+8.14. User-Name AVP
+
+ The User-Name AVP (AVP Code 1) [RFC2865] is of type UTF8String, which
+ 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]
+
+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
+
+ The user's session has timed out, and service has been terminated.
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 123]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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.
+
+ 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
+ Origin-State-Id to the time of startup, or it MAY use an incrementing
+ counter retained in non-volatile memory across restarts.
+
+ The Origin-State-Id, if present, MUST reflect the state of the entity
+ indicated by Origin-Host. If a proxy modifies Origin-Host, it MUST
+ either remove Origin-State-Id or modify it appropriately as well.
+ Typically, Origin-State-Id is used by an access device that always
+ starts up with no active sessions; that is, any session active prior
+ to restart will have been lost. By including Origin-State-Id in a
+ 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.
+
+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
+ 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:
+
+
+ RE_AUTH 1
+
+ When set, future re-auth messages for this session MUST NOT
+ include the Destination-Host AVP. When cleared, the default
+ 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
+ include the Destination-Host AVP. When cleared, the default
+ 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,
+ 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
+ value. If present, this AVP MAY inform the Diameter client that if a
+ re-auth or STR message fails due to a delivery problem, the Diameter
+ client SHOULD issue a subsequent message without the Destination-Host
+ AVP. When absent, the default value is REFUSE_SERVICE.
+
+ 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.
+
+
+ TRY_AGAIN 1
+
+ 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
+ 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
+ request.
+
+8.20. Class AVP
+
+ The Class AVP (AVP Code 25) is of type OctetString and is used by
+ Diameter servers to return state information to the access device.
+ When one or more Class AVPs are present in application-specific
+ authorization answer messages, they MUST be present in subsequent re-
+ authorization, session termination and accounting messages. Class
+ AVPs found in a re-authorization answer message override the ones
+ found in any previous authorization answer message. Diameter server
+ implementations SHOULD NOT return Class AVPs that require more than
+ 4096 bytes of storage on the Diameter client. A Diameter client that
+ receives Class AVPs whose size exceeds local available storage MUST
+ terminate the session.
+
+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.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 126]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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
+ protocol in order minimize loss of accounting data in various fault
+ situations and under different assumptions about the capabilities of
+ the used devices.
+
+9.1. Server Directed Model
+
+ The server directed model means that the device generating the
+ accounting data gets information from either the authorization server
+ (if contacted) or the accounting server regarding the way accounting
+ data shall be forwarded. This information includes accounting record
+ 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
+ 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.
+
+ The authorization server (chain) directs the selection of proper
+ transfer strategy, based on its knowledge of the user and
+ relationships of roaming partnerships. The server (or agents) uses
+ the Acct-Interim-Interval and Accounting-Realtime-Required AVPs to
+ control the operation of the Diameter peer operating as a client.
+ The Acct-Interim-Interval AVP, when present, instructs the Diameter
+ node acting as a client to produce accounting records continuously
+ even during a session. Accounting-Realtime-Required AVP is used to
+ control the behavior of the client when the transfer of accounting
+ 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
+ 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.
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 127]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+9.2. Protocol Messages
+
+ A Diameter node that receives a successful authentication and/or
+ authorization messages 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
+ to confirm reception. The Accounting-Answer message includes the
+ Result-Code AVP, which MAY indicate that an error was present in the
+ accounting message. The value of the Accounting-Realtime-Required
+ AVP received earlier for the session in question may indicate that
+ the user's session has to be terminated when a rejected Accounting-
+ Request message was received.
+
+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.
+
+ Applications have the option of using one or both of the following
+ accounting application extension models:
+
+ Split Accounting Service
+
+ The accounting message will carry the Application Id of the
+ Diameter base accounting application (see Section 2.4).
+ Accounting messages may be routed to Diameter nodes other than the
+ corresponding Diameter application. These nodes might be
+ centralized accounting servers that provide accounting service for
+ multiple different Diameter applications. These nodes MUST
+ advertise the Diameter base accounting Application Id during
+ capabilities exchange.
+
+
+ Coupled Accounting Service
+
+ The accounting messages 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.
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 128]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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 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
+ discusses duplicate detection needs and implementation issues.
+
+ Diameter clients MAY have non-volatile memory for the safe storage of
+ accounting records over reboots or extended network failures, network
+ 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
+ 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
+ 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.
+
+9.5. Accounting Records
+
+ In all accounting records, the Session-Id AVP MUST be present; the
+ User-Name AVP MUST be present if it is available to the Diameter
+ client.
+
+ Different types of accounting records are sent depending on the
+ actual type of accounted service and the authorization server's
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 129]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+ If the accounted service is of a measurable length, then the AVP MUST
+ use the values START_RECORD, STOP_RECORD, and possibly,
+ INTERIM_RECORD. If the authorization server has not directed interim
+ accounting to be enabled for the session, two accounting records MUST
+ be generated for each service of type session. When the initial
+ Accounting-Request for a given session is sent, the Accounting-
+ Record-Type AVP MUST be set to the value START_RECORD. When the last
+ Accounting-Request is sent, the value MUST be STOP_RECORD.
+
+ If the authorization server has directed interim accounting to be
+ enabled, the Diameter client MUST produce additional records between
+ the START_RECORD and STOP_RECORD, marked INTERIM_RECORD. The
+ production of these records is directed by Acct-Interim-Interval as
+ well as any re-authentication or re-authorization of the session.
+ The Diameter client MUST overwrite any previous interim accounting
+ records that are locally stored for delivery, if a new record is
+ being generated for the same session. This ensures that only one
+ pending interim record can exist on an access device for any given
+ session.
+
+ A particular value of Accounting-Sub-Session-Id MUST appear only in
+ 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
+ STOP_RECORD. A particular Diameter application specification MUST
+ define the type of sequences that MUST be used.
+
+9.6. Correlation of Accounting Records
+
+ If an application uses accounting messages, it can correlate
+ 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
+ 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
+ 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
+ particular application session. Note that receiving a STOP_RECORD
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 130]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ with no Accounting-Sub-Session-Id AVP when sub-sessions were
+ originally used in the START_RECORD messages implies that all sub-
+ sessions are terminated.
+
+ There are also cases where an application needs to correlate multiple
+ application sessions into a single accounting record; the accounting
+ 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
+ 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
+ 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
+ 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.
+
+9.7. Accounting Command-Codes
+
+ 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
+ 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.
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 131]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Message Format
+
+ <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 ]
+ [ Destination-Host ]
+ [ 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 ]
+
+9.7.2. Accounting-Answer
+
+ 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,
+ SHOULD respond with the Accounting-Answer command.
+
+ The AVP listed below SHOULD include service-specific accounting AVPs,
+ as described in Section 9.3.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 132]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Message Format
+
+ <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-Message ]
+ [ Error-Reporting-Host ]
+ [ Failed-AVP ]
+ [ Acct-Interim-Interval ]
+ [ Accounting-Realtime-Required ]
+ [ Origin-State-Id ]
+ [ Event-Timestamp ]
+ * [ Proxy-Info ]
+ * [ AVP ]
+
+9.8. Accounting AVPs
+
+ This section contains AVPs that describe accounting usage information
+ related to a specific session.
+
+9.8.1. Accounting-Record-Type AVP
+
+ The Accounting-Record-Type AVP (AVP Code 480) is of type Enumerated
+ 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.
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 133]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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,
+ and contains accounting information that is relevant to the
+ initiation of the session.
+
+
+ INTERIM_RECORD 3
+
+ An Interim Accounting Record contains cumulative accounting
+ information for an existing accounting session. Interim
+ Accounting Records SHOULD be sent every time a re-authentication
+ or re-authorization occurs. Further, additional interim record
+ triggers MAY be defined by application-specific Diameter
+ 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
+ is sent from the Diameter home authorization server to the Diameter
+ 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
+ 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.
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 134]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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.
+
+ The client MUST ensure that the interim record production times
+ are randomized so that large accounting message storms are not
+ created either among records or around a common service start
+ time.
+
+9.8.3. Accounting-Record-Number AVP
+
+ 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
+ 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
+ INTERIM_RECORD, 2 for the second, and so on until the value for
+ STOP_RECORD is one more than for the last INTERIM_RECORD.
+
+9.8.4. Acct-Session-Id AVP
+
+ The Acct-Session-Id AVP (AVP Code 44) is of type OctetString is only
+ used when RADIUS/Diameter translation occurs. This AVP contains the
+ contents of the RADIUS Acct-Session-Id attribute.
+
+9.8.5. Acct-Multi-Session-Id AVP
+
+ 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
+ accounting messages for the given session.
+
+9.8.6. Accounting-Sub-Session-Id AVP
+
+ The Accounting-Sub-Session-Id AVP (AVP Code 287) is of type
+ Unsigned64 and contains the accounting sub-session identifier. The
+ combination of the Session-Id and this AVP MUST be unique per sub-
+ 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
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 135]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ 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
+ Enumerated and is sent from the Diameter home authorization server to
+ the Diameter client or in the Accounting-Answer from the accounting
+ server. The client uses information in this AVP to decide what to do
+ 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
+ service MUST only be granted as long as there is a connection to
+ an accounting server. Note that the set of alternative accounting
+ servers are treated as one server in this sense. Having to move
+ 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
+ SHOULD be granted if there is a connection, or as long as records
+ can still be stored as described in Section 9.4.
+
+ 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.
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 136]
+
+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.
+
+ The table uses 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.
+
+ 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.
+
+10.1. Base Protocol Command AVP Table
+
+ The table in this section is limited to the non-accounting Command
+ Codes defined in this specification.
+
+ +-----------------------------------------------+
+ | Command-Code |
+ +---+---+---+---+---+---+---+---+---+---+---+---+
+ Attribute Name |CER|CEA|DPR|DPA|DWR|DWA|RAR|RAA|ASR|ASA|STR|STA|
+ --------------------+---+---+---+---+---+---+---+---+---+---+---+---+
+ Acct-Interim- |0 |0 |0 |0 |0 |0 |0-1|0 |0 |0 |0 |0 |
+ Interval | | | | | | | | | | | | |
+ Accounting-Realtime-|0 |0 |0 |0 |0 |0 |0-1|0 |0 |0 |0 |0 |
+ Required | | | | | | | | | | | | |
+ Acct-Application-Id |0+ |0+ |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Auth-Application-Id |0+ |0+ |0 |0 |0 |0 |1 |0 |1 |0 |1 |0 |
+ Auth-Grace-Period |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Auth-Request-Type |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Auth-Session-State |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Authorization- |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Lifetime | | | | | | | | | | | | |
+ 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+ |
+ 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 |
+ 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|
+ Product-Name |1 |1 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Proxy-Info |0 |0 |0 |0 |0 |0 |0+ |0+ |0+ |0+ |0+ |0+ |
+ Redirect-Host |0 |0 |0 |0 |0 |0 |0 |0+ |0 |0+ |0 |0+ |
+ Redirect-Host-Usage |0 |0 |0 |0 |0 |0 |0 |0-1|0 |0-1|0 |0-1|
+ Redirect-Max-Cache- |0 |0 |0 |0 |0 |0 |0 |0-1|0 |0-1|0 |0-1|
+ Time | | | | | | | | | | | | |
+ Result-Code |0 |1 |0 |1 |0 |1 |0 |1 |0 |1 |0 |1 |
+ Re-Auth-Request-Type|0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |
+ Route-Record |0 |0 |0 |0 |0 |0 |0+ |0 |0+ |0 |0+ |0 |
+ Session-Binding |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Session-Id |0 |0 |0 |0 |0 |0 |1 |1 |1 |1 |1 |1 |
+ Session-Server- |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Failover | | | | | | | | | | | | |
+ Session-Timeout |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Supported-Vendor-Id |0+ |0+ |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Termination-Cause |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |1 |0 |
+ User-Name |0 |0 |0 |0 |0 |0 |0-1|0-1|0-1|0-1|0-1|0-1|
+ Vendor-Id |1 |1 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Vendor-Specific- |0+ |0+ |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Application-Id | | | | | | | | | | | | |
+ --------------------+---+---+---+---+---+---+---+---+---+---+---+---+
+
+10.2. Accounting AVP Table
+
+ The table in this section is used to represent which AVPs defined in
+ this document are to be present in the Accounting messages. These
+ AVP occurrence requirements are guidelines, which may be expanded,
+ and/or overridden by application-specific requirements in the
+ Diameter applications documents.
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 138]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ +-----------+
+ | Command |
+ | Code |
+ +-----+-----+
+ Attribute Name | ACR | ACA |
+ ------------------------------+-----+-----+
+ Acct-Interim-Interval | 0-1 | 0-1 |
+ Acct-Multi-Session-Id | 0-1 | 0-1 |
+ Accounting-Record-Number | 1 | 1 |
+ Accounting-Record-Type | 1 | 1 |
+ Acct-Session-Id | 0-1 | 0-1 |
+ Accounting-Sub-Session-Id | 0-1 | 0-1 |
+ Accounting-Realtime-Required | 0-1 | 0-1 |
+ Acct-Application-Id | 0-1 | 0-1 |
+ Auth-Application-Id | 0 | 0 |
+ Class | 0+ | 0+ |
+ Destination-Host | 0-1 | 0 |
+ Destination-Realm | 1 | 0 |
+ Error-Reporting-Host | 0 | 0+ |
+ Event-Timestamp | 0-1 | 0-1 |
+ Origin-Host | 1 | 1 |
+ Origin-Realm | 1 | 1 |
+ Proxy-Info | 0+ | 0+ |
+ Route-Record | 0+ | 0 |
+ Result-Code | 0 | 1 |
+ Session-Id | 1 | 1 |
+ Termination-Cause | 0 | 0 |
+ User-Name | 0-1 | 0-1 |
+ Vendor-Specific-Application-Id| 0-1 | 0-1 |
+ ------------------------------+-----+-----+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 139]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+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 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.
+
+11.1. Changes to AVP Header Allocation
+
+ 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.
+
+11.2. Diameter Header
+
+ 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
+ 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
+ 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
+ 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
+ MUST include the contact information of persons and/or entities
+ responsible for authoring and maintaining the command.
+
+11.3. AVP Values
+
+ For AVP values, the Experimental-Result-Code AVP value allocation has
+ been added. The new rule is as follows:
+
+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.
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 140]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+11.4. Diameter TCP, SCTP, TLS/TCP and DTLS/SCTP Port Numbers
+
+ 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.
+
+11.5. S-NAPTR Parameters
+
+ This document registers a new S-NAPTR Application Service Tag value
+ of "aaa".
+
+ This document also registers the following S-NAPTR Application
+ Protocol Tags:
+
+ Tag | Protocol
+ -------------------|---------
+ diameter.tcp | TCP
+ diameter.sctp | SCTP
+ diameter.tls.tcp | TLS/TCP
+ diameter.dtls.sctp | DTLS/SCTP
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 141]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+12. Diameter protocol related configurable parameters
+
+ This section contains the configurable parameters that are found
+ throughout this document:
+
+ Diameter Peer
+
+ A Diameter entity MAY communicate with peers that are statically
+ configured. A statically configured Diameter peer would require
+ that either the IP address or the fully qualified domain name
+ (FQDN) be supplied, which would then be used to resolve through
+ DNS.
+
+ Routing Table
+
+ 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
+ cannot be locally processed.
+
+ Tc timer
+
+ The Tc timer controls the frequency that transport connection
+ attempts are done to a peer with whom no active transport
+ connection exists. The recommended value is 30 seconds.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 142]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+13. Security Considerations
+
+ The Diameter base protocol messages SHOULD be secured by using TLS
+ [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.
+
+ 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
+ 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
+ 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.
+
+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
+ 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 nodes MUST be able to negotiate the following TLS/TCP and
+ DTLS/SCTP cipher suites:
+
+ TLS_RSA_WITH_RC4_128_MD5
+ TLS_RSA_WITH_RC4_128_SHA
+ TLS_RSA_WITH_3DES_EDE_CBC_SHA
+
+ Diameter nodes SHOULD be able to negotiate the following TLS/TCP and
+ DTLS/SCTP cipher suite:
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ suites.
+
+13.2. Peer-to-Peer Considerations
+
+ As with any peer-to-peer protocol, proper configuration of the trust
+ model within a Diameter peer is essential to security. When
+ certificates are used, it is necessary to configure the root
+ certificate authorities trusted by the Diameter peer. These root CAs
+ are likely to be unique to Diameter usage and distinct from the root
+ CAs that might be trusted for other purposes such as Web browsing.
+ In general, it is expected that those root CAs will be configured so
+ as to reflect the business relationships between the organization
+ hosting the Diameter peer and other organizations. As a result, a
+ Diameter peer will typically not be configured to allow connectivity
+ with any arbitrary peer. With certificate authentication, Diameter
+ peers may not be known beforehand and therefore peer discovery may be
+ required.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 144]
+
+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.
+
+ [IANAADFAM]
+ IANA,, "Address Family Numbers",
+ http://www.iana.org/assignments/address-family-numbers.
+
+ [RADTYPE] IANA,, "RADIUS Types",
+ http://www.iana.org/assignments/radius-types.
+
+ [RFC791] Postel, J., "Internet Protocol", RFC 791, September 1981.
+
+ [RFC793] Postel, J., "Transmission Control Protocol", RFC 793,
+ January 1981.
+
+ [RFC3539] Aboba, B. and J. Wood, "Authentication, Authorization and
+ Accounting (AAA) Transport Profile", RFC 3539, June 2003.
+
+ [RFC4004] Calhoun, P., Johansson, T., Perkins, C., Hiller, T., and
+ P. McCann, "Diameter Mobile IPv4 Application", RFC 4004,
+ August 2005.
+
+ [RFC4005] Calhoun, P., Zorn, G., Spence, D., and D. Mitton,
+ "Diameter Network Access Server Application", RFC 4005,
+ August 2005.
+
+ [RFC4006] Hakala, H., Mattila, L., Koskinen, J-P., Stura, M., and J.
+ 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.
+
+ [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an
+ IANA Considerations Section in RFCs", BCP 26, RFC 5226,
+ May 2008.
+
+ [RFC4291] Hinden, R. and S. Deering, "IP Version 6 Addressing
+ Architecture", RFC 4291, February 2006.
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 145]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+ [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.
+
+ [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.
+
+ [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO
+ 10646", STD 63, RFC 3629, November 2003.
+
+ [RFC5890] Klensin, J., "Internationalized Domain Names for
+ Applications (IDNA): Definitions and Document Framework",
+ RFC 5890, August 2010.
+
+ [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.
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 146]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+14.2. Informational References
+
+ [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.
+
+ [RFC2975] Aboba, B., Arkko, J., and D. Harrington, "Introduction to
+ Accounting Management", RFC 2975, October 2000.
+
+ [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.
+
+ [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.
+
+ [RFC4301] Kent, S. and K. Seo, "Security Architecture for the
+ Internet Protocol", RFC 4301, December 2005.
+
+ [RFC5905] Mills, D., Martin, J., Burbank, J., and W. Kasch, "Network
+ Time Protocol Version 4: Protocol and Algorithms
+ Specification", RFC 5905, June 2010.
+
+ [RFC1492] Finseth, C., "An Access Control Protocol, Sometimes Called
+ TACACS", RFC 1492, July 1993.
+
+ [RFC4690] Klensin, J., Faltstrom, P., Karp, C., and IAB, "Review and
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 147]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+ Recommendations for Internationalized Domain Names
+ (IDNs)", RFC 4690, September 2006.
+
+ [RFC5461] Gont, F., "TCP's Reaction to Soft Errors", RFC 5461,
+ February 2009.
+
+ [RFC5927] Gont, F., "ICMP Attacks against TCP", RFC 5927, July 2010.
+
+ [RFC3692] Narten, T., "Assigning Experimental and Testing Numbers
+ Considered Useful", BCP 82, RFC 3692, January 2004.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 148]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+Appendix A. Acknowledgements
+
+A.1. RFC3588bis
+
+ 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
+ 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
+ topics. To Jan Nordqvist for clearly stating the usage of
+ 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.
+
+ 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.
+
+ 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.
+
+ Finally, we would like to thank the original authors of this
+ document:
+
+ 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]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+A.2. RFC3588
+
+ 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.
+
+ 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
+ comments as a result of a thorough review of the spec.
+
+ The authors would also like to acknowledge the following people for
+ their contribution in the development of the Diameter protocol:
+
+ Allan C. Rubens, Haseeb Akhtar, William Bulley, Stephen Farrell,
+ 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
+ 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:
+
+ ;; order pref flags service regexp replacement
+ IN NAPTR 50 50 "s" "aaa:diameter.tls.tcp" ""
+ _diameter._tls.example1.com
+ IN NAPTR 100 50 "s" "aaa:diameter.tcp" ""
+ _aaa._tcp.example1.com
+ IN NAPTR 150 50 "s" "aaa:diameter.sctp" ""
+ _diameter._sctp.example1.com
+
+ 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.
+ That lookup would return:
+
+ ;; Priority Weight Port Target
+ IN SRV 0 1 5060 server1.example1.com
+ IN SRV 0 2 5060 server2.example1.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:
+
+ ;; order pref flags service regexp replacement
+ IN NAPTR 150 50 "a" "aaa:diameter.tls.tcp" ""
+ server1.example2.com
+ IN NAPTR 150 50 "a" "aaa:diameter.tls.tcp" ""
+ server2.example2.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
+ based on session identifiers. Duplicates can appear for various
+ 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
+ rebooted.
+
+ o Duplicates received from RADIUS gateways. Since the
+ retransmission behavior of RADIUS is not defined within [RFC2865],
+ the likelihood of duplication will vary according to the
+ implementation.
+
+ o Implementation problems and misconfiguration.
+
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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.
+
+ As an example, it can be usually be assumed that duplicates appear
+ within a time window of longest recorded network partition or device
+ fault, perhaps a day. So only records within this time window need
+ to be looked at in the backward direction. Secondly, hashing
+ techniques or other schemes, such as the use of the T flag in the
+ received messages, may be used to eliminate the need to do a full
+ search even in this set except for rare cases.
+
+ 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
+ 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
+ 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
+ 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
+ host and domain name comparison, Diameter identities (FQDNs) are
+ represented in ASCII form. This allows the Diameter protocol to fall
+ in-line with the DNS strategy of being transparent from the effects
+ of Internationalized Domain Names (IDNs) by following the
+ 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].
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 154]
+
+Internet-Draft Diameter Base Protocol January 2011
+
+
+Authors' Addresses
+
+ Victor Fajardo (editor)
+ Telcordia Technologies
+ One Telcordia Drive, 1S-222
+ Piscataway, NJ 08854
+ USA
+
+ Phone: +1-908-421-1845
+
+
+ Jari Arkko
+ Ericsson Research
+ 02420 Jorvas
+ Finland
+
+ Phone: +358 40 5079256
+
+
+ John Loughney
+ Nokia Research Center
+ 955 Page Mill Road
+ Palo Alto, CA 94304
+ US
+
+ Phone: +1-650-283-8068
+
+
+ Glenn Zorn
+ Network Zen
+ 1310 East Thomas Street
+ Seattle, WA 98102
+ US
+
+ Phone:
+
+
+
+
+
+
+
+
+
+
+
+
+Fajardo, et al. Expires July 24, 2011 [Page 155]
+
+
diff --git a/lib/diameter/doc/standard/rfc3124.txt b/lib/diameter/doc/standard/rfc3124.txt
new file mode 100644
index 0000000000..db57bc370f
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc3124.txt
@@ -0,0 +1,1235 @@
+
+
+
+
+
+
+Network Working Group H. Balakrishnan
+Request for Comments: 3124 MIT LCS
+Category: Standards Track S. Seshan
+ CMU
+ June 2001
+
+
+ The Congestion Manager
+
+
+Status of this Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The Internet Society (2001). All Rights Reserved.
+
+Abstract
+
+ This document describes the Congestion Manager (CM), an end-system
+ module that:
+
+ (i) Enables an ensemble of multiple concurrent streams from a sender
+ destined to the same receiver and sharing the same congestion
+ properties to perform proper congestion avoidance and control, and
+
+ (ii) Allows applications to easily adapt to network congestion.
+
+1. Conventions used in this document:
+
+ 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 [Bradner97].
+
+ STREAM
+
+ A group of packets that all share the same source and destination
+ IP address, IP type-of-service, transport protocol, and source and
+ destination transport-layer port numbers.
+
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 1]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ MACROFLOW
+
+ A group of CM-enabled streams that all use the same congestion
+ management and scheduling algorithms, and share congestion state
+ information. Currently, streams destined to different receivers
+ belong to different macroflows. Streams destined to the same
+ receiver MAY belong to different macroflows. When the Congestion
+ Manager is in use, streams that experience identical congestion
+ behavior and use the same congestion control algorithm SHOULD
+ belong to the same macroflow.
+
+ APPLICATION
+
+ Any software module that uses the CM. This includes user-level
+ applications such as Web servers or audio/video servers, as well
+ as in-kernel protocols such as TCP [Postel81] that use the CM for
+ congestion control.
+
+ WELL-BEHAVED APPLICATION
+
+ An application that only transmits when allowed by the CM and
+ accurately accounts for all data that it has sent to the receiver
+ by informing the CM using the CM API.
+
+ PATH MAXIMUM TRANSMISSION UNIT (PMTU)
+
+ The size of the largest packet that the sender can transmit
+ without it being fragmented en route to the receiver. It includes
+ the sizes of all headers and data except the IP header.
+
+ CONGESTION WINDOW (cwnd)
+
+ A CM state variable that modulates the amount of outstanding data
+ between sender and receiver.
+
+ OUTSTANDING WINDOW (ownd)
+
+ The number of bytes that has been transmitted by the source, but
+ not known to have been either received by the destination or lost
+ in the network.
+
+ INITIAL WINDOW (IW)
+
+ The size of the sender's congestion window at the beginning of a
+ macroflow.
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 2]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ DATA TYPE SYNTAX
+
+ We use "u64" for unsigned 64-bit, "u32" for unsigned 32-bit, "u16"
+ for unsigned 16-bit, "u8" for unsigned 8-bit, "i32" for signed
+ 32-bit, "i16" for signed 16-bit quantities, "float" for IEEE
+ floating point values. The type "void" is used to indicate that
+ no return value is expected from a call. Pointers are referred to
+ using "*" syntax, following C language convention.
+
+ We emphasize that all the API functions described in this document
+ are "abstract" calls and that conformant CM implementations may
+ differ in specific implementation details.
+
+2. Introduction
+
+ The framework described in this document integrates congestion
+ management across all applications and transport protocols. The CM
+ maintains congestion parameters (available aggregate and per-stream
+ bandwidth, per-receiver round-trip times, etc.) and exports an API
+ that enables applications to learn about network characteristics,
+ pass information to the CM, share congestion information with each
+ other, and schedule data transmissions. This document focuses on
+ applications and transport protocols with their own independent per-
+ byte or per-packet sequence number information, and does not require
+ modifications to the receiver protocol stack. However, the receiving
+ application must provide feedback to the sending application about
+ received packets and losses, and the latter is expected to use the CM
+ API to update CM state. This document does not address networks with
+ reservations or service differentiation.
+
+ The CM is an end-system module that enables an ensemble of multiple
+ concurrent streams to perform stable congestion avoidance and
+ control, and allows applications to easily adapt their transmissions
+ to prevailing network conditions. It integrates congestion
+ management across all applications and transport protocols. It
+ maintains congestion parameters (available aggregate and per-stream
+ bandwidth, per-receiver round-trip times, etc.) and exports an API
+ that enables applications to learn about network characteristics,
+ pass information to the CM, share congestion information with each
+ other, and schedule data transmissions. When the CM is used, all
+ data transmissions subject to the CM must be done with the explicit
+ consent of the CM via this API to ensure proper congestion behavior.
+
+ Systems MAY choose to use CM, and if so they MUST follow this
+ specification.
+
+ This document focuses on applications and networks where the
+ following conditions hold:
+
+
+
+Balakrishnan, et. al. Standards Track [Page 3]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ 1. Applications are well-behaved with their own independent
+ per-byte or per-packet sequence number information, and use the
+ CM API to update internal state in the CM.
+
+ 2. Networks are best-effort without service discrimination or
+ reservations. In particular, it does not address situations
+ where different streams between the same pair of hosts traverse
+ paths with differing characteristics.
+
+ The Congestion Manager framework can be extended to support
+ applications that do not provide their own feedback and to
+ differentially-served networks. These extensions will be addressed
+ in later documents.
+
+ The CM is motivated by two main goals:
+
+ (i) Enable efficient multiplexing. Increasingly, the trend on the
+ Internet is for unicast data senders (e.g., Web servers) to transmit
+ heterogeneous types of data to receivers, ranging from unreliable
+ real-time streaming content to reliable Web pages and applets. As a
+ result, many logically different streams share the same path between
+ sender and receiver. For the Internet to remain stable, each of
+ these streams must incorporate control protocols that safely probe
+ for spare bandwidth and react to congestion. Unfortunately, these
+ concurrent streams typically compete with each other for network
+ resources, rather than share them effectively. Furthermore, they do
+ not learn from each other about the state of the network. Even if
+ they each independently implement congestion control (e.g., a group
+ of TCP connections each implementing the algorithms in [Jacobson88,
+ Allman99]), the ensemble of streams tends to be more aggressive in
+ the face of congestion than a single TCP connection implementing
+ standard TCP congestion control and avoidance [Balakrishnan98].
+
+ (ii) Enable application adaptation to congestion. Increasingly,
+ popular real-time streaming applications run over UDP using their own
+ user-level transport protocols for good application performance, but
+ in most cases today do not adapt or react properly to network
+ congestion. By implementing a stable control algorithm and exposing
+ an adaptation API, the CM enables easy application adaptation to
+ congestion. Applications adapt the data they transmit to the current
+ network conditions.
+
+ The CM framework builds on recent work on TCP control block sharing
+ [Touch97], integrated TCP congestion control (TCP-Int)
+ [Balakrishnan98] and TCP sessions [Padmanabhan98]. [Touch97]
+ advocates the sharing of some of the state in the TCP control block
+ to improve transient transport performance and describes sharing
+ across an ensemble of TCP connections. [Balakrishnan98],
+
+
+
+Balakrishnan, et. al. Standards Track [Page 4]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ [Padmanabhan98], and [Eggert00] describe several experiments that
+ quantify the benefits of sharing congestion state, including improved
+ stability in the face of congestion and better loss recovery.
+ Integrating loss recovery across concurrent connections significantly
+ improves performance because losses on one connection can be detected
+ by noticing that later data sent on another connection has been
+ received and acknowledged. The CM framework extends these ideas in
+ two significant ways: (i) it extends congestion management to non-TCP
+ streams, which are becoming increasingly common and often do not
+ implement proper congestion management, and (ii) it provides an API
+ for applications to adapt their transmissions to current network
+ conditions. For an extended discussion of the motivation for the CM,
+ its architecture, API, and algorithms, see [Balakrishnan99]; for a
+ description of an implementation and performance results, see
+ [Andersen00].
+
+ The resulting end-host protocol architecture at the sender is shown
+ in Figure 1. The CM helps achieve network stability by implementing
+ stable congestion avoidance and control algorithms that are "TCP-
+ friendly" [Mahdavi98] based on algorithms described in [Allman99].
+ However, it does not attempt to enforce proper congestion behavior
+ for all applications (but it does not preclude a policer on the host
+ that performs this task). Note that while the policer at the end-
+ host can use CM, the network has to be protected against compromises
+ to the CM and the policer at the end hosts, a task that requires
+ router machinery [Floyd99a]. We do not address this issue further in
+ this document.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 5]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ |--------| |--------| |--------| |--------| |--------------|
+ | HTTP | | FTP | | RTP 1 | | RTP 2 | | |
+ |--------| |--------| |--------| |--------| | |
+ | | | ^ | ^ | |
+ | | | | | | | Scheduler |
+ | | | | | | |---| | |
+ | | | |-------|--+->| | | |
+ | | | | | |<--| |
+ v v v v | | |--------------|
+ |--------| |--------| |-------------| | | ^
+ | TCP 1 | | TCP 2 | | UDP 1 | | A | |
+ |--------| |--------| |-------------| | | |
+ ^ | ^ | | | | |--------------|
+ | | | | | | P |-->| |
+ | | | | | | | | |
+ |---|------+---|--------------|------->| | | Congestion |
+ | | | | I | | |
+ v v v | | | Controller |
+ |-----------------------------------| | | | |
+ | IP |-->| | | |
+ |-----------------------------------| | | |--------------|
+ |---|
+
+ Figure 1
+
+ The key components of the CM framework are (i) the API, (ii) the
+ congestion controller, and (iii) the scheduler. The API is (in part)
+ motivated by the requirements of application-level framing (ALF)
+ [Clark90], and is described in Section 4. The CM internals (Section
+ 5) include a congestion controller (Section 5.1) and a scheduler to
+ orchestrate data transmissions between concurrent streams in a
+ macroflow (Section 5.2). The congestion controller adjusts the
+ aggregate transmission rate between sender and receiver based on its
+ estimate of congestion in the network. It obtains feedback about its
+ past transmissions from applications themselves via the API. The
+ scheduler apportions available bandwidth amongst the different
+ streams within each macroflow and notifies applications when they are
+ permitted to send data. This document focuses on well-behaved
+ applications; a future one will describe the sender-receiver protocol
+ and header formats that will handle applications that do not
+ incorporate their own feedback to the CM.
+
+3. CM API
+
+ By convention, the IETF does not treat Application Programming
+ Interfaces as standards track. However, it is considered important
+ to have the CM API and CM algorithm requirements in one coherent
+ document. The following section on the CM API uses the terms MUST,
+
+
+
+Balakrishnan, et. al. Standards Track [Page 6]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ SHOULD, etc., but the terms are meant to apply within the context of
+ an implementation of the CM API. The section does not apply to
+ congestion control implementations in general, only to those
+ implementations offering the CM API.
+
+ Using the CM API, streams can determine their share of the available
+ bandwidth, request and have their data transmissions scheduled,
+ inform the CM about successful transmissions, and be informed when
+ the CM's estimate of path bandwidth changes. Thus, the CM frees
+ applications from having to maintain information about the state of
+ congestion and available bandwidth along any path.
+
+ The function prototypes below follow standard C language convention.
+ We emphasize that these API functions are abstract calls and
+ conformant CM implementations may differ in specific details, as long
+ as equivalent functionality is provided.
+
+ When a new stream is created by an application, it passes some
+ information to the CM via the cm_open(stream_info) API call.
+ Currently, stream_info consists of the following information: (i) the
+ source IP address, (ii) the source port, (iii) the destination IP
+ address, (iv) the destination port, and (v) the IP protocol number.
+
+3.1 State maintenance
+
+ 1. Open: All applications MUST call cm_open(stream_info) before
+ using the CM API. This returns a handle, cm_streamid, for the
+ application to use for all further CM API invocations for that
+ stream. If the returned cm_streamid is -1, then the cm_open()
+ failed and that stream cannot use the CM.
+
+ All other calls to the CM for a stream use the cm_streamid
+ returned from the cm_open() call.
+
+ 2. Close: When a stream terminates, the application SHOULD invoke
+ cm_close(cm_streamid) to inform the CM about the termination
+ of the stream.
+
+ 3. Packet size: cm_mtu(cm_streamid) returns the estimated PMTU of
+ the path between sender and receiver. Internally, this
+ information SHOULD be obtained via path MTU discovery
+ [Mogul90]. It MAY be statically configured in the absence of
+ such a mechanism.
+
+
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 7]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+3.2 Data transmission
+
+ The CM accommodates two types of adaptive senders, enabling
+ applications to dynamically adapt their content based on prevailing
+ network conditions, and supporting ALF-based applications.
+
+ 1. Callback-based transmission. The callback-based transmission API
+ puts the stream in firm control of deciding what to transmit at each
+ point in time. To achieve this, the CM does not buffer any data;
+ instead, it allows streams the opportunity to adapt to unexpected
+ network changes at the last possible instant. Thus, this enables
+ streams to "pull out" and repacketize data upon learning about any
+ rate change, which is hard to do once the data has been buffered.
+ The CM must implement a cm_request(i32 cm_streamid) call for streams
+ wishing to send data in this style. After some time, depending on
+ the rate, the CM MUST invoke a callback using cmapp_send(), which is
+ a grant for the stream to send up to PMTU bytes. The callback-style
+ API is the recommended choice for ALF-based streams. Note that
+ cm_request() does not take the number of bytes or MTU-sized units as
+ an argument; each call to cm_request() is an implicit request for
+ sending up to PMTU bytes. The CM MAY provide an alternate interface,
+ cm_request(int k). The cmapp_send callback for this request is
+ granted the right to send up to k PMTU sized segments. Section 4.3
+ discusses the time duration for which the transmission grant is
+ valid, while Section 5.2 describes how these requests are scheduled
+ and callbacks made.
+
+ 2. Synchronous-style. The above callback-based API accommodates a
+ class of ALF streams that are "asynchronous." Asynchronous
+ transmitters do not transmit based on a periodic clock, but do so
+ triggered by asynchronous events like file reads or captured frames.
+ On the other hand, there are many streams that are "synchronous"
+ transmitters, which transmit periodically based on their own internal
+ timers (e.g., an audio senders that sends at a constant sampling
+ rate). While CM callbacks could be configured to periodically
+ interrupt such transmitters, the transmit loop of such applications
+ is less affected if they retain their original timer-based loop. In
+ addition, it complicates the CM API to have a stream express the
+ periodicity and granularity of its callbacks. Thus, the CM MUST
+ export an API that allows such streams to be informed of changes in
+ rates using the cmapp_update(u64 newrate, u32 srtt, u32 rttdev)
+ callback function, where newrate is the new rate in bits per second
+ for this stream, srtt is the current smoothed round trip time
+ estimate in microseconds, and rttdev is the smoothed linear deviation
+ in the round-trip time estimate calculated using the same algorithm
+ as in TCP [Paxson00]. The newrate value reports an instantaneous
+ rate calculated, for example, by taking the ratio of cwnd and srtt,
+ and dividing by the fraction of that ratio allocated to the stream.
+
+
+
+Balakrishnan, et. al. Standards Track [Page 8]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ In response, the stream MUST adapt its packet size or change its
+ timer interval to conform to (i.e., not exceed) the allowed rate. Of
+ course, it may choose not to use all of this rate. Note that the CM
+ is not on the data path of the actual transmission.
+
+ To avoid unnecessary cmapp_update() callbacks that the application
+ will only ignore, the CM MUST provide a cm_thresh(float
+ rate_downthresh, float rate_upthresh, float rtt_downthresh, float
+ rtt_upthresh) function that a stream can use at any stage in its
+ execution. In response, the CM SHOULD invoke the callback only when
+ the rate decreases to less than (rate_downthresh * lastrate) or
+ increases to more than (rate_upthresh * lastrate), where lastrate is
+ the rate last notified to the stream, or when the round-trip time
+ changes correspondingly by the requisite thresholds. This
+ information is used as a hint by the CM, in the sense the
+ cmapp_update() can be called even if these conditions are not met.
+
+ The CM MUST implement a cm_query(i32 cm_streamid, u64* rate, u32*
+ srtt, u32* rttdev) to allow an application to query the current CM
+ state. This sets the rate variable to the current rate estimate in
+ bits per second, the srtt variable to the current smoothed round-trip
+ time estimate in microseconds, and rttdev to the mean linear
+ deviation. If the CM does not have valid estimates for the
+ macroflow, it fills in negative values for the rate, srtt, and
+ rttdev.
+
+ Note that a stream can use more than one of the above transmission
+ APIs at the same time. In particular, the knowledge of sustainable
+ rate is useful for asynchronous streams as well as synchronous ones;
+ e.g., an asynchronous Web server disseminating images using TCP may
+ use cmapp_send() to schedule its transmissions and cmapp_update() to
+ decide whether to send a low-resolution or high-resolution image. A
+ TCP implementation using the CM is described in Section 6.1.1, where
+ the benefit of the cm_request() callback API for TCP will become
+ apparent.
+
+ The reader will notice that the basic CM API does not provide an
+ interface for buffered congestion-controlled transmissions. This is
+ intentional, since this transmission mode can be implemented using
+ the callback-based primitive. Section 6.1.2 describes how
+ congestion-controlled UDP sockets may be implemented using the CM
+ API.
+
+3.3 Application notification
+
+ When a stream receives feedback from receivers, it MUST use
+ cm_update(i32 cm_streamid, u32 nrecd, u32 nlost, u8 lossmode, i32
+ rtt) to inform the CM about events such as congestion losses,
+
+
+
+Balakrishnan, et. al. Standards Track [Page 9]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ successful receptions, type of loss (timeout event, Explicit
+ Congestion Notification [Ramakrishnan99], etc.) and round-trip time
+ samples. The nrecd parameter indicates how many bytes were
+ successfully received by the receiver since the last cm_update call,
+ while the nrecd parameter identifies how many bytes were received
+ were lost during the same time period. The rtt value indicates the
+ round-trip time measured during the transmission of these bytes. The
+ rtt value must be set to -1 if no valid round-trip sample was
+ obtained by the application. The lossmode parameter provides an
+ indicator of how a loss was detected. A value of CM_NO_FEEDBACK
+ indicates that the application has received no feedback for all its
+ outstanding data, and is reporting this to the CM. For example, a
+ TCP that has experienced a timeout would use this parameter to inform
+ the CM of this. A value of CM_LOSS_FEEDBACK indicates that the
+ application has experienced some loss, which it believes to be due to
+ congestion, but not all outstanding data has been lost. For example,
+ a TCP segment loss detected using duplicate (selective)
+ acknowledgments or other data-driven techniques fits this category.
+ A value of CM_EXPLICIT_CONGESTION indicates that the receiver echoed
+ an explicit congestion notification message. Finally, a value of
+ CM_NO_CONGESTION indicates that no congestion-related loss has
+ occurred. The lossmode parameter MUST be reported as a bit-vector
+ where the bits correspond to CM_NO_FEEDBACK, CM_LOSS_FEEDBACK,
+ CM_EXPLICIT_CONGESTION, and CM_NO_CONGESTION. Note that over links
+ (paths) that experience losses for reasons other than congestion, an
+ application SHOULD inform the CM of losses, with the CM_NO_CONGESTION
+ field set.
+
+ cm_notify(i32 cm_streamid, u32 nsent) MUST be called when data is
+ transmitted from the host (e.g., in the IP output routine) to inform
+ the CM that nsent bytes were just transmitted on a given stream.
+ This allows the CM to update its estimate of the number of
+ outstanding bytes for the macroflow and for the stream.
+
+ A cmapp_send() grant from the CM to an application is valid only for
+ an expiration time, equal to the larger of the round-trip time and an
+ implementation-dependent threshold communicated as an argument to the
+ cmapp_send() callback function. The application MUST NOT send data
+ based on this callback after this time has expired. Furthermore, if
+ the application decides not to send data after receiving this
+ callback, it SHOULD call cm_notify(stream_info, 0) to allow the CM to
+ permit other streams in the macroflow to transmit data. The CM
+ congestion controller MUST be robust to applications forgetting to
+ invoke cm_notify(stream_info, 0) correctly, or applications that
+ crash or disappear after having made a cm_request() call.
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 10]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+3.4 Querying
+
+ If applications wish to learn about per-stream available bandwidth
+ and round-trip time, they can use the CM's cm_query(i32 cm_streamid,
+ i64* rate, i32* srtt, i32* rttdev) call, which fills in the desired
+ quantities. If the CM does not have valid estimates for the
+ macroflow, it fills in negative values for the rate, srtt, and
+ rttdev.
+
+3.5 Sharing granularity
+
+ One of the decisions the CM needs to make is the granularity at which
+ a macroflow is constructed, by deciding which streams belong to the
+ same macroflow and share congestion information. The API provides
+ two functions that allow applications to decide which of their
+ streams ought to belong to the same macroflow.
+
+ cm_getmacroflow(i32 cm_streamid) returns a unique i32 macroflow
+ identifier. cm_setmacroflow(i32 cm_macroflowid, i32 cm_streamid)
+ sets the macroflow of the stream cm_streamid to cm_macroflowid. If
+ the cm_macroflowid that is passed to cm_setmacroflow() is -1, then a
+ new macroflow is constructed and this is returned to the caller.
+ Each call to cm_setmacroflow() overrides the previous macroflow
+ association for the stream, should one exist.
+
+ The default suggested aggregation method is to aggregate by
+ destination IP address; i.e., all streams to the same destination
+ address are aggregated to a single macroflow by default. The
+ cm_getmacroflow() and cm_setmacroflow() calls can then be used to
+ change this as needed. We do note that there are some cases where
+ this may not be optimal, even over best-effort networks. For
+ example, when a group of receivers are behind a NAT device, the
+ sender will see them all as one address. If the hosts behind the NAT
+ are in fact connected over different bottleneck links, some of those
+ hosts could see worse performance than before. It is possible to
+ detect such hosts when using delay and loss estimates, although the
+ specific mechanisms for doing so are beyond the scope of this
+ document.
+
+ The objective of this interface is to set up sharing of groups not
+ sharing policy of relative weights of streams in a macroflow. The
+ latter requires the scheduler to provide an interface to set sharing
+ policy. However, because we want to support many different
+ schedulers (each of which may need different information to set
+ policy), we do not specify a complete API to the scheduler (but see
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 11]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ Section 5.2). A later guideline document is expected to describe a
+ few simple schedulers (e.g., weighted round-robin, hierarchical
+ scheduling) and the API they export to provide relative
+ prioritization.
+
+4. CM internals
+
+ This section describes the internal components of the CM. It
+ includes a Congestion Controller and a Scheduler, with well-defined,
+ abstract interfaces exported by them.
+
+4.1 Congestion controller
+
+ Associated with each macroflow is a congestion control algorithm; the
+ collection of all these algorithms comprises the congestion
+ controller of the CM. The control algorithm decides when and how
+ much data can be transmitted by a macroflow. It uses application
+ notifications (Section 4.3) from concurrent streams on the same
+ macroflow to build up information about the congestion state of the
+ network path used by the macroflow.
+
+ The congestion controller MUST implement a "TCP-friendly" [Mahdavi98]
+ congestion control algorithm. Several macroflows MAY (and indeed,
+ often will) use the same congestion control algorithm but each
+ macroflow maintains state about the network used by its streams.
+
+ The congestion control module MUST implement the following abstract
+ interfaces. We emphasize that these are not directly visible to
+ applications; they are within the context of a macroflow, and are
+ different from the CM API functions of Section 4.
+
+ - void query(u64 *rate, u32 *srtt, u32 *rttdev): This function
+ returns the estimated rate (in bits per second) and smoothed
+ round trip time (in microseconds) for the macroflow.
+
+ - void notify(u32 nsent): This function MUST be used to notify the
+ congestion control module whenever data is sent by an
+ application. The nsent parameter indicates the number of bytes
+ just sent by the application.
+
+ - void update(u32 nsent, u32 nrecd, u32 rtt, u32 lossmode): This
+ function is called whenever any of the CM streams associated with
+ a macroflow identifies that data has reached the receiver or has
+ been lost en route. The nrecd parameter indicates the number of
+ bytes that have just arrived at the receiver. The nsent
+ parameter is the sum of the number of bytes just received and the
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 12]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ number of bytes identified as lost en route. The rtt parameter is
+ the estimated round trip time in microseconds during the
+ transfer. The lossmode parameter provides an indicator of how a
+ loss was detected (section 4.3).
+
+ Although these interfaces are not visible to applications, the
+ congestion controller MUST implement these abstract interfaces to
+ provide for modular inter-operability with different separately-
+ developed schedulers.
+
+ The congestion control module MUST also call the associated
+ scheduler's schedule function (section 5.2) when it believes that the
+ current congestion state allows an MTU-sized packet to be sent.
+
+4.2 Scheduler
+
+ While it is the responsibility of the congestion control module to
+ determine when and how much data can be transmitted, it is the
+ responsibility of a macroflow's scheduler module to determine which
+ of the streams should get the opportunity to transmit data.
+
+ The Scheduler MUST implement the following interfaces:
+
+ - void schedule(u32 num_bytes): When the congestion control module
+ determines that data can be sent, the schedule() routine MUST be
+ called with no more than the number of bytes that can be sent.
+ In turn, the scheduler MAY call the cmapp_send() function that CM
+ applications must provide.
+
+ - float query_share(i32 cm_streamid): This call returns the
+ described stream's share of the total bandwidth available to the
+ macroflow. This call combined with the query call of the
+ congestion controller provides the information to satisfy an
+ application's cm_query() request.
+
+ - void notify(i32 cm_streamid, u32 nsent): This interface is used
+ to notify the scheduler module whenever data is sent by a CM
+ application. The nsent parameter indicates the number of bytes
+ just sent by the application.
+
+ The Scheduler MAY implement many additional interfaces. As
+ experience with CM schedulers increases, future documents may
+ make additions and/or changes to some parts of the scheduler
+ API.
+
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 13]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+5. Examples
+
+5.1 Example applications
+
+ This section describes three possible uses of the CM API by
+ applications. We describe two asynchronous applications---an
+ implementation of a TCP sender and an implementation of congestion-
+ controlled UDP sockets, and a synchronous application---a streaming
+ audio server. More details of these applications and CM
+ implementation optimizations for efficient operation are described in
+ [Andersen00].
+
+ All applications that use the CM MUST incorporate feedback from the
+ receiver. For example, it must periodically (typically once or twice
+ per round trip time) determine how many of its packets arrived at the
+ receiver. When the source gets this feedback, it MUST use
+ cm_update() to inform the CM of this new information. This results
+ in the CM updating ownd and may result in the CM changing its
+ estimates and calling cmapp_update() of the streams of the macroflow.
+
+ The protocols in this section are examples and suggestions for
+ implementation, rather than requirements for any conformant
+ implementation.
+
+5.1.1 TCP
+
+ A TCP implementation that uses CM should use the cmapp_send()
+ callback API. TCP only identifies which data it should send upon the
+ arrival of an acknowledgement or expiration of a timer. As a result,
+ it requires tight control over when and if new data or
+ retransmissions are sent.
+
+ When TCP either connects to or accepts a connection from another
+ host, it performs a cm_open() call to associate the TCP connection
+ with a cm_streamid.
+
+ Once a connection is established, the CM is used to control the
+ transmission of outgoing data. The CM eliminates the need for
+ tracking and reacting to congestion in TCP, because the CM and its
+ transmission API ensure proper congestion behavior. Loss recovery is
+ still performed by TCP based on fast retransmissions and recovery as
+ well as timeouts. In addition, TCP is also modified to have its own
+ outstanding window (tcp_ownd) estimate. Whenever data segments are
+ sent from its cmapp_send() callback, TCP updates its tcp_ownd value.
+ The ownd variable is also updated after each cm_update() call. TCP
+ also maintains a count of the number of outstanding segments
+ (pkt_cnt). At any time, TCP can calculate the average packet size
+ (avg_pkt_size) as tcp_ownd/pkt_cnt. The avg_pkt_size is used by TCP
+
+
+
+Balakrishnan, et. al. Standards Track [Page 14]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ to help estimate the amount of outstanding data. Note that this is
+ not needed if the SACK option is used on the connection, since this
+ information is explicitly available.
+
+ The TCP output routines are modified as follows:
+
+ 1. All congestion window (cwnd) checks are removed.
+
+ 2. When application data is available. The TCP output routines
+ perform all non-congestion checks (Nagle algorithm, receiver-
+ advertised window check, etc). If these checks pass, the output
+ routine queues the data and calls cm_request() for the stream.
+
+ 3. If incoming data or timers result in a loss being detected, the
+ retransmission is also placed in a queue and cm_request() is
+ called for the stream.
+
+ 4. The cmapp_send() callback for TCP is set to an output routine.
+ If any retransmission is enqueued, the routine outputs the
+ retransmission. Otherwise, the routine outputs as much new data
+ as the TCP connection state allows. However, the cmapp_send()
+ never sends more than a single segment per call. This routine
+ arranges for the other output computations to be done, such as
+ header and options computations.
+
+ The IP output routine on the host calls cm_notify() when the packets
+ are actually sent out. Because it does not know which cm_streamid is
+ responsible for the packet, cm_notify() takes the stream_info as
+ argument (see Section 4 for what the stream_info should contain).
+ Because cm_notify() reports the IP payload size, TCP keeps track of
+ the total header size and incorporates these updates.
+
+ The TCP input routines are modified as follows:
+
+ 1. RTT estimation is done as normal using either timestamps or
+ Karn's algorithm. Any rtt estimate that is generated is passed to
+ CM via the cm_update call.
+
+ 2. All cwnd and slow start threshold (ssthresh) updates are
+ removed.
+
+ 3. Upon the arrival of an ack for new data, TCP computes the value
+ of in_flight (the amount of data in flight) as snd_max-ack-1
+ (i.e., MAX Sequence Sent - Current Ack - 1). TCP then calls
+ cm_update(streamid, tcp_ownd - in_flight, 0, CM_NO_CONGESTION,
+ rtt).
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 15]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ 4. Upon the arrival of a duplicate acknowledgement, TCP must check
+ its dupack count (dup_acks) to determine its action. If dup_acks
+ < 3, the TCP does nothing. If dup_acks == 3, TCP assumes that a
+ packet was lost and that at least 3 packets arrived to generate
+ these duplicate acks. Therefore, it calls cm_update(streamid, 4 *
+ avg_pkt_size, 3 * avg_pkt_size, CM_LOSS_FEEDBACK, rtt). The
+ average packet size is used since the acknowledgments do not
+ indicate exactly how much data has reached the other end. Most
+ TCP implementations interpret a duplicate ACK as an indication
+ that a full MSS has reached its destination. Once a new ACK is
+ received, these TCP sender implementations may resynchronize with
+ TCP receiver. The CM API does not provide a mechanism for TCP to
+ pass information from this resynchronization. Therefore, TCP can
+ only infer the arrival of an avg_pkt_size amount of data from each
+ duplicate ack. TCP also enqueues a retransmission of the lost
+ segment and calls cm_request(). If dup_acks > 3, TCP assumes that
+ a packet has reached the other end and caused this ack to be sent.
+ As a result, it calls cm_update(streamid, avg_pkt_size,
+ avg_pkt_size, CM_NO_CONGESTION, rtt).
+
+ 5. Upon the arrival of a partial acknowledgment (one that does not
+ exceed the highest segment transmitted at the time the loss
+ occurred, as defined in [Floyd99b]), TCP assumes that a packet was
+ lost and that the retransmitted packet has reached the recipient.
+ Therefore, it calls cm_update(streamid, 2 * avg_pkt_size,
+ avg_pkt_size, CM_NO_CONGESTION, rtt). CM_NO_CONGESTION is used
+ since the loss period has already been reported. TCP also
+ enqueues a retransmission of the lost segment and calls
+ cm_request().
+
+ When the TCP retransmission timer expires, the sender identifies that
+ a segment has been lost and calls cm_update(streamid, avg_pkt_size,
+ 0, CM_NO_FEEDBACK, 0) to signify that no feedback has been received
+ from the receiver and that one segment is sure to have "left the
+ pipe." TCP also enqueues a retransmission of the lost segment and
+ calls cm_request().
+
+5.1.2 Congestion-controlled UDP
+
+ Congestion-controlled UDP is a useful CM application, which we
+ describe in the context of Berkeley sockets [Stevens94]. They
+ provide the same functionality as standard Berkeley UDP sockets, but
+ instead of immediately sending the data from the kernel packet queue
+ to lower layers for transmission, the buffered socket implementation
+ makes calls to the API exported by the CM inside the kernel and gets
+ callbacks from the CM. When a CM UDP socket is created, it is bound
+ to a particular stream. Later, when data is added to the packet
+ queue, cm_request() is called on the stream associated with the
+
+
+
+Balakrishnan, et. al. Standards Track [Page 16]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ socket. When the CM schedules this stream for transmission, it calls
+ udp_ccappsend() in the UDP module. This function transmits one MTU
+ from the packet queue, and schedules the transmission of any
+ remaining packets. The in-kernel implementation of the CM UDP API
+ should not require any additional data copies and should support all
+ standard UDP options. Modifying existing applications to use
+ congestion-controlled UDP requires the implementation of a new socket
+ option on the socket. To work correctly, the sender must obtain
+ feedback about congestion. This can be done in at least two ways:
+ (i) the UDP receiver application can provide feedback to the sender
+ application, which will inform the CM of network conditions using
+ cm_update(); (ii) the UDP receiver implementation can provide
+ feedback to the sending UDP. Note that this latter alternative
+ requires changes to the receiver's network stack and the sender UDP
+ cannot assume that all receivers support this option without explicit
+ negotiation.
+
+5.1.3 Audio server
+
+ A typical audio application often has access to the sample in a
+ multitude of data rates and qualities. The objective of the
+ application is then to deliver the highest possible quality of audio
+ (typically the highest data rate) its clients. The selection of
+ which version of audio to transmit should be based on the current
+ congestion state of the network. In addition, the source will want
+ audio delivered to its users at a consistent sampling rate. As a
+ result, it must send data a regular rate, minimizing delaying
+ transmissions and reducing buffering before playback. To meet these
+ requirements, this application can use the synchronous sender API
+ (Section 4.2).
+
+ When the source first starts, it uses the cm_query() call to get an
+ initial estimate of network bandwidth and delay. If some other
+ streams on that macroflow have already been active, then it gets an
+ initial estimate that is valid; otherwise, it gets negative values,
+ which it ignores. It then chooses an encoding that does not exceed
+ these estimates (or, in the case of an invalid estimate, uses
+ application-specific initial values) and begins transmitting data.
+ The application also implements the cmapp_update() callback. When
+ the CM determines that network characteristics have changed, it calls
+ the application's cmapp_update() function and passes it a new rate
+ and round-trip time estimate. The application must change its choice
+ of audio encoding to ensure that it does not exceed these new
+ estimates.
+
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 17]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+5.2 Example congestion control module
+
+ To illustrate the responsibilities of a congestion control module,
+ the following describes some of the actions of a simple TCP-like
+ congestion control module that implements Additive Increase
+ Multiplicative Decrease congestion control (AIMD_CC):
+
+ - query(): AIMD_CC returns the current congestion window (cwnd)
+ divided by the smoothed rtt (srtt) as its bandwidth estimate. It
+ returns the smoothed rtt estimate as srtt.
+
+ - notify(): AIMD_CC adds the number of bytes sent to its
+ outstanding data window (ownd).
+
+ - update(): AIMD_CC subtracts nsent from ownd. If the value of rtt
+ is non-zero, AIMD_CC updates srtt using the TCP srtt calculation.
+ If the update indicates that data has been lost, AIMD_CC sets
+ cwnd to 1 MTU if the loss_mode is CM_NO_FEEDBACK and to cwnd/2
+ (with a minimum of 1 MTU) if the loss_mode is CM_LOSS_FEEDBACK or
+ CM_EXPLICIT_CONGESTION. AIMD_CC also sets its internal ssthresh
+ variable to cwnd/2. If no loss had occurred, AIMD_CC mimics TCP
+ slow start and linear growth modes. It increments cwnd by nsent
+ when cwnd < ssthresh (bounded by a maximum of ssthresh-cwnd) and
+ by nsent * MTU/cwnd when cwnd > ssthresh.
+
+ - When cwnd or ownd are updated and indicate that at least one MTU
+ may be transmitted, AIMD_CC calls the CM to schedule a
+ transmission.
+
+5.3 Example Scheduler Module
+
+ To clarify the responsibilities of a scheduler module, the following
+ describes some of the actions of a simple round robin scheduler
+ module (RR_sched):
+
+ - schedule(): RR_sched schedules as many streams as possible in round
+ robin fashion.
+
+ - query_share(): RR_sched returns 1/(number of streams in macroflow).
+
+ - notify(): RR_sched does nothing. Round robin scheduling is not
+ affected by the amount of data sent.
+
+6. Security Considerations
+
+ The CM provides many of the same services that the congestion control
+ in TCP provides. As such, it is vulnerable to many of the same
+ security problems. For example, incorrect reports of losses and
+
+
+
+Balakrishnan, et. al. Standards Track [Page 18]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ transmissions will give the CM an inaccurate picture of the network's
+ congestion state. By giving CM a high estimate of congestion, an
+ attacker can degrade the performance observed by applications. For
+ example, a stream on a host can arbitrarily slow down any other
+ stream on the same macroflow, a form of denial of service.
+
+ The more dangerous form of attack occurs when an application gives
+ the CM a low estimate of congestion. This would cause CM to be
+ overly aggressive and allow data to be sent much more quickly than
+ sound congestion control policies would allow.
+
+ [Touch97] describes a number of the security problems that arise with
+ congestion information sharing. An additional vulnerability (not
+ covered by [Touch97])) occurs because applications have access
+ through the CM API to control shared state that will affect other
+ applications on the same computer. For instance, a poorly designed,
+ possibly a compromised, or intentionally malicious UDP application
+ could misuse cm_update() to cause starvation and/or too-aggressive
+ behavior of others in the macroflow.
+
+7. References
+
+ [Allman99] Allman, M. and Paxson, V., "TCP Congestion
+ Control", RFC 2581, April 1999.
+
+ [Andersen00] Balakrishnan, H., System Support for Bandwidth
+ Management and Content Adaptation in Internet
+ Applications, Proc. 4th Symp. on Operating Systems
+ Design and Implementation, San Diego, CA, October
+ 2000. Available from
+ http://nms.lcs.mit.edu/papers/cm-osdi2000.html
+
+ [Balakrishnan98] Balakrishnan, H., Padmanabhan, V., Seshan, S.,
+ Stemm, M., and Katz, R., "TCP Behavior of a Busy
+ Web Server: Analysis and Improvements," Proc. IEEE
+ INFOCOM, San Francisco, CA, March 1998.
+
+ [Balakrishnan99] Balakrishnan, H., Rahul, H., and Seshan, S., "An
+ Integrated Congestion Management Architecture for
+ Internet Hosts," Proc. ACM SIGCOMM, Cambridge, MA,
+ September 1999.
+
+ [Bradner96] Bradner, S., "The Internet Standards Process ---
+ Revision 3", BCP 9, RFC 2026, October 1996.
+
+ [Bradner97] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 19]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+ [Clark90] Clark, D. and Tennenhouse, D., "Architectural
+ Consideration for a New Generation of Protocols",
+ Proc. ACM SIGCOMM, Philadelphia, PA, September
+ 1990.
+
+ [Eggert00] Eggert, L., Heidemann, J., and Touch, J., "Effects
+ of Ensemble TCP," ACM Computer Comm. Review,
+ January 2000.
+
+ [Floyd99a] Floyd, S. and Fall, K.," Promoting the Use of End-
+ to-End Congestion Control in the Internet,"
+ IEEE/ACM Trans. on Networking, 7(4), August 1999,
+ pp. 458-472.
+
+ [Floyd99b] Floyd, S. and T. Henderson,"The New Reno
+ Modification to TCP's Fast Recovery Algorithm," RFC
+ 2582, April 1999.
+
+ [Jacobson88] Jacobson, V., "Congestion Avoidance and Control,"
+ Proc. ACM SIGCOMM, Stanford, CA, August 1988.
+
+ [Mahdavi98] Mahdavi, J. and Floyd, S., "The TCP Friendly
+ Website,"
+ http://www.psc.edu/networking/tcp_friendly.html
+
+ [Mogul90] Mogul, J. and S. Deering, "Path MTU Discovery," RFC
+ 1191, November 1990.
+
+ [Padmanabhan98] Padmanabhan, V., "Addressing the Challenges of Web
+ Data Transport," PhD thesis, Univ. of California,
+ Berkeley, December 1998.
+
+ [Paxson00] Paxson, V. and M. Allman, "Computing TCP's
+ Retransmission Timer", RFC 2988, November 2000.
+
+ [Postel81] Postel, J., Editor, "Transmission Control
+ Protocol", STD 7, RFC 793, September 1981.
+
+ [Ramakrishnan99] Ramakrishnan, K. and Floyd, S., "A Proposal to Add
+ Explicit Congestion Notification (ECN) to IP," RFC
+ 2481, January 1999.
+
+
+ [Stevens94] Stevens, W., TCP/IP Illustrated, Volume 1.
+ Addison-Wesley, Reading, MA, 1994.
+
+ [Touch97] Touch, J., "TCP Control Block Interdependence", RFC
+ 2140, April 1997.
+
+
+
+Balakrishnan, et. al. Standards Track [Page 20]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+8. Acknowledgments
+
+ We thank David Andersen, Deepak Bansal, and Dorothy Curtis for their
+ work on the CM design and implementation. We thank Vern Paxson for
+ his detailed comments, feedback, and patience, and Sally Floyd, Mark
+ Handley, and Steven McCanne for useful feedback on the CM
+ architecture. Allison Mankin and Joe Touch provided several useful
+ comments on previous drafts of this document.
+
+9. Authors' Addresses
+
+ Hari Balakrishnan
+ Laboratory for Computer Science
+ 200 Technology Square
+ Massachusetts Institute of Technology
+ Cambridge, MA 02139
+
+ Web: http://nms.lcs.mit.edu/~hari/
+
+
+ Srinivasan Seshan
+ School of Computer Science
+ Carnegie Mellon University
+ 5000 Forbes Ave.
+ Pittsburgh, PA 15213
+
+ Web: http://www.cs.cmu.edu/~srini/
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 21]
+
+RFC 3124 The Congestion Manager June 2001
+
+
+Full Copyright Statement
+
+ Copyright (C) The Internet Society (2001). All Rights Reserved.
+
+ This document and translations of it may be copied and furnished to
+ others, and derivative works that comment on or otherwise explain it
+ or assist in its implementation may be prepared, copied, published
+ and distributed, in whole or in part, without restriction of any
+ kind, provided that the above copyright notice and this paragraph are
+ included on all such copies and derivative works. However, this
+ document itself may not be modified in any way, such as by removing
+ the copyright notice or references to the Internet Society or other
+ Internet organizations, except as needed for the purpose of
+ developing Internet standards in which case the procedures for
+ copyrights defined in the Internet Standards process must be
+ followed, or as required to translate it into languages other than
+ English.
+
+ The limited permissions granted above are perpetual and will not be
+ revoked by the Internet Society or its successors or assigns.
+
+ This document and the information contained herein is provided on an
+ "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+ TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
+ BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
+ HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+ MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Balakrishnan, et. al. Standards Track [Page 22]
+
diff --git a/lib/diameter/doc/standard/rfc3539.txt b/lib/diameter/doc/standard/rfc3539.txt
new file mode 100644
index 0000000000..0b18625cc5
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc3539.txt
@@ -0,0 +1,2299 @@
+
+
+
+
+
+
+Network Working Group B. Aboba
+Request for Comments: 3539 Microsoft
+Category: Standards Track J. Wood
+ Sun Microsystems, Inc.
+ June 2003
+
+
+ Authentication, Authorization and Accounting (AAA) Transport Profile
+
+Status of this Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The Internet Society (2003). All Rights Reserved.
+
+Abstract
+
+ This document discusses transport issues that arise within protocols
+ for Authentication, Authorization and Accounting (AAA). It also
+ provides recommendations on the use of transport by AAA protocols.
+ This includes usage of standards-track RFCs as well as experimental
+ proposals.
+
+Table of Contents
+
+ 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 2
+ 1.1. Requirements Language. . . . . . . . . . . . . . . . . . 2
+ 1.2. Terminology. . . . . . . . . . . . . . . . . . . . . . . 2
+ 2. Issues in Transport Usage. . . . . . . . . . . . . . . . . . . 5
+ 2.1. Application-driven Versus Network-driven . . . . . . . . 5
+ 2.2. Slow Failover. . . . . . . . . . . . . . . . . . . . . . 6
+ 2.3. Use of Nagle Algorithm . . . . . . . . . . . . . . . . . 7
+ 2.4. Multiple Connections . . . . . . . . . . . . . . . . . . 7
+ 2.5. Duplicate Detection. . . . . . . . . . . . . . . . . . . 8
+ 2.6. Invalidation of Transport Parameter Estimates. . . . . . 8
+ 2.7. Inability to use Fast Re-Transmit. . . . . . . . . . . . 9
+ 2.8. Congestion Avoidance . . . . . . . . . . . . . . . . . . 9
+ 2.9. Delayed Acknowledgments. . . . . . . . . . . . . . . . . 11
+ 2.10. Premature Failover . . . . . . . . . . . . . . . . . . . 11
+ 2.11. Head of Line Blocking. . . . . . . . . . . . . . . . . . 11
+ 2.12. Connection Load Balancing. . . . . . . . . . . . . . . . 12
+
+
+
+
+Aboba & Wood Standards Track [Page 1]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ 3. AAA Transport Profile. . . . . . . . . . . . . . . . . . . . . 12
+ 3.1. Transport Mappings . . . . . . . . . . . . . . . . . . . 12
+ 3.2. Use of Nagle Algorithm . . . . . . . . . . . . . . . . . 12
+ 3.3. Multiple Connections . . . . . . . . . . . . . . . . . . 13
+ 3.4. Application Layer Watchdog . . . . . . . . . . . . . . . 13
+ 3.5. Duplicate Detection. . . . . . . . . . . . . . . . . . . 19
+ 3.6. Invalidation of Transport Parameter Estimates. . . . . . 20
+ 3.7. Inability to use Fast Re-Transmit. . . . . . . . . . . . 21
+ 3.8. Head of Line Blocking. . . . . . . . . . . . . . . . . . 22
+ 3.9. Congestion Avoidance . . . . . . . . . . . . . . . . . . 23
+ 3.10. Premature Failover . . . . . . . . . . . . . . . . . . . 24
+ 4. Security Considerations. . . . . . . . . . . . . . . . . . . . 24
+ 5. IANA Considerations. . . . . . . . . . . . . . . . . . . . . . 25
+ 6. References . . . . . . . . . . . . . . . . . . . . . . . . . . 25
+ 6.1. Normative References . . . . . . . . . . . . . . . . . . 25
+ 6.2. Informative References . . . . . . . . . . . . . . . . . 26
+ Appendix A - Detailed Watchdog Algorithm Description . . . . . . . 28
+ Appendix B - AAA Agents. . . . . . . . . . . . . . . . . . . . . . 33
+ B.1. Relays and Proxies . . . . . . . . . . . . . . . . . . . 33
+ B.2. Re-directs . . . . . . . . . . . . . . . . . . . . . . . 35
+ B.3. Store and Forward Proxies. . . . . . . . . . . . . . . . 36
+ B.4. Transport Layer Proxies. . . . . . . . . . . . . . . . . 38
+ Intellectual Property Statement. . . . . . . . . . . . . . . . . . 39
+ Acknowledgments. . . . . . . . . . . . . . . . . . . . . . . . . . 39
+ Author Addresses . . . . . . . . . . . . . . . . . . . . . . . . . 40
+ Full Copyright Statement . . . . . . . . . . . . . . . . . . . . . 41
+
+1. Introduction
+
+ This document discusses transport issues that arise within protocols
+ for Authentication, Authorization and Accounting (AAA). It also
+ provides recommendations on the use of transport by AAA protocols.
+ This includes usage of standards-track RFCs as well as experimental
+ proposals.
+
+1.1. Requirements Language
+
+ In this document, the key words "MAY", "MUST, "MUST NOT", "optional",
+ "recommended", "SHOULD", and "SHOULD NOT", are to be interpreted as
+ described in [RFC2119].
+
+1.2. Terminology
+
+ Accounting
+ The act of collecting information on resource usage for the
+ purpose of trend analysis, auditing, billing, or cost
+ allocation.
+
+
+
+
+Aboba & Wood Standards Track [Page 2]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ Administrative Domain
+ An internet, or a collection of networks, computers, and
+ databases under a common administration.
+
+ Agent A AAA agent is an intermediary that communicates with AAA
+ clients and servers. Several types of AAA agents exist,
+ including Relays, Re-directs, and Proxies.
+
+ Application-driven transport
+ Transport behavior is said to be "application-driven" when
+ the rate at which messages are sent is limited by the rate
+ at which the application generates data, rather than by the
+ size of the congestion window. In the most extreme case,
+ the time between transactions exceeds the round-trip time
+ between sender and receiver, implying that the application
+ operates with an effective congestion window of one. AAA
+ transport is typically application driven.
+
+ Attribute Value Pair (AVP)
+ The variable length concatenation of a unique Attribute
+ (represented by an integer) and a Value containing the
+ actual value identified by the attribute.
+
+ Authentication
+ The act of verifying a claimed identity, in the form of a
+ pre-existing label from a mutually known name space, as the
+ originator of a message (message authentication) or as the
+ end-point of a channel (entity authentication).
+
+ Authorization
+ The act of determining if a particular right, such as
+ access to some resource, can be granted to the presenter of
+ a particular credential.
+
+ Billing The act of preparing an invoice.
+
+ Network Access Identifier
+ The Network Access Identifier (NAI) is the userID submitted
+ by the host during network access authentication. In
+ roaming, the purpose of the NAI is to identify the user as
+ well as to assist in the routing of the authentication
+ request. The NAI may not necessarily be the same as the
+ user's e-mail address or the user-ID submitted in an
+ application layer authentication.
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 3]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ Network Access Server (NAS)
+ A Network Access Server (NAS) is a device that hosts
+ connect to in order to get access to the network.
+
+ Proxy In addition to forwarding requests and responses, proxies
+ enforce policies 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 extensions.
+
+ Local Proxy
+ A Local Proxy is a proxy that exists within the same
+ administrative domain as the network device (e.g. NAS) that
+ issued the AAA request. Typically a local proxy is used to
+ multiplex AAA messages to and from a large number of
+ network devices, and may implement policy.
+
+ Store and forward proxy
+ Store and forward proxies distinguish themselves from other
+ proxy species by sending a reply to the NAS prior to
+ proxying the request to the server. As a result, store and
+ forward proxies need to implement AAA client and server
+ functionality for the messages that they handle. Store and
+ Forward proxies also typically keep state on conversations
+ in progress in order to assure delivery of proxied Requests
+ and Responses. While store and forward proxies are most
+ frequently deployed for accounting, they also can be used
+ to implement authentication/authorization policy.
+
+ Network-driven transport
+ Transport behavior is said to be "network driven" when the
+ rate at which messages are sent is limited by the
+ congestion window, not by the rate at which the application
+ can generate data. File transfer is an example of an
+ application where transport is network driven.
+
+ Re-direct Rather than forwarding Requests and Responses between
+ clients and servers, Re-directs refer clients to servers
+ and allow them to communicate directly. Since Re-directs
+ do not sit in the forwarding path, they do not alter any
+ AVPs transitting between client and server. Re-directs do
+ not originate messages and are capable of handling any
+ message type. A Re-direct may be configured only to re-
+ direct messages of certain types, while acting as a Relay
+
+
+
+Aboba & Wood Standards Track [Page 4]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ or Proxy for other types. As with Relays, re-directs do
+ not keep state with respect to conversations or NAS
+ resources.
+
+ Relay Relays forward requests and responses based on routing-
+ related AVPs and domain forwarding table entries. Since
+ relays do not enforce policies, they do not examine or
+ alter non-routing AVPs. As a result, relays never
+ originate messages, do not need to understand the semantics
+ of messages or non-routing AVPs, and are capable of
+ handling any extension or message type. Since relays make
+ decisions based on information in routing AVPs and domain
+ forwarding tables they do not keep state on NAS resource
+ usage or conversations in progress.
+
+2. Issues in AAA Transport Usage
+
+ Issues that arise in AAA transport usage include:
+
+ Application-driven versus network-driven
+ Slow failover
+ Use of Nagle Algorithm
+ Multiple connections
+ Duplicate detection
+ Invalidation of transport parameter estimates
+ Inability to use fast re-transmit
+ Congestion avoidance
+ Delayed acknowledgments
+ Premature Failover
+ Head of line blocking
+ Connection load balancing
+
+ We discuss each of these issues in turn.
+
+2.1. Application-driven versus Network-driven
+
+ AAA transport behavior is typically application rather than network
+ driven. This means that the rate at which messages are sent is
+ typically limited by how quickly they are generated by the
+ application, rather than by the size of the congestion window.
+
+ For example, let us assume a 48-port NAS with an average session time
+ of 20 minutes. This device will, on average, send only 144
+ authentication/authorization requests/hour, and an equivalent number
+ of accounting requests. This represents an average inter-packet
+ spacing of 25 seconds, which is much larger than the Round Trip Time
+ (RTT) in most networks.
+
+
+
+
+Aboba & Wood Standards Track [Page 5]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ Even on much larger NAS devices, the inter-packet spacing is often
+ larger than the RTT. For example, consider a 2048-port NAS with an
+ average session time of 10 minutes. It will on average send 3.4
+ authentication/authorization requests/second, and an equivalent
+ number of accounting requests. This translates to an average inter-
+ packet spacing of 293 ms.
+
+ However, even where transport behavior is largely application-driven,
+ periods of network-driven behavior can occur. For example, after a
+ NAS reboot, previously stored accounting records may be sent to the
+ accounting server in rapid succession. Similarly, after recovery
+ from a power failure, users may respond with a large number of
+ simultaneous logins. In both cases, AAA messages may be generated
+ more quickly than the network will allow them to be sent, and a queue
+ will build up.
+
+ Network congestion can occur when transport behavior is network-
+ driven or application-driven. For example, while a single NAS may
+ not send substantial AAA traffic, many NASes may communicate with a
+ single AAA proxy or server. As a result, routers close to a heavily
+ loaded proxy or server may experience congestion, even though traffic
+ from each individual NAS is light. Such "convergent congestion" can
+ result in dropped packets in routers near the AAA server, or even
+ within the AAA server itself.
+
+ Let us consider what happens when 10,000 48-ports NASes, each with an
+ average session time of 20 minutes, are configured with the same AAA
+ agent or server. The unfortunate proxy or server would receive 400
+ authentication/authorization requests/second and an equivalent number
+ of accounting requests. For 1000 octet requests, this would generate
+ 6.4 Mbps of incoming traffic at the AAA agent or server.
+
+ While this transaction load is within the capabilities of the fastest
+ AAA agents and servers, implementations exist that cannot handle such
+ a high load. Thus high queuing delays and/or dropped packets may be
+ experienced at the agent or server, even if routers on the path are
+ not congested. Thus, a well designed AAA protocol needs to be able
+ to handle congestion occurring at the AAA server, as well as
+ congestion experienced within the network.
+
+2.2. Slow Failover
+
+ Where TCP [RFC793] is used as the transport, AAA implementations will
+ experience very slow fail over times if they wait until a TCP
+ connection times out before resending on another connection. This is
+ not an issue for SCTP [RFC2960], which supports endpoint and path
+ failure detection. As described in section 8 of [RFC2960], when the
+ number of retransmissions exceeds the maximum
+
+
+
+Aboba & Wood Standards Track [Page 6]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ ("Association.Max.Retrans"), the peer endpoint is considered
+ unreachable, the association enters the CLOSED state, and the failure
+ is reported to the application. This enables more rapid failure
+ detection.
+
+2.3. Use of Nagle Algorithm
+
+ AAA protocol messages are often smaller than the maximum segment size
+ (MSS). While exceptions occur when certificate-based authentication
+ messages are issued or where a low path MTU is found, typically AAA
+ protocol messages are less than 1000 octets. Therefore, when using
+ TCP [RFC793], the total packet count and associated network overhead
+ can be reduced by combining multiple AAA messages within a single
+ packet.
+
+ Where AAA runs over TCP and transport behavior is network-driven,
+ such as after a reboot when many users login simultaneously, or many
+ stored accounting records need to be sent, the Nagle algorithm will
+ result in "transport layer batching" of AAA messages. While this
+ does not reduce the work required by the application in parsing
+ packets and responding to the messages, it does reduce the number of
+ packets processed by routers along the path. The Nagle algorithm is
+ not used with SCTP.
+
+ Where AAA transport is application-driven, the NAS will typically
+ receive a reply from the home server prior to having another request
+ to send. This implies, for example, that accounting requests will
+ typically be sent individually rather than being batched by the
+ transport layer. As a result, within the application-driven regime,
+ the Nagle algorithm [RFC896] is ineffective.
+
+2.4. Multiple Connections
+
+ Since the RADIUS [RFC2865] Identifier field is a single octet, a
+ maximum of 256 requests can be in progress between two endpoints
+ described by a 5-tuple: (Client IP address, Client port, UDP, Server
+ IP address, Server port). In order to get around this limitation,
+ RADIUS clients have utilized more than one sending port, sometimes
+ even going to the extreme of using a different UDP source port for
+ each NAS port.
+
+ Were this behavior to be extended to AAA protocols operating over
+ reliable transport, the result would be multiplication of the
+ effective slow-start ramp-up by the number of connections. For
+ example, if a AAA client had ten connections open to a AAA agent, and
+ used a per-connection initial window [RFC3390] of 2, then the
+
+
+
+
+
+Aboba & Wood Standards Track [Page 7]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ effective initial window would be 20. This is inappropriate, since
+ it would permit the AAA client to send a large burst of packets into
+ the network.
+
+2.5. Duplicate Detection
+
+ Where a AAA client maintains connections to multiple AAA agents or
+ servers, and where failover/failback or connection load balancing is
+ supported, it is possible for multiple agents or servers to receive
+ duplicate copies of the same transaction. A transaction may be sent
+ on another connection before expiration of the "time wait" interval
+ necessary to guarantee that all packets sent on the original
+ connection have left the network. Therefore it is conceivable that
+ transactions sent on the alternate connection will arrive before
+ those sent on the failed connection. As a result, AAA agents and
+ servers MUST be prepared to handle duplicates, and MUST assume that
+ duplicates can arrive on any connection.
+
+ For example, in billing, it is necessary to be able to weed out
+ duplicate accounting records, based on the accounting session-id,
+ event-timestamp and NAS identification information. Where
+ authentication requests are always idempotent, the resultant
+ duplicate responses from multiple servers will presumably be
+ identical, so that little harm will result.
+
+ However, there are situations where the response to an authentication
+ request will depend on a previously established state, such as when
+ simultaneous usage restrictions are being enforced. In such cases,
+ authentication requests will not be idempotent. For example, while
+ an initial request might elicit an Accept response, a duplicate
+ request might elicit a Reject response from another server, if the
+ user were already presumed to be logged in, and only one simultaneous
+ session were permitted. In these situations, the AAA client might
+ receive both Accept and Reject responses to the same duplicate
+ request, and the outcome will depend on which response arrives first.
+
+2.6. Invalidation of Transport Parameter Estimates
+
+ Congestion control principles [Congest],[RFC2914] require the ability
+ of a transport protocol to respond effectively to congestion, as
+ sensed via increasing delays, packet loss, or explicit congestion
+ notification.
+
+ With network-driven applications, it is possible to respond to
+ congestion on a timescale comparable to the round-trip time (RTT).
+
+ However, with AAA protocols, the time between sends may be longer
+ than the RTT, so that the network conditions can not be assumed to
+
+
+
+Aboba & Wood Standards Track [Page 8]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ persist between sends. For example, the congestion window may grow
+ during a period in which congestion is being experienced because few
+ packets are sent, limiting the opportunity for feedback. Similarly,
+ after congestion is detected, the congestion window may remain small,
+ even though the network conditions that existed at the time of
+ congestion no longer apply by the time when the next packets are
+ sent. In addition, due to the low sampling interval, estimates of
+ RTT and RTO made via the procedure described in [RFC2988] may become
+ invalid.
+
+2.7. Inability to Use Fast Re-transmit
+
+ When congestion window validation [RFC2861] is implemented, the
+ result is that AAA protocols operate much of the time in slow-start
+ with an initial congestion window set to 1 or 2, depending on the
+ implementation [RFC3390]. This implies that AAA protocols gain
+ little benefit from the windowing features of reliable transport.
+
+ Since the congestion window is so small, it is generally not possible
+ to receive enough duplicate ACKs (3) to trigger fast re-transmit. In
+ addition, since AAA traffic is two-way, ACKs including data will not
+ count as part of the duplicate ACKs necessary to trigger fast re-
+ transmit. As a result, dropped packets will require a retransmission
+ timeout (RTO).
+
+2.8. Congestion Avoidance
+
+ The law of conservation of packets [Congest] suggests that a client
+ should not send another packet into the network until it can be
+ reasonably sure that a packet has exited the network on the same
+ path. In the case of a AAA client, the law suggests that it should
+ not retransmit to the same server or choose another server until it
+ can be reasonably sure that a packet has exited the network on the
+ same path. If the client advances the window as responses arrive,
+ then the client will "self clock", adjusting its transmission rate to
+ the available bandwidth.
+
+ While a AAA client using a reliable transport such as TCP [RFC793] or
+ SCTP [RFC2960] will self-clock when communicating directly with a
+ AAA-server, end-to-end self-clocking is not assured when AAA agents
+ are present.
+
+ As described in the Appendix, AAA agents include Relays, Proxies,
+ Re-directs, Store and Forward proxies, and Transport proxies. Of
+ these agents, only Transport proxies and Re-directs provide a direct
+ transport connection between the AAA client and server, allowing
+ end-to-end self-clocking to occur.
+
+
+
+
+Aboba & Wood Standards Track [Page 9]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ With Relays, Proxies or Store and Forward proxies, two separate and
+ de-coupled transport connections are used. One connection operates
+ between the AAA client and agent, and another between the agent and
+ server. Since the two transport connections are de-coupled,
+ transport layer ACKs do not flow end-to-end, and self-clocking does
+ not occur.
+
+ For example, consider what happens when the bottleneck exists between
+ a AAA Relay and a AAA server. Self-clocking will occur between the
+ AAA client and AAA Relay, causing the AAA client to adjust its
+ sending rate to the rate at which transport ACKs flow back from the
+ AAA Relay. However, since this rate is higher than the bottleneck
+ bandwidth, the overall system will not self-clock.
+
+ Since there is no direct transport connection between the AAA client
+ and AAA server, the AAA client does not have the ability to estimate
+ end-to-end transport parameters and adjust its sending rate to the
+ bottleneck bandwidth between the Relay and server. As a result, the
+ incoming rate at the AAA Relay can be higher than the rate at which
+ packets can be sent to the AAA server.
+
+ In this case, the end-to-end performance will be determined by
+ details of the agent implementation. In general, the end-to-end
+ transport performance in the presence of Relays, Proxies or Store and
+ Forward proxies will always be worse in terms of delay and packet
+ loss than if the AAA client and server were communicating directly.
+
+ For example, if the agent operates with a large receive buffer, it is
+ possible that a large queue will develop on the receiving side, since
+ the AAA client is able to send packets to the AAA agent more rapidly
+ than the agent can send them to the AAA server. Eventually, the
+ buffer will overflow, causing wholesale packet loss as well as high
+ delay.
+
+ Methods to induce fine-grained coupling between the two transport
+ connections are difficult to implement. One possible solution is for
+ the AAA agent to operate with a receive buffer that is no larger than
+ its send buffer. If this is done, "back pressure" (closing of the
+ receive window) will cause the agent to reduce the AAA client sending
+ rate when the agent send buffer fills. However, unless multiple
+ connections exist between the AAA client and AAA agent, closing of
+ the receive window will affect all traffic sent by the AAA client,
+ even traffic destined to AAA servers where no bottleneck exists.
+ Since multiple connections between a AAA client and agent result in
+ multiplication of the effective slow-start ramp rate, this is not
+ recommended. As a result, use of "back pressure" cannot enable
+ individual AAA client-server conversations to self-clock, and this
+ technique appears impractical for use in AAA.
+
+
+
+Aboba & Wood Standards Track [Page 10]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+2.9. Delayed Acknowledgments
+
+ As described in Appendix B, ACKs may comprise as much as half of the
+ traffic generated in a AAA exchange. This occurs because AAA
+ conversations are typically application-driven, and therefore there
+ is frequently not enough traffic to enable ACK piggybacking. As a
+ result, AAA protocols running over TCP or SCTP transport may
+ experience a doubling of traffic as compared with implementations
+ utilizing UDP transport.
+
+ It is typically not possible to address this issue via the sockets
+ API. ACK parameters (such as the value of the delayed ACK timer) are
+ typically fixed by TCP and SCTP implementations and are therefore not
+ tunable by the application.
+
+2.10. Premature Failover
+
+ RADIUS failover implementations are typically based on the concept of
+ primary and secondary servers, in which all traffic flows to the
+ primary server unless it is unavailable. However, the failover
+ algorithm was not specified in [RFC2865] or [RFC2866]. As a result,
+ RADIUS failover implementations vary in quality, with some failing
+ over prematurely, violating the law of "conservation of packets".
+
+ Where a Relay, Proxy or Store and Forward proxy is present, the AAA
+ client has no direct connection to a AAA server, and is unable to
+ estimate the end-to-end transport parameters. As a result, a AAA
+ client awaiting an application-layer response from the server has no
+ transport-based mechanism for determining an appropriate failover
+ timer.
+
+ For example, if the path between the AAA agent and server includes a
+ high delay link, or if the AAA server is very heavily loaded, it is
+ possible that the NAS will failover to another agent while packets
+ are still in flight. This violates the principle of "conservation of
+ packets", since the AAA client will inject additional packets into
+ the network before having evidence that a previously sent packet has
+ left the network. Such behavior can result in a worse situation on
+ an already congested link, resulting in congestive collapse
+ [Congest].
+
+2.11. Head of Line Blocking
+
+ Head of line blocking occurs during periods of packet loss where the
+ time between sends is shorter than the re-transmission timeout value
+ (RTO). In such situations, packets back up in the send queue until
+
+
+
+
+
+Aboba & Wood Standards Track [Page 11]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ the lost packet can be successfully re-transmitted. This can be an
+ issue for SCTP when using ordered delivery over a single stream, and
+ for TCP.
+
+ Head of line blocking is typically an issue only on larger NASes.
+ For example, a 48-port NAS with an average inter-packet spacing of 25
+ seconds is unlikely to have an RTO greater than this, unless severe
+ packet loss has been experienced. However, a 2048-port NAS with an
+ average inter-packet spacing of 293 ms may experience head-of-line
+ blocking since the inter-packet spacing is less than the minimum RTO
+ value of 1 second [RFC2988].
+
+2.12. Connection Load Balancing
+
+ In order to lessen queuing delays and address head of line blocking,
+ a AAA implementation may wish to load balance between connections to
+ multiple destinations. While it is possible to employ dynamic load
+ balancing techniques, this level of sophistication may not be
+ required. In many situations, adequate reliability and load
+ balancing can be achieved via static load balancing, where traffic is
+ distributed between destinations based on static "weights".
+
+3. AAA Transport Profile
+
+ In order to address AAA transport issues, it is recommended that AAA
+ protocols make use of standards track as well as experimental
+ techniques. More details are provided in the sections that follow.
+
+3.1. Transport Mappings
+
+ AAA Servers MUST support TCP and SCTP. AAA clients SHOULD support
+ SCTP, but MUST support TCP if SCTP is not available. As support for
+ SCTP improves, it is possible that SCTP support will be required on
+ clients at some point in the future. AAA agents inherit all the
+ obligations of Servers with respect to transport support.
+
+3.2. Use of Nagle Algorithm
+
+ While AAA protocols typically operate in the application-driven
+ regime, there are circumstances in which they are network driven.
+ For example, where an NAS reboots, or where connectivity is restored
+ between an NAS and a AAA agent, it is possible that multiple packets
+ will be available for sending.
+
+ As a result, there are circumstances where the transport-layer
+ batching provided by the Nagle Algorithm (12) is useful, and as a
+ result, AAA implementations running over TCP MUST enable the Nagle
+ algorithm, [RFC896]. The Nagle algorithm is not used with SCTP.
+
+
+
+Aboba & Wood Standards Track [Page 12]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+3.3. Multiple Connections
+
+ AAA protocols SHOULD use only a single persistent connection between
+ a AAA client and a AAA agent or server. They SHOULD provide for
+ pipelining of requests, so that more than one request can be in
+ progress at a time. In order to minimize use of inactive connections
+ in roaming situations, a AAA client or agent MAY bring down a
+ connection to a AAA agent or server if the connection has been
+ unutilized (discounting the watchdog) for a certain period of time,
+ which MUST NOT be less than BRINGDOWN_INTERVAL (5 minutes).
+
+ While a AAA client/agent SHOULD only use a single persistent
+ connection to a given AAA agent or server, it MAY have connections to
+ multiple AAA agents or servers. A AAA client/agent connected to
+ multiple agents/servers can treat them as primary/secondary or
+ balance load between them.
+
+3.4. Application Layer Watchdog
+
+ In order to enable AAA implementations to more quickly detect
+ transport and application-layer failures, AAA protocols MUST support
+ an application layer watchdog message.
+
+ The application layer watchdog message enables failover from a peer
+ that has failed, either because it is unreachable or because its
+ applications functions have failed. This is distinct from the
+ purpose of the SCTP heartbeat, which is to enable failover between
+ interfaces. The SCTP heartbeat may enable a failover to another path
+ to reach the same server, but does not address the situation where
+ the server system or the application service has failed. Therefore
+ both mechanisms MAY be used together.
+
+ The watchdog is used in order to enable a AAA client or agent to
+ determine when to resend on another connection. It operates on all
+ open connections and is used to suspend and eventually close
+ connections that are experiencing difficulties. The watchdog is also
+ used to re-open and validate connections that have returned to
+ health. The watchdog may be utilized either within primary/secondary
+ or load balancing configurations. However, it is not intended as a
+ cluster heartbeat mechanism.
+
+ The application layer watchdog is designed to detect failures of the
+ immediate peer, and not to be affected by failures of downstream
+ proxies or servers. This prevents instability in downstream AAA
+ components from propagating upstream. While the receipt of any AAA
+ Response from a peer is taken as evidence that the peer is up, lack
+ of a Response is insufficient to conclude that the peer is down.
+ Since the lack of Response may be the result of problems with a
+
+
+
+Aboba & Wood Standards Track [Page 13]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ downstream proxy or server, only after failure to respond to the
+ watchdog message can it be determined that the peer is down.
+
+ Since the watchdog algorithm takes any AAA Response into account in
+ determining peer liveness, decreases in the watchdog timer interval
+ do not significantly increase the level of watchdog traffic on
+ heavily loaded networks. This is because watchdog messages do not
+ need to be sent where other AAA Response traffic serves as a constant
+ reminder of peer liveness. Watchdog traffic only increases when AAA
+ traffic is light, and therefore a AAA Response "signal" is not
+ present. Nevertheless, decreasing the timer interval TWINIT does
+ increase the probability of false failover significantly, and so this
+ decision should be made with care.
+
+3.4.1. Algorithm Overview
+
+ The watchdog behavior is controlled by an algorithm defined in this
+ section. This algorithm is appropriate for use either within
+ primary/secondary or load balancing configurations. Implementations
+ SHOULD implement this algorithm, which operates as follows:
+
+ [1] Watchdog behavior is controlled by a single timer (Tw). The
+ initial value of Tw, prior to jittering is Twinit. The default
+ value of Twinit is 30 seconds. This value was selected because
+ it minimizes the probability that failover will be initiated due
+ to a routing flap, as noted in [Paxson].
+
+ While Twinit MAY be set as low as 6 seconds (not including
+ jitter), it MUST NOT be set lower than this. Note that setting
+ such a low value for Twinit is likely to result in an increased
+ probability of duplicates, as well as an increase in spurious
+ failover and failback attempts.
+
+ In order to avoid synchronization behaviors that can occur with
+ fixed timers among distributed systems, each time the watchdog
+ interval is calculated with a jitter by using the Twinit value
+ and randomly adding a value drawn between -2 and 2 seconds.
+ Alternative calculations to create jitter MAY be used. These
+ MUST be pseudo-random, generated by a PRNG seeded as per
+ [RFC1750].
+
+ [2] When any AAA message is received, Tw is reset. This need not be
+ a response to a watchdog request. Receiving a watchdog response
+ from a peer constitutes activity, and Tw should be reset. If the
+ watchdog timer expires and no watchdog response is pending, then
+ a watchdog message is sent. On sending a watchdog request, Tw is
+ reset.
+
+
+
+
+Aboba & Wood Standards Track [Page 14]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ Watchdog packets are not retransmitted by the AAA protocol, since
+ AAA protocols run over reliable transports that will handle all
+ retransmissions internally. As a result, a watchdog request is
+ only sent when there is no watchdog response pending.
+
+ [3] If the watchdog timer expires and a watchdog response is pending,
+ then failover is initiated. In order for a AAA client or agent
+ to perform failover procedures, it is necessary to maintain a
+ pending message queue for a given peer. When an answer message
+ is received, the corresponding request is removed from the queue.
+ The Hop-by-Hop Identifier field MAY be used to match the answer
+ with the queued request.
+
+ When failover is initiated, all messages in the queue are sent to
+ an alternate agent, if available. Multiple identical requests or
+ answers may be received as a result of a failover. The
+ combination of an end-to-end identifier and the origin host MUST
+ be used to identify duplicate messages.
+
+ Note that where traffic is heavy, the application layer watchdog
+ can take as long as 2Tw to determine that a peer has gone down.
+ For peers receiving a high volume of AAA Requests, AAA Responses
+ will continually reset the timer, so that after a failure it will
+ take Tw for the lack of traffic to be noticed, and for the
+ watchdog message to be sent. Another Tw will elapse before
+ failover is initiated.
+
+ On a lightly loaded network without much AAA Response traffic,
+ the watchdog timer will typically expire without being reset, so
+ that a watchdog response will be outstanding and failover will be
+ initiated after only a single timer interval has expired.
+
+ [4] The client MUST NOT close the primary connection until the
+ primary's watchdog timer has expired at least twice without a
+ response (note that the watchdog is not sent a second time,
+ however). Once this has occurred, the client SHOULD cause a
+ transport reset or close to be done on the connection.
+
+ Once the primary connection has failed, subsequent requests are
+ sent to the alternate server until the watchdog timer on the
+ primary connection is reset.
+
+ Suspension of the primary connection prevents flapping between
+ primary and alternate connections, and ensures that failover
+ behavior remains consistent. The application may not receive a
+ response to the watchdog request message due to a connectivity
+ problem, in which case a transport layer ACK will not have been
+ received, or the lack of response may be due to an application
+
+
+
+Aboba & Wood Standards Track [Page 15]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ problem. Without transport layer visibility, the application is
+ unable to tell the difference, and must behave conservatively.
+
+ In situations where no transport layer ACK is received on the
+ primary connection after multiple re-transmissions, the RTO will
+ be exponentially backed off as described in [RFC2988]. Due to
+ Karn's algorithm as implemented in SCTP and TCP, the RTO
+ estimator will not be reset until another ACK is received in
+ response to a non-re-transmitted request. Thus, in cases where
+ the problem occurs at the transport layer, after the client fails
+ over to the alternate server, the RTO of the primary will remain
+ at a high value unless an ACK is received on the primary
+ connection.
+
+ In the case where the problem occurs at the transport layer,
+ subsequent requests sent on the primary connection will not
+ receive the same service as was originally provided. For
+ example, instead of failover occurring after 3 retransmissions,
+ failover might occur without even a single retransmission if RTO
+ has been sufficiently backed off. Of course, if the lack of a
+ watchdog response was due to an application layer problem, then
+ RTO will not have been backed off. However, without transport
+ layer visibility, there is no way for the application to know
+ this.
+
+ Suspending use of the primary connection until a response to a
+ watchdog message is received guarantees that the RTO timer will
+ have been reset before the primary connection is reused. If no
+ response is received after the second watchdog timer expiration,
+ then the primary connection is closed and the suspension becomes
+ permanent.
+
+ [5] While the connection is in the closed state, the AAA client MUST
+ NOT attempt to send further watchdog messages on the connection.
+ However, after the connection is closed, the AAA client continues
+ to periodically attempt to reopen the connection.
+
+ The AAA client SHOULD wait for the transport layer to report
+ connection failure before attempting again, but MAY choose to
+ bound this wait time by the watchdog interval, Tw. If the
+ connection is successfully opened, then the watchdog message is
+ sent. Once three watchdog messages have been sent and responded
+ to, the connection is returned to service, and transactions are
+ once again sent over it. Connection validation via receipt of
+ multiple watchdogs is not required when a connection is initially
+ brought up -- in this case, the connection can immediately be put
+ into service.
+
+
+
+
+Aboba & Wood Standards Track [Page 16]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ [6] When using SCTP as a transport, it is not necessary to disable
+ SCTP's transport-layer heartbeats. However, if AAA
+ implementations have access to SCTP's heartbeat parameters, they
+ MAY chose to ensure that SCTP's heartbeat interval is longer than
+ the AAA watchdog interval, Tw. This will ensure that alternate
+ paths are still probed by SCTP, while the primary path has a
+ minimum of heartbeat redundancy.
+
+3.4.2. Primary/Secondary Failover Support
+
+ The watchdog timer MAY be integrated with primary/secondary style
+ failover so as to provide improved reliability and basic load
+ balancing. In order to balance load among multiple AAA servers, each
+ AAA server is designated the primary for a portion of the clients,
+ and designated as secondaries of varying priority for the remainder.
+ In this way, load can be balanced among the AAA servers.
+
+ Within primary/secondary configurations, the watchdog timer operates
+ as follows:
+
+ [1] Assume that each client or agent is initially configured with a
+ single primary agent or server, and one or more secondary
+ connections.
+
+ [2] The watchdog mechanism is used to suspend and eventually close
+ primary connections that are experiencing difficulties. It is
+ also used to re-open and validate connections that have returned
+ to health.
+
+ [3] Once a secondary is promoted to primary status, either on a
+ temporary or permanent basis, the next server on the list of
+ secondaries is promoted to fill the open secondary slot.
+
+ [4] The client or agent periodically attempts to re-open closed
+ connections, so that it is possible that a previously closed
+ connection can be returned to service and become eligible for use
+ again. Implementations will typically retain a limit on the
+ number of connections open at a time, so that once a previously
+ closed connection is brought online again, the lowest priority
+ secondary connection will be closed. In order to prevent
+ periodic closing and re-opening of secondary connections, it is
+ recommended that functioning connections remain open for a
+ minimum of 5 minutes.
+
+ [5] In order to enable diagnosis of failover behavior, it is
+ recommended that a table of failover events be kept within the
+ MIB. These failover events SHOULD include appropriate
+ transaction identifiers so that client and server data can be
+
+
+
+Aboba & Wood Standards Track [Page 17]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ compared, providing insight into the cause of the problem
+ (transport or application layer).
+
+3.4.3. Connection Load Balancing
+
+ Primary/secondary failover is capable of providing improved
+ resilience and basic load balancing. However, it does not address
+ TCP head of line blocking, since only a single connection is in use
+ at a time.
+
+ A AAA client or agent maintaining connections to multiple agents or
+ servers MAY load balance between them. Establishing connections to
+ multiple agents or servers reduces, but does not eliminate, head of
+ line blocking issues experienced on TCP connections. This issue does
+ not exist with SCTP connections utilizing multiple streams.
+
+ In connection load balancing configurations, the application watchdog
+ operates as follows:
+
+ [1] Assume that each client or agent is initially configured with
+ connections to multiple AAA agents or servers, with one
+ connection between a given client/agent and an agent/server.
+
+ [2] In static load balancing, transactions are apportioned among the
+ connections based on the total number of connections and a
+ "weight" assigned to each connection. Pearson's hash [RFC3074]
+ applied to the NAI [RFC2486] can be used to determine which
+ connection will handle a given transaction. Hashing on the NAI
+ provides highly granular load balancing, while ensuring that all
+ traffic for a given conversation will be sent to the same agent
+ or server. In dynamic load balancing, the value of the "weight"
+ can vary based on conditions such as AAA server load. Such
+ techniques, while sophisticated, are beyond the scope of this
+ document.
+
+ [3] Transactions are distributed to connections based on the total
+ number of available connections and their weights. A change in
+ the number of available connections forces recomputation of the
+ hash table. In order not to cause conversations in progress to
+ be switched to new destinations, on recomputation, a transitional
+ period is required in which both old and new hash tables are
+ needed in order to permit aging out of conversations in progress.
+ Note that this requires a way to easily determine whether a
+ Request represents a new conversation or the continuation of an
+ existing conversation. As a result, removing and adding of
+ connections is an expensive operation, and it is recommended that
+ the hash table only be recomputed once a connection is closed or
+ returned to service.
+
+
+
+Aboba & Wood Standards Track [Page 18]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ Suspended connections, although they are not used, do not force
+ hash table reconfiguration until they are closed. Similarly,
+ re-opened connections not accumulating sufficient watchdog
+ responses do not force a reconfiguration until they are returned
+ to service.
+
+ While a connection is suspended, transactions that were to have
+ been assigned to it are instead assigned to the next available
+ server. While this results in a momentary imbalance, it is felt
+ that this is a relatively small price to pay in order to reduce
+ hash table thrashing.
+
+ [4] In order to enable diagnosis of load balancing behavior, it is
+ recommended that in addition to a table of failover events, a
+ table of statistics be kept on each client, indexed by a AAA
+ server. That way, the effectiveness of the load balancing
+ algorithm can be evaluated.
+
+3.5. Duplicate Detection
+
+ Multiple facilities are required to enable duplicate detection.
+ These include session identifiers as well as hop-by-hop and end-to-
+ end message identifiers. Hop-by-hop identifiers whose value may
+ change at each hop are not sufficient, since a AAA server may receive
+ the same message from multiple agents. For example, a AAA client can
+ send a request to Agent1, then failover and resend the request to
+ Agent2; both agents forward the request to the home AAA server, with
+ different hop-by-hop identifiers. A Session Identifier is
+ insufficient as it does not distinguish different messages for the
+ the same session.
+
+ Proper treatment of the end-to-end message identifier ensures that
+ AAA operations are idempotent. For example, without an end-to-end
+ identifier, a AAA server keeping track of simultaneous logins might
+ send an Accept in response to an initial Request, and then a Reject
+ in response to a duplicate Request (where the user was allowed only
+ one simultaneous login). Depending on which Response arrived first,
+ the user might be allowed access or not.
+
+ However, if the server were to store the end-to-end message
+ identifier along with the simultaneous login information, then the
+ duplicate Request (which utilizes the same end-to-end message
+ identifier) could be identified and the correct response could be
+ returned.
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 19]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+3.6. Invalidation of Transport Parameter Estimates
+
+ In order to address invalidation of transport parameter estimates,
+ AAA protocol implementations MAY utilize Congestion Window Validation
+ [RFC2861] and RTO validation when using TCP. This specification also
+ recommends a procedure for RTO validation.
+
+ [RFC2581] and [RFC2861] both recommend that a connection go into
+ slow-start after a period where no traffic has been sent within the
+ RTO interval. [RFC2861] recommends only increasing the congestion
+ window if it was full when the ACK arrived. The congestion window is
+ reduced by half once every RTO interval if no traffic is received.
+
+ When Congestion Window Validation is used, the congestion window will
+ not build during application-driven periods, and instead will be
+ decayed. As a result, AAA applications operating within the
+ application-driven regime will typically run with a congestion window
+ equal to the initial window much of the time, operating in "perpetual
+ slowstart".
+
+ During periods in which AAA behavior is application-driven this will
+ have no effect. Since the time between packets will be larger than
+ RTT, AAA will operate with an effective congestion window equal to
+ the initial window. However, during network-driven periods, the
+ effect will be to space out sending of AAA packets. Thus instead of
+ being able to send a large burst of packets into the network, a
+ client will need to wait several RTTs as the congestion window builds
+ during slow-start.
+
+ For example, a client operating over TCP with an initial window of 2,
+ with 35 AAA requests to send would take approximately 6 RTTs to send
+ them, as the congestion window builds during slow start: 2, 3, 3, 6,
+ 9, 12. After the backlog is cleared, the implementation will once
+ again be application-driven and the congestion window size will
+ decay. If the client were using SCTP, the number of RTTs needed to
+ transmit all requests would usually be less, and would depend on the
+ size of the requests, since SCTP tracks the progress for the opening
+ of the congestion window by bytes, not segments.
+
+ Note that [RFC2861] and [RFC2988] do not address the issue of RTO
+ validation. This is also a problem, particularly when the Congestion
+ Manager [RFC3124] is implemented. During periods of high packet
+ loss, the RTO may be repeatedly increased via exponential back-off,
+ and may attain a high value. Due to lack of timely feedback on RTT
+ and RTO during application-driven periods, the high RTO estimate may
+ persist long after the conditions that generated it have dissipated.
+
+
+
+
+
+Aboba & Wood Standards Track [Page 20]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ RTO validation MAY be used to address this issue for TCP, via the
+ following procedure:
+
+ After the congestion window is decayed according to [RFC2861],
+ reset the estimated RTO to 3 seconds. After the next packet comes
+ in, re-calculate RTTavg, RTTdev, and RTO according to the method
+ described in [RFC2581].
+
+ To address this issue for SCTP, AAA implementations SHOULD use SCTP
+ heartbeats. [RFC2960] states that heartbeats should be enabled by
+ default, with an interval of 30 seconds. If this interval proves to
+ be too long to resolve this issue, AAA implementations MAY reduce the
+ heartbeat interval.
+
+3.7. Inability to Use Fast Re-Transmit
+
+ When Congestion Window Validation [RFC2861] is used, AAA
+ implementations will operate with a congestion window equal to the
+ initial window much of the time. As a result, the window size will
+ often not be large enough to enable use of fast re-transmit for TCP.
+ In addition, since AAA traffic is two-way, ACKs carrying data will
+ not count towards triggering fast re-transmit. SCTP is less likely
+ to encounter this issue, so the measures described below apply to
+ TCP.
+
+ To address this issue, AAA implementations SHOULD support selective
+ acknowledgement as described in [RFC2018] and [RFC2883]. AAA
+ implementations SHOULD also implement Limited Transmit for TCP, as
+ described in [RFC3042]. Rather than reducing the number of duplicate
+ ACKs required for triggering fast recovery, which would increase the
+ number of inappropriate re-transmissions, Limited Transmit enables
+ the window size be increased, thus enabling the sending of additional
+ packets which in turn may trigger fast re-transmit without a change
+ to the algorithm.
+
+ However, if congestion window validation [RFC2861] is implemented,
+ this proposal will only have an effect in situations where the time
+ between packets is less than the estimated retransmission timeout
+ (RTO). If the time between packets is greater than RTO, additional
+ packets will typically not be available for sending so as to take
+ advantage of the increased window size. As a result, AAA protocols
+ will typically operate with the lowest possible congestion window
+ size, resulting in a re-transmission timeout for every lost packet.
+
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 21]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+3.8. Head of Line Blocking
+
+ TCP inherently does not provide a solution to the head-of-line
+ blocking problem, although its effects can be lessened by
+ implementation of Limited Transmit [RFC3042], and connection load
+ balancing.
+
+3.8.1. Using SCTP Streams to Prevent Head of Line Blocking
+
+ Each AAA node SHOULD distribute its messages evenly across the range
+ of SCTP streams that it and its peer have agreed upon. (A lost
+ message in one stream will not cause any other streams to block.) A
+ trivial and effective implementation of this simply increments a
+ counter for the stream ID to send on. When the counter reaches the
+ maximum number of streams for the association, it resets to 0.
+
+ AAA peers MUST be able to accept messages on any stream. Note that
+ streams are used *solely* to prevent head-of-the-line blocking. All
+ identifying information is carried within the Diameter payload.
+ Messages distributed across multiple streams may not be received in
+ the order they are sent.
+
+ SCTP peers can allocate up to 65535 streams for an association. The
+ cost for idle streams may or may not be zero, depending on the
+ implementation, and the cost for non-idle streams is always greater
+ than 0. So administrators may wish to limit the number of possible
+ streams on their diameter nodes according to the resources (i.e.
+ memory, CPU power, etc.) of a particular node.
+
+ On a Diameter client, the number of streams may be determined by the
+ maximum number of peak users on the NAS. If a stream is available
+ per user, then this should be sufficient to prevent head-of-line
+ blocking. On a Diameter proxy, the number of streams may be
+ determined by the maximum number of peak sessions in progress from
+ that proxy to each downstream AAA server.
+
+ Stream IDs do not need to be preserved by relay agents. This
+ simplifies implementation, as agents can easily handle forwarding
+ between two associations with different numbers of streams. For
+ example, consider the following case, where a relay server DRL
+ forwards messages between a NAS and a home server, HMS. The NAS and
+ DRL have agreed upon 1000 streams for their association, and DRL and
+ HMS have agreed upon 2000 streams for their association. The
+ following figure shows the message flow from NAS to HMS via DRL, and
+ the stream ID assignments for each message:
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 22]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ +------+ +------+ +------+
+ | | | | | |
+ | NAS | ---------> | DRL | ---------> | HMS |
+ | | | | | |
+ +------+ 1000 streams +------+ 2000 streams +------+
+
+ msg 1: str id 0 msg 1: str id 0
+ msg 2: str id 1 msg 2: str id 1
+ ...
+ msg 1000: str id 999 msg 1000: str id 999
+ msg 1001: str id 0 msg 1001: str id 1000
+
+ DRL can forward messages 1 through 1000 to HMS using the same stream
+ ID that NAS used to send to DRL. However, since the NAS / DRL
+ association has only 1000 streams, NAS wraps around to stream ID 0
+ when sending message 1001. The DRL / HMS association, on the other
+ hand, has 2000 streams, so DRL can reassign message 1001 to stream ID
+ 1000 when forwarding it on to HMS.
+
+ This distribution scheme acts like a hash table. It is possible, yet
+ unlikely, that two messages will end up in the same stream, and even
+ less likely that there will be message loss resulting in blocking
+ when this happens. If it does turn out to be a problem, local
+ administrators can increase the number of streams on their nodes to
+ improve performance.
+
+3.9. Congestion Avoidance
+
+ In order to improve upon default timer estimates, AAA implementations
+ MAY implement the Congestion Manager (CM) [RFC3124]. CM is an end-
+ system module that:
+
+ (i) Enables an ensemble of multiple concurrent streams from a
+ sender destined to the same receiver and sharing the same
+ congestion properties to perform proper congestion avoidance
+ and control, and
+
+ (ii) Allows applications to easily adapt to network congestion.
+
+ The CM helps integrate congestion management across all applications
+ and transport protocols. The CM maintains congestion parameters
+ (available aggregate and per-stream bandwidth, per-receiver round-
+ trip times, etc.) and exports an API that enables applications to
+ learn about network characteristics, pass information to the CM,
+ share congestion information with each other, and schedule data
+ transmissions.
+
+
+
+
+
+Aboba & Wood Standards Track [Page 23]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ The CM enables the AAA application to access transport parameters
+ (RTTavg, RTTdev) via callbacks. RTO estimates are currently not
+ available via the callback interface, though they probably should be.
+ Where available, transport parameters SHOULD be used to improve upon
+ default timer values.
+
+3.10. Premature Failover
+
+ Premature failover is prevented by the watchdog functionality
+ described above. If the next hop does not return a reply, the AAA
+ client will send a watchdog message to it to verify liveness. If a
+ watchdog reply is received, then the AAA client will know that the
+ next hop server is functioning at the application layer. As a
+ result, it is only necessary to provide terminal error messages, such
+ as the following:
+
+ "Busy": agent/Server too busy to handle additional requests, NAS
+ should failover all requests to another agent/server.
+
+ "Can't Locate": agent can't locate the AAA server for the
+ indicated realm; NAS should failover that request to another
+ proxy.
+
+ "Can't Forward": agent has tried both primary and secondary AAA
+ servers with no response; NAS should failover the request to
+ another agent.
+
+ Note that these messages differ in their scope. The "Busy" message
+ tells the NAS that the agent/server is too busy for ANY request. The
+ "Can't Locate" and "Can't Forward" messages indicate that the
+ ultimate destination cannot be reached or isn't responding, implying
+ per-request failover.
+
+4. Security Considerations
+
+ Since AAA clients, agents and servers serve as network access
+ gatekeepers, they are tempting targets for attackers. General
+ security considerations concerning TCP congestion control are
+ discussed in [RFC2581]. However, there are some additional
+ considerations that apply to this specification.
+
+ By enabling failover between AAA agents, this specification improves
+ the resilience of AAA applications. However, it may also open
+ avenues for denial of service attacks.
+
+ The failover algorithm is driven by lack of response to AAA requests
+ and watchdog packets. On a lightly loaded network where AAA
+ responses would not be received prior to expiration of the watchdog
+
+
+
+Aboba & Wood Standards Track [Page 24]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ timer, an attacker can swamp the network, causing watchdog packets to
+ be dropped. This will cause the AAA client to switch to another AAA
+ agent, where the attack can be repeated. By causing the AAA client
+ to cycle between AAA agents, service can be denied to users desiring
+ network access.
+
+ Where TLS [RFC2246] is being used to provide AAA security, there will
+ be a vulnerability to spoofed reset packets, as well as other
+ transport layer denial of service attacks (e.g. SYN flooding). Since
+ SCTP offers improved denial of service resilience compared with TCP,
+ where AAA applications run over SCTP, this can be mitigated to some
+ extent.
+
+ Where IPsec [RFC2401] is used to provide security, it is important
+ that IPsec policy require IPsec on incoming packets. In order to
+ enable a AAA client to determine what security mechanisms are in use
+ on an agent or server without prior knowledge, it may be tempting to
+ initiate a connection in the clear, and then to have the AAA agent
+ respond with IKE [RFC2409]. While this approach minimizes required
+ client configuration, it increases the vulnerability to denial of
+ service attack, since a connection request can now not only tie up
+ transport resources, but also resources within the IKE
+ implementation.
+
+5. IANA Considerations
+
+ This document does not create any new number spaces for IANA
+ administration.
+
+References
+
+6.1. Normative References
+
+ [RFC793] Postel, J., "Transmission Control Protocol", STD 7, RFC
+ 793, September 1981.
+
+ [RFC896] Nagle, J., "Congestion Control in IP/TCP internetworks",
+ RFC 896, January 1984.
+
+ [RFC1750] Eastlake, D., Crocker, S. and J. Schiller, "Randomness
+ Recommendations for Security", RFC 1750, December 1994.
+
+ [RFC2018] Mathis, M., Mahdavi, J., Floyd, S. and A. Romanow, "TCP
+ Selective Acknowledgment Options", RFC 2018, October 1996.
+
+ [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+
+
+
+Aboba & Wood Standards Track [Page 25]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ [RFC2486] Aboba, B. and M. Beadles, "The Network Access Identifier",
+ RFC 2486, January 1999.
+
+ [RFC2581] Allman, M., Paxson, V. and W. Stevens, "TCP Congestion
+ Control", RFC 2581, April 1999.
+
+ [RFC2883] Floyd, S., Mahdavi, J., Mathis, M., Podolsky, M. and A.
+ Romanow, "An Extension to the Selective Acknowledgment
+ (SACK) Option for TCP", RFC 2883, July 2000.
+
+ [RFC2960] Stewart, R., Xie, Q., Morneault, K., Sharp, C.,
+ Schwarzbauer, H., Taylor, T., Rytina, I., Kalla, M., Zhang,
+ L. and V. Paxson, "Stream Control Transmission Protocol",
+ RFC 2960, October 2000.
+
+ [RFC2988] Paxson, V. and M. Allman, "Computing TCP's Retransmission
+ Timer", RFC 2988, November 2000.
+
+ [RFC3042] Allman, M., Balakrishnan H. and S. Floyd, "Enhancing TCP's
+ Loss Recovery Using Limited Transmit", RFC 3042, January
+ 2001.
+
+ [RFC3074] Volz, B., Gonczi, S., Lemon, T. and R. Stevens, "DHC Load
+ Balancing Algorithm", RFC 3074, February 2001.
+
+ [RFC3124] Balakrishnan, H. and S. Seshan, "The Congestion Manager",
+ RFC 3124, June 2001.
+
+6.2. Informative References
+
+ [RFC2246] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0",
+ RFC 2246, January 1999.
+
+ [RFC2401] Atkinson, R. and S. Kent, "Security Architecture for the
+ Internet Protocol", RFC 2401, November 1998.
+
+ [RFC2409] Harkins, D. and D. Carrel, "The Internet Key Exchange
+ (IKE)", RFC 2409, November 1998.
+
+ [RFC2607] Aboba, B. and J. Vollbrecht, "Proxy Chaining and Policy
+ Implementation in Roaming", RFC 2607, June 1999.
+
+ [RFC2861] Handley, M., Padhye, J. and S. Floyd, "TCP Congestion
+ Window Validation", RFC 2861, June 2000.
+
+ [RFC2865] Rigney, C., Willens, S., Rubens, A. and W. Simpson, "Remote
+ Authentication Dial In User Service (RADIUS)", RFC 2865,
+ June 2000.
+
+
+
+Aboba & Wood Standards Track [Page 26]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ [RFC2866] Rigney, C., "RADIUS Accounting", RFC 2866, June 2000.
+
+ [RFC2914] Floyd, S., "Congestion Control Principles", BCP 41, RFC
+ 2914, September 2000.
+
+ [RFC2975] Aboba, B., Arkko, J. and D. Harrington, "Introduction to
+ Accounting Management", RFC 2975, June 2000.
+
+ [RFC3390] Allman, M., Floyd, S. and C. Partridge, "Increasing TCP's
+ Initial Window", RFC 3390, October 2002.
+
+ [Congest] Jacobson, V., "Congestion Avoidance and Control", Computer
+ Communication Review, vol. 18, no. 4, pp. 314-329, Aug.
+ 1988. ftp://ftp.ee.lbl.gov/papers/congavoid.ps.Z
+
+ [Paxson] Paxson, V., "Measurement and Analysis of End-to-End
+ Internet Dynamics", Ph.D. Thesis, Computer Science
+ Division, University of California, Berkeley, April 1997.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 27]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+Appendix A - Detailed Watchdog Algorithm
+
+ In this Appendix, the memory control structure that contains all
+ information regarding a specific peer is referred to as a Peer
+ Control Block, or PCB. The PCB contains the following fields:
+
+ Status:
+ OKAY: The connection is up
+ SUSPECT: Failover has been initiated on the connection.
+ DOWN: Connection has been closed.
+ REOPEN: Attempting to reopen a closed connection
+ INITIAL: The initial state of the pcb when it is first created.
+ The pcb has never been opened.
+
+ Variables:
+ Pending: Set to TRUE if there is an outstanding unanswered
+ watchdog request
+ Tw: Watchdog timer value
+ NumDWA: Number of DWAs received during REOPEN
+
+ Tw is the watchdog timer, measured in seconds. Every second, Tw is
+ decremented. When it reaches 0, the OnTimerElapsed event (see below)
+ is invoked. Pseudo-code for the algorithm is included on the
+ following pages.
+
+ SetWatchdog()
+ {
+ /*
+ SetWatchdog() is called whenever it is necessary
+ to reset the watchdog timer Tw. The value of the
+ watchdog timer is calculated based on the default
+ initial value TWINIT and a jitter ranging from
+ -2 to 2 seconds. The default for TWINIT is 30 seconds,
+ and MUST NOT be set lower than 6 seconds.
+ */
+ Tw=TWINIT -2.0 + 4.0 * random() ;
+ SetTimer(Tw) ;
+ return ;
+ }
+
+ /*
+ OnReceive() is called whenever a message
+ is received from the peer. This message MAY
+ be a request or an answer, and can include
+ DWR and DWA messages. Pending is assumed to
+ be a global variable.
+ */
+ OnReceive(pcb, msgType)
+
+
+
+Aboba & Wood Standards Track [Page 28]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ {
+ if (msgType == DWA) {
+ Pending = FALSE;
+ }
+ switch (pcb->Status){
+ case OKAY:
+ SetWatchdog();
+ break;
+ case SUSPECT:
+ pcb->Status = OKAY;
+ Failback(pcb);
+ SetWatchdog();
+ break;
+ case REOPEN:
+ if (msgType == DWA) {
+ NumDWA++;
+ if (NumDWA == 3) {
+ pcb->status = OKAY;
+ Failback();
+ }
+ } else {
+ Throwaway(received packet);
+ }
+ break;
+ case INITIAL:
+ case DOWN:
+ Throwaway(received packet);
+ break;
+ default:
+ Error("Shouldn't be here!");
+ break;
+ }
+ }
+
+ /*
+ OnTimerElapsed() is called whenever Tw reaches zero (0).
+ */
+ OnTimerElapsed(pcb)
+ {
+ switch (pcb->status){
+ case OKAY:
+ if (!Pending) {
+ SendWatchdog(pcb);
+ SetWatchdog();
+ Pending = TRUE;
+ break;
+ }
+ pcb->status = SUSPECT;
+
+
+
+Aboba & Wood Standards Track [Page 29]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ FailOver(pcb);
+ SetWatchdog();
+ break ;
+ case SUSPECT:
+ pcb->status = DOWN;
+ CloseConnection(pcb);
+ SetWatchdog();
+ break;
+ case INITIAL:
+ case DOWN:
+ AttemptOpen(pcb);
+ SetWatchdog();
+ break;
+ case REOPEN:
+ if (!Pending) {
+ SendWatchdog(pbc);
+ SetWatchdog();
+ Pending = TRUE;
+ break;
+ }
+ if (NumDWA < 0) {
+ pcb->status = DOWN;
+ CloseConnection(pcb);
+ } else {
+ NumDWA = -1;
+ }
+ SetWatchdog();
+ break;
+ default:
+ error("Shouldn't be here!);
+ break;
+ }
+ }
+
+ /*
+ OnConnectionUp() is called whenever a connection comes up
+ */
+ OnConnectionUp(pcb)
+ {
+ switch (pcb->status){
+ case INITIAL:
+ pcb->status = OKAY;
+ SetWatchdog();
+ break;
+ case DOWN:
+ pcb->status = REOPEN;
+ NumDWA = 0;
+ SendWatchdog(pcb);
+
+
+
+Aboba & Wood Standards Track [Page 30]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ SetWatchdog();
+ Pending = TRUE;
+ break;
+ default:
+ error("Shouldn't be here!);
+ break;
+ }
+ }
+
+ /*
+ OnConnectionDown() is called whenever a connection goes down
+ */
+ OnConnectionDown(pcb)
+ {
+ pcb->status = DOWN;
+ CloseConnection();
+ switch (pcb->status){
+ case OKAY:
+ Failover(pcb);
+ SetWatchdog();
+ break;
+ case SUSPECT:
+ case REOPEN:
+ SetWatchdog();
+ break;
+ default:
+ error("Shouldn't be here!);
+ break;
+ }
+ }
+
+ /* Here is the state machine equivalent to the above code:
+
+ STATE Event Actions New State
+ ===== ------ ------- ----------
+ OKAY Receive DWA Pending = FALSE
+ SetWatchdog() OKAY
+ OKAY Receive non-DWA SetWatchdog() OKAY
+ SUSPECT Receive DWA Pending = FALSE
+ Failback()
+ SetWatchdog() OKAY
+ SUSPECT Receive non-DWA Failback()
+ SetWatchdog() OKAY
+ REOPEN Receive DWA & Pending = FALSE
+ NumDWA == 2 NumDWA++
+ Failback() OKAY
+ REOPEN Receive DWA & Pending = FALSE
+ NumDWA < 2 NumDWA++ REOPEN
+
+
+
+Aboba & Wood Standards Track [Page 31]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ STATE Event Actions New State
+ ===== ------ ------- ----------
+ REOPEN Receive non-DWA Throwaway() REOPEN
+ INITIAL Receive DWA Pending = FALSE
+ Throwaway() INITIAL
+ INITIAL Receive non-DWA Throwaway() INITIAL
+ DOWN Receive DWA Pending = FALSE
+ Throwaway() DOWN
+ DOWN Receive non-DWA Throwaway() DOWN
+ OKAY Timer expires & SendWatchdog()
+ !Pending SetWatchdog()
+ Pending = TRUE OKAY
+ OKAY Timer expires & Failover()
+ Pending SetWatchdog() SUSPECT
+ SUSPECT Timer expires CloseConnection()
+ SetWatchdog() DOWN
+ INITIAL Timer expires AttemptOpen()
+ SetWatchdog() INITIAL
+ DOWN Timer expires AttemptOpen()
+ SetWatchdog() DOWN
+ REOPEN Timer expires & SendWatchdog()
+ !Pending SetWatchdog()
+ Pending = TRUE REOPEN
+ REOPEN Timer expires & CloseConnection()
+ Pending & SetWatchdog()
+ NumDWA < 0 DOWN
+ REOPEN Timer expires & NumDWA = -1
+ Pending & SetWatchdog()
+ NumDWA >= 0 REOPEN
+ INITIAL Connection up SetWatchdog() OKAY
+ DOWN Connection up NumDWA = 0
+ SendWatchdog()
+ SetWatchdog()
+ Pending = TRUE REOPEN
+ OKAY Connection down CloseConnection()
+ Failover()
+ SetWatchdog() DOWN
+ SUSPECT Connection down CloseConnection()
+ SetWatchdog() DOWN
+ REOPEN Connection down CloseConnection()
+ SetWatchdog() DOWN
+ */
+
+
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 32]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+Appendix B - AAA Agents
+
+ As described in [RFC2865] and [RFC2607], AAA agents have become
+ popular in order to support services such as roaming and shared use
+ networks. Such agents are used both for
+ authentication/authorization, as well as accounting [RFC2975].
+
+ AAA agents include:
+
+ Relays
+ Proxies
+ Re-directs
+ Store and Forward proxies
+ Transport layer proxies
+
+ The transport layer behavior of each of these agents is described
+ below.
+
+B.1 Relays and Proxies
+
+ While the application-layer behavior of relays and proxies are
+ different, at the transport layer the behavior is similar. In both
+ cases, two connections are established: one from the AAA client (NAS)
+ to the relay/proxy, and another from the relay/proxy to the AAA
+ server. The relay/proxy does not respond to a client request until
+ it receives a response from the server. Since the two connections
+ are de-coupled, the end-to-end conversation between the client and
+ server may not self clock.
+
+ Since AAA transport is typically application-driven, there is
+ frequently not enough traffic to enable ACK piggybacking. As a
+ result, the Nagle algorithm is rarely triggered, and delayed ACKs may
+ comprise nearly half the traffic. Thus AAA protocols running over
+ reliable transport will see packet traffic nearly double that
+ experienced with UDP transport. Since ACK parameters (such as the
+ value of the delayed ACK timer) are typically fixed by the TCP
+ implementation and are not tunable by the application, there is
+ little that can be done about this.
+
+
+
+
+
+
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 33]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ A typical trace of a conversation between a NAS, proxy and server is
+ shown below:
+
+ Time NAS Relay/Proxy Server
+ ------ --- ----------- ------
+
+ 0 Request
+ ------->
+ OTTnp + Tpr Request
+ ------->
+
+ OTTnp + TdA Delayed ACK
+ <-------
+
+ OTTnp + OTTps + Reply/ACK
+ Tpr + Tsr <-------
+
+ OTTnp + OTTps +
+ Tpr + Tsr + Reply
+ OTTsp + TpR <-------
+
+ OTTnp + OTTps +
+ Tpr + Tsr + Delayed ACK
+ OTTsp + TdA ------->
+
+ OTTnp + OTTps +
+ OTTsp + OTTpn +
+ Tpr + Tsr + Delayed ACK
+ TpR + TdA ------->
+
+ Key
+ ---
+ OTT = One-way Trip Time
+ OTTnp = One-way trip time (NAS to Relay/Proxy)
+ OTTpn = One-way trip time (Relay/Proxy to NAS)
+ OTTps = One-way trip time (Relay/Proxy to Server)
+ OTTsp = One-way trip time (Server to Relay/Proxy)
+ TdA = Delayed ACK timer
+ Tpr = Relay/Proxy request processing time
+ TpR = Relay/Proxy reply processing time
+ Tsr = Server request processing time
+
+ At time 0, the NAS sends a request to the relay/proxy. Ignoring the
+ serialization time, the request arrives at the relay/proxy at time
+ OTTnp, and the relay/proxy takes an additional Tpr in order to
+ forward the request toward the home server. At time TdA after
+
+
+
+
+
+Aboba & Wood Standards Track [Page 34]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ receiving the request, the relay/proxy sends a delayed ACK. The
+ delayed ACK is sent, rather than being piggybacked on the reply, as
+ long as TdA < OTTps + OTTsp + Tpr + Tsr + TpR.
+
+ Typically Tpr < TdA, so that the delayed ACK is sent after the
+ relay/proxy forwards the request toward the server, but before the
+ relay/proxy receives the reply from the server. However, depending
+ on the TCP implementation on the relay/proxy and when the request is
+ received, it is also possible for the delayed ACK to be sent prior to
+ forwarding the request.
+
+ At time OTTnp + OTTps + Tpr, the server receives the request, and Tsr
+ later, it generates the reply. Where Tsr < TdA, the reply will
+ contain a piggybacked ACK. However, depending on the server
+ responsiveness and TCP implementation, the ACK and reply may be sent
+ separately. This can occur, for example, where a slow database or
+ storage system must be accessed prior to sending the reply.
+
+ At time OTTnp + OTTps + OTTsp + Tpr + Tsr the reply/ACK reaches the
+ relay/proxy, which then takes TpR additional time to forward the
+ reply to the NAS. At TdA after receiving the reply, the relay/proxy
+ generates a delayed ACK. Typically TpR < TdA so that the delayed ACK
+ is sent to the server after the relay/proxy forwards the reply to the
+ NAS. However, depending on the circumstances and the relay/proxy TCP
+ implementation, the delayed ACK may be sent first.
+
+ As with a delayed ACK sent in response to a request, which may be
+ piggybacked if the reply can be received quickly enough, piggybacking
+ of the ACK sent in response to a reply from the server is only
+ possible if additional request traffic is available. However, due to
+ the high inter-packet spacings in typical AAA scenarios, this is
+ unlikely unless the AAA protocol supports a reply ACK.
+
+ At time OTTnp + OTTps + OTTsp + OTTpn + Tpr + Tsr + TpR the NAS
+ receives the reply. TdA later, a delayed ACK is generated.
+
+B.2 Re-directs
+
+ Re-directs operate by referring a NAS to the AAA server, enabling the
+ NAS to talk to the AAA server directly. Since a direct transport
+ connection is established, the end-to-end connection will self-clock.
+
+ With re-directs, delayed ACKs are less frequent than with
+ application-layer proxies since the Re-direct and Server will
+ typically piggyback replies with ACKs.
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 35]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ The sequence of events is as follows:
+
+ Time NAS Re-direct Server
+ ------ --- --------- ------
+
+ 0 Request
+ ------->
+ OTTnp + Tpr Redirect/ACK
+ <-------
+
+ OTTnp + Tpr + Request
+ OTTpn + Tnr ------->
+
+ OTTnp + OTTpn +
+ Tpr + Tsr + Reply/ACK
+ OTTns <-------
+
+ OTTnp + OTTpn +
+ OTTns + OTTsn +
+ Tpr + Tsr + Delayed ACK
+ TdA ------->
+
+ Key
+ ---
+ OTT = One-way Trip Time
+ OTTnp = One-way trip time (NAS to Re-direct)
+ OTTpn = One-way trip time (Re-direct to NAS)
+ OTTns = One-way trip time (NAS to Server)
+ OTTsn = One-way trip time (Server to NAS)
+ TdA = Delayed ACK timer
+ Tpr = Re-direct processing time
+ Tnr = NAS re-direct processing time
+ Tsr = Server request processing time
+
+B.3 Store and Forward Proxies
+
+ With a store and forward proxy, the proxy may send a reply to the NAS
+ prior to forwarding the request to the server. While store and
+ forward proxies are most frequently deployed for accounting
+ [RFC2975], they also can be used to implement
+ authentication/authorization policy, as described in [RFC2607].
+
+ As noted in [RFC2975], store and forward proxies can have a negative
+ effect on accounting reliability. By sending a reply to the NAS
+ without receiving one from the accounting server, store and forward
+ proxies fool the NAS into thinking that the accounting request had
+ been accepted by the accounting server when this is not the case. As
+ a result, the NAS can delete the accounting packet from non-volatile
+
+
+
+Aboba & Wood Standards Track [Page 36]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ storage before it has been accepted by the accounting server. That
+ leaves the proxy responsible for delivering accounting packets. If
+ the proxy involves moving parts (e.g. a disk drive) while the NAS
+ does not, overall system reliability can be reduced. As a result,
+ store and forward proxies SHOULD NOT be used.
+
+ The sequence of events is as follows:
+
+ Time NAS Proxy Server
+ ------ --- ----- ------
+
+ 0 Request
+ ------->
+ OTTnp + TpR Reply/ACK
+ <-------
+
+ OTTnp + Tpr Request
+ ------->
+
+ OTTnp + OTTph + Reply/ACK
+ Tpr + Tsr <-------
+
+ OTTnp + OTTph +
+ Tpr + Tsr + Reply
+ OTThp + TpR <-------
+
+ OTTnp + OTTph +
+ Tpr + Tsr + Delayed ACK
+ OTThp + TdA ------->
+
+ OTTnp + OTTph +
+ OTThp + OTTpn +
+ Tpr + Tsr + Delayed ACK
+ TpR + TdA ------->
+
+ Key
+ ---
+ OTT = One-way Trip Time
+ OTTnp = One-way trip time (NAS to Proxy)
+ OTTpn = One-way trip time (Proxy to NAS)
+ OTTph = One-way trip time (Proxy to Home server)
+ OTThp = One-way trip time (Home Server to Proxy)
+ TdA = Delayed ACK timer
+ Tpr = Proxy request processing time
+ TpR = Proxy reply processing time
+ Tsr = Server request processing time
+
+
+
+
+
+Aboba & Wood Standards Track [Page 37]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+B.4 Transport Layer Proxies
+
+ In addition to acting as proxies at the application layer, transport
+ layer proxies forward transport ACKs between the AAA client and
+ server. This splices together the client-proxy and proxy-server
+ connections into a single connection that behaves as though it
+ operates end-to-end, exhibiting self-clocking. However, since
+ transport proxies operate at the transport layer, they cannot be
+ implemented purely as applications and they are rarely deployed.
+
+ With a transport proxy, the sequence of events is as follows:
+
+ Time NAS Proxy Home Server
+ ------ --- ----- -----------
+
+ 0 Request
+ ------->
+ OTTnp + Tpr Request
+ ------->
+
+ OTTnp + OTTph + Reply/ACK
+ Tpr + Tsr <-------
+
+ OTTnp + OTTph +
+ Tpr + Tsr + Reply/ACK
+ OTThp + TpR <-------
+
+ OTTnp + OTTph +
+ OTThp + OTTpn +
+ Tpr + Tsr + Delayed ACK
+ TpR + TdA ------->
+
+
+ OTTnp + OTTph +
+ OTThp + OTTpn +
+ Tpr + Tsr + Delayed ACK
+ TpR + TpD ------->
+
+ Key
+ ---
+ OTT = One-way Trip Time
+ OTTnp = One-way trip time (NAS to Proxy)
+ OTTpn = One-way trip time (Proxy to NAS)
+ OTTph = One-way trip time (Proxy to Home server)
+ OTThp = One-way trip time (Home Server to Proxy)
+ TdA = Delayed ACK timer
+ Tpr = Proxy request processing time
+ TpR = Proxy reply processing time
+
+
+
+Aboba & Wood Standards Track [Page 38]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+ Tsr = Server request processing time
+ TpD = Proxy delayed ack processing time
+
+Intellectual Property Statement
+
+ The IETF takes no position regarding the validity or scope of any
+ intellectual property or other rights that might be claimed to
+ pertain to the implementation or use of the technology described in
+ this document or the extent to which any license under such rights
+ might or might not be available; neither does it represent that it
+ has made any effort to identify any such rights. Information on the
+ IETF's procedures with respect to rights in standards-track and
+ standards-related documentation can be found in BCP-11. Copies of
+ claims of rights made available for publication and any assurances of
+ licenses to be made available, or the result of an attempt made to
+ obtain a general license or permission for the use of such
+ proprietary rights by implementors or users of this specification can
+ be obtained from the IETF Secretariat.
+
+ The IETF invites any interested party to bring to its attention any
+ copyrights, patents or patent applications, or other proprietary
+ rights which may cover technology that may be required to practice
+ this standard. Please address the information to the IETF Executive
+ Director.
+
+Acknowledgments
+
+ Thanks to Allison Mankin of AT&T, Barney Wolff of Databus, Steve Rich
+ of Cisco, Randy Bush of AT&T, Bo Landarv of IP Unplugged, Jari Arkko
+ of Ericsson, and Pat Calhoun of Blackstorm Networks for fruitful
+ discussions relating to AAA transport.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 39]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+Authors' Addresses
+
+ Bernard Aboba
+ Microsoft Corporation
+ One Microsoft Way
+ Redmond, WA 98052
+
+ Phone: +1 425 706 6605
+ Fax: +1 425 936 7329
+
+
+ Jonathan Wood
+ Sun Microsystems, Inc.
+ 901 San Antonio Road
+ Palo Alto, CA 94303
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 40]
+
+RFC 3539 AAA Transport Profile June 2003
+
+
+Full Copyright Statement
+
+ Copyright (C) The Internet Society (2003). All Rights Reserved.
+
+ This document and translations of it may be copied and furnished to
+ others, and derivative works that comment on or otherwise explain it
+ or assist in its implementation may be prepared, copied, published
+ and distributed, in whole or in part, without restriction of any
+ kind, provided that the above copyright notice and this paragraph are
+ included on all such copies and derivative works. However, this
+ document itself may not be modified in any way, such as by removing
+ the copyright notice or references to the Internet Society or other
+ Internet organizations, except as needed for the purpose of
+ developing Internet standards in which case the procedures for
+ copyrights defined in the Internet Standards process must be
+ followed, or as required to translate it into languages other than
+ English.
+
+ The limited permissions granted above are perpetual and will not be
+ revoked by the Internet Society or its successors or assigns.
+
+ This document and the information contained herein is provided on an
+ "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+ TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
+ BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
+ HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+ MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Aboba & Wood Standards Track [Page 41]
+
diff --git a/lib/diameter/doc/standard/rfc3588.txt b/lib/diameter/doc/standard/rfc3588.txt
new file mode 100644
index 0000000000..fe4ff08c81
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc3588.txt
@@ -0,0 +1,8235 @@
+
+
+
+
+
+
+Network Working Group P. Calhoun
+Request for Comments: 3588 Airespace, Inc.
+Category: Standards Track J. Loughney
+ Nokia
+ E. Guttman
+ Sun Microsystems, Inc.
+ G. Zorn
+ Cisco Systems, Inc.
+ J. Arkko
+ Ericsson
+ September 2003
+
+
+ Diameter Base Protocol
+
+Status of this Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The Internet Society (2003). All Rights Reserved.
+
+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. Diameter is also intended to work in
+ both local Authentication, Authorization & Accounting and roaming
+ situations. This document specifies the message format, transport,
+ error reporting, accounting and security services to be used by all
+ Diameter applications. The Diameter base application needs to be
+ supported by all Diameter implementations.
+
+Conventions Used In This Document
+
+ 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 BCP 14, RFC 2119
+ [KEYWORD].
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 1]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+Table of Contents
+
+ 1. Introduction................................................. 6
+ 1.1. Diameter Protocol..................................... 9
+ 1.1.1. Description of the Document Set.............. 10
+ 1.2. Approach to Extensibility............................. 11
+ 1.2.1. Defining New AVP Values...................... 11
+ 1.2.2. Creating New AVPs............................ 11
+ 1.2.3. Creating New Authentication Applications..... 11
+ 1.2.4. Creating New Accounting Applications......... 12
+ 1.2.5. Application Authentication Procedures........ 14
+ 1.3. Terminology........................................... 14
+ 2. Protocol Overview............................................ 18
+ 2.1. Transport............................................. 20
+ 2.1.1. SCTP Guidelines.............................. 21
+ 2.2. Securing Diameter Messages............................ 21
+ 2.3. Diameter Application Compliance....................... 21
+ 2.4. Application Identifiers............................... 22
+ 2.5. Connections vs. Sessions.............................. 22
+ 2.6. Peer Table............................................ 23
+ 2.7. Realm-Based Routing Table............................. 24
+ 2.8. Role of Diameter Agents............................... 25
+ 2.8.1. Relay Agents................................. 26
+ 2.8.2. Proxy Agents................................. 27
+ 2.8.3. Redirect Agents.............................. 28
+ 2.8.4. Translation Agents........................... 29
+ 2.9. End-to-End Security Framework......................... 30
+ 2.10. Diameter Path Authorization........................... 30
+ 3. Diameter Header.............................................. 32
+ 3.1. Command Codes......................................... 35
+ 3.2. Command Code ABNF specification....................... 36
+ 3.3. Diameter Command Naming Conventions................... 38
+ 4. Diameter AVPs................................................ 38
+ 4.1. AVP Header............................................ 39
+ 4.1.1. Optional Header Elements..................... 41
+ 4.2. Basic AVP Data Formats................................ 41
+ 4.3. Derived AVP Data Formats.............................. 42
+ 4.4. Grouped AVP Values.................................... 49
+ 4.4.1. Example AVP with a Grouped Data Type......... 50
+ 4.5. Diameter Base Protocol AVPs........................... 53
+ 5. Diameter Peers............................................... 56
+ 5.1. Peer Connections...................................... 56
+ 5.2. Diameter Peer Discovery............................... 56
+ 5.3. Capabilities Exchange................................. 59
+ 5.3.1. Capabilities-Exchange-Request................ 60
+ 5.3.2. Capabilities-Exchange-Answer................. 60
+ 5.3.3. Vendor-Id AVP................................ 61
+ 5.3.4. Firmware-Revision AVP........................ 61
+
+
+
+Calhoun, et al. Standards Track [Page 2]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 5.3.5. Host-IP-Address AVP.......................... 62
+ 5.3.6. Supported-Vendor-Id AVP...................... 62
+ 5.3.7. Product-Name AVP............................. 62
+ 5.4. Disconnecting Peer Connections........................ 62
+ 5.4.1. Disconnect-Peer-Request...................... 63
+ 5.4.2. Disconnect-Peer-Answer....................... 63
+ 5.4.3. Disconnect-Cause AVP......................... 63
+ 5.5. Transport Failure Detection........................... 64
+ 5.5.1. Device-Watchdog-Request...................... 64
+ 5.5.2. Device-Watchdog-Answer....................... 64
+ 5.5.3. Transport Failure Algorithm.................. 65
+ 5.5.4. Failover and Failback Procedures............. 65
+ 5.6. Peer State Machine.................................... 66
+ 5.6.1. Incoming connections......................... 68
+ 5.6.2. Events....................................... 69
+ 5.6.3. Actions...................................... 70
+ 5.6.4. The Election Process......................... 71
+ 6. Diameter Message Processing.................................. 71
+ 6.1. Diameter Request Routing Overview..................... 71
+ 6.1.1. Originating a Request........................ 73
+ 6.1.2. Sending a Request............................ 73
+ 6.1.3. Receiving Requests........................... 73
+ 6.1.4. Processing Local Requests.................... 73
+ 6.1.5. Request Forwarding........................... 74
+ 6.1.6. Request Routing.............................. 74
+ 6.1.7. Redirecting Requests......................... 74
+ 6.1.8. Relaying and Proxying Requests............... 75
+ 6.2. Diameter Answer Processing............................ 76
+ 6.2.1. Processing Received Answers.................. 77
+ 6.2.2. Relaying and Proxying Answers................ 77
+ 6.3. Origin-Host AVP....................................... 77
+ 6.4. Origin-Realm AVP...................................... 78
+ 6.5. Destination-Host AVP.................................. 78
+ 6.6. Destination-Realm AVP................................. 78
+ 6.7. Routing AVPs.......................................... 78
+ 6.7.1. Route-Record AVP............................. 79
+ 6.7.2. Proxy-Info AVP............................... 79
+ 6.7.3. Proxy-Host AVP............................... 79
+ 6.7.4. Proxy-State AVP.............................. 79
+ 6.8. Auth-Application-Id AVP............................... 79
+ 6.9. Acct-Application-Id AVP............................... 79
+ 6.10. Inband-Security-Id AVP................................ 79
+ 6.11. Vendor-Specific-Application-Id AVP.................... 80
+ 6.12. Redirect-Host AVP..................................... 80
+ 6.13. Redirect-Host-Usage AVP............................... 80
+ 6.14. Redirect-Max-Cache-Time AVP........................... 81
+ 6.15. E2E-Sequence AVP...................................... 82
+
+
+
+
+Calhoun, et al. Standards Track [Page 3]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 7. Error Handling............................................... 82
+ 7.1. Result-Code AVP....................................... 84
+ 7.1.1. Informational................................ 84
+ 7.1.2. Success...................................... 84
+ 7.1.3. Protocol Errors.............................. 85
+ 7.1.4. Transient Failures........................... 86
+ 7.1.5. Permanent Failures........................... 86
+ 7.2. Error Bit............................................. 88
+ 7.3. Error-Message AVP..................................... 89
+ 7.4. Error-Reporting-Host AVP.............................. 89
+ 7.5. Failed-AVP AVP........................................ 89
+ 7.6. Experimental-Result AVP............................... 90
+ 7.7. Experimental-Result-Code AVP.......................... 90
+ 8. Diameter User Sessions....................................... 90
+ 8.1. Authorization Session State Machine................... 92
+ 8.2. Accounting Session State Machine...................... 96
+ 8.3. Server-Initiated Re-Auth.............................. 101
+ 8.3.1. Re-Auth-Request.............................. 102
+ 8.3.2. Re-Auth-Answer............................... 102
+ 8.4. Session Termination................................... 103
+ 8.4.1. Session-Termination-Request.................. 104
+ 8.4.2. Session-Termination-Answer................... 105
+ 8.5. Aborting a Session.................................... 105
+ 8.5.1. Abort-Session-Request........................ 106
+ 8.5.2. Abort-Session-Answer......................... 106
+ 8.6. Inferring Session Termination from Origin-State-Id.... 107
+ 8.7. Auth-Request-Type AVP................................. 108
+ 8.8. Session-Id AVP........................................ 108
+ 8.9. Authorization-Lifetime AVP............................ 109
+ 8.10. Auth-Grace-Period AVP................................. 110
+ 8.11. Auth-Session-State AVP................................ 110
+ 8.12. Re-Auth-Request-Type AVP.............................. 110
+ 8.13. Session-Timeout AVP................................... 111
+ 8.14. User-Name AVP......................................... 111
+ 8.15. Termination-Cause AVP................................. 111
+ 8.16. Origin-State-Id AVP................................... 112
+ 8.17. Session-Binding AVP................................... 113
+ 8.18. Session-Server-Failover AVP........................... 113
+ 8.19. Multi-Round-Time-Out AVP.............................. 114
+ 8.20. Class AVP............................................. 114
+ 8.21. Event-Timestamp AVP................................... 115
+ 9. Accounting................................................... 115
+ 9.1. Server Directed Model................................. 115
+ 9.2. Protocol Messages..................................... 116
+ 9.3. Application Document Requirements..................... 116
+ 9.4. Fault Resilience...................................... 116
+ 9.5. Accounting Records.................................... 117
+ 9.6. Correlation of Accounting Records..................... 118
+
+
+
+Calhoun, et al. Standards Track [Page 4]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 9.7. Accounting Command-Codes.............................. 119
+ 9.7.1. Accounting-Request........................... 119
+ 9.7.2. Accounting-Answer............................ 120
+ 9.8. Accounting AVPs....................................... 121
+ 9.8.1. Accounting-Record-Type AVP................... 121
+ 9.8.2. Acct-Interim-Interval AVP.................... 122
+ 9.8.3. Accounting-Record-Number AVP................. 123
+ 9.8.4. Acct-Session-Id AVP.......................... 123
+ 9.8.5. Acct-Multi-Session-Id AVP.................... 123
+ 9.8.6. Accounting-Sub-Session-Id AVP................ 123
+ 9.8.7. Accounting-Realtime-Required AVP............. 123
+ 10. AVP Occurrence Table......................................... 124
+ 10.1. Base Protocol Command AVP Table....................... 124
+ 10.2. Accounting AVP Table.................................. 126
+ 11. IANA Considerations.......................................... 127
+ 11.1. AVP Header............................................ 127
+ 11.1.1. AVP Code..................................... 127
+ 11.1.2. AVP Flags.................................... 128
+ 11.2. Diameter Header....................................... 128
+ 11.2.1. Command Codes................................ 128
+ 11.2.2. Command Flags................................ 129
+ 11.3. Application Identifiers............................... 129
+ 11.4. AVP Values............................................ 129
+ 11.4.1. Result-Code AVP Values....................... 129
+ 11.4.2. Accounting-Record-Type AVP Values............ 130
+ 11.4.3. Termination-Cause AVP Values................. 130
+ 11.4.4. Redirect-Host-Usage AVP Values............... 130
+ 11.4.5. Session-Server-Failover AVP Values........... 130
+ 11.4.6. Session-Binding AVP Values................... 130
+ 11.4.7. Disconnect-Cause AVP Values.................. 130
+ 11.4.8. Auth-Request-Type AVP Values................. 130
+ 11.4.9. Auth-Session-State AVP Values................ 130
+ 11.4.10. Re-Auth-Request-Type AVP Values.............. 131
+ 11.4.11. Accounting-Realtime-Required AVP Values...... 131
+ 11.5. Diameter TCP/SCTP Port Numbers........................ 131
+ 11.6. NAPTR Service Fields.................................. 131
+ 12. Diameter Protocol Related Configurable Parameters............ 131
+ 13. Security Considerations...................................... 132
+ 13.1. IPsec Usage........................................... 133
+ 13.2. TLS Usage............................................. 134
+ 13.3. Peer-to-Peer Considerations........................... 134
+ 14. References................................................... 136
+ 14.1. Normative References.................................. 136
+ 14.2. Informative References................................ 138
+ 15. Acknowledgements............................................. 140
+ Appendix A. Diameter Service Template........................... 141
+ Appendix B. NAPTR Example....................................... 142
+ Appendix C. Duplicate Detection................................. 143
+
+
+
+Calhoun, et al. Standards Track [Page 5]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Appendix D. Intellectual Property Statement..................... 145
+ Authors' Addresses............................................... 146
+ Full Copyright Statement......................................... 147
+
+1. Introduction
+
+ Authentication, Authorization and Accounting (AAA) protocols such as
+ TACACS [TACACS] and RADIUS [RADIUS] were initially deployed to
+ provide dial-up PPP [PPP] and terminal server access. Over time,
+ with the growth of the Internet and the introduction of new access
+ technologies, including wireless, DSL, Mobile IP and Ethernet,
+ routers and network access servers (NAS) have increased in complexity
+ and density, putting new demands on AAA protocols.
+
+ Network access requirements for AAA protocols are summarized in
+ [AAAREQ]. These include:
+
+ Failover
+ [RADIUS] 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 [AAATRANS].
+
+ Transmission-level security
+ [RADIUS] defines an application-layer authentication and integrity
+ scheme that is required only for use with Response packets. While
+ [RADEXT] defines an additional authentication and integrity
+ mechanism, use is only required during Extensible Authentication
+ Protocol (EAP) sessions. While attribute-hiding is supported,
+ [RADIUS] does not provide support for per-packet confidentiality.
+ In accounting, [RADACCT] 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. Since within [IKE] authentication occurs
+ only within Phase 1 prior to the establishment of IPsec SAs in
+ Phase 2, it is typically not possible to define separate trust or
+ authorization schemes for each application. This limits the
+ usefulness of IPsec in inter-domain AAA applications (such as
+ roaming) where it may be desirable to define a distinct
+ certificate hierarchy for use in a AAA deployment. In order to
+ provide universal support for transmission-level security, and
+ enable both intra- and inter-domain AAA deployments, IPsec support
+ is mandatory in Diameter, and TLS support is optional. Security
+ is discussed in Section 13.
+
+
+
+Calhoun, et al. Standards Track [Page 6]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Reliable transport
+ RADIUS runs over UDP, and does not define retransmission behavior;
+ as a result, reliability varies between implementations. As
+ described in [ACCMGMT], this is a major issue in accounting, where
+ 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
+ [AAATRANS].
+
+ 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 [DYNAUTH],
+ support is optional. This makes it difficult to implement
+ features such as unsolicited disconnect or
+ reauthentication/reauthorization on demand across a heterogeneous
+ deployment. Support for server-initiated messages is mandatory in
+ Diameter, and is described in Section 8.
+
+ Auditability
+ RADIUS does not define data-object security mechanisms, and as a
+ result, untrusted proxies may modify attributes or even packet
+ headers without being detected. Combined with lack of support for
+ capabilities negotiation, this makes it very difficult to
+ determine what occurred in the event of a dispute. While
+ implementation of data object security is not mandatory within
+ Diameter, these capabilities are supported, and are described in
+ [AAACMS].
+
+ 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
+ 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
+ devices and Diameter agents. This capability, described in
+ [NASREQ], enables Diameter support to be added to legacy networks,
+ by addition of a gateway or server speaking both RADIUS and
+ Diameter.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 7]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ In addition to addressing the above requirements, Diameter also
+ provides support for the following:
+
+ Capability negotiation
+ RADIUS does not support error messages, capability negotiation, or
+ 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
+ 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).
+
+ Peer discovery and configuration
+ 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
+ RADIUS shared secret, which can result in major security
+ vulnerabilities if the Request Authenticator is not globally and
+ temporally unique as required in [RADIUS]. Through DNS, Diameter
+ enables dynamic discovery of peers. Derivation of dynamic session
+ keys is enabled via transmission-level security.
+
+ Roaming support
+ The ROAMOPS WG provided a survey of roaming implementations
+ [ROAMREV], detailed roaming requirements [ROAMCRIT], defined the
+ Network Access Identifier (NAI) [NAI], and documented existing
+ implementations (and imitations) of RADIUS-based roaming
+ [PROXYCHAIN]. In order to improve scalability, [PROXYCHAIN]
+ introduced the concept of proxy chaining via an intermediate
+ server, facilitating roaming between providers. However, since
+ RADIUS does not provide explicit support for proxies, and lacks
+ auditability and transmission-level security features, RADIUS-
+ based roaming is vulnerable to attack from external parties as
+ well as susceptible to fraud perpetrated by the roaming partners
+ themselves. As a result, it is not suitable for wide-scale
+ deployment on the Internet [PROXYCHAIN]. By providing explicit
+ support for inter-domain roaming and message routing (Sections 2.7
+ and 6), auditability [AAACMS], and transmission-layer security
+ (Section 13) features, Diameter addresses these limitations and
+ provides for secure and scalable roaming.
+
+ In the decade since AAA protocols were first introduced, 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 feasible to implement
+
+
+
+Calhoun, et al. Standards Track [Page 8]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ within embedded devices, given improvements in processor speeds and
+ the widespread availability of embedded IPsec and TLS
+ implementations.
+
+1.1. Diameter Protocol
+
+ The Diameter base protocol provides the following facilities:
+
+ - Delivery of AVPs (attribute value pairs)
+ - Capabilities negotiation
+ - Error notification
+ - Extensibility, through addition of new commands and AVPs (required
+ in [AAAREQ]).
+ - Basic services necessary for applications, such as handling of
+ user sessions or accounting
+
+ All data delivered by the protocol is in the form of an AVP. 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 added arbitrarily to Diameter messages,
+ so long as the required AVPs are included and AVPs that are
+ explicitly excluded are not included. AVPs are used by the base
+ Diameter protocol to support the following required features:
+
+ - Transporting of user authentication information, for the purposes
+ of enabling the Diameter server to authenticate the user.
+
+ - Transporting of service specific authorization information,
+ between client and servers, allowing the peers to decide whether a
+ user's access request should be granted.
+
+ - Exchanging resource usage information, which MAY be used for
+ accounting purposes, capacity planning, etc.
+
+ - Relaying, proxying and redirecting of Diameter messages through a
+ server hierarchy.
+
+ The Diameter base protocol provides the minimum requirements needed
+ for a AAA protocol, as required by [AAAREQ]. 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 [DIAMMIP], or
+ network access [NASREQ]. It is also possible for the base protocol
+ to be extended for use in new applications, via the addition of new
+ commands or AVPs. At this time the focus of Diameter is network
+ access and accounting applications. A truly generic AAA protocol
+ used by 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.
+
+
+
+Calhoun, et al. Standards Track [Page 9]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ See Section 2.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
+ 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 authenticate and/or authorize messages
+ locally; 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.
+
+ The Diameter protocol also supports server-initiated messages, such
+ as a request to abort service to a particular user.
+
+1.1.1. Description of the Document Set
+
+ Currently, the Diameter specification consists of a base
+ specification (this document), Transport Profile [AAATRANS] and
+ applications: Mobile IPv4 [DIAMMIP], and NASREQ [NASREQ].
+
+ The Transport Profile document [AAATRANS] 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.
+
+ The Mobile IPv4 [DIAMMIP] application defines a Diameter application
+ that allows a Diameter server to perform AAA functions for Mobile
+ IPv4 services to a mobile node.
+
+ The NASREQ [NASREQ] application defines a Diameter Application that
+ allows a Diameter server to be used in a PPP/SLIP Dial-Up and
+ Terminal Server Access environment. Consideration was given for
+ servers that need to perform protocol conversion between Diameter and
+ RADIUS.
+
+ In summary, this document defines the base protocol specification for
+ AAA, which includes support for accounting. The Mobile IPv4 and the
+ NASREQ documents describe applications that use this base
+ specification for Authentication, Authorization and Accounting.
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 10]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+1.2. Approach to Extensibility
+
+ The Diameter protocol is designed to be extensible, using several
+ mechanisms, including:
+
+ - Defining new AVP values
+ - Creating new AVPs
+ - Creating new authentication/authorization applications
+ - Creating new accounting applications
+ - Application authentication procedures
+
+ Reuse of existing AVP values, AVPs and Diameter applications are
+ strongly recommended. Reuse simplifies standardization and
+ implementation and avoids potential interoperability issues. It is
+ expected that command codes are reused; new command codes can only be
+ created by IETF Consensus (see Section 11.2.1).
+
+1.2.1. Defining New AVP Values
+
+ New applications should attempt to reuse AVPs defined in existing
+ applications when possible, as opposed to creating new AVPs. For
+ AVPs of type Enumerated, an application may require a new value to
+ communicate some service-specific information.
+
+ In order to allocate a new AVP value, a request MUST be sent to IANA
+ [IANA], along with an explanation of the new AVP value. IANA
+ considerations for Diameter are discussed in Section 11.
+
+1.2.2. Creating New AVPs
+
+ When no existing AVP can be used, a new AVP should be created. The
+ new AVP being defined MUST use one of the data types listed in
+ Section 4.2.
+
+ 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).
+
+ In order to create a new AVP, a request MUST be sent to IANA, with a
+ specification for the AVP. The request MUST include the commands
+ that would make use of the AVP.
+
+1.2.3. Creating New Authentication Applications
+
+ Every Diameter application specification MUST have an IANA assigned
+ Application Identifier (see Section 2.4) or a vendor specific
+ Application Identifier.
+
+
+
+
+Calhoun, et al. Standards Track [Page 11]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Should a new Diameter usage scenario find itself unable to fit within
+ an existing application without requiring major changes to the
+ specification, it may be desirable to create a new Diameter
+ application. Major changes to an application include:
+
+ - Adding new AVPs to the command, which have the "M" bit set.
+
+ - Requiring a command that has a different number of round trips to
+ satisfy a request (e.g., application foo has a command that
+ requires one round trip, but new application bar has a command
+ that requires two round trips to complete).
+
+ - Adding support for an authentication method requiring definition
+ of new AVPs for use with the application. Since a new EAP
+ authentication method can be supported within Diameter without
+ requiring new AVPs, addition of EAP methods does not require the
+ creation of a new authentication application.
+
+ Creation of a new application should be viewed as a last resort. An
+ implementation MAY add arbitrary non-mandatory AVPs to any command
+ defined in an application, including vendor-specific AVPs without
+ needing to define a new application. Please refer to Section 11.1.1
+ for details.
+
+ In order to justify allocation of a new application identifier,
+ Diameter applications MUST define one Command Code, or add new
+ mandatory AVPs to the ABNF.
+
+ The expected AVPs MUST be defined in an ABNF [ABNF] grammar (see
+ Section 3.2). If the Diameter application has accounting
+ requirements, it MUST also specify the AVPs that are to be present in
+ the Diameter Accounting messages (see Section 9.3). However, just
+ because a new authentication application id is required, does not
+ imply that a new accounting application id is required.
+
+ When possible, a new Diameter application SHOULD reuse existing
+ Diameter AVPs, in order to avoid defining multiple AVPs that carry
+ similar information.
+
+1.2.4. Creating New Accounting Applications
+
+ There are services that only require Diameter accounting. Such
+ services need to define the AVPs carried in the Accounting-Request
+ (ACR)/ Accounting-Answer (ACA) messages, but do not need to define
+ new command codes. An implementation MAY add arbitrary non-mandatory
+ AVPs (AVPs with the "M" bit not set) to any command defined in an
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 12]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ application, including vendor-specific AVPs, without needing to
+ define a new accounting application. Please refer to Section 11.1.1
+ for details.
+
+ Application Identifiers are still required for Diameter capability
+ exchange. Every Diameter accounting application specification MUST
+ have an IANA assigned Application Identifier (see Section 2.4) or a
+ vendor specific Application Identifier.
+
+ Every Diameter implementation MUST support accounting. Basic
+ accounting support is sufficient to handle any application that uses
+ the ACR/ACA commands defined in this document, as long as no new
+ mandatory AVPs are added. A mandatory AVP is defined as one which
+ has the "M" bit set when sent within an accounting command,
+ regardless of whether it is required or optional within the ABNF for
+ the accounting application.
+
+ The creation of a new accounting application should be viewed as a
+ last resort and MUST NOT be used unless a new command or additional
+ mechanisms (e.g., application defined state machine) is defined
+ within the application, or new mandatory AVPs are added to the ABNF.
+
+ Within an accounting command, setting the "M" bit implies that a
+ backend server (e.g., billing server) or the accounting server itself
+ MUST understand the AVP in order to compute a correct bill. If the
+ AVP is not relevant to the billing process, when the AVP is included
+ within an accounting command, it MUST NOT have the "M" bit set, even
+ if the "M" bit is set when the same AVP is used within other Diameter
+ commands (i.e., authentication/authorization commands).
+
+ A DIAMETER base accounting implementation MUST be configurable to
+ advertise supported accounting applications in order to prevent the
+ accounting server from accepting accounting requests for unbillable
+ services. The combination of the home domain and the accounting
+ application Id can be used in order to route the request to the
+ appropriate accounting server.
+
+ When possible, a new Diameter accounting application SHOULD attempt
+ to reuse existing AVPs, in order to avoid defining multiple AVPs that
+ carry similar information.
+
+ If the base accounting is used without any mandatory AVPs, new
+ commands or additional mechanisms (e.g., application defined state
+ machine), then the base protocol defined standard accounting
+ application Id (Section 2.4) MUST be used in ACR/ACA commands.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 13]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+1.2.5. Application Authentication Procedures
+
+ When possible, applications SHOULD be designed such that new
+ authentication methods MAY be added without requiring changes to the
+ application. This MAY require that new AVP values be assigned to
+ represent the new authentication transform, or any other scheme that
+ produces similar results. When possible, authentication frameworks,
+ such as Extensible Authentication Protocol [EAP], SHOULD be used.
+
+1.3. Terminology
+
+ AAA
+ Authentication, Authorization and Accounting.
+
+ Accounting
+ The act of collecting information on resource usage for the
+ purpose of capacity planning, auditing, billing or cost
+ allocation.
+
+ Accounting Record
+ An accounting record represents a summary of the resource
+ consumption of a user over the entire session. Accounting servers
+ creating the accounting record may do so by processing interim
+ 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
+ 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
+ accounting information.
+
+ Broker
+ A broker is a business term commonly used in AAA infrastructures.
+ A broker is either a relay, proxy or redirect agent, and MAY be
+ operated by roaming consortiums. Depending on the business model,
+ a broker may either choose to deploy relay agents or proxy
+ agents.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 14]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Diameter Agent
+ A Diameter Agent is a Diameter node that provides either relay,
+ proxy, redirect or translation services.
+
+ Diameter Client
+ A Diameter Client is a device at the edge of the network that
+ performs access control. An example of a Diameter client is a
+ Network Access Server (NAS) or a 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.
+
+ Diameter Peer
+ A Diameter Peer is a Diameter Node to which a given Diameter Node
+ has a direct transport connection.
+
+ Diameter Security Exchange
+ A Diameter Security Exchange is a process through which two
+ Diameter nodes establish end-to-end security.
+
+ Diameter Server
+ A Diameter Server is one that handles authentication,
+ authorization and accounting requests for a particular realm. By
+ its very nature, a Diameter Server MUST support Diameter
+ 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 access device.
+
+ End-to-End Security
+ TLS and IPsec provide hop-by-hop security, or security across a
+ transport connection. When relays or proxy are involved, this
+ hop-by-hop security does not protect the entire Diameter user
+ session. End-to-end security is security between two Diameter
+ nodes, possibly communicating through Diameter Agents. This
+ security protects the entire Diameter communications path from the
+ originating Diameter node to the terminating Diameter node.
+
+ Home Realm
+ A Home Realm is the administrative domain with which the user
+ maintains an account relationship.
+
+ Home Server
+ See Diameter Server.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 15]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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 of a device
+ reboot or other network problem prevents the reception of a
+ session summary message or session record.
+
+ 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.
+
+ Multi-session
+ A multi-session represents a logical linking of several sessions.
+ Multi-sessions are tracked by using the Acct-Multi-Session-Id. An
+ example of a multi-session would be a Multi-link PPP bundle. Each
+ 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 [NAI], 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
+ purposes.
+
+ 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
+ applications.
+
+ Realm
+ The string in the NAI that immediately follows the '@' character.
+ 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
+ routed or redirected. In RADIUS, realm names are not necessarily
+ piggybacked on the DNS namespace but may be independent of it.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 16]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+ Relay Agent or Relay
+ Relays forward requests and responses based on routing-related
+ AVPs and realm routing table entries. Since relays do not make
+ policy decisions, they do not examine or alter non-routing AVPs.
+ As a result, relays never originate messages, do not need to
+ understand 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 sessions in progress.
+
+ Redirect Agent
+ Rather than forwarding requests and responses between clients and
+ servers, redirect agents refer clients to servers and allow them
+ to communicate directly. Since redirect agents do not sit in the
+ forwarding path, they do not alter any AVPs transiting between
+ 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
+ agents, redirect agents do not keep state with respect to sessions
+ or NAS resources.
+
+ Roaming Relationships
+ Roaming relationships include relationships between companies and
+ ISPs, relationships among peer ISPs within a roaming consortium,
+ and relationships between an ISP and a roaming consortium.
+
+ Security Association
+ A security association is an association between two endpoints in
+ a Diameter session which allows the endpoints to communicate with
+ integrity and confidentially, even in the presence of relays
+ and/or proxies.
+
+ Session
+ A session is a related progression of events devoted to a
+ particular activity. Each application SHOULD provide guidelines
+ as to when a session begins and ends. All Diameter packets with
+ the same Session-Identifier are considered to be part of the same
+ session.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 17]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Session state
+ 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.
+
+ Sub-session
+ A sub-session represents a distinct service (e.g., QoS or data
+ characteristics) provided to a given session. These services may
+ happen concurrently (e.g., simultaneous voice and data transfer
+ during the same session) or serially. These changes in sessions
+ are tracked with the Accounting-Sub-Session-Id.
+
+ 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
+ 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 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.
+
+ Upstream
+ Upstream is used to identify the direction of a particular
+ Diameter message from the access device towards the home server.
+
+ User
+ The entity requesting or using some resource, in support of which
+ a Diameter client has generated a request.
+
+2. Protocol Overview
+
+ The base Diameter protocol may be used by itself for accounting
+ applications, but for use in authentication and authorization it is
+ always extended for a particular application. Two Diameter
+ applications are defined by companion documents: NASREQ [NASREQ],
+
+
+
+Calhoun, et al. Standards Track [Page 18]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Mobile IPv4 [DIAMMIP]. These applications are introduced in this
+ document but specified elsewhere. Additional Diameter applications
+ MAY be defined in the future (see Section 11.3).
+
+ 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 that does not support
+ both NASREQ and Mobile IPv4, MUST be referred to as "Diameter X
+ Client" where X is the application which it supports, and not a
+ "Diameter Client".
+
+ 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 that does not support
+ both NASREQ and Mobile IPv4, MUST be referred to as "Diameter X
+ Server" where X is the application which it supports, and not a
+ "Diameter Server".
+
+ Diameter Relays and redirect agents are, by definition, protocol
+ transparent, and MUST transparently support the Diameter base
+ protocol, which includes accounting, and all Diameter applications.
+
+ Diameter proxies MUST support the base protocol, which includes
+ accounting. In addition, they MUST fully support each Diameter
+ application that is needed to implement proxied services, e.g.,
+ NASREQ and/or Mobile IPv4. A Diameter proxy which does not support
+ also both NASREQ and Mobile IPv4, MUST be referred to as "Diameter X
+ Proxy" where X is the application which it supports, and not a
+ "Diameter Proxy".
+
+ The base Diameter protocol concerns itself with capabilities
+ negotiation, how messages are sent and how peers may eventually be
+ abandoned. The base protocol also defines certain rules that apply
+ to all exchanges of messages between Diameter nodes.
+
+ Communication between Diameter peers begins with one peer sending a
+ message to another Diameter peer. The set of AVPs included in the
+ message is determined by a particular Diameter application. One AVP
+ that is included to reference a user's session is the Session-Id.
+
+ The initial request for authentication and/or authorization of a user
+ would include the Session-Id. 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
+
+
+
+
+Calhoun, et al. Standards Track [Page 19]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ set to indicate an error occurred. The specific behavior of the
+ Diameter server or client receiving a request depends on the Diameter
+ application employed.
+
+ Session state (associated with a Session-Id) MUST be freed upon
+ receipt of the Session-Termination-Request, Session-Termination-
+ Answer, expiration of authorized service time in the Session-Timeout
+ AVP, and according to rules established in a particular Diameter
+ application.
+
+2.1. Transport
+
+ Transport profile is defined in [AAATRANS].
+
+ The base Diameter protocol is run on port 3868 of both TCP [TCP] and
+ SCTP [SCTP] transport protocols.
+
+ Diameter clients MUST support either TCP or SCTP, while agents and
+ servers MUST support both. Future versions of this specification MAY
+ mandate that clients support SCTP.
+
+ 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. 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
+ the Tc timer, 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, SCTP SHOULD be tried first, followed by TCP. See Section
+ 5.2 for more information on peer discovery.
+
+ Diameter implementations SHOULD be able to interpret ICMP protocol
+ port unreachable messages as explicit indications that the server is
+ not reachable, subject to security policy on trusting such messages.
+ Diameter implementations SHOULD also be able to interpret a reset
+ from the transport and timed-out connection attempts.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 20]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ If Diameter receives data up from TCP that cannot be parsed or
+ identified as a Diameter error made by the peer, the stream is
+ compromised and cannot be recovered. The transport connection MUST
+ be closed using a RESET call (send a TCP RST bit) or an SCTP ABORT
+ message (graceful closure is compromised).
+
+2.1.1. SCTP Guidelines
+
+ The following are guidelines for Diameter implementations that
+ support SCTP:
+
+ 1. For interoperability: All Diameter nodes MUST be prepared to
+ receive Diameter messages on any SCTP stream in the association.
+
+ 2. To prevent blocking: All Diameter nodes SHOULD utilize all SCTP
+ streams available to the association to prevent head-of-the-line
+ blocking.
+
+2.2. Securing Diameter Messages
+
+ Diameter clients, such as Network Access Servers (NASes) and Mobility
+ Agents MUST support IP Security [SECARCH], and MAY support TLS [TLS].
+ Diameter servers MUST support TLS and IPsec. The Diameter protocol
+ MUST NOT be used without any security mechanism (TLS or IPsec).
+
+ It is suggested that IPsec can be used primarily at the edges and in
+ intra-domain traffic, such as using pre-shared keys between a NAS a
+ local AAA proxy. This also eases the requirements on the NAS to
+ support certificates. It is also suggested that inter-domain traffic
+ would primarily use TLS. See Sections 13.1 and 13.2 for more details
+ on IPsec and TLS usage.
+
+2.3. Diameter Application Compliance
+
+ Application Identifiers are advertised during the capabilities
+ exchange phase (see Section 5.3). For a given application,
+ advertising support of an application implies that the sender
+ supports all command codes, and the AVPs specified in the associated
+ ABNFs, described in the specification.
+
+ An implementation MAY add arbitrary non-mandatory AVPs to any command
+ defined in an application, including vendor-specific AVPs. Please
+ refer to Section 11.1.1 for details.
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 21]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+2.4. Application Identifiers
+
+ Each Diameter application MUST have an IANA assigned Application
+ Identifier (see Section 11.3). The base protocol does not require an
+ Application Identifier 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 Identifier, which is used in the message forwarding
+ process.
+
+ The following Application Identifier values are defined:
+
+ Diameter Common Messages 0
+ NASREQ 1 [NASREQ]
+ Mobile-IP 2 [DIAMMIP]
+ Diameter Base Accounting 3
+ Relay 0xffffffff
+
+ Relay and redirect agents MUST advertise the Relay Application
+ 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.
+
+ Diameter relay and proxy agents are responsible for finding an
+ upstream server that supports the application of a particular
+ message. If none can be found, an error message is returned with the
+ Result-Code AVP set to DIAMETER_UNABLE_TO_DELIVER.
+
+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.
+
+ A connection is a transport level connection between two peers, used
+ to send and receive Diameter messages. A session is a logical
+ concept at the application layer, and is shared between an access
+ device and a server, and is identified via the Session-Id AVP
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 22]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ +--------+ +-------+ +--------+
+ | Client | | Relay | | Server |
+ +--------+ +-------+ +--------+
+ <----------> <---------->
+ peer connection A peer connection B
+
+ <----------------------------->
+ User session x
+
+ Figure 1: Diameter connections and sessions
+
+ In the example provided in Figure 1, peer connection A is established
+ between the Client and its local 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.
+
+2.6. Peer Table
+
+ The Diameter Peer Table is used in message forwarding, and referenced
+ by the Realm Routing Table. A Peer Table entry contains the
+ following fields:
+
+ Host identity
+ Following the conventions described for the DiameterIdentity
+ derived AVP data format in Section 4.4. 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
+ values listed in Section 5.6.
+
+ Static or Dynamic
+ Specifies whether a peer entry was statically configured, or
+ dynamically discovered.
+
+ Expiration time
+ Specifies the time at which dynamically discovered peer table
+ entries are to be either refreshed, or expired.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 23]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ TLS Enabled
+ Specifies whether TLS is to be used when communicating with the
+ peer.
+
+ Additional security information, when needed (e.g., keys,
+ certificates)
+
+2.7. Realm-Based Routing Table
+
+ All Realm-Based routing lookups are performed against what is
+ commonly known as the Realm Routing Table (see Section 12). A Realm
+ Routing Table Entry contains the following fields:
+
+ Realm Name
+ This is the field that is typically 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 a vendor id and an application id.
+ For all IETF standards track Diameter applications, the vendor id
+ is zero. A route entry can have a different destination based on
+ the application identification AVP of the message. 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 resolve to a route entry with
+ the Local Action set to Local can be satisfied locally, and do
+ not need to be routed to another server.
+
+ 2. RELAY - All Diameter messages that fall within this category
+ MUST be routed to a next hop server, without modifying any
+ non-routing AVPs. See Section 6.1.8 for relaying guidelines
+
+ 3. PROXY - All Diameter messages that fall within this category
+ MUST be routed to a next hop server. The local server MAY
+ apply its local policies to the message by including new AVPs
+ to the message prior to routing. See Section 6.1.8 for
+ proxying guidelines.
+
+ 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.7
+ for redirect guidelines.
+
+
+
+Calhoun, et al. Standards Track [Page 24]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Server Identifier
+ One or more servers the message is to be routed to. 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 Action
+ field is set to REDIRECT, this field contains the identity of one
+ or more servers the message should be redirected to.
+
+ Static or Dynamic
+ Specifies whether a route entry was statically configured, or
+ dynamically discovered.
+
+ Expiration time
+ Specifies the time which a dynamically discovered route table
+ entry expires.
+
+ It is important to note that Diameter agents MUST support at least
+ 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 MUST NOT reorder
+ AVPs, 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 Identifier (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.
+
+2.8. Role of Diameter Agents
+
+ In addition to client 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
+ reasons:
+
+ - They can distribute administration of systems to a configurable
+ grouping, including the maintenance of security associations.
+
+ - 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.
+
+ - They can do value-added processing to the requests or responses.
+
+
+
+Calhoun, et al. Standards Track [Page 25]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ - They can be used for load balancing.
+
+ - A complex network will have multiple authentication sources, they
+ can sort requests and forward towards the correct target.
+
+ 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
+ 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
+ answer. A stateless agent is one that only maintains transaction
+ state.
+
+ The Proxy-Info AVP allows stateless agents to add local state to a
+ Diameter request, with the guarantee that the same state will be
+ present in the answer. However, the protocol's failover procedures
+ require that agents maintain a copy of pending requests.
+
+ 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. Each
+ authorized session has an expiration, which is communicated by
+ Diameter servers via the Session-Timeout AVP.
+
+ Maintaining session state MAY be useful in certain applications, such
+ as:
+
+ - Protocol translation (e.g., RADIUS <-> Diameter)
+
+ - Limiting resources authorized to a particular user
+
+ - Per user or 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
+ 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
+ known as the Realm Routing Table, as is defined further in Section
+ 2.7.
+
+
+
+Calhoun, et al. Standards Track [Page 26]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Relays MAY 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.
+
+ Relays modify Diameter messages by inserting and removing routing
+ information, but do not modify any other portion of a message.
+ Relays SHOULD NOT maintain session state but MUST maintain
+ transaction state.
+
+ +------+ ---------> +------+ ---------> +------+
+ | | 1. Request | | 2. Request | |
+ | NAS | | DRL | | HMS |
+ | | 4. Answer | | 3. Answer | |
+ +------+ <--------- +------+ <--------- +------+
+ example.net example.net example.com
+
+ Figure 2: Relaying of Diameter messages
+
+ The example provided in Figure 2 depicts a request issued from NAS,
+ which is an access device, for the user [email protected]. Prior to
+ issuing the request, 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
+ 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 Identifier.
+
+2.8.2. Proxy Agents
+
+ 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.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 27]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ It is important to note that although proxies MAY provide a value-add
+ function for NASes, they do not allow access devices to use end-to-
+ end security, since modifying messages breaks authentication.
+
+ Proxies MAY 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.
+
+ Proxies that wish to limit resources MUST maintain session state.
+ All proxies MUST maintain transaction state.
+
+ Since enforcing policies requires an understanding of the service
+ being provided, Proxies MUST only advertise the Diameter applications
+ they support.
+
+2.8.3. Redirect Agents
+
+ Redirect agents are useful in scenarios where the Diameter routing
+ configuration needs to be centralized. An example is a redirect
+ agent that provides services to all members of a consortium, but does
+ not wish to be burdened with relaying all messages between realms.
+ This scenario is advantageous since it does not require that the
+ consortium provide routing updates to its members when changes are
+ made to a member's infrastructure.
+
+ Since redirect agents do not relay messages, and only return an
+ answer with the information necessary for Diameter agents to
+ communicate directly, they do not modify messages. Since redirect
+ agents do not receive answer messages, they cannot maintain session
+ state. Further, since redirect agents never relay requests, they are
+ not required to maintain transaction state.
+
+ 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
+ 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.
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 28]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ +------+
+ | |
+ | DRD |
+ | |
+ +------+
+ ^ |
+ 2. Request | | 3. Redirection
+ | | Notification
+ | v
+ +------+ ---------> +------+ ---------> +------+
+ | | 1. Request | | 4. Request | |
+ | NAS | | DRL | | HMS |
+ | | 6. Answer | | 5. Answer | |
+ +------+ <--------- +------+ <--------- +------+
+ example.net example.net example.com
+
+ Figure 3: Redirecting a Diameter Message
+
+ 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.
+
+2.8.4. Translation Agents
+
+ A translation agent is a device that provides translation between two
+ protocols (e.g., RADIUS<->Diameter, TACACS+<->Diameter). Translation
+ agents are likely to be used as aggregation servers to communicate
+ with a Diameter infrastructure, while allowing for the embedded
+ systems to be migrated at a slower pace.
+
+ Given that the Diameter protocol introduces the concept of long-lived
+ authorized sessions, translation agents MUST be session stateful and
+ MUST maintain transaction state.
+
+ Translation of messages can only occur if the agent recognizes the
+ application of a particular request, and therefore translation agents
+ MUST only advertise their locally supported applications.
+
+ +------+ ---------> +------+ ---------> +------+
+ | | RADIUS Request | | Diameter Request | |
+ | NAS | | TLA | | HMS |
+ | | RADIUS Answer | | Diameter Answer | |
+ +------+ <--------- +------+ <--------- +------+
+ example.net example.net example.com
+
+ Figure 4: Translation of RADIUS to Diameter
+
+
+
+
+Calhoun, et al. Standards Track [Page 29]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+2.9. End-to-End Security Framework
+
+ End-to-end security services include confidentiality and message
+ origin authentication. These services are provided by supporting AVP
+ integrity and confidentiality between two peers, communicating
+ through agents.
+
+ End-to-end security is provided via the End-to-End security
+ extension, described in [AAACMS]. The circumstances requiring the
+ use of end-to-end security are determined by policy on each of the
+ peers. Security policies, which are not the subject of
+ standardization, may be applied by next hop Diameter peer or by
+ destination realm. For example, where TLS or IPsec transmission-
+ level security is sufficient, there may be no need for end-to-end
+ security.
+
+ End-to-end security policies include:
+
+ - Never use end-to-end security.
+
+ - Use end-to-end security on messages containing sensitive AVPs.
+ Which AVPs are sensitive is determined by service provider policy.
+ AVPs containing keys and passwords should be considered sensitive.
+ Accounting AVPs may be considered sensitive. Any AVP for which
+ the P bit may be set or which may be encrypted may be considered
+ sensitive.
+
+ - Always use end-to-end security.
+
+ It is strongly RECOMMENDED that all Diameter implementations support
+ end-to-end security.
+
+2.10. Diameter Path Authorization
+
+ As noted in Section 2.2, Diameter requires transmission level
+ security to be used on each connection (TLS or IPsec). Therefore,
+ each connection is authenticated, replay and integrity protected and
+ confidential on a per-packet basis.
+
+ 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.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 30]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Prior to bringing up a connection, authorization checks are performed
+ at each connection along the path. Diameter capabilities negotiation
+ (CER/CEA) also MUST be carried out, in order to determine what
+ Diameter applications are supported by each peer. Diameter sessions
+ MUST be routed only through authorized nodes that have advertised
+ support for the Diameter application required by the session.
+
+ As noted in Section 6.1.8, 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.
+
+ The home Diameter server, prior to authorizing a session, MUST check
+ the Route-Record AVPs to make sure that the route traversed by the
+ request is acceptable. For example, administrators within the home
+ 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
+ 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.
+
+ A home realm may also wish to check that each accounting request
+ message corresponds to a Diameter response authorizing the session.
+ Accounting requests without corresponding authorization responses
+ SHOULD be subjected to further scrutiny, as should accounting
+ requests indicating a difference between the requested and provided
+ service.
+
+ Similarly, the local Diameter agent, on receiving a Diameter response
+ authorizing a session, MUST check the Route-Record AVPs to make sure
+ that the route traversed by the response is acceptable. At each
+ step, forwarding of an authorization response is considered evidence
+ of a 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
+ 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
+ accounting requests for the alternate service instead.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 31]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+3. Diameter Header
+
+ A summary of the Diameter header format is shown below. The fields
+ are transmitted in network byte order.
+
+ 0 1 2 3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Version | Message Length |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | command flags | Command-Code |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Application-ID |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Hop-by-Hop Identifier |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | End-to-End Identifier |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | AVPs ...
+ +-+-+-+-+-+-+-+-+-+-+-+-+-
+
+ Version
+ This Version field MUST be set to 1 to indicate Diameter Version
+ 1.
+
+ Message Length
+ The Message Length field is three octets and indicates the length
+ of the Diameter message including the header fields.
+
+ Command Flags
+ The Command Flags field is eight bits. The following bits are
+ assigned:
+
+ 0 1 2 3 4 5 6 7
+ +-+-+-+-+-+-+-+-+
+ |R P E T r r r r|
+ +-+-+-+-+-+-+-+-+
+
+ R(equest) - If set, the message is a request. If cleared, the
+ message is an answer.
+ P(roxiable) - 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. Messages with the 'E'
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 32]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ bit set are commonly referred to as error
+ messages. This bit MUST NOT be set in request
+ messages. See Section 7.2.
+ T(Potentially re-transmitted 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.
+
+ r(eserved) - these flag bits are reserved for future use, and
+ 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).
+
+ 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.
+
+ The application-id in the header MUST be the same as what is
+ contained in any relevant AVPs contained in the message.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 33]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+ 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
+ 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
+ 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
+ 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.
+
+ AVPs
+ AVPs are a method of encapsulating information relevant to the
+ Diameter message. See Section 4 for more information on AVPs.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 34]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+3.1. Command Codes
+
+ 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
+ be taken for a particular message. The following Command Codes are
+ defined in the Diameter base protocol:
+
+ Command-Name Abbrev. Code Reference
+ --------------------------------------------------------
+ Abort-Session-Request ASR 274 8.5.1
+ Abort-Session-Answer ASA 274 8.5.2
+ Accounting-Request ACR 271 9.7.1
+ Accounting-Answer ACA 271 9.7.2
+ Capabilities-Exchange- CER 257 5.3.1
+ Request
+ Capabilities-Exchange- CEA 257 5.3.2
+ Answer
+ Device-Watchdog-Request DWR 280 5.5.1
+ Device-Watchdog-Answer DWA 280 5.5.2
+ Disconnect-Peer-Request DPR 282 5.4.1
+ Disconnect-Peer-Answer DPA 282 5.4.2
+ Re-Auth-Request RAR 258 8.3.1
+ Re-Auth-Answer RAA 258 8.3.2
+ Session-Termination- STR 275 8.4.1
+ Request
+ Session-Termination- STA 275 8.4.2
+ Answer
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 35]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+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. 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]
+ [ *fixed]
+
+ header = "<" Diameter-Header:" command-id
+ [r-bit] [p-bit] [e-bit] [application-id]">"
+
+ 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.
+
+ 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.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 36]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 37]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ The following is a definition of a fictitious command code:
+
+ Example-Request ::= < "Diameter-Header: 9999999, REQ, PXY >
+ { User-Name }
+ * { 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
+ delimited by a hyphen. A three-letter acronym for both the request
+ and answer is also normally provided.
+
+ An example is a message set used to terminate a session. The command
+ name is Session-Terminate-Request and Session-Terminate-Answer, while
+ 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
+ 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
+ answer, which includes a result code that communicates one of the
+ following:
+
+ - The request was successful
+
+ - The request failed
+
+ - An additional request must be sent to provide information the peer
+ requires prior to returning a successful or failed answer.
+
+ - The receiver could not process the request, but provides
+ information about a Diameter peer that is able to satisfy the
+ request, known as redirect.
+
+ Additional information, encoded within AVPs, MAY also be included in
+ answer messages.
+
+4. Diameter AVPs
+
+ Diameter AVPs carry specific authentication, accounting,
+ authorization, routing and security information as well as
+ configuration details for the request and reply.
+
+ Some AVPs MAY be listed more than once. The effect of such an AVP is
+ specific, and is specified in each case by the AVP description.
+
+
+
+Calhoun, et al. Standards Track [Page 38]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+ boundary is reached. The length of the padding is not reflected in
+ the AVP Length field.
+
+4.1. AVP Header
+
+ The fields in the AVP header MUST be sent in network byte order. The
+ format of the header is:
+
+ 0 1 2 3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | AVP Code |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ |V M P r r r r r| AVP Length |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Vendor-ID (opt) |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Data ...
+ +-+-+-+-+-+-+-+-+
+
+ AVP Code
+ The AVP Code, combined with the Vendor-Id field, identifies the
+ attribute uniquely. AVP numbers 1 through 255 are reserved for
+ backward compatibility with RADIUS, without setting the Vendor-Id
+ field. AVP numbers 256 and above are used for Diameter, which are
+ allocated by IANA (see Section 11.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 indicates the need for
+ encryption for end-to-end security.
+
+ The 'M' Bit, known as the Mandatory bit, indicates whether support
+ of the AVP is required. If an AVP with the 'M' bit set is
+ received by a Diameter client, server, proxy, or translation agent
+ and either the AVP or its value is unrecognized, the message MUST
+ be rejected. Diameter Relay and redirect agents MUST NOT reject
+ messages with unrecognized AVPs.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 39]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ The 'M' bit MUST be set according to the rules defined for the AVP
+ containing it. In order to preserve interoperability, a Diameter
+ implementation MUST be able to exclude from a Diameter message any
+ Mandatory AVP which is neither defined in the base Diameter
+ protocol nor in any of the Diameter Application specifications
+ governing the message in which it appears. It MAY do this in one
+ of the following ways:
+
+ 1) If a message is rejected because it contains a Mandatory AVP
+ which is neither defined in the base Diameter standard nor in
+ any of the Diameter Application specifications governing the
+ message in which it appears, the implementation may resend the
+ message without the AVP, possibly inserting additional standard
+ AVPs instead.
+
+ 2) A configuration option may be provided on a system wide, per
+ peer, or per realm basis that would allow/prevent particular
+ Mandatory AVPs to be sent. Thus an administrator could change
+ the configuration to avoid interoperability problems.
+
+ Diameter implementations are required to support all Mandatory
+ AVPs which are allowed by the message's formal syntax and defined
+ either in the base Diameter standard or in one of the Diameter
+ Application specifications governing the message.
+
+ 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.
+
+ 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
+ space.
+
+ Unless otherwise noted, AVPs will have the following default AVP
+ Flags field settings:
+
+ The 'M' bit MUST be set. The 'V' bit MUST NOT be set.
+
+ 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 SHOULD be
+ rejected.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 40]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+4.1.1. Optional Header Elements
+
+ 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"
+ [ASSIGNNO] value, encoded in network byte order. Any vendor
+ 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), nor with future IETF
+ applications.
+
+ 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.
+
+4.2. Basic AVP Data Formats
+
+ The Data field is zero or more octets and contains information
+ specific to the Attribute. The format and length of the Data field
+ is determined by the AVP Code and AVP Length fields. The format of
+ the Data field MUST be one of the following base data types or a data
+ 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.
+
+ Integer32
+ 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
+ MUST be set to 16 (20 if the 'V' bit is enabled).
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 41]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Unsigned32
+ 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).
+
+ Float32
+ This represents floating point values of single precision as
+ described by [FLOATPOINT]. The 32-bit value is transmitted in
+ 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
+ described by [FLOATPOINT]. The 64-bit value is transmitted in
+ 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.
+
+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 AVP Derived Data Formats MUST include
+ them in a section entitled "AVP Derived 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.
+
+ The below AVP Derived Data Formats are commonly used by applications.
+
+ Address
+ The Address format is derived from the OctetString AVP Base
+ Format. It is a discriminated union, representing, for example a
+ 32-bit (IPv4) [IPV4] or 128-bit (IPv6) [IPV6] address, most
+ significant octet first. The first two octets of the Address
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 42]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+ Time
+ The Time format is derived from the OctetString AVP Base 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 [SNTP].
+
+ 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 [SNTP] 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
+ ISO/IEC IS 10646-1 character set, encoded as an OctetString using
+ the UTF-8 [UFT8] transformation format described in RFC 2279.
+
+ Since additional code points are added by amendments to the 10646
+ standard from time to time, implementations MUST be prepared to
+ encounter any code point from 0x00000001 to 0x7fffffff. Byte
+ sequences that do not correspond to the valid encoding of a code
+ point into UTF-8 charset or are outside this range are prohibited.
+
+ The use of control codes SHOULD be avoided. When it is necessary
+ to represent a new line, the control code sequence CR LF SHOULD be
+ used.
+
+ The use of leading or trailing white space SHOULD be avoided.
+
+ For code points not directly supported by user interface hardware
+ or software, an alternative means of entry and display, such as
+ hexadecimal, MAY be provided.
+
+ 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
+ different from the number of characters encoded.
+
+ Note that the AVP Length field of an UTF8String is measured in
+ octets, not characters.
+
+
+
+Calhoun, et al. Standards Track [Page 43]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ DiameterIdentity
+ The DiameterIdentity format is derived from the OctetString AVP
+ Base Format.
+
+ DiameterIdentity = FQDN
+
+ DiameterIdentity value is used to uniquely identify a Diameter
+ node for purposes of duplicate connection and routing loop
+ detection.
+
+ 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.
+
+ DiameterURI
+
+ The DiameterURI MUST follow the Uniform Resource Identifiers (URI)
+ syntax [URI] rules specified below:
+
+ "aaa://" FQDN [ port ] [ transport ] [ protocol ]
+
+ ; No transport security
+
+ "aaas://" FQDN [ port ] [ transport ] [ protocol ]
+
+ ; Transport security used
+
+ FQDN = Fully Qualified Host Name
+
+ port = ":" 1*DIGIT
+
+ ; One of the ports used to listen for
+ ; incoming connections.
+ ; If absent,
+ ; the default Diameter port (3868) is
+ ; assumed.
+
+ transport = ";transport=" transport-protocol
+
+ ; One of the transports used to listen
+ ; for incoming connections. If absent,
+ ; the default SCTP [SCTP] protocol is
+ ; assumed. UDP MUST NOT be used when
+ ; the aaa-protocol field is set to
+ ; diameter.
+
+
+
+Calhoun, et al. Standards Track [Page 44]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ transport-protocol = ( "tcp" / "sctp" / "udp" )
+
+ protocol = ";protocol=" aaa-protocol
+
+ ; If absent, the default AAA protocol
+ ; is diameter.
+
+ aaa-protocol = ( "diameter" / "radius" / "tacacs+" )
+
+ 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
+
+ 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.
+
+ IPFilterRule
+ The IPFilterRule format is derived from the OctetString AVP Base
+ Format. It uses the ASCII charset. Packets may be filtered based
+ on the following information that is associated with it:
+
+ Direction (in or out)
+ Source and destination IP address (possibly masked)
+ Protocol
+ Source and destination port (lists or ranges)
+ TCP flags
+ IP fragment flag
+ 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.
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 45]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ IPFilterRule filters MUST follow the format:
+
+ action dir proto from src to dst [options]
+
+ action permit - Allow packets that match the rule.
+ deny - Drop packets that match the rule.
+
+ dir "in" is from the terminal, "out" is to the
+ terminal.
+
+ proto An IP protocol specified by number. The "ip"
+ keyword means any protocol will match.
+
+ src and dst <address/mask> [ports]
+
+ 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.
+ ipno/bits An IP number as above with a mask
+ width of the form 1.2.3.4/24. In
+ this case, all IP numbers from
+ 1.2.3.0 to 1.2.3.255 will match.
+ The bit width MUST be valid for the
+ 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
+ packet that was used in describing
+ the IP address. To test for a
+ particular IP version, the bits part
+ can be set to zero. The keyword
+ "any" is 0.0.0.0/0 or the IPv6
+ equivalent. The keyword "assigned"
+ is the address or set of addresses
+ assigned to the terminal. For IPv4,
+ a typical first rule is often "deny
+ in ip! assigned"
+
+ The sense of the match can be inverted by
+ preceding an address with the not modifier (!),
+ causing all other addresses to be matched
+ instead. This does not affect the selection of
+ port numbers.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 46]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ With the TCP, UDP and SCTP protocols, optional
+ ports may be specified as:
+
+ {port/port-port}[,ports[,...]]
+
+ The '-' notation specifies a range of ports
+ (including boundaries).
+
+ Fragmented packets that have a non-zero offset
+ (i.e., not the first fragment) will never match
+ a rule that has one or more port
+ specifications. See the frag option for
+ details on matching fragmented packets.
+
+ options:
+ frag Match if the packet is a fragment and this is not
+ the first fragment of the datagram. frag may not
+ be used in conjunction with either tcpflags or
+ TCP/UDP port specifications.
+
+ 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
+ (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
+ supported TCP options are:
+
+ mss (maximum segment size), window (tcp window
+ advertisement), sack (selective ack), ts (rfc1323
+ timestamp) and cc (rfc1644 t/tcp connection
+ count). The absence of a particular option may
+ be denoted with a '!'.
+
+ established
+ TCP packets only. Match packets that have the RST
+ or ACK bits set.
+
+ setup TCP packets only. Match packets that have the SYN
+ bit set but no ACK bit.
+
+
+
+
+Calhoun, et al. Standards Track [Page 47]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ tcpflags spec
+ TCP packets only. Match if the TCP header
+ 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
+ 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
+ offset. See the frag option for details on
+ matching fragmented packets.
+
+ icmptypes types
+ ICMP packets only. Match if the ICMP type is in
+ the list types. The list may be specified as any
+ combination of ranges or individual types
+ separated by commas. Both the numeric values and
+ the symbolic values listed below can be used. The
+ supported ICMP types are:
+
+ echo reply (0), destination unreachable (3),
+ source quench (4), redirect (5), echo request
+ (8), router advertisement (9), router
+ 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)
+ 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.
+
+ The rule syntax is a modified subset of ipfw(8) from FreeBSD, and the
+ ipfw.c code may provide a useful base for implementations.
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 48]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ QoSFilterRule
+ The QosFilterRule format is derived from the OctetString AVP Base
+ Format. It uses the ASCII charset. Packets may be marked or
+ metered based on the following information that is associated with
+ it:
+
+ Direction (in or out)
+ Source and destination IP address (possibly masked)
+ Protocol
+ Source and destination port (lists or ranges)
+ DSCP values (no mask or range)
+
+ 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 treated as best
+ effort. An access device that is unable to interpret or apply a
+ QoS rule SHOULD NOT terminate the session.
+
+ QoSFilterRule filters MUST follow the format:
+
+ action dir proto from src to dst [options]
+
+ tag - Mark packet with a specific DSCP
+ [DIFFSERV]. The DSCP option MUST be
+ included.
+ meter - Meter traffic. The metering options
+ MUST be included.
+
+ dir The format is as described under IPFilterRule.
+
+ proto The format is as described under
+ IPFilterRule.
+
+ src and dst The format is as described under
+ IPFilterRule.
+
+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.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 49]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ The AVP Code numbering space of all AVPs included in a Grouped AVP is
+ the same as for non-grouped AVPs. Further, if any of the AVPs
+ encapsulated within a Grouped AVP has the 'M' (mandatory) bit set,
+ the Grouped AVP itself MUST also include the 'M' bit set.
+
+ Every Grouped AVP defined MUST include a corresponding grammar, using
+ ABNF [ABNF] (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]
+ [ *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.
+
+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:
+
+ 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".
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 50]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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>
+ 2163bc1d0ad82371f6bc09484133c3f09ad74a0dd5346d54195a7cf0b35
+ 2cabc881839a4fdcfbc1769e2677a4c1fb499284c5f70b48f58503a45c5
+ c2d6943f82d5930f2b7c1da640f476f0e9c9572a50db8ea6e51e1c2c7bd
+ f8bb43dc995144b8dbe297ac739493946803e1cee3e15d9b765008a1b2a
+ cf4ac777c80041d72c01e691cf751dbf86e85f509f3988e5875dc905119
+ 26841f00f0e29a6d1ddc1a842289d440268681e052b30fb638045f7779c
+ 1d873c784f054f688f5001559ecff64865ef975f3e60d2fd7966b8c7f92
+
+ Futuristic-Acct-Record = <binary>
+ fe19da5802acd98b07a5b86cb4d5d03f0314ab9ef1ad0b67111ff3b90a0
+ 57fe29620bf3585fd2dd9fcc38ce62f6cc208c6163c008f4258d1bc88b8
+ 17694a74ccad3ec69269461b14b2e7a4c111fb239e33714da207983f58c
+ 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).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 51]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ This AVP would be encoded as follows:
+
+ 0 1 2 3 4 5 6 7
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 0 | Example AVP Header (AVP Code = 999999), Length = 468 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 8 | Origin-Host AVP Header (AVP Code = 264), Length = 19 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 16 | 'e' | 'x' | 'a' | 'm' | 'p' | 'l' | 'e' | '.' |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 24 | 'c' | 'o' | 'm' |Padding| Session-Id AVP Header |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 32 | (AVP Code = 263), Length = 50 | 'g' | 'r' | 'u' | 'm' |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 64 | 'A' | 'F' | '3' | 'B' | '8' | '1' |Padding|Padding|
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 72 | Session-Id AVP Header (AVP Code = 263), Length = 51 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 80 | 'g' | 'r' | 'u' | 'm' | 'p' | '.' | 'e' | 'x' |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 104 | '0' | 'A' | 'F' | '3' | 'B' | '8' | '2' |Padding|
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 112 | Recovery-Policy Header (AVP Code = 8341), Length = 223 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 120 | 0x21 | 0x63 | 0xbc | 0x1d | 0x0a | 0xd8 | 0x23 | 0x71 |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 320 | 0x2f | 0xd7 | 0x96 | 0x6b | 0x8c | 0x7f | 0x92 |Padding|
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 328 | Futuristic-Acct-Record Header (AVP Code = 15930), Length = 137|
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 336 | 0xfe | 0x19 | 0xda | 0x58 | 0x02 | 0xac | 0xd9 | 0x8b |
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ . . .
+ +-------+-------+-------+-------+-------+-------+-------+-------+
+ 464 | 0x41 |Padding|Padding|Padding|
+ +-------+-------+-------+-------+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 52]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+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 and
+ whether the AVP MAY be encrypted. For the originator of a Diameter
+ message, "Encr" (Encryption) means that if a message containing that
+ AVP is to be sent via a Diameter agent (proxy, redirect or relay)
+ then the message MUST NOT be sent unless there is end-to-end security
+ between the originator and the recipient and integrity /
+ confidentiality protection is offered for this AVP OR the originator
+ has locally trusted configuration that indicates that end-to-end
+ security is not needed. Similarly, for the originator of a Diameter
+ message, a "P" in the "MAY" column means that if a message containing
+ that AVP is to be sent via a Diameter agent (proxy, redirect or
+ relay) then the message MUST NOT be sent unless there is end-to-end
+ security between the originator and the recipient or the originator
+ has locally trusted configuration that indicates that end-to-end
+ security is not needed.
+
+ Due to space constraints, the short form DiamIdent is used to
+ represent DiameterIdentity.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 53]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST| |
+ Attribute Name Code Defined Data Type |MUST| MAY | NOT| NOT|Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ Acct- 85 9.8.2 Unsigned32 | M | P | | V | Y |
+ Interim-Interval | | | | | |
+ Accounting- 483 9.8.7 Enumerated | M | P | | V | Y |
+ Realtime-Required | | | | | |
+ Acct- 50 9.8.5 UTF8String | M | P | | V | Y |
+ Multi-Session-Id | | | | | |
+ Accounting- 485 9.8.3 Unsigned32 | M | P | | V | Y |
+ Record-Number | | | | | |
+ Accounting- 480 9.8.1 Enumerated | M | P | | V | Y |
+ Record-Type | | | | | |
+ Accounting- 44 9.8.4 OctetString| M | P | | V | Y |
+ Session-Id | | | | | |
+ Accounting- 287 9.8.6 Unsigned64 | M | P | | V | Y |
+ Sub-Session-Id | | | | | |
+ Acct- 259 6.9 Unsigned32 | M | P | | V | N |
+ Application-Id | | | | | |
+ Auth- 258 6.8 Unsigned32 | M | P | | V | N |
+ Application-Id | | | | | |
+ Auth-Request- 274 8.7 Enumerated | M | P | | V | N |
+ Type | | | | | |
+ Authorization- 291 8.9 Unsigned32 | M | P | | V | N |
+ Lifetime | | | | | |
+ Auth-Grace- 276 8.10 Unsigned32 | M | P | | V | N |
+ Period | | | | | |
+ Auth-Session- 277 8.11 Enumerated | M | P | | V | N |
+ State | | | | | |
+ Re-Auth-Request- 285 8.12 Enumerated | M | P | | V | N |
+ Type | | | | | |
+ Class 25 8.20 OctetString| M | P | | V | Y |
+ Destination-Host 293 6.5 DiamIdent | M | P | | V | N |
+ Destination- 283 6.6 DiamIdent | M | P | | V | N |
+ Realm | | | | | |
+ Disconnect-Cause 273 5.4.3 Enumerated | M | P | | V | N |
+ E2E-Sequence AVP 300 6.15 Grouped | M | P | | V | Y |
+ Error-Message 281 7.3 UTF8String | | P | | V,M | N |
+ Error-Reporting- 294 7.4 DiamIdent | | P | | V,M | N |
+ Host | | | | | |
+ Event-Timestamp 55 8.21 Time | M | P | | V | N |
+ Experimental- 297 7.6 Grouped | M | P | | V | N |
+ Result | | | | | |
+ -----------------------------------------|----+-----+----+-----|----|
+
+
+
+
+Calhoun, et al. Standards Track [Page 54]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST|MAY |
+ Attribute Name Code Defined Data Type |MUST| MAY | NOT| NOT|Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ Experimental- 298 7.7 Unsigned32 | M | P | | V | N |
+ Result-Code | | | | | |
+ Failed-AVP 279 7.5 Grouped | M | P | | V | N |
+ Firmware- 267 5.3.4 Unsigned32 | | | |P,V,M| N |
+ Revision | | | | | |
+ Host-IP-Address 257 5.3.5 Address | M | P | | V | N |
+ Inband-Security | M | P | | V | N |
+ -Id 299 6.10 Unsigned32 | | | | | |
+ Multi-Round- 272 8.19 Unsigned32 | M | P | | V | Y |
+ Time-Out | | | | | |
+ Origin-Host 264 6.3 DiamIdent | M | P | | V | N |
+ Origin-Realm 296 6.4 DiamIdent | M | P | | V | N |
+ Origin-State-Id 278 8.16 Unsigned32 | M | P | | V | N |
+ Product-Name 269 5.3.7 UTF8String | | | |P,V,M| N |
+ Proxy-Host 280 6.7.3 DiamIdent | M | | | P,V | N |
+ Proxy-Info 284 6.7.2 Grouped | M | | | P,V | N |
+ Proxy-State 33 6.7.4 OctetString| M | | | P,V | N |
+ Redirect-Host 292 6.12 DiamURI | M | P | | V | N |
+ Redirect-Host- 261 6.13 Enumerated | M | P | | V | N |
+ Usage | | | | | |
+ Redirect-Max- 262 6.14 Unsigned32 | M | P | | V | N |
+ Cache-Time | | | | | |
+ Result-Code 268 7.1 Unsigned32 | M | P | | V | N |
+ Route-Record 282 6.7.1 DiamIdent | M | | | P,V | N |
+ Session-Id 263 8.8 UTF8String | M | P | | V | Y |
+ Session-Timeout 27 8.13 Unsigned32 | M | P | | V | N |
+ Session-Binding 270 8.17 Unsigned32 | M | P | | V | Y |
+ Session-Server- 271 8.18 Enumerated | M | P | | V | Y |
+ Failover | | | | | |
+ Supported- 265 5.3.6 Unsigned32 | M | P | | V | N |
+ Vendor-Id | | | | | |
+ Termination- 295 8.15 Enumerated | M | P | | V | N |
+ Cause | | | | | |
+ User-Name 1 8.14 UTF8String | M | P | | V | Y |
+ Vendor-Id 266 5.3.3 Unsigned32 | M | P | | V | N |
+ Vendor-Specific- 260 6.11 Grouped | M | P | | V | N |
+ Application-Id | | | | | |
+ -----------------------------------------|----+-----+----+-----|----|
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 55]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+5. Diameter Peers
+
+ This section describes how Diameter nodes establish connections and
+ communicate with peers.
+
+5.1. Peer Connections
+
+ 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
+ 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
+ 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
+ of active connections exists.
+
+ 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.
+
+ 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
+ assume the role of either primary or secondary.
+
+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
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 56]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ on existing IETF standards. The first option (manual configuration)
+ MUST be supported by all DIAMETER nodes, while the latter two options
+ (SRVLOC and DNS) MAY be supported.
+
+ 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:
+
+ 1. The Diameter implementation consults its list of static (manually)
+ configured Diameter agent locations. These will be used if they
+ exist and respond.
+
+ 2. The Diameter implementation uses SLPv2 [SLP] to discover Diameter
+ services. The Diameter service template [TEMPLATE] is included in
+ Appendix A.
+
+ It is recommended that SLPv2 security be deployed (this requires
+ distributing keys to SLPv2 agents). This is discussed further in
+ Appendix A. SLPv2 security SHOULD be used (requiring distribution
+ of keys to SLPv2 agents) in order to ensure that discovered peers
+ are authorized for their roles. SLPv2 is discussed further in
+ Appendix A.
+
+ 3. 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 in. This could
+ be deduced, for example, from the 'realm' in a NAI that a Diameter
+ implementation needed to perform a Diameter operation on.
+
+ 3.1 The services relevant for the task of transport protocol
+ selection are those with NAPTR service fields with values
+ "AAA+D2x", where x is a letter that corresponds to a transport
+ protocol supported by the domain. This specification defines
+ D2T for TCP and D2S for SCTP. We also establish an IANA
+ registry for NAPTR service name to transport protocol
+ mappings.
+
+ These NAPTR records provide a mapping from a domain, to the
+ SRV record for contacting a server with the specific transport
+ protocol in the NAPTR services field. The resource record
+ will contain an empty regular expression and a replacement
+ value, which is the SRV record for that particular transport
+ protocol. If the server supports multiple transport
+ protocols, there will be multiple NAPTR records, each with a
+ different service value. As per RFC 2915 [NAPTR], the client
+
+
+
+Calhoun, et al. Standards Track [Page 57]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ discards any records whose services fields are not applicable.
+ For the purposes of this specification, several rules are
+ defined.
+
+ 3.2 A client MUST discard any service fields that identify a
+ resolution service whose value is not "D2X", for values of X
+ that indicate transport protocols supported by the client.
+ The NAPTR processing as described in RFC 2915 will result in
+ discovery of the most preferred transport protocol of the
+ server that is supported by the client, as well as an SRV
+ record for the server.
+
+ The domain suffixes in the NAPTR replacement field SHOULD
+ match the domain of the original query.
+
+ 4. If no NAPTR records are found, the requester queries for those
+ address records for the destination address,
+ '_diameter._sctp'.realm or '_diameter._tcp'.realm. Address
+ records include A RR's, AAAA RR's or other similar records, chosen
+ according to the requestor's network protocol capabilities. If
+ the DNS server returns no address records, the requestor gives up.
+
+ If the server is using a site certificate, the domain name in the
+ 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 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 peers are authorized to act in its role.
+ Authentication via IKE or TLS, or validation of DNS RRs via DNSSEC
+ is not sufficient to conclude this. For example, a web server may
+ have obtained a valid TLS 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 or IKE certificates so as to signify
+ Diameter Server authorization.
+
+ 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
+
+
+
+Calhoun, et al. Standards Track [Page 58]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+
+ When two Diameter peers establish a transport connection, they MUST
+ 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 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
+ 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
+ layer connection. Note that receiving a CER or CEA from a peer
+ advertising itself as a Relay (see Section 2.4) MUST be interpreted
+ as having common applications with the peer.
+
+ Similarly, a 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.
+
+ 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.
+ In both cases, the transport connection is closed. If the local
+ policy permits receiving CERs from unknown hosts, a successful CEA
+ MAY be returned. If a CER from an unknown peer is answered with a
+ successful CEA, the lifetime of the peer entry is equal to the
+ lifetime of the transport connection. In case of a transport
+ 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.
+
+ 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
+
+
+
+Calhoun, et al. Standards Track [Page 59]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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).
+
+ 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
+ advertised support for the application (or has advertised the Relay
+ Application Identifier).
+
+5.3.1. Capabilities-Exchange-Request
+
+ 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.
+
+ When Diameter is run over SCTP [SCTP], which allows 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 locally used
+ when transmitting Diameter messages.
+
+ Message Format
+
+ <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 ]
+
+5.3.2. Capabilities-Exchange-Answer
+
+ 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.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 60]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ When Diameter is run over SCTP [SCTP], which allows connections to
+ span multiple interfaces, hence, multiple IP addresses, the
+ Capabilities-Exchange-Answer message MUST contain one Host-IP-Address
+ AVP for each potential IP address that MAY be locally used when
+ transmitting Diameter messages.
+
+ Message Format
+
+ <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 ]
+
+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" [ASSIGNNO]
+ value assigned to the vendor of the Diameter application. In
+ combination with the Supported-Vendor-Id AVP (Section 5.3.6), this
+ MAY be used in order to know which vendor specific attributes may be
+ sent to the peer. It is also envisioned that the combination of the
+ Vendor-Id, Product-Name (Section 5.3.7) and the Firmware-Revision
+ (Section 5.3.4) AVPs MAY provide very useful debugging information.
+
+ A Vendor-Id value of zero in the CER or CEA messages is reserved and
+ indicates that this field is ignored.
+
+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.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 61]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+5.3.5. Host-IP-Address AVP
+
+ The Host-IP-Address AVP (AVP Code 257) is of type Address and is used
+ to inform a Diameter peer of the sender's IP address. All source
+ addresses that a Diameter node expects to use with SCTP [SCTP] MUST
+ be advertised in the CER and CEA messages by including a Host-IP-
+ Address AVP for each address. This AVP MUST ONLY be used in the CER
+ and CEA messages.
+
+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"
+ [ASSIGNNO] value assigned to a vendor other than the device 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.
+
+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
+ AVP SHOULD remain constant across firmware revisions for the same
+ product.
+
+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
+ 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.
+
+ 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
+
+
+
+
+Calhoun, et al. Standards Track [Page 62]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+5.4.1. Disconnect-Peer-Request
+
+ 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.
+
+ Message Format
+
+ <DPR> ::= < Diameter Header: 282, REQ >
+ { Origin-Host }
+ { Origin-Realm }
+ { Disconnect-Cause }
+
+5.4.2. Disconnect-Peer-Answer
+
+ 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 Format
+
+ <DPA> ::= < Diameter Header: 282 >
+ { Result-Code }
+ { Origin-Host }
+ { Origin-Realm }
+ [ Error-Message ]
+ * [ Failed-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:
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 63]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ REBOOTING 0
+ A scheduled reboot is imminent.
+
+ BUSY 1
+ The peer's internal resources are constrained, and it has
+ determined that the transport connection needs to be closed.
+
+ 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.
+
+5.5. Transport Failure Detection
+
+ Given the nature of the Diameter protocol, it is recommended that
+ transport failures be detected as soon as possible. Detecting such
+ failures will minimize the occurrence of messages sent to unavailable
+ agents, resulting in unnecessary delays, and will provide better
+ failover performance. The Device-Watchdog-Request and Device-
+ Watchdog-Answer messages, defined in this section, are used to pro-
+ actively detect transport failures.
+
+5.5.1. Device-Watchdog-Request
+
+ 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
+ to an alternate peer.
+
+ Message Format
+
+ <DWR> ::= < Diameter Header: 280, REQ >
+ { Origin-Host }
+ { Origin-Realm }
+ [ Origin-State-Id ]
+
+5.5.2. Device-Watchdog-Answer
+
+ 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.
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 64]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Message Format
+
+ <DWA> ::= < Diameter Header: 280 >
+ { Result-Code }
+ { Origin-Host }
+ { Origin-Realm }
+ [ Error-Message ]
+ * [ Failed-AVP ]
+ [ Original-State-Id ]
+
+5.5.3. Transport Failure Algorithm
+
+ The transport failure algorithm is defined in [AAATRANS]. All
+ Diameter implementations MUST support the algorithm defined in the
+ specification in order to be compliant to the Diameter base protocol.
+
+5.5.4. Failover and Failback Procedures
+
+ 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.
+
+ In order for a Diameter node to perform failover procedures, it is
+ necessary for the node to maintain a pending message queue for a
+ given peer. When an answer message is received, the corresponding
+ 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.
+
+ 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
+ field in the Diameter header along with the Origin-Host AVP MUST be
+ used to identify duplicate messages.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 65]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ As described in Section 2.1, a connection request should be
+ periodically attempted with the failed peer in order to re-establish
+ 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.
+
+5.6. Peer State Machine
+
+ This section contains a finite state machine that MUST be observed by
+ all Diameter implementations. Each Diameter node MUST follow the
+ state machine described below when communicating with each peer.
+ Multiple actions are separated by commas, and may continue on
+ succeeding lines, as space requires. Similarly, state and next state
+ may also span multiple lines, as space requires.
+
+ This state machine is closely coupled with the state machine
+ described in [AAATRANS], which is used to open, close, failover,
+ probe, and reopen transport connections. Note in particular that
+ [AAATRANS] 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 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.
+
+ A CER message is always sent on the initiating connection immediately
+ after the connection request is successfully completed. In the case
+ of an election, one of the two connections will shut down. The
+ responder connection will survive if the Origin-Host of the local
+ Diameter entity is higher than that of the peer; the initiator
+ connection will survive if the peer's Origin-Host is higher. All
+ subsequent messages are sent on the surviving connection. Note that
+ the results of an election on one peer are guaranteed to be the
+ inverse of the results on the other.
+
+ For TLS usage, a TLS handshake will begin when both ends are in the
+ open state. If the TLS handshake is successful, all further messages
+ will be sent via TLS. If the handshake fails, both ends move to the
+ closed state.
+
+ The state machine constrains only the behavior of a Diameter
+ implementation as seen by Diameter peers through events on the wire.
+
+
+
+Calhoun, et al. Standards Track [Page 66]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Any implementation that produces equivalent results is considered
+ compliant.
+
+ state event action next state
+ -----------------------------------------------------------------
+ Closed Start I-Snd-Conn-Req Wait-Conn-Ack
+ R-Conn-CER R-Accept, R-Open
+ Process-CER,
+ R-Snd-CEA
+
+ Wait-Conn-Ack I-Rcv-Conn-Ack I-Snd-CER Wait-I-CEA
+ I-Rcv-Conn-Nack Cleanup Closed
+ R-Conn-CER R-Accept, Wait-Conn-Ack/
+ Process-CER Elect
+ Timeout Error Closed
+
+ Wait-I-CEA I-Rcv-CEA Process-CEA I-Open
+ R-Conn-CER R-Accept, Wait-Returns
+ Process-CER,
+ Elect
+ I-Peer-Disc I-Disc Closed
+ I-Rcv-Non-CEA Error Closed
+ Timeout Error Closed
+
+ Wait-Conn-Ack/ I-Rcv-Conn-Ack I-Snd-CER,Elect Wait-Returns
+ Elect I-Rcv-Conn-Nack R-Snd-CEA R-Open
+ R-Peer-Disc R-Disc Wait-Conn-Ack
+ R-Conn-CER R-Reject Wait-Conn-Ack/
+ Elect
+ Timeout Error Closed
+
+ Wait-Returns Win-Election I-Disc,R-Snd-CEA R-Open
+ I-Peer-Disc I-Disc, R-Open
+ R-Snd-CEA
+ I-Rcv-CEA R-Disc I-Open
+ R-Peer-Disc R-Disc Wait-I-CEA
+ R-Conn-CER R-Reject Wait-Returns
+ Timeout Error Closed
+
+ R-Open Send-Message R-Snd-Message R-Open
+ R-Rcv-Message Process R-Open
+ R-Rcv-DWR Process-DWR, R-Open
+ R-Snd-DWA
+ 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
+
+
+
+Calhoun, et al. Standards Track [Page 67]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ R-Peer-Disc R-Disc Closed
+ R-Rcv-CER R-Snd-CEA R-Open
+ R-Rcv-CEA Process-CEA R-Open
+
+ I-Open Send-Message I-Snd-Message I-Open
+ I-Rcv-Message Process I-Open
+ I-Rcv-DWR Process-DWR, I-Open
+ I-Snd-DWA
+ 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-Peer-Disc I-Disc Closed
+ I-Rcv-CER I-Snd-CEA I-Open
+ I-Rcv-CEA Process-CEA I-Open
+
+ Closing I-Rcv-DPA I-Disc Closed
+ R-Rcv-DPA R-Disc Closed
+ Timeout Error Closed
+ I-Peer-Disc I-Disc Closed
+ R-Peer-Disc R-Disc Closed
+
+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.
+
+ 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 logic that handles incoming connections SHOULD close and discard
+ the connection if any message other than CER arrives, or if an
+ implementation-defined timeout occurs prior to receipt of CER.
+
+ Because handling of incoming connections up to and including receipt
+ of 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.
+
+
+
+
+Calhoun, et al. Standards Track [Page 68]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+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
+ connections.
+
+ Start The Diameter application has signaled that a
+ connection should be initiated with the peer.
+
+ R-Conn-CER An acknowledgement is received stating that the
+ transport connection has been established, and the
+ associated CER has arrived.
+
+ Rcv-Conn-Ack A positive acknowledgement is received confirming that
+ the transport connection is established.
+
+ Rcv-Conn-Nack A negative acknowledgement was received stating that
+ the transport connection was not established.
+
+ Timeout An application-defined timer has expired while waiting
+ for some event.
+
+ Rcv-CER A CER message from the peer was received.
+
+ Rcv-CEA A CEA message from the peer was received.
+
+ Rcv-Non-CEA A message other than CEA from the peer was received.
+
+ Peer-Disc A disconnection indication from the peer was received.
+
+ Rcv-DPR A DPR message from the peer was received.
+
+ Rcv-DPA A DPA message from the peer was received.
+
+ Win-Election An election was held, and the local node was the
+ winner.
+
+ Send-Message A message is to be sent.
+
+ Rcv-Message A message other than CER, CEA, DPR, DPA, DWR or DWA
+ was received.
+
+ Stop The Diameter application has signaled that a
+ connection should be terminated (e.g., on system
+ shutdown).
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 69]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+5.6.3. Actions
+
+ 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.
+
+ Snd-Conn-Req A transport connection is initiated with the peer.
+
+ Accept The incoming connection associated with the R-Conn-CER
+ is accepted as the responder connection.
+
+ Reject The incoming connection associated with the R-Conn-CER
+ 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
+ local resources are freed.
+
+ Error The transport layer connection is disconnected, either
+ politely or abortively, in response to an error
+ condition. Local resources are freed.
+
+ Process-CEA A received CEA is processed.
+
+ Snd-DPR A DPR message is sent to the peer.
+
+ Snd-DPA A DPA message is sent to the peer.
+
+ Disc The transport layer connection is disconnected, and
+ local resources are freed.
+
+ Elect An election occurs (see Section 5.6.4 for more
+ information).
+
+ Snd-Message A message is sent.
+
+ Snd-DWR A DWR message is sent.
+
+ Snd-DWA A DWA message is sent.
+
+ Process-DWR The DWR message is serviced.
+
+
+
+Calhoun, et al. Standards Track [Page 70]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Process-DWA The DWA message is serviced.
+
+ Process A message is serviced.
+
+5.6.4. The Election Process
+
+ The election is performed on the responder. The responder compares
+ the Origin-Host received in the CER sent by its peer with its own
+ Origin-Host. If the local Diameter entity's Origin-Host is higher
+ than the peer's, a Win-Election event is issued locally.
+
+ The comparison proceeds by considering the shorter OctetString to be
+ padded with zeros so that it length is the same as the length of the
+ longer, then performing an octet-by-octet unsigned comparison with
+ the first octet being most significant. Any remaining octets are
+ assumed to have value 0x80.
+
+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 that is not able to be proxied (such as CER) MUST NOT
+ contain either Destination-Realm or Destination-Host AVPs.
+
+ - 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.
+
+ - 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:
+
+ - Authentication requests that span multiple round trips
+
+ - 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.
+
+
+
+Calhoun, et al. Standards Track [Page 71]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ - 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).
+
+ The Destination-Realm AVP MUST be present if the message is
+ proxiable. Request messages that may be forwarded by Diameter agents
+ (proxies, redirects or relays) MUST also contain an Acct-
+ Application-Id AVP, an Auth-Application-Id AVP or a Vendor-Specific-
+ Application-Id AVP. A message that MUST NOT be forwarded by Diameter
+ agents (proxies, redirects or relays) MUST not include the
+ Destination-Realm in its ABNF. The value of the Destination-Realm
+ AVP MAY be extracted from the User-Name AVP, or other application-
+ specific methods.
+
+ When a message is received, the message is processed in the following
+ order:
+
+ 1. If the message is destined for the local host, the procedures
+ listed in Section 6.1.4 are followed.
+
+ 2. 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.
+
+ 3. The procedures listed in Section 6.1.6 are followed, which is
+ known as Request Routing.
+
+ 4. 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.
+
+ 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.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 72]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+6.1.1. Originating a Request
+
+ When creating a request, in addition to any other procedures
+ described in the application definition for that specific request,
+ the following procedures MUST be followed:
+
+ - the Command-Code is set to the appropriate value
+
+ - the 'R' bit is set
+
+ - the End-to-End Identifier is set to a locally unique value
+
+ - the Origin-Host and Origin-Realm AVPs MUST be set to the
+ appropriate values, used to identify the source of the message
+
+ - the Destination-Host and Destination-Realm AVPs MUST be set to the
+ appropriate values as described in Section 6.1.
+
+ - an Acct-Application-Id AVP, an Auth-Application-Id or a Vendor-
+ Specific-Application-Id AVP must be included if the request is
+ proxiable.
+
+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 MUST
+ be followed:
+
+ - the Hop-by-Hop Identifier should be set to a locally unique value
+
+ - The message should be saved in the list of pending requests.
+
+ Other actions to perform on the message based on the particular role
+ the agent is playing are described in the following sections.
+
+6.1.3. Receiving Requests
+
+ A relay or proxy agent MUST check for forwarding loops when receiving
+ requests. A loop is detected if the server finds its own identity in
+ a Route-Record AVP. When such an event occurs, the agent MUST answer
+ with the Result-Code AVP set to DIAMETER_LOOP_DETECTED.
+
+6.1.4. Processing Local Requests
+
+ A request is known to be for local consumption when one of the
+ following conditions occur:
+
+ - The Destination-Host AVP contains the local host's identity,
+
+
+
+Calhoun, et al. Standards Track [Page 73]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ - 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
+
+ - Both the Destination-Host and the Destination-Realm are not
+ present.
+
+ 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.
+
+ 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
+ be forwarded to the peer.
+
+6.1.6. Request Routing
+
+ Diameter request message routing is done via realms and applications.
+ A Diameter message that may be forwarded by Diameter agents (proxies,
+ redirects or relays) MUST include the target realm in the
+ Destination-Realm AVP and one of the application identification AVPs
+ Auth-Application-Id, Acct-Application-Id or Vendor-Specific-
+ Application-Id. The realm MAY be retrieved from the User-Name AVP,
+ which is in the form of a 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
+ and/or application that is not locally supported, the message is
+ routed to the peer configured in the Realm Routing Table (see Section
+ 2.7).
+
+6.1.7. Redirecting requests
+
+ When a redirect agent receives a request whose routing entry is set
+ 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
+ Redirect-Host AVP.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 74]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ +------------------+
+ | Diameter |
+ | Redirect Agent |
+ +------------------+
+ ^ | 2. command + 'E' bit
+ 1. Request | | Result-Code =
+ [email protected] | | DIAMETER_REDIRECT_INDICATION +
+ | | Redirect-Host AVP(s)
+ | v
+ +-------------+ 3. Request +-------------+
+ | example.com |------------->| example.net |
+ | Relay | | Diameter |
+ | Agent |<-------------| Server |
+ +-------------+ 4. Answer +-------------+
+
+ 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,
+ and the request is sent directly to it.
+
+ Multiple Redirect-Host AVPs are allowed. The receiver of the answer
+ message with the 'E' bit set selects exactly one of these hosts as
+ the destination of the redirected message.
+
+6.1.8. 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.
+
+ 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. Proxy-Info AVP has certain
+ security implications and SHOULD contain an embedded HMAC with a
+ node-local key. Alternatively, it MAY simply use local storage to
+ store state information.
+
+ The message is then forwarded to the next hop, as identified in the
+ Realm Routing Table.
+
+
+
+
+Calhoun, et al. Standards Track [Page 75]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Figure 6 provides an example of message routing using the procedures
+ listed in these sections.
+
+ (Origin-Host=nas.mno.net) (Origin-Host=nas.mno.net)
+ (Origin-Realm=mno.net) (Origin-Realm=mno.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)
+
+ Figure 6: Routing of Diameter messages
+
+6.2. Diameter Answer Processing
+
+ When a request is locally processed, the following procedures MUST be
+ applied to create the associated answer, in addition to any
+ additional procedures that MAY be discussed in the Diameter
+ application defining the command:
+
+ - The same Hop-by-Hop identifier in the request is used in the
+ answer.
+
+ - The local host's identity is encoded in the Origin-Host AVP.
+
+ - The Destination-Host and Destination-Realm AVPs MUST NOT be
+ present in the answer message.
+
+ - The Result-Code AVP is added with its value indicating success or
+ failure.
+
+ - If the Session-Id is present in the request, it MUST be included
+ in the answer.
+
+ - Any Proxy-Info AVPs in the request MUST be added to the answer
+ message, in the same order they were present in the request.
+
+ - The 'P' bit is set to the same value as the one in the request.
+
+ - The same End-to-End identifier in the request is used in the
+ answer.
+
+
+
+
+Calhoun, et al. Standards Track [Page 76]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Note that the error messages (see Section 7.3) are also subjected to
+ the above processing rules.
+
+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
+ corresponding message should be removed from the list of pending
+ requests. It SHOULD ignore answers received that do not match a
+ known Hop-by-Hop Identifier.
+
+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 last Proxy-Info AVP in the message is targeted to the local
+ Diameter server, the AVP MUST be removed before the answer is
+ 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
+ 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.
+
+ The agent MUST then send the answer to the host that it received the
+ original request from.
+
+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
+ endpoint that originated the Diameter message. Relay agents MUST NOT
+ modify this AVP.
+
+ The value of the Origin-Host AVP is guaranteed to be unique within a
+ single host.
+
+ Note that the Origin-Host AVP may resolve to more than one address as
+ the Diameter peer may support more than one address.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 77]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible. 6.10
+
+6.4. Origin-Realm AVP
+
+ The Origin-Realm AVP (AVP Code 296) is of type DiameterIdentity.
+ This AVP contains the Realm of the originator of any Diameter message
+ and MUST be present in all messages.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+6.5. Destination-Host AVP
+
+ 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
+ messages.
+
+ 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.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+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.
+ 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.
+
+ Request messages whose ABNF does not list the Destination-Realm AVP
+ as a mandatory AVP are inherently non-routable messages.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+6.7. Routing AVPs
+
+ The AVPs defined in this section are Diameter AVPs used for routing
+ purposes. These AVPs change as Diameter messages are processed by
+ agents, and therefore MUST NOT be protected by end-to-end security.
+
+
+
+Calhoun, et al. Standards Track [Page 78]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+6.7.1. Route-Record AVP
+
+ The Route-Record AVP (AVP Code 282) is of type DiameterIdentity. The
+ identity added in this AVP MUST be the same as the one received in
+ the Origin-Host of the Capabilities Exchange message.
+
+6.7.2. Proxy-Info AVP
+
+ The Proxy-Info AVP (AVP Code 284) is of type Grouped. The Grouped
+ Data field has the following ABNF grammar:
+
+ Proxy-Info ::= < AVP Header: 284 >
+ { Proxy-Host }
+ { Proxy-State }
+ * [ AVP ]
+
+6.7.3. Proxy-Host AVP
+
+ The Proxy-Host AVP (AVP Code 280) is of type DiameterIdentity. This
+ AVP contains the identity of the host that added the Proxy-Info AVP.
+
+6.7.4. Proxy-State AVP
+
+ The Proxy-State AVP (AVP Code 33) is of type OctetString, and
+ contains state local information, and MUST be treated as opaque data.
+
+6.8. Auth-Application-Id AVP
+
+ The Auth-Application-Id AVP (AVP Code 258) is of type Unsigned32 and
+ is used in order to advertise support of the Authentication and
+ Authorization portion of an application (see Section 2.4). The
+ Auth-Application-Id MUST also be present in all Authentication and/or
+ Authorization messages that are defined in a separate Diameter
+ specification and have an Application ID assigned.
+
+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
+ application (see Section 2.4). The Acct-Application-Id MUST also be
+ present in all Accounting messages. Exactly one of the Auth-
+ Application-Id and Acct-Application-Id AVPs MAY be present.
+
+6.10. Inband-Security-Id AVP
+
+ 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.
+
+
+
+Calhoun, et al. Standards Track [Page 79]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Currently, the following values are supported, but there is ample
+ room to add new security Ids.
+
+ 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].
+
+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 of the Auth-Application-Id and
+ Acct-Application-Id AVPs MAY be present.
+
+ This AVP MUST also be present as the first AVP in all experimental
+ commands defined in the vendor-specific application.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+ AVP Format
+
+ <Vendor-Specific-Application-Id> ::= < AVP Header: 260 >
+ 1* [ Vendor-Id ]
+ 0*1{ Auth-Application-Id }
+ 0*1{ Acct-Application-Id }
+
+6.12. Redirect-Host AVP
+
+ One or more of 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.
+
+ Upon receiving the above, the receiving Diameter node SHOULD forward
+ the request directly to one of the hosts identified in these AVPs.
+ The server contained in the selected Redirect-Host AVP SHOULD be used
+ for all messages pertaining to this session.
+
+6.13. Redirect-Host-Usage AVP
+
+ The Redirect-Host-Usage AVP (AVP Code 261) is of type Enumerated.
+ This AVP MAY be present in answer messages whose 'E' bit is set and
+ the Result-Code AVP is set to DIAMETER_REDIRECT_INDICATION.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 80]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ When present, this AVP dictates how the routing entry resulting from
+ the Redirect-Host is to be used. The following values are supported:
+
+ 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 MAY be sent to the host specified in the
+ Redirect-Host AVP.
+
+ ALL_REALM 2
+ All messages destined for the realm requested MAY 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
+ MAY be sent to the host specified in the Redirect-Host AVP.
+
+ ALL_APPLICATION 4
+ All messages for the application requested MAY 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 MAY be sent to the host specified in the Redirect-
+ Host AVP.
+
+ ALL_USER 6
+ All messages for the user requested MAY be sent to the host
+ specified in the Redirect-Host AVP.
+
+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.
+
+ This AVP contains the maximum number of seconds the peer and route
+ table entries, created as a result of the Redirect-Host, will be
+ cached. Note that once a host created due to a redirect indication
+ is no longer reachable, any associated peer and routing table entries
+ MUST be deleted.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 81]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+6.15. E2E-Sequence AVP
+
+ The E2E-Sequence AVP (AVP Code 300) provides anti-replay protection
+ for end to end messages and is of type grouped. It contains a random
+ value (an OctetString with a nonce) and counter (an Integer). For
+ each end-to-end peer with which a node communicates (or remembers
+ communicating) a different nonce value MUST be used and the counter
+ is initiated at zero and increases by one each time this AVP is
+ emitted to that peer. This AVP MUST be included in all messages
+ which use end-to-end protection (e.g., CMS signing or encryption).
+
+7. Error Handling
+
+ 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 |----///----+
+ | +---------------------| | v
+ +------+--+ | 2. answer + 'E' set | Relay 2 | +--------+
+ |Diameter |<-+ (Unable to Forward) +---------+ |Diameter|
+ | | | Home |
+ | Relay 1 |--+ +---------+ | Server |
+ +---------+ | 3. Request |Diameter | +--------+
+ +-------------------->| | ^
+ | Relay 3 |-----------+
+ +---------+
+
+ 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
+ detects that it cannot forward the request to the home server, an
+ answer message is returned with the 'E' bit set and the Result-Code
+ AVP set to DIAMETER_UNABLE_TO_DELIVER. Given that this error falls
+
+
+
+
+Calhoun, et al. Standards Track [Page 82]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ within the protocol error category, Relay 1 would take special
+ action, and given the error, attempt to route the message through its
+ alternate Relay 3.
+
+ +---------+ 1. Request +---------+ 2. Request +---------+
+ | Access |------------>|Diameter |------------>|Diameter |
+ | | | | | Home |
+ | Device |<------------| Relay |<------------| Server |
+ +---------+ 4. Answer +---------+ 3. Answer +---------+
+ (Missing AVP) (Missing AVP)
+
+ 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,
+ 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
+ the request.
+
+ 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:
+
+ - 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 containing the
+ offending AVP.
+
+ - An AVP that is received with an unrecognized value causes an
+ answer to be returned with the Result-Code AVP set to
+ DIAMETER_INVALID_AVP_VALUE, with the Failed-AVP AVP containing the
+ AVP causing the error.
+
+ - A command is received with an AVP that is omitted, yet is
+ mandatory according to the command's ABNF. The receiver issues an
+ answer with the Result-Code set to 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.
+
+ 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
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 83]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ (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
+ whether an error occurred. All Diameter answer messages defined in
+ IETF applications 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.4). Diameter provides the
+ following classes of errors, all identified by the thousands digit in
+ the decimal notation:
+
+ - 1xxx (Informational)
+ - 2xxx (Success)
+ - 3xxx (Protocol Errors)
+ - 4xxx (Transient Failures)
+ - 5xxx (Permanent Failure)
+
+ A non-recognized class (one whose first digit is not defined in this
+ section) MUST be handled as a permanent failure.
+
+7.1.1. Informational
+
+ Errors that fall within this category are used to inform the
+ 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
+ inform the access device that the authentication mechanism being
+ used requires multiple round trips, and a subsequent request needs
+ to be issued in order for access to be granted.
+
+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.
+
+
+
+Calhoun, et al. Standards Track [Page 84]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ DIAMETER_LIMITED_SUCCESS 2002
+ When returned, the request was successfully completed, but
+ additional processing is required by the application in order to
+ provide service to the user.
+
+7.1.3. Protocol Errors
+
+ 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 and only these errors MUST
+ only be used in answer messages whose 'E' bit is set.
+
+ DIAMETER_COMMAND_UNSUPPORTED 3001
+ The Request contained a Command-Code that the receiver did not
+ recognize or support. This MUST be used when a Diameter node
+ receives an experimental command that it does not understand.
+
+ DIAMETER_UNABLE_TO_DELIVER 3002
+ This error is given when Diameter can not 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
+ 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
+ to an alternate peer. This error MUST only be used when a
+ specific server is requested, and it cannot provide the requested
+ service.
+
+ DIAMETER_LOOP_DETECTED 3005
+ An agent detected a loop while trying to get the message to the
+ intended recipient. The message MAY be sent to an alternate peer,
+ 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
+ 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.
+
+
+
+Calhoun, et al. Standards Track [Page 85]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+ 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.
+
+ 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
+ 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 again.
+
+ 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.
+
+
+
+
+Calhoun, et al. Standards Track [Page 86]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+ Code definition. If this value is sent in the Result-Code AVP, a
+ Failed-AVP AVP SHOULD be included in the message. The Failed-AVP
+ AVP MUST contain an example of the missing AVP complete with the
+ Vendor-Id if applicable. The value field of the missing AVP
+ should be of correct minimum length and contain zeroes.
+
+ 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.
+
+ 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. One or more Failed-AVP AVPs MUST be present, containing
+ the AVPs that contradicted each other.
+
+ DIAMETER_AVP_NOT_ALLOWED 5008
+ A message was received with an AVP that MUST NOT be present. The
+ 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
+ the offending AVP that exceeded the maximum number of occurrences
+
+ 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.
+
+
+
+Calhoun, et al. Standards Track [Page 87]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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 an unrecognized bit in the Diameter
+ header is set to one (1).
+
+ DIAMETER_INVALID_AVP_LENGTH 5014
+ The request contained an AVP with an invalid length. A Diameter
+ message indicating this error MUST include the offending AVPs
+ within a Failed-AVP AVP.
+
+ DIAMETER_INVALID_MESSAGE_LENGTH 5015
+ This error is returned when a request is received with an invalid
+ message length.
+
+ DIAMETER_INVALID_AVP_BIT_COMBO 5016
+ 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.
+
+ 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.
+
+7.2. Error Bit
+
+ The 'E' (Error Bit) in the Diameter header is set when the request
+ caused a protocol-related error (see Section 7.1.3). A message with
+ 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:
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 88]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Message Format
+
+ <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 ]
+
+ 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
+ found in the request message.
+
+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
+ Error-Message AVP is not intended to be useful in real-time, and
+ SHOULD NOT be expected to be parsed by network entities.
+
+7.4. Error-Reporting-Host AVP
+
+ The Error-Reporting-Host AVP (AVP Code 294) is of type
+ DiameterIdentity. This AVP contains the identity of the Diameter
+ 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.
+
+7.5. Failed-AVP AVP
+
+ The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
+ 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.
+
+ 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
+ occurrences.
+
+
+
+Calhoun, et al. Standards Track [Page 89]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ A Diameter message MAY 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
+ required length for the omitted AVP will be added.
+
+ AVP Format
+
+ <Failed-AVP> ::= < AVP Header: 279 >
+ 1* {AVP}
+
+7.6. Experimental-Result AVP
+
+ The Experimental-Result AVP (AVP Code 297) is of type Grouped, and
+ indicates whether a particular vendor-specific request was completed
+ successfully or whether an error occurred. Its Data field has the
+ following ABNF grammar:
+
+ AVP Format
+
+ Experimental-Result ::= < AVP Header: 297 >
+ { Vendor-Id }
+ { 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
+ follows. All Diameter answer messages defined in vendor-specific
+ applications MUST include either one Result-Code AVP or one
+ Experimental-Result AVP.
+
+7.7. Experimental-Result-Code AVP
+
+ The Experimental-Result-Code AVP (AVP Code 298) is of type Unsigned32
+ and contains a vendor-assigned value representing the result of
+ processing the request.
+
+ 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
+ values).
+
+8. Diameter User Sessions
+
+ 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.
+
+
+
+
+Calhoun, et al. Standards Track [Page 90]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ When a service makes use of the authentication and/or authorization
+ portion of an application, and a user requests access to the network,
+ the Diameter client issues an auth request to its local server. The
+ 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
+ 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.
+
+ An access device that does not expect to send a re-authorization or a
+ session termination request to the server MAY include the Auth-
+ Session-State AVP with the value set to NO_STATE_MAINTAINED as a hint
+ to the server. If the server accepts the hint, it agrees that since
+ no session termination message will be received once service to the
+ user is terminated, it cannot maintain state for the session. If the
+ answer message from the server contains a different value in the
+ Auth-Session-State AVP (or the default value if the AVP is absent),
+ the access device MUST follow the server's directives. Note that the
+ value NO_STATE_MAINTAINED MUST NOT be set in subsequent re-
+ authorization requests and answers.
+
+ 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 is used to terminate user
+ sessions. These are used to allow servers that maintain state
+ information to free resources.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 91]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+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).
+
+ There are four different authorization session state machines
+ supported in the Diameter base protocol. The first two describe a
+ session in which the server is maintaining session state, indicated
+ by the value of the Auth-Session-State AVP (or its absence). One
+ describes the session from a client perspective, the other from a
+ server perspective. The second two state machines are used when the
+ server does not maintain session state. Here again, one describes
+ the session from a client perspective, the other from a server
+ perspective.
+
+ 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.
+
+ 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
+ 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
+ successfully sent' is the complement of 'Failure to send X'.
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 92]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ The following state machine is observed by a client when state is
+ maintained on the server:
+
+ CLIENT, STATEFUL
+ State Event Action New State
+ -------------------------------------------------------------
+ Idle Client or Device Requests Send Pending
+ access service
+ specific
+ auth req
+
+ Idle ASR Received Send ASA Idle
+ for unknown session with
+ Result-Code
+ = UNKNOWN_
+ SESSION_ID
+
+ 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
+ but service not provided
+
+ Pending Error processing successful Sent STR Discon
+ Service-specific authorization
+ answer
+
+ Pending Failed Service-specific Cleanup Idle
+ authorization answer received
+
+ Open User or client device Send Open
+ requests access to service service
+ specific
+ auth req
+
+ Open Successful Service-specific Provide Open
+ authorization answer received Service
+
+ Open Failed Service-specific Discon. Idle
+ authorization answer user/device
+ received.
+
+ Open Session-Timeout Expires on Send STR Discon
+ Access Device
+
+
+
+
+Calhoun, et al. Standards Track [Page 93]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Open ASR Received, Send ASA Discon
+ client will comply with with
+ request to end the session Result-Code
+ = SUCCESS,
+ Send STR.
+
+ Open ASR Received, Send ASA Open
+ client will not comply with with
+ request to end the session Result-Code
+ != SUCCESS
+
+ Open Authorization-Lifetime + Send STR Discon
+ Auth-Grace-Period expires on
+ access device
+
+ Discon ASR Received Send ASA Discon
+
+ Discon STA Received Discon. Idle
+ user/device
+
+ The following state machine is observed by a server when it is
+ maintaining state for the session:
+
+ SERVER, STATEFUL
+ State Event Action New State
+ -------------------------------------------------------------
+ Idle Service-specific authorization Send Open
+ request received, and successful
+ user is authorized serv.
+ specific answer
+
+ Idle Service-specific authorization Send Idle
+ request received, and failed serv.
+ user is not authorized specific answer
+
+ Open Service-specific authorization Send Open
+ request received, and user successful
+ is authorized serv. specific
+ answer
+
+ Open Service-specific authorization Send Idle
+ request received, and user failed serv.
+ is not authorized specific
+ answer,
+ Cleanup
+
+ Open Home server wants to Send ASR Discon
+ terminate the service
+
+
+
+Calhoun, et al. Standards Track [Page 94]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Open Authorization-Lifetime (and Cleanup Idle
+ Auth-Grace-Period) expires
+ on home server.
+
+ Open Session-Timeout expires on Cleanup Idle
+ home server
+
+ Discon Failure to send ASR Wait, Discon
+ resend ASR
+
+ Discon ASR successfully sent and Cleanup Idle
+ ASA Received with Result-Code
+
+ Not ASA Received None No Change.
+ Discon
+
+ Any STR Received Send STA, Idle
+ Cleanup.
+
+ The following state machine is observed by a client when state is not
+ maintained on the server:
+
+ CLIENT, STATELESS
+ State Event Action New State
+ -------------------------------------------------------------
+ Idle Client or Device Requests Send Pending
+ access service
+ specific
+ auth req
+
+ 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
+ authorization answer
+ received
+
+ Open Session-Timeout Expires on Discon. Idle
+ Access Device user/device
+
+ Open Service to user is terminated Discon. Idle
+ user/device
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 95]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+
+8.2. Accounting Session State Machine
+
+ The following state machines MUST be supported for applications that
+ have an accounting portion or that require only accounting services.
+ The first state machine is to be observed by clients.
+
+ See Section 9.7 for Accounting Command Codes and Section 9.8 for
+ Accounting AVPs.
+
+ The server side in the accounting state machine depends in some cases
+ on the particular application. The Diameter base protocol defines a
+ default state machine that MUST be followed by all applications that
+ have not specified other state machines. This is the second state
+ 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.
+ Implementations of Diameter MAY perform checking, ordering,
+ correlation, fraud detection, and other tasks based on these records.
+ Both base Diameter AVPs as well as application specific AVPs MAY be
+ inspected as a part of these tasks. The tasks can happen either
+ immediately after record reception or in a post-processing phase.
+ However, as these tasks are typically application 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.
+
+ However, the Diameter base protocol defines one optional server side
+ state machine that MAY be followed by applications that require
+ keeping track of the session state at the accounting server. Note
+ 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 connectivity problems are required to cause the serviced
+ user to be disconnected. Otherwise, records produced by the client
+
+
+
+Calhoun, et al. Standards Track [Page 96]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+ 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
+ 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
+ notification DIAMETER_OUT_OF_SPACE, DIAMETER_TOO_BUSY, or
+ DIAMETER_LOOP_DETECTED in the Result-Code AVP of the Accounting
+ Answer command.
+
+ 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
+ to be sent, if the given application has both
+ authentication/authorization and accounting portions.
+
+ 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,
+ respectively.
+
+ CLIENT, ACCOUNTING
+ State Event Action New State
+ -------------------------------------------------------------
+ Idle Client or device requests Send PendingS
+ access accounting
+ start req.
+
+ Idle Client or device requests Send PendingE
+ a one-time service accounting
+ event req
+
+ Idle Records in storage Send PendingB
+ record
+
+
+
+
+Calhoun, et al. Standards Track [Page 97]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ PendingS Successful accounting Open
+ start answer received
+
+ PendingS Failure to send and buffer Store Open
+ space available and realtime Start
+ not equal to DELIVER_AND_GRANT Record
+
+ PendingS Failure to send and no buffer Open
+ space available and realtime
+ equal to GRANT_AND_LOSE
+
+ PendingS Failure to send and no buffer Disconnect Idle
+ space available and realtime user/dev
+ not equal to
+ GRANT_AND_LOSE
+
+ PendingS Failed accounting start answer Open
+ received and realtime equal
+ to GRANT_AND_LOSE
+
+ PendingS Failed accounting start answer Disconnect Idle
+ received and realtime not user/dev
+ equal to GRANT_AND_LOSE
+
+ PendingS User service terminated Store PendingS
+ stop
+ record
+
+ Open Interim interval elapses Send PendingI
+ accounting
+ interim
+ record
+ Open User service terminated Send PendingL
+ accounting
+ stop req.
+
+ PendingI Successful accounting interim Open
+ answer received
+
+ PendingI Failure to send and (buffer Store Open
+ space available or old record interim
+ can be overwritten) and record
+ realtime not equal to
+ DELIVER_AND_GRANT
+
+ PendingI Failure to send and no buffer Open
+ space available and realtime
+ equal to GRANT_AND_LOSE
+
+
+
+Calhoun, et al. Standards Track [Page 98]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ PendingI Failure to send and no buffer Disconnect Idle
+ space available and realtime user/dev
+ not equal to GRANT_AND_LOSE
+
+ PendingI Failed accounting interim Open
+ answer received and realtime
+ equal to GRANT_AND_LOSE
+
+ PendingI Failed accounting interim Disconnect Idle
+ answer received and realtime user/dev
+ not equal to GRANT_AND_LOSE
+
+ PendingI User service terminated Store PendingI
+ stop
+ record
+ PendingE Successful accounting Idle
+ event answer received
+
+ PendingE Failure to send and buffer Store Idle
+ space available event
+ record
+
+ PendingE Failure to send and no buffer Idle
+ space available
+
+ PendingE Failed accounting event answer Idle
+ received
+
+ PendingB Successful accounting answer Delete Idle
+ received record
+
+ PendingB Failure to send Idle
+
+ PendingB Failed accounting answer Delete Idle
+ received record
+
+ PendingL Successful accounting Idle
+ stop answer received
+
+ PendingL Failure to send and buffer Store Idle
+ space available stop
+ record
+
+ PendingL Failure to send and no buffer Idle
+ space available
+
+ PendingL Failed accounting stop answer Idle
+ received
+
+
+
+Calhoun, et al. Standards Track [Page 99]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ SERVER, STATELESS ACCOUNTING
+ State Event Action New State
+ -------------------------------------------------------------
+
+ Idle Accounting start request Send Idle
+ received, and successfully accounting
+ processed. start
+ answer
+
+ Idle Accounting event request Send Idle
+ received, and successfully accounting
+ processed. event
+ answer
+
+ Idle Interim record received, Send Idle
+ and successfully processed. accounting
+ interim
+ answer
+
+ Idle Accounting stop request Send Idle
+ received, and successfully accounting
+ processed stop answer
+
+ Idle Accounting request received, Send Idle
+ no space left to store accounting
+ records answer,
+ Result-Code
+ = OUT_OF_
+ SPACE
+
+ SERVER, STATEFUL ACCOUNTING
+ State Event Action New State
+ -------------------------------------------------------------
+
+ Idle Accounting start request Send Open
+ received, and successfully accounting
+ processed. start
+ answer,
+ Start Ts
+
+ Idle Accounting event request Send Idle
+ received, and successfully accounting
+ processed. event
+ answer
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 100]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Idle Accounting request received, Send Idle
+ no space left to store accounting
+ records answer,
+ Result-Code
+ = OUT_OF_
+ SPACE
+
+ Open Interim record received, Send Open
+ and successfully processed. accounting
+ interim
+ answer,
+ Restart Ts
+
+ Open Accounting stop request Send Idle
+ received, and successfully accounting
+ processed stop answer,
+ Stop Ts
+
+ Open Accounting request received, Send Idle
+ no space left to store accounting
+ records answer,
+ Result-Code
+ = OUT_OF_
+ SPACE,
+ Stop Ts
+
+ Open Session supervision timer Ts Stop Ts Idle
+ expired
+
+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
+ 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 service-initiated re-auth is
+ supported, since some applications do not allow access devices to
+ prompt the user for re-auth.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 101]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+8.3.1. Re-Auth-Request
+
+ 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
+ user be re-authenticated and/or re-authorized.
+
+ Message Format
+
+ <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 ]
+
+8.3.2. Re-Auth-Answer
+
+ 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.
+
+ A successful RAA message MUST be followed by an application-specific
+ authentication and/or authorization message.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 102]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Message Format
+
+ <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-Host-Cache-Time ]
+ * [ Proxy-Info ]
+ * [ AVP ]
+
+8.4. Session Termination
+
+ It is necessary for a Diameter server that authorized a session, for
+ which it is maintaining state, to be notified when that session is no
+ longer active, both for tracking purposes as well as to allow
+ stateful agents to release any resources that they may have provided
+ for the user's session. For sessions whose state is not being
+ maintained, this section is not used.
+
+ When a user session that required Diameter authorization terminates,
+ the access device that provided the service MUST issue a Session-
+ Termination-Request (STR) message to the Diameter server that
+ authorized the service, to notify it that the session is no longer
+ active. An STR MUST be issued when a user session terminates for any
+ reason, including user logoff, expiration of Session-Timeout,
+ administrative action, termination upon receipt of an Abort-Session-
+ Request (see below), orderly shutdown of the access device, etc.
+
+ The access device also MUST issue an STR for a session that was
+ authorized but never actually started. This could occur, for
+ example, due to a sudden resource shortage in the access device, or
+ because the access device is unwilling to provide the type of service
+ requested in the authorization, or because the access device does not
+ support a mandatory AVP returned in the authorization, etc.
+
+ 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
+ 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
+
+
+
+Calhoun, et al. Standards Track [Page 103]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ NO_STATE_MAINTAINED, a proxy that causes an authorized session not to
+ be started MUST issue an STR to the Diameter server that authorized
+ the session, since the access device has no way of knowing that the
+ session had been authorized.
+
+ 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.
+
+ 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
+ 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.
+
+8.4.1. Session-Termination-Request
+
+ The Session-Termination-Request (STR), indicated by the Command-Code
+ set to 275 and the Command Flags' 'R' bit set, is sent by the access
+ device to inform the Diameter Server that an authenticated and/or
+ authorized session is being terminated.
+
+ Message Format
+
+ <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 ]
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 104]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+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.
+
+ Message Format
+
+ <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 ]
+
+8.5. Aborting a Session
+
+ A Diameter server may request that the access device stop providing
+ service for a particular session by issuing an Abort-Session-Request
+ (ASR).
+
+ For example, the Diameter server that originally authorized the
+ session may be required to cause that session to be stopped for
+ credit or other reasons that were not anticipated when the session
+ was first authorized. On the other hand, an operator may maintain a
+ management server for the purpose of issuing ASRs to administratively
+ remove users from the network.
+
+ An access device that receives an ASR with Session-ID equal to a
+ currently active session MAY stop the session. Whether the access
+
+
+
+Calhoun, et al. Standards Track [Page 105]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+ respond with an Abort-Session-Answer, including a Result-Code AVP to
+ indicate what action it took.
+
+ Note that if the access device does stop the session upon receipt of
+ an ASR, it issues an STR to the authorizing server (which may or may
+ not be the agent issuing the ASR) just as it would if the session
+ were terminated for any other reason.
+
+8.5.1. Abort-Session-Request
+
+ 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 server to
+ the access device that is providing session service, to request that
+ the session identified by the Session-Id be stopped.
+
+ Message Format
+
+ <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 ]
+
+8.5.2. Abort-Session-Answer
+
+ 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
+ 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
+ DIAMETER_UNKNOWN_SESSION_ID. If the access device does not stop the
+ session for any other reason, Result-Code is set to
+ DIAMETER_UNABLE_TO_COMPLY.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 106]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Message Format
+
+ <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 ]
+
+8.6. Inferring Session Termination from Origin-State-Id
+
+ Origin-State-Id is used to allow rapid detection of terminated
+ sessions for which no STR would have been issued, due to
+ unanticipated shutdown of an access device.
+
+ By including Origin-State-Id in CER/CEA messages, an access device
+ allows a next-hop server to determine immediately upon connection
+ whether the device has lost its sessions since the last connection.
+
+ By including Origin-State-Id in request messages, an access device
+ also allows a server with which it communicates via proxy to make
+ such a determination. However, a server that is not directly
+ connected with the access device will not discover that the access
+ device has been restarted unless and until it receives a new request
+ from the access device. Thus, use of this mechanism across proxies
+ is opportunistic rather than reliable, but useful nonetheless.
+
+ When a Diameter server receives an Origin-State-Id that is greater
+ than the Origin-State-Id previously received from the same issuer, it
+ may assume that the issuer has lost state since the previous message
+ and that all sessions that were active under the lower Origin-State-
+ Id 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 that were authorized on upstream
+ servers, to allow session state to be cleaned up globally.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 107]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+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.
+ 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
+ are needed by the Diameter server to authenticate the user.
+
+ 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.
+
+ 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
+ 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).
+
+ 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.
+
+ 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):
+
+
+
+Calhoun, et al. Standards Track [Page 108]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ <DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>]
+
+ <high 32 bits> and <low 32 bits> are decimal representations of the
+ high and low 32 bits of a monotonically increasing 64-bit value. The
+ 64-bit value is rendered in two part to simplify formatting by 32-bit
+ processors. At startup, the high 32 bits of the 64-bit value MAY be
+ initialized to the time, and the low 32 bits MAY be initialized to
+ zero. This will for practical purposes 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.
+
+ Example, in which there is no optional value:
+ accesspoint7.acme.com;1876543210;523
+
+ Example, in which there is an optional value:
+ accesspoint7.acme.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 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. Great 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. This is typically used in cases where multiple
+ authentication methods are used, and a successful auth response with
+ this AVP set to zero is used to signal that the next authentication
+ method is to be immediately initiated. 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-auth is expected.
+
+ 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.
+
+
+
+
+Calhoun, et al. Standards Track [Page 109]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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.
+
+ This AVP MAY be provided by the client as a hint of the maximum
+ lifetime 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 client.
+
+8.10. Auth-Grace-Period AVP
+
+ The Auth-Grace-Period AVP (AVP Code 276) is of type Unsigned32 and
+ contains the number of seconds the Diameter server will wait
+ following the expiration of the Authorization-Lifetime AVP before
+ cleaning up resources for the session.
+
+8.11. Auth-Session-State AVP
+
+ The Auth-Session-State AVP (AVP Code 277) is of type Enumerated and
+ specifies whether state is maintained for a particular session. The
+ client MAY include this AVP in requests as a hint to the server, but
+ 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
+ maintained, and the access device MUST issue a session termination
+ 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:
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 110]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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) [RADIUS] is of type Unsigned32
+ and contains the maximum number of seconds of service to be provided
+ to the user before termination of the session. When both the
+ Session-Timeout and the Authorization-Lifetime AVPs are present in an
+ answer message, the former MUST be equal to or greater than the value
+ of the latter.
+
+ 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.9).
+
+ A Session-Timeout AVP MAY be present in a re-authorization answer
+ message, and 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
+ has an unlimited number of seconds before termination.
+
+ 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
+ client.
+
+8.14. User-Name AVP
+
+ The User-Name AVP (AVP Code 1) [RADIUS] is of type UTF8String, which
+ contains the User-Name, in a format consistent with the NAI
+ specification [NAI].
+
+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:
+
+
+
+
+Calhoun, et al. Standards Track [Page 111]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+ The user's session has timed out, and service has been terminated.
+
+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.
+
+ 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
+ Origin-State-Id to the time of startup, or it MAY use an incrementing
+ counter retained in non-volatile memory across restarts.
+
+ The Origin-State-Id, if present, MUST reflect the state of the entity
+ indicated by Origin-Host. If a proxy modifies Origin-Host, it MUST
+ either remove Origin-State-Id or modify it appropriately as well.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 112]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Typically, Origin-State-Id is used by an access device that always
+ starts up with no active sessions; that is, any session active prior
+ to restart will have been lost. By including Origin-State-Id in a
+ 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.
+
+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
+ application-specific re-auth messages for this session MUST be sent
+ to the same authorization server. This AVP MAY also specify that a
+ Session-Termination-Request message for this session MUST be sent to
+ the same authorizing server.
+
+ 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
+ include the Destination-Host AVP. When cleared, the default
+ 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
+ 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
+ include the Destination-Host AVP. When cleared, the default
+ 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,
+ 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
+ value. If present, this AVP MAY inform the Diameter client that if a
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 113]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ re-auth or STR message fails due to a delivery problem, the Diameter
+ client SHOULD issue a subsequent message without the Destination-Host
+ AVP. When absent, the default value is REFUSE_SERVICE.
+
+ 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.
+
+ TRY_AGAIN 1
+ 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
+ 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
+ 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
+ request.
+
+8.20. Class AVP
+
+ The Class AVP (AVP Code 25) is of type OctetString and is used to by
+ Diameter servers to return state information to the access device.
+ When one or more Class AVPs are present in application-specific
+ authorization answer messages, they MUST be present in subsequent
+ re-authorization, session termination and accounting messages. Class
+ AVPs found in a re-authorization answer message override the ones
+ found in any previous authorization answer message. Diameter server
+ implementations SHOULD NOT return Class AVPs that require more than
+ 4096 bytes of storage on the Diameter client. A Diameter client that
+ receives Class AVPs whose size exceeds local available storage MUST
+ terminate the session.
+
+
+
+
+Calhoun, et al. Standards Track [Page 114]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+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.
+
+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 [ACCMGMT] have been built in to the
+ protocol in order minimize loss of accounting data in various fault
+ situations and under different assumptions about the capabilities of
+ the used devices.
+
+9.1. Server Directed Model
+
+ The server directed model means that the device generating the
+ accounting data gets information from either the authorization server
+ (if contacted) or the accounting server regarding the way accounting
+ data shall be forwarded. This information includes accounting record
+ timeliness requirements.
+
+ As discussed in [ACCMGMT], real-time transfer of accounting records
+ 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.
+
+ The authorization server (chain) directs the selection of proper
+ transfer strategy, based on its knowledge of the user and
+ relationships of roaming partnerships. The server (or agents) uses
+ the Acct-Interim-Interval and Accounting-Realtime-Required AVPs to
+ control the operation of the Diameter peer operating as a client.
+ The Acct-Interim-Interval AVP, when present, instructs the Diameter
+ node acting as a client to produce accounting records continuously
+ even during a session. Accounting-Realtime-Required AVP is used to
+ control the behavior of the client when the transfer of accounting
+ records from the Diameter client is delayed or unsuccessful.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 115]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ The Diameter accounting server MAY override the interim interval or
+ the realtime 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.
+
+9.2. Protocol Messages
+
+ A Diameter node that receives a successful authentication and/or
+ authorization messages from the Home AAA server MUST collect
+ accounting information for the session. The Accounting-Request
+ message is used to transmit the accounting information to the Home
+ AAA server, which MUST reply with the Accounting-Answer message to
+ confirm reception. The Accounting-Answer message includes the
+ Result-Code AVP, which MAY indicate that an error was present in the
+ accounting message. A rejected Accounting-Request message MAY cause
+ the user's session to be terminated, depending on the value of the
+ Accounting-Realtime-Required AVP received earlier for the session in
+ question.
+
+ Each Diameter Accounting protocol message MAY be compressed, in order
+ to reduce network bandwidth usage. If IPsec and IKE are used to
+ secure the Diameter session, then IP compression [IPComp] MAY be used
+ and IKE [IKE] MAY be used to negotiate the compression parameters.
+ If TLS is used to secure the Diameter session, then TLS compression
+ [TLS] MAY be used.
+
+9.3. Application document requirements
+
+ Each Diameter application (e.g., NASREQ, MobileIP), MUST 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 this section.
+
+9.4. Fault Resilience
+
+ Diameter Base protocol mechanisms are used to overcome small message
+ loss and network faults of 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
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 116]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+ accounting records over reboots or extended network failures, network
+ 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
+ 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
+ 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.
+
+9.5. Accounting Records
+
+ In all accounting records, the Session-Id AVP MUST be present; the
+ User-Name AVP MUST be present if it is available to the Diameter
+ client. If strong authentication across agents is required, end-to-
+ end security may be used for authentication purposes.
+
+ 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
+ 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.
+
+ If the accounted service is of a measurable length, then the AVP MUST
+ use the values START_RECORD, STOP_RECORD, and possibly,
+ INTERIM_RECORD. If the authorization server has not directed interim
+ accounting to be enabled for the session, two accounting records MUST
+ be generated for each service of type session. When the initial
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 117]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Accounting-Request for a given session is sent, the Accounting-
+ Record-Type AVP MUST be set to the value START_RECORD. When the last
+ Accounting-Request is sent, the value MUST be STOP_RECORD.
+
+ If the authorization server has directed interim accounting to be
+ enabled, the Diameter client MUST produce additional records between
+ the START_RECORD and STOP_RECORD, marked INTERIM_RECORD. The
+ production of these records is directed by Acct-Interim-Interval as
+ well as any re-authentication or re-authorization of the session. The
+ Diameter client MUST overwrite any previous interim accounting
+ records that are locally stored for delivery, if a new record is
+ being generated for the same session. This ensures that only one
+ pending interim record can exist on an access device for any given
+ session.
+
+ A particular value of Accounting-Sub-Session-Id MUST appear only in
+ 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
+ STOP_RECORD. A particular Diameter application specification MUST
+ define the type of sequences that MUST be used.
+
+9.6. Correlation of Accounting Records
+
+ The Diameter protocol's Session-Id AVP, which is globally unique (see
+ Section 8.8), is used during the authorization phase to identify a
+ particular session. Services that do not require any authorization
+ still use the Session-Id AVP to identify sessions. Accounting
+ messages MAY use a different Session-Id from that sent in
+ authorization messages. Specific applications MAY require different
+ a Session-ID for accounting messages.
+
+ However, there are certain applications that require multiple
+ accounting sub-sessions. Such applications would send messages with
+ a constant Session-Id AVP, but a different Accounting-Sub-Session-Id
+ AVP. In these cases, correlation is performed using the Session-Id.
+ It is important to note that receiving a STOP_RECORD with no
+ Accounting-Sub-Session-Id AVP when sub-sessions were originally used
+ in the START_RECORD messages implies that all sub-sessions are
+ terminated.
+
+ Furthermore, there are certain applications where a user receives
+ service from different access devices (e.g., Mobile IPv4), each with
+ their own unique Session-Id. In such cases, the Acct-Multi-Session-
+ Id AVP is used for correlation. During authorization, a server that
+
+
+
+
+Calhoun, et al. Standards Track [Page 118]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ determines that a request is for an existing session SHOULD include
+ the Acct-Multi-Session-Id AVP, which the access device MUST include
+ 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
+ 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
+ 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.
+
+9.7. Accounting Command-Codes
+
+ 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
+ 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.
+
+ One of Acct-Application-Id and Vendor-Specific-Application-Id AVPs
+ MUST be present. If the Vendor-Specific-Application-Id grouped AVP
+ is present, it must have an Acct-Application-Id inside.
+
+ The AVP listed below SHOULD include service specific accounting AVPs,
+ as described in Section 9.3.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 119]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Message Format
+
+ <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 ]
+
+9.7.2. Accounting-Answer
+
+ 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 and includes the usage AVPs only
+ if CMS is in use when sending this command. Note that the inclusion
+ of the usage AVPs when CMS is not being used leads to unnecessarily
+ large answer messages, and can not be used as a server's proof of the
+ receipt of these AVPs in an end-to-end fashion. If the Accounting-
+ Request was protected by end-to-end security, then the corresponding
+ ACA message MUST be protected by end-to-end security.
+
+ Only the target Diameter Server, known as the home Diameter Server,
+ SHOULD respond with the Accounting-Answer command.
+
+ One of Acct-Application-Id and Vendor-Specific-Application-Id AVPs
+ MUST be present. If the Vendor-Specific-Application-Id grouped AVP
+ is present, it must have an Acct-Application-Id inside.
+
+ The AVP listed below SHOULD include service specific accounting AVPs,
+ as described in Section 9.3.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 120]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Message Format
+
+ <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 ]
+
+9.8. Accounting AVPs
+
+ This section contains AVPs that describe accounting usage information
+ related to a specific session.
+
+9.8.1. Accounting-Record-Type AVP
+
+ The Accounting-Record-Type AVP (AVP Code 480) is of type Enumerated
+ 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.
+
+ 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,
+ and contains accounting information that is relevant to the
+ initiation of the session.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 121]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ INTERIM_RECORD 3
+ An Interim Accounting Record contains cumulative accounting
+ information for an existing accounting session. Interim
+ Accounting Records SHOULD be sent every time a re-authentication
+ or re-authorization occurs. Further, additional interim record
+ triggers MAY be defined by application-specific Diameter
+ 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
+
+ The Acct-Interim-Interval AVP (AVP Code 85) is of type Unsigned32 and
+ is sent from the Diameter home authorization server to the Diameter
+ 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
+ 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 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.
+
+ The client MUST ensure that the interim record production times
+ are randomized so that large accounting message storms are not
+ created either among records or around a common service start
+ time.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 122]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+9.8.3. Accounting-Record-Number AVP
+
+ 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
+ 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
+ INTERIM_RECORD, 2 for the second, and so on until the value for
+ STOP_RECORD is one more than for the last INTERIM_RECORD.
+
+9.8.4. Acct-Session-Id AVP
+
+ The Acct-Session-Id AVP (AVP Code 44) is of type OctetString is only
+ used when RADIUS/Diameter translation occurs. This AVP contains the
+ contents of the RADIUS Acct-Session-Id attribute.
+
+9.8.5. Acct-Multi-Session-Id AVP
+
+ 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
+ accounting messages for the given session.
+
+9.8.6. Accounting-Sub-Session-Id AVP
+
+ The Accounting-Sub-Session-Id AVP (AVP Code 287) is of type
+ Unsigned64 and contains the accounting sub-session identifier. The
+ combination of the Session-Id and this AVP MUST be unique per sub-
+ 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.
+
+9.8.7. Accounting-Realtime-Required AVP
+
+ The Accounting-Realtime-Required AVP (AVP Code 483) is of type
+ Enumerated and is sent from the Diameter home authorization server to
+ the Diameter client or in the Accounting-Answer from the accounting
+ server. The client uses information in this AVP to decide what to do
+ if the sending of accounting records to the accounting server has
+ been temporarily prevented due to, for instance, a network problem.
+
+
+
+Calhoun, et al. Standards Track [Page 123]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ DELIVER_AND_GRANT 1
+ The AVP with Value field set to DELIVER_AND_GRANT means that the
+ service MUST only be granted as long as there is a connection to
+ an accounting server. Note that the set of alternative accounting
+ servers are treated as one server in this sense. Having to move
+ 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
+ SHOULD be granted if there is a connection, or as long as records
+ can still be stored as described in Section 9.4.
+
+ 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 can not be delivered or
+ stored.
+
+10. AVP Occurrence Table
+
+ The following tables presents the AVPs defined in this document, and
+ specifies in which Diameter messages they MAY, or MAY NOT be present.
+ Note that AVPs that can only be present within a Grouped AVP are not
+ represented in this table.
+
+ The table uses 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.
+ 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.
+
+10.1. Base Protocol Command AVP Table
+
+ The table in this section is limited to the non-accounting Command
+ Codes defined in this specification.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 124]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ +-----------------------------------------------+
+ | Command-Code |
+ +---+---+---+---+---+---+---+---+---+---+---+---+
+ Attribute Name |CER|CEA|DPR|DPA|DWR|DWA|RAR|RAA|ASR|ASA|STR|STA|
+ --------------------+---+---+---+---+---+---+---+---+---+---+---+---+
+ Acct-Interim- |0 |0 |0 |0 |0 |0 |0-1|0 |0 |0 |0 |0 |
+ Interval | | | | | | | | | | | | |
+ Accounting-Realtime-|0 |0 |0 |0 |0 |0 |0-1|0 |0 |0 |0 |0 |
+ Required | | | | | | | | | | | | |
+ Acct-Application-Id |0+ |0+ |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Auth-Application-Id |0+ |0+ |0 |0 |0 |0 |1 |0 |1 |0 |1 |0 |
+ Auth-Grace-Period |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Auth-Request-Type |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Auth-Session-State |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Authorization- |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Lifetime | | | | | | | | | | | | |
+ 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 |
+ 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+ |
+ 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 |
+ 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|
+ Product-Name |1 |1 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Proxy-Info |0 |0 |0 |0 |0 |0 |0+ |0+ |0+ |0+ |0+ |0+ |
+ Redirect-Host |0 |0 |0 |0 |0 |0 |0 |0+ |0 |0+ |0 |0+ |
+ Redirect-Host-Usage |0 |0 |0 |0 |0 |0 |0 |0-1|0 |0-1|0 |0-1|
+ Redirect-Max-Cache- |0 |0 |0 |0 |0 |0 |0 |0-1|0 |0-1|0 |0-1|
+ Time | | | | | | | | | | | | |
+ Result-Code |0 |1 |0 |1 |0 |1 |0 |1 |0 |0 |0 |1 |
+ Re-Auth-Request-Type|0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |
+ Route-Record |0 |0 |0 |0 |0 |0 |0+ |0 |0+ |0 |0+ |0 |
+ Session-Binding |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Session-Id |0 |0 |0 |0 |0 |0 |1 |1 |1 |1 |1 |1 |
+ Session-Server- |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Failover | | | | | | | | | | | | |
+ Session-Timeout |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Supported-Vendor-Id |0+ |0+ |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Termination-Cause |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |1 |0 |
+ User-Name |0 |0 |0 |0 |0 |0 |0-1|0-1|0-1|0-1|0-1|0-1|
+ Vendor-Id |1 |1 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+
+
+
+Calhoun, et al. Standards Track [Page 125]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Vendor-Specific- |0+ |0+ |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |
+ Application-Id | | | | | | | | | | | | |
+ --------------------+---+---+---+---+---+---+---+---+---+---+---+---+
+
+10.2. Accounting AVP Table
+
+ The table in this section is used to represent which AVPs defined in
+ this document are to be present in the Accounting messages. These
+ AVP occurrence requirements are guidelines, which may be expanded,
+ and/or overridden by application-specific requirements in the
+ Diameter applications documents.
+
+ +-----------+
+ | Command |
+ | Code |
+ +-----+-----+
+ Attribute Name | ACR | ACA |
+ ------------------------------+-----+-----+
+ Acct-Interim-Interval | 0-1 | 0-1 |
+ Acct-Multi-Session-Id | 0-1 | 0-1 |
+ Accounting-Record-Number | 1 | 1 |
+ Accounting-Record-Type | 1 | 1 |
+ Acct-Session-Id | 0-1 | 0-1 |
+ Accounting-Sub-Session-Id | 0-1 | 0-1 |
+ Accounting-Realtime-Required | 0-1 | 0-1 |
+ Acct-Application-Id | 0-1 | 0-1 |
+ Auth-Application-Id | 0 | 0 |
+ Class | 0+ | 0+ |
+ Destination-Host | 0-1 | 0 |
+ Destination-Realm | 1 | 0 |
+ Error-Reporting-Host | 0 | 0+ |
+ Event-Timestamp | 0-1 | 0-1 |
+ Origin-Host | 1 | 1 |
+ Origin-Realm | 1 | 1 |
+ Proxy-Info | 0+ | 0+ |
+ Route-Record | 0+ | 0+ |
+ Result-Code | 0 | 1 |
+ Session-Id | 1 | 1 |
+ Termination-Cause | 0-1 | 0-1 |
+ User-Name | 0-1 | 0-1 |
+ Vendor-Specific-Application-Id| 0-1 | 0-1 |
+ ------------------------------+-----+-----+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 126]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+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 BCP 26 [IANA]. The following
+ policies are used here with the meanings defined in BCP 26: "Private
+ Use", "First Come First Served", "Expert Review", "Specification
+ Required", "IETF Consensus", "Standards Action".
+
+ This section explains the criteria to be used by the IANA for
+ assignment of numbers within namespaces defined within this document.
+
+ Diameter is not intended as a general purpose protocol, and
+ allocations SHOULD NOT be made for purposes unrelated to
+ authentication, authorization or accounting.
+
+ For registration requests where a Designated Expert should be
+ consulted, the responsible IESG area director should appoint the
+ Designated Expert. For Designated Expert with Specification
+ Required, the request is posted to the AAA WG mailing list (or, if it
+ has been disbanded, a successor designated by the Area Director) for
+ comment and review, and MUST include a pointer to a public
+ specification. Before a period of 30 days has passed, the Designated
+ Expert will either approve or deny the registration request and
+ publish a notice of the decision to the AAA WG mailing list or its
+ successor. A denial notice must be justified by an explanation and,
+ in the cases where it is possible, concrete suggestions on how the
+ request can be modified so as to become acceptable.
+
+11.1. AVP Header
+
+ As defined in Section 4, the AVP header contains three fields that
+ requires IANA namespace management; the AVP Code, Vendor-ID and Flags
+ field.
+
+11.1.1. AVP Codes
+
+ The AVP Code namespace is used to identify attributes. There are
+ multiple namespaces. Vendors can have their own AVP Codes namespace
+ which 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 IANA
+ controlled AVP Codes namespace. The AVP Codes and sometimes also
+ possible values in an AVP are controlled and maintained by IANA.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 127]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ AVP Code 0 is not used. AVP Codes 1-255 are managed separately as
+ RADIUS Attribute Types [RADTYPE]. This document defines the AVP
+ Codes 257-274, 276-285, 287, 291-300, 480, 483 and 485-486. See
+ Section 4.5 for the assignment of the namespace in this
+ specification.
+
+ AVPs may be allocated following Designated Expert with Specification
+ Required [IANA]. Release of blocks of AVPs (more than 3 at a time
+ for a given purpose) should require IETF Consensus.
+
+ Note that Diameter defines a mechanism for Vendor-Specific AVPs,
+ where the Vendor-Id field in the AVP header is set to a non-zero
+ value. Vendor-Specific AVPs codes are for Private Use and should be
+ encouraged instead of allocation of global attribute types, for
+ functions specific only to one vendor's implementation of Diameter,
+ where no interoperability is deemed useful. Where a Vendor-Specific
+ AVP is implemented by more than one vendor, allocation of global AVPs
+ should be encouraged instead.
+
+11.1.2. AVP Flags
+
+ There are 8 bits in the AVP Flags field of the AVP header, defined in
+ Section 4. This document assigns bit 0 ('V'endor Specific), bit 1
+ ('M'andatory) and bit 2 ('P'rotected). The remaining bits should
+ only be assigned via a Standards Action [IANA].
+
+11.2. Diameter Header
+
+ As defined in Section 3, the Diameter header contains two fields that
+ require IANA namespace management; Command Code and Command Flags.
+
+11.2.1. Command Codes
+
+ The Command Code namespace is used to identify Diameter commands.
+ The values 0-255 are reserved for RADIUS backward compatibility, and
+ are defined as "RADIUS Packet Type Codes" in [RADTYPE]. Values 256-
+ 16,777,213 are for permanent, standard commands, allocated by IETF
+ Consensus [IANA]. This document defines the Command Codes 257, 258,
+ 271, 274-275, 280 and 282. See Section 3.1 for the assignment of the
+ namespace in this specification.
+
+ 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,
+ as outlined in [IANA-EXP].
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 128]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+11.2.2. Command Flags
+
+ There are eight bits in the Command Flags field of the Diameter
+ header. This document assigns bit 0 ('R'equest), bit 1 ('P'roxy),
+ bit 2 ('E'rror) and bit 3 ('T'). Bits 4 through 7 MUST only be
+ assigned via a Standards Action [IANA].
+
+11.3. Application Identifiers
+
+ As defined in Section 2.4, the Application Identifier is used to
+ identify a specific Diameter Application. There are standards-track
+ application ids and vendor specific application ids.
+
+ IANA [IANA] has assigned the range 0x00000001 to 0x00ffffff for
+ standards-track applications; and 0x01000000 - 0xfffffffe for vendor
+ specific applications, on a first-come, first-served basis. The
+ following values are allocated.
+
+ Diameter Common Messages 0
+ NASREQ 1 [NASREQ]
+ Mobile-IP 2 [DIAMMIP]
+ Diameter Base Accounting 3
+ Relay 0xffffffff
+
+ Assignment of standards-track application IDs are by Designated
+ Expert with Specification Required [IANA].
+
+ Both Application-Id and Acct-Application-Id AVPs use the same
+ Application Identifier space.
+
+ Vendor-Specific Application Identifiers, are for Private Use.
+ Vendor-Specific Application Identifiers are assigned on a First Come,
+ First Served basis by IANA.
+
+11.4. AVP Values
+
+ Certain AVPs in Diameter define a list of values with various
+ meanings. For attributes other than those specified in this section,
+ adding additional values to the list can be done on a First Come,
+ First Served basis by IANA.
+
+11.4.1. Result-Code AVP Values
+
+ As defined in Section 7.1, the Result-Code AVP (AVP Code 268) defines
+ the values 1001, 2001-2002, 3001-3010, 4001-4002 and 5001-5017.
+
+ All remaining values are available for assignment via IETF Consensus
+ [IANA].
+
+
+
+Calhoun, et al. Standards Track [Page 129]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+11.4.2. Accounting-Record-Type AVP Values
+
+ As defined in Section 9.8.1, the Accounting-Record-Type AVP (AVP Code
+ 480) defines the values 1-4. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.3. Termination-Cause AVP Values
+
+ As defined in Section 8.15, the Termination-Cause AVP (AVP Code 295)
+ defines the values 1-8. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.4. Redirect-Host-Usage AVP Values
+
+ As defined in Section 6.13, the Redirect-Host-Usage AVP (AVP Code
+ 261) defines the values 0-5. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.5. Session-Server-Failover AVP Values
+
+ As defined in Section 8.18, the Session-Server-Failover AVP (AVP Code
+ 271) defines the values 0-3. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.6. Session-Binding AVP Values
+
+ As defined in Section 8.17, the Session-Binding AVP (AVP Code 270)
+ defines the bits 1-4. All remaining bits are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.7. Disconnect-Cause AVP Values
+
+ As defined in Section 5.4.3, the Disconnect-Cause AVP (AVP Code 273)
+ defines the values 0-2. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.8. Auth-Request-Type AVP Values
+
+ As defined in Section 8.7, the Auth-Request-Type AVP (AVP Code 274)
+ defines the values 1-3. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.9. Auth-Session-State AVP Values
+
+ As defined in Section 8.11, the Auth-Session-State AVP (AVP Code 277)
+ defines the values 0-1. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+
+
+
+Calhoun, et al. Standards Track [Page 130]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+11.4.10. Re-Auth-Request-Type AVP Values
+
+ As defined in Section 8.12, the Re-Auth-Request-Type AVP (AVP Code
+ 285) defines the values 0-1. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.4.11. Accounting-Realtime-Required AVP Values
+
+ As defined in Section 9.8.7, the Accounting-Realtime-Required AVP
+ (AVP Code 483) defines the values 1-3. All remaining values are
+ available for assignment via IETF Consensus [IANA].
+
+11.4.12. Inband-Security-Id AVP (code 299)
+
+ As defined in Section 6.10, the Inband-Security-Id AVP (AVP Code 299)
+ defines the values 0-1. All remaining values are available for
+ assignment via IETF Consensus [IANA].
+
+11.5. Diameter TCP/SCTP Port Numbers
+
+ The IANA has assigned TCP and SCTP port number 3868 to Diameter.
+
+11.6. NAPTR Service Fields
+
+ The registration in the RFC MUST include the following information:
+
+ Service Field: The service field being registered. An example for a
+ new fictitious transport protocol called NCTP might be "AAA+D2N".
+
+ Protocol: The specific transport protocol associated with that
+ service field. This MUST include the name and acronym for the
+ protocol, along with reference to a document that describes the
+ transport protocol. For example - "New Connectionless Transport
+ Protocol (NCTP), RFC 5766".
+
+ Name and Contact Information: The name, address, email address and
+ telephone number for the person performing the registration.
+
+ The following values have been placed into the registry:
+
+ Services Field Protocol
+ AAA+D2T TCP
+ AAA+D2S SCTP
+
+12. Diameter protocol related configurable parameters
+
+ This section contains the configurable parameters that are found
+ throughout this document:
+
+
+
+Calhoun, et al. Standards Track [Page 131]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ Diameter Peer
+ A Diameter entity MAY communicate with peers that are statically
+ configured. A statically configured Diameter peer would require
+ that either the IP address or the fully qualified domain name
+ (FQDN) be supplied, which would then be used to resolve through
+ DNS.
+
+ Realm Routing Table
+ 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
+ cannot be locally processed.
+
+ Tc timer
+ The Tc timer controls the frequency that transport connection
+ attempts are done to a peer with whom no active transport
+ connection exists. The recommended value is 30 seconds.
+
+13. Security Considerations
+
+ The Diameter base protocol assumes that messages are secured by using
+ either IPSec or TLS. This security mechanism is acceptable in
+ environments where there is no untrusted third party agent. In other
+ situations, end-to-end security is needed.
+
+ Diameter clients, such as Network Access Servers (NASes) and Mobility
+ Agents MUST support IP Security [SECARCH] and MAY support TLS [TLS].
+ Diameter servers MUST support TLS and IPsec. Diameter
+ implementations MUST use transmission-level security of some kind
+ (IPsec or TLS) on each connection.
+
+ If a Diameter connection is not protected by IPsec, then the CER/CEA
+ exchange MUST include an Inband-Security-ID AVP with a value of TLS.
+ For TLS usage, a TLS handshake will begin when both ends are in the
+ open state, after completion of the CER/CEA exchange. If the TLS
+ handshake is successful, all further messages will be sent via TLS.
+ If the handshake fails, both ends move to the closed state.
+
+ It is suggested that IPsec be used primarily at the edges for intra-
+ domain exchanges. For NAS devices without certificate support, pre-
+ shared keys can be used between the NAS and a local AAA proxy.
+
+ For protection of inter-domain exchanges, TLS is recommended. See
+ Sections 13.1 and 13.2 for more details on IPsec and TLS usage.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 132]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+13.1. IPsec Usage
+
+ All Diameter implementations MUST support IPsec ESP [IPsec] in
+ transport mode with non-null encryption and authentication algorithms
+ to provide per-packet authentication, integrity protection and
+ confidentiality, and MUST support the replay protection mechanisms of
+ IPsec.
+
+ Diameter implementations MUST support IKE for peer authentication,
+ negotiation of security associations, and key management, using the
+ IPsec DOI [IPSECDOI]. Diameter implementations MUST support peer
+ authentication using a pre-shared key, and MAY support certificate-
+ based peer authentication using digital signatures. Peer
+ authentication using the public key encryption methods outlined in
+ IKE's Sections 5.2 and 5.3 [IKE] SHOULD NOT be used.
+
+ Conformant implementations MUST support both IKE Main Mode and
+ Aggressive Mode. When pre-shared keys are used for authentication,
+ IKE Aggressive Mode SHOULD be used, and IKE Main Mode SHOULD NOT be
+ used. When digital signatures are used for authentication, either
+ IKE Main Mode or IKE Aggressive Mode MAY be used.
+
+ When digital signatures are used to achieve authentication, an IKE
+ negotiator SHOULD use IKE Certificate Request Payload(s) to specify
+ the certificate authority (or authorities) that are trusted in
+ accordance with its local policy. IKE negotiators SHOULD use
+ pertinent certificate revocation checks before accepting a PKI
+ certificate for use in IKE's authentication procedures.
+
+ The Phase 2 Quick Mode exchanges used to negotiate protection for
+ Diameter connections MUST explicitly carry the Identity Payload
+ fields (IDci and IDcr). The DOI provides for several types of
+ identification data. However, when used in conformant
+ implementations, each ID Payload MUST carry a single IP address and a
+ single non-zero port number, and MUST NOT use the IP Subnet or IP
+ Address Range formats. This allows the Phase 2 security association
+ to correspond to specific TCP and SCTP connections.
+
+ Since IPsec acceleration hardware may only be able to handle a
+ limited number of active IKE Phase 2 SAs, Phase 2 delete messages may
+ be sent for idle SAs, as a means of keeping the number of active
+ Phase 2 SAs to a minimum. The receipt of an IKE Phase 2 delete
+ message SHOULD NOT be interpreted as a reason for tearing down a
+ Diameter connection. Rather, it is preferable to leave the
+ connection up, and if additional traffic is sent on it, to bring up
+ another IKE Phase 2 SA to protect it. This avoids the potential for
+ continually bringing connections up and down.
+
+
+
+
+Calhoun, et al. Standards Track [Page 133]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+13.2. TLS Usage
+
+ A Diameter node that initiates a connection to another Diameter node
+ acts as a TLS client according to [TLS], and a Diameter node that
+ accepts a connection acts as a TLS server. Diameter nodes
+ implementing TLS for security MUST mutually authenticate as part of
+ TLS session establishment. In order to ensure mutual authentication,
+ the Diameter node acting as TLS server must request a certificate
+ from the Diameter node acting as TLS client, and the Diameter node
+ acting as TLS client MUST be prepared to supply a certificate on
+ request.
+
+ Diameter nodes MUST be able to negotiate the following TLS cipher
+ suites:
+
+ TLS_RSA_WITH_RC4_128_MD5
+ TLS_RSA_WITH_RC4_128_SHA
+ TLS_RSA_WITH_3DES_EDE_CBC_SHA
+
+ Diameter nodes SHOULD be able to negotiate the following TLS cipher
+ suite:
+
+ TLS_RSA_WITH_AES_128_CBC_SHA
+
+ Diameter nodes MAY negotiate other TLS cipher suites.
+
+13.3. Peer-to-Peer Considerations
+
+ As with any peer-to-peer protocol, proper configuration of the trust
+ model within a Diameter peer is essential to security. When
+ certificates are used, it is necessary to configure the root
+ certificate authorities trusted by the Diameter peer. These root CAs
+ are likely to be unique to Diameter usage and distinct from the root
+ CAs that might be trusted for other purposes such as Web browsing.
+ In general, it is expected that those root CAs will be configured so
+ as to reflect the business relationships between the organization
+ hosting the Diameter peer and other organizations. As a result, a
+ Diameter peer will typically not be configured to allow connectivity
+ with any arbitrary peer. When certificate authentication Diameter
+ peers may not be known beforehand, and therefore peer discovery may
+ be required.
+
+ Note that IPsec is considerably less flexible than TLS when it comes
+ to configuring root CAs. Since use of Port identifiers is prohibited
+ within IKE Phase 1, within IPsec it is not possible to uniquely
+ configure trusted root CAs for each application individually; the
+ same policy must be used for all applications. This implies, for
+ example, that a root CA trusted for use with Diameter must also be
+
+
+
+Calhoun, et al. Standards Track [Page 134]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ trusted to protect SNMP. These restrictions can be awkward at best.
+ Since TLS supports application-level granularity in certificate
+ policy, TLS SHOULD be used to protect Diameter connections between
+ administrative domains. IPsec is most appropriate for intra-domain
+ usage when pre-shared keys are used as a security mechanism.
+
+ When pre-shared key authentication is used with IPsec to protect
+ Diameter, unique pre-shared keys are configured with Diameter peers,
+ who are identified by their IP address (Main Mode), or possibly their
+ FQDN (Aggressive Mode). As a result, it is necessary for the set of
+ Diameter peers to be known beforehand. Therefore, peer discovery is
+ typically not necessary.
+
+ The following is intended to provide some guidance on the issue.
+
+ It is recommended that a Diameter peer implement the same security
+ mechanism (IPsec or TLS) across all its peer-to-peer connections.
+ Inconsistent use of security mechanisms can result in redundant
+ security mechanisms being used (e.g., TLS over IPsec) or worse,
+ potential security vulnerabilities. When IPsec is used with
+ Diameter, a typical security policy for outbound traffic is "Initiate
+ IPsec, from me to any, destination port Diameter"; for inbound
+ traffic, the policy would be "Require IPsec, from any to me,
+ destination port Diameter".
+
+ This policy causes IPsec to be used whenever a Diameter peer
+ initiates a connection to another Diameter peer, and to be required
+ whenever an inbound Diameter connection occurs. This policy is
+ attractive, since it does not require policy to be set for each peer
+ or dynamically modified each time a new Diameter connection is
+ created; an IPsec SA is automatically created based on a simple
+ static policy. Since IPsec extensions are typically not available to
+ the sockets API on most platforms, and IPsec policy functionality is
+ implementation dependent, use of a simple static policy is the often
+ the simplest route to IPsec-enabling a Diameter implementation.
+
+ One implication of the recommended policy is that if a node is using
+ both TLS and IPsec, there is not a convenient way in which to use
+ either TLS or IPsec, but not both, without reserving an additional
+ port for TLS usage. Since Diameter uses the same port for TLS and
+ non-TLS usage, where the recommended IPsec policy is put in place, a
+ TLS-protected connection will match the IPsec policy, and both IPsec
+ and TLS will be used to protect the Diameter connection. To avoid
+ this, it would be necessary to plumb peer-specific policies either
+ statically or dynamically.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 135]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ If IPsec is used to secure Diameter peer-to-peer connections, IPsec
+ policy SHOULD be set so as to require IPsec protection for inbound
+ connections, and to initiate IPsec protection for outbound
+ connections. This can be accomplished via use of inbound and
+ outbound filter policy.
+
+14. References
+
+14.1. Normative References
+
+ [AAATRANS] Aboba, B. and J. Wood, "Authentication, Authorization
+ and Accounting (AAA) Transport Profile", RFC 3539,
+ June 2003.
+
+ [ABNF] Crocker, D. and P. Overell, "Augmented BNF for Syntax
+ Specifications: ABNF", RFC 2234, November 1997.
+
+ [ASSIGNNO] Reynolds, J., "Assigned Numbers: RFC 1700 is Replaced
+ by an On-line Database", RFC 3232, January 2002.
+
+ [DIFFSERV] Nichols, K., Blake, S., Baker, F. and D. Black,
+ "Definition of the Differentiated Services Field (DS
+ Field) in the IPv4 and IPv6 Headers", RFC 2474,
+ December 1998.
+
+ [DIFFSERVAF] Heinanen, J., Baker, F., Weiss, W. and J. Wroclawski,
+ "Assured Forwarding PHB Group", RFC 2597, June 1999.
+
+ [DIFFSERVEF] Davie, B., Charny, A., Bennet, J., Benson, K., Le
+ Boudec, J., Courtney, W., Davari, S., Firoiu, V. and
+ D. Stiliadis, "An Expedited Forwarding PHB", RFC 3246,
+ March 2002.
+
+ [DNSSRV] Gulbrandsen, A., Vixie, P. and L. Esibov, "A DNS RR
+ for specifying the location of services (DNS SRV)",
+ RFC 2782, February 2000.
+
+ [EAP] Blunk, L. and J. Vollbrecht, "PPP Extensible
+ Authentication Protocol (EAP)", RFC 2284, March 1998.
+
+ [FLOATPOINT] Institute of Electrical and Electronics Engineers,
+ "IEEE Standard for Binary Floating-Point Arithmetic",
+ ANSI/IEEE Standard 754-1985, August 1985.
+
+ [IANA] Narten, T. and H. Alvestrand, "Guidelines for Writing
+ an IANA Considerations Section in RFCs", BCP 26, RFC
+ 2434, October 1998.
+
+
+
+
+Calhoun, et al. Standards Track [Page 136]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ [IANAADFAM] IANA; "Address Family Numbers",
+ http://www.iana.org/assignments/address-family-numbers
+
+ [IANAWEB] IANA, "Number assignment", http://www.iana.org
+
+ [IKE] Harkins, D. and D. Carrel, "The Internet Key Exchange
+ (IKE)", RFC 2409, November 1998.
+
+ [IPComp] Shacham, A., Monsour, R., Pereira, R. and M. Thomas,
+ "IP Payload Compression Protocol (IPComp)", RFC 3173,
+ September 2001.
+
+ [IPSECDOI] Piper, D., "The Internet IP Security Domain of
+ Interpretation for ISAKMP", RFC 2407, November 1998.
+
+ [IPV4] Postel, J., "Internet Protocol", STD 5, RFC 791,
+ September 1981.
+
+ [IPV6] Hinden, R. and S. Deering, "IP Version 6 Addressing
+ Architecture", RFC 2373, July 1998.
+
+ [KEYWORDS] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+ [NAI] Aboba, B. and M. Beadles, "The Network Access
+ Identifier", RFC 2486, January 1999.
+
+ [NAPTR] Mealling, M. and R. Daniel, "The naming authority
+ pointer (NAPTR) DNS resource record," RFC 2915,
+ September 2000.
+
+ [RADTYPE] IANA, "RADIUS Types",
+ http://www.iana.org/assignments/radius-types
+
+ [SCTP] Stewart, R., Xie, Q., Morneault, K., Sharp, C.,
+ Schwarzbauer, H., Taylor, T., Rytina, I., Kalla, M.,
+ Zhang, L. and V. Paxson, "Stream Control Transmission
+ Protocol", RFC 2960, October 2000.
+
+ [SLP] Veizades, J., Guttman, E., Perkins, C. and M. Day,
+ "Service Location Protocol, Version 2", RFC 2165, June
+ 1999.
+
+ [SNTP] Mills, D., "Simple Network Time Protocol (SNTP)
+ Version 4 for IPv4, IPv6 and OSI", RFC 2030, October
+ 1996.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 137]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ [TCP] Postel, J. "Transmission Control Protocol", STD 7, RFC
+ 793, January 1981.
+
+ [TEMPLATE] Guttman, E., Perkins, C. and J. Kempf, "Service
+ Templates and Service: Schemes", RFC 2609, June 1999.
+
+ [TLS] Dierks, T. and C. Allen, "The TLS Protocol Version
+ 1.0", RFC 2246, January 1999.
+
+ [TLSSCTP] Jungmaier, A., Rescorla, E. and M. Tuexen, "Transport
+ Layer Security over Stream Control Transmission
+ Protocol", RFC 3436, December 2002.
+
+ [URI] Berners-Lee, T., Fielding, R. and L. Masinter,
+ "Uniform Resource Identifiers (URI): Generic Syntax",
+ RFC 2396, August 1998.
+
+ [UTF8] Yergeau, F., "UTF-8, a transformation format of ISO
+ 10646", RFC 2279, January 1998.
+
+14.2. Informative References
+
+ [AAACMS] P. Calhoun, W. Bulley, S. Farrell, "Diameter CMS
+ Security Application", Work in Progress.
+
+ [AAAREQ] Aboba, B., Calhoun, P., Glass, S., Hiller, T., McCann,
+ P., Shiino, H., Zorn, G., Dommety, G., Perkins, C.,
+ Patil, B., Mitton, D., Manning, S., Beadles, M.,
+ Walsh, P., Chen, X., Sivalingham, S., Hameed, A.,
+ Munson, M., Jacobs, S., Lim, B., Hirschman, B., Hsu,
+ R., Xu, Y., Campbell, E., Baba, S. and E. Jaques,
+ "Criteria for Evaluating AAA Protocols for Network
+ Access", RFC 2989, November 2000.
+
+ [ACCMGMT] Aboba, B., Arkko, J. and D. Harrington. "Introduction
+ to Accounting Management", RFC 2975, October 2000.
+
+ [CDMA2000] Hiller, T., Walsh, P., Chen, X., Munson, M., Dommety,
+ G., Sivalingham, S., Lim, B., McCann, P., Shiino, H.,
+ Hirschman, B., Manning, S., Hsu, R., Koo, H., Lipford,
+ M., Calhoun, P., Lo, C., Jaques, E., Campbell, E., Xu,
+ Y., Baba, S., Ayaki, T., Seki, T. and A. Hameed,
+ "CDMA2000 Wireless Data Requirements for AAA", RFC
+ 3141, June 2001.
+
+ [DIAMMIP] P. Calhoun, C. Perkins, "Diameter Mobile IP
+ Application", Work in Progress.
+
+
+
+
+Calhoun, et al. Standards Track [Page 138]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ [DYNAUTH] Chiba, M., Dommety, G., Eklund, M., Mitton, D. and B.
+ Aboba, "Dynamic Authorization Extensions to Remote
+ Authentication Dial In User Service (RADIUS)", RFC
+ 3576, July 2003.
+
+ [IANA-EXP] T. Narten, "Assigning Experimental and Testing Numbers
+ Considered Useful", Work in Progress.
+
+ [MIPV4] Perkins, C., "IP Mobility Support for IPv4", RFC 3344,
+ August 2002.
+
+ [MIPREQ] Glass, S., Hiller, T., Jacobs, S. and C. Perkins,
+ "Mobile IP Authentication, Authorization, and
+ Accounting Requirements", RFC 2977, October 2000.
+
+ [NASNG] Mitton, D. and M. Beadles, "Network Access Server
+ Requirements Next Generation (NASREQNG) NAS Model",
+ RFC 2881, July 2000.
+
+ [NASREQ] P. Calhoun, W. Bulley, A. Rubens, J. Haag, "Diameter
+ NASREQ Application", Work in Progress.
+
+ [NASCRIT] Beadles, M. and D. Mitton, "Criteria for Evaluating
+ Network Access Server Protocols", RFC 3169, September
+ 2001.
+
+ [PPP] Simpson, W., "The Point-to-Point Protocol (PPP)", STD
+ 51, RFC 1661, July 1994.
+
+ [PROXYCHAIN] Aboba, B. and J. Vollbrecht, "Proxy Chaining and
+ Policy Implementation in Roaming", RFC 2607, June
+ 1999.
+
+ [RADACCT] Rigney, C., "RADIUS Accounting", RFC 2866, June 2000.
+
+ [RADEXT] Rigney, C., Willats, W. and P. Calhoun, "RADIUS
+ Extensions", RFC 2869, June 2000.
+
+ [RADIUS] Rigney, C., Willens, S., Rubens, A. and W. Simpson,
+ "Remote Authentication Dial In User Service (RADIUS)",
+ RFC 2865, June 2000.
+
+ [ROAMREV] Aboba, B., Lu, J., Alsop, J., Ding, J. and W. Wang,
+ "Review of Roaming Implementations", RFC 2194,
+ September 1997.
+
+ [ROAMCRIT] Aboba, B. and G. Zorn, "Criteria for Evaluating
+ Roaming Protocols", RFC 2477, January 1999.
+
+
+
+Calhoun, et al. Standards Track [Page 139]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ [SECARCH] Kent, S. and R. Atkinson, "Security Architecture for
+ the Internet Protocol", RFC 2401, November 1998.
+
+ [TACACS] Finseth, C., "An Access Control Protocol, Sometimes
+ Called TACACS", RFC 1492, July 1993.
+
+15. Acknowledgements
+
+ 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.
+
+ 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
+ comments as a result of a thorough review of the spec.
+
+ The authors would also like to acknowledge the following people for
+ their contribution in the development of the Diameter protocol:
+
+ Allan C. Rubens, Haseeb Akhtar, William Bulley, Stephen Farrell,
+ 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
+ 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.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 140]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+Appendix A. Diameter Service Template
+
+ The following service template describes the attributes used by
+ Diameter servers to advertise themselves. This simplifies the
+ process of selecting an appropriate server to communicate with. A
+ Diameter client can request specific Diameter servers based on
+ characteristics of the Diameter service desired (for example, an AAA
+ server to use for accounting.)
+
+ Name of submitter: "Erik Guttman" <[email protected]> Language of
+ service template: en
+
+ Security Considerations:
+ Diameter clients and servers use various cryptographic mechanisms
+ to protect communication integrity, confidentiality as well as
+ perform end-point authentication. It would thus be difficult if
+ not impossible for an attacker to advertise itself using SLPv2 and
+ pose as a legitimate Diameter peer without proper preconfigured
+ secrets or cryptographic keys. Still, as Diameter services are
+ vital for network operation it is important to use SLPv2
+ authentication to prevent an attacker from modifying or
+ eliminating service advertisements for legitimate Diameter
+ servers.
+
+ Template text:
+ -------------------------template begins here-----------------------
+ template-type=service:diameter
+
+ template-version=0.0
+
+ template-description=
+ The Diameter protocol is defined by RFC 3588.
+
+ template-url-syntax=
+ url-path= ; The Diameter URL format is described in Section 2.9.
+ ; Example: 'aaa://aaa.example.com:1812;transport=tcp
+ supported-auth-applications= string L M
+ # This attribute lists the Diameter applications supported by the
+ # AAA implementation. The applications currently defined are:
+ # Application Name Defined by
+ # ---------------- -----------------------------------
+ # NASREQ Diameter Network Access Server Application
+ # MobileIP Diameter Mobile IP Application
+ #
+ # Notes:
+ # . Diameter implementations support one or more applications.
+ # . Additional applications may be defined in the future.
+ # An updated service template will be created at that time.
+
+
+
+Calhoun, et al. Standards Track [Page 141]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ #
+ NASREQ,MobileIP
+
+ supported-acct-applications= string L M
+ # This attribute lists the Diameter applications supported by the
+ # AAA implementation. The applications currently defined are:
+ # Application Name Defined by
+ # ---------------- -----------------------------------
+ # NASREQ Diameter Network Access Server Application
+ # MobileIP Diameter Mobile IP Application
+ #
+ # Notes:
+ # . Diameter implementations support one or more applications.
+ # . Additional applications may be defined in the future.
+ # An updated service template will be created at that time.
+ #
+ NASREQ,MobileIP
+
+ supported-transports= string L M
+ SCTP
+ # This attribute lists the supported transports that the Diameter
+ # implementation accepts. Note that a compliant Diameter
+ # implementation MUST support SCTP, though it MAY support other
+ # transports, too.
+ SCTP,TCP
+
+ -------------------------template ends here-----------------------
+
+Appendix B. NAPTR Example
+
+ As an example, consider a client that wishes to resolve aaa:ex.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+D2S" ""
+ _diameter._sctp.example.com IN NAPTR 100 50 "s" "AAA+D2T"
+ "" _aaa._tcp.example.com
+
+ This indicates that the server supports SCTP, and TCP, in that order.
+ If the client supports over SCTP, SCTP will be used, targeted to a
+ host determined by an SRV lookup of _diameter._sctp.ex.com. That
+ lookup would return:
+
+ ;; Priority Weight Port Target
+ IN SRV 0 1 5060 server1.example.com IN SRV 0
+ 2 5060 server2.example.com
+
+
+
+
+Calhoun, et al. Standards Track [Page 142]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+Appendix C. Duplicate Detection
+
+ As described in Section 9.4, accounting record duplicate detection is
+ based on session identifiers. Duplicates can appear for various
+ reasons:
+
+ - 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.
+
+ - 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
+ rebooted.
+
+ - Duplicates received from RADIUS gateways. Since the
+ retransmission behavior of RADIUS is not defined within [RFC2865],
+ the likelihood of duplication will vary according to the
+ implementation.
+
+ - Implementation problems and misconfiguration.
+
+ 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
+ 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
+ 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
+ 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
+ real-time duplicate detection, such as when credit limits are imposed
+ or real-time fraud detection is desired.
+
+
+
+
+Calhoun, et al. Standards Track [Page 143]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+ 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
+ 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.
+
+ As an example, it can be usually be assumed that duplicates appear
+ within a time window of longest recorded network partition or device
+ fault, perhaps a day. So only records within this time window need
+ to be looked at in the backward direction. Secondly, hashing
+ techniques or other schemes, such as the use of the T flag in the
+ received messages, may be used to eliminate the need to do a full
+ search even in this set except for rare cases.
+
+ 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
+ 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
+ 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
+ database with relative assurance that the original records, if
+ sent, have been received and recorded.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 144]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+Appendix D. Intellectual Property Statement
+
+ The IETF takes no position regarding the validity or scope of any
+ intellectual property or other rights that might be claimed to
+ pertain to the implementation or use of the technology described in
+ this document or the extent to which any license under such rights
+ might or might not be available; neither does it represent that it
+ has made any effort to identify any such rights. Information on the
+ IETF's procedures with respect to rights in standards-track and
+ standards-related documentation can be found in BCP-11. Copies of
+ claims of rights made available for publication and any assurances of
+ licenses to be made available, or the result of an attempt made to
+ obtain a general license or permission for the use of such
+ proprietary rights by implementers or users of this specification can
+ be obtained from the IETF Secretariat.
+
+ The IETF invites any interested party to bring to its attention any
+ copyrights, patents or patent applications, or other proprietary
+ rights which may cover technology that may be required to practice
+ this standard. Please address the information to the IETF Executive
+ Director.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 145]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+Authors' Addresses
+
+ Pat R. Calhoun
+ Airespace, Inc.
+ 110 Nortech Parkway
+ San Jose, California, 95134
+ USA
+
+ Phone: +1 408-635-2023
+ Fax: +1 408-635-2020
+
+ John Loughney
+ Nokia Research Center
+ Itamerenkatu 11-13
+ 00180 Helsinki
+ Finland
+
+ Phone: +358 50 483 6242
+
+ Jari Arkko
+ Ericsson
+ 02420 Jorvas
+ Finland
+
+ Phone: +358 40 5079256
+
+ Erik Guttman
+ Sun Microsystems, Inc.
+ Eichhoelzelstr. 7
+ 74915 Waibstadt
+ Germany
+
+ Phone: +49 7263 911 701
+
+ Glen Zorn
+ Cisco Systems, Inc.
+ 500 108th Avenue N.E., Suite 500
+ Bellevue, WA 98004
+ USA
+
+ Phone: +1 425 438 8218
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 146]
+
+RFC 3588 Diameter Based Protocol September 2003
+
+
+Full Copyright Statement
+
+ Copyright (C) The Internet Society (2003). All Rights Reserved.
+
+ This document and translations of it may be copied and furnished to
+ others, and derivative works that comment on or otherwise explain it
+ or assist in its implementation may be prepared, copied, published
+ and distributed, in whole or in part, without restriction of any
+ kind, provided that the above copyright notice and this paragraph are
+ included on all such copies and derivative works. However, this
+ document itself may not be modified in any way, such as by removing
+ the copyright notice or references to the Internet Society or other
+ Internet organizations, except as needed for the purpose of
+ developing Internet standards in which case the procedures for
+ copyrights defined in the Internet Standards process must be
+ followed, or as required to translate it into languages other than
+ English.
+
+ The limited permissions granted above are perpetual and will not be
+ revoked by the Internet Society or its successors or assigns.
+
+ This document and the information contained herein is provided on an
+ "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+ TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
+ BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
+ HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+ MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 147]
+
diff --git a/lib/diameter/doc/standard/rfc4005.txt b/lib/diameter/doc/standard/rfc4005.txt
new file mode 100644
index 0000000000..561508b53b
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc4005.txt
@@ -0,0 +1,4763 @@
+
+
+
+
+
+
+Network Working Group P. Calhoun
+Request for Comments: 4005 G. Zorn
+Category: Standards Track Cisco Systems Inc.
+ D. Spence
+ Consultant
+ D. Mitton
+ Circular Networks
+ August 2005
+
+
+ Diameter Network Access Server Application
+
+Status of This Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The Internet Society (2005).
+
+Abstract
+
+ This document describes the Diameter protocol application used for
+ Authentication, Authorization, and Accounting (AAA) services in the
+ Network Access Server (NAS) environment. When combined with the
+ Diameter Base protocol, Transport Profile, and Extensible
+ Authentication Protocol specifications, this application
+ specification satisfies typical network access services requirements.
+
+ Initial deployments of the Diameter protocol are expected to include
+ legacy systems. Therefore, this application has been carefully
+ designed to ease the burden of protocol conversion between RADIUS and
+ Diameter. This is achieved by including the RADIUS attribute space
+ to eliminate the need to perform many attribute translations.
+
+ The interactions between Diameter applications and RADIUS specified
+ in this document are to be applied to all Diameter applications. In
+ this sense, this document extends the Base Diameter protocol.
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 1]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+Table of Contents
+
+ 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 5
+ 1.1. Terminology . . . . . . . . . . . . . . . . . . . . . . 5
+ 1.2. Requirements Language . . . . . . . . . . . . . . . . . 6
+ 1.3. Advertising Application Support . . . . . . . . . . . . 6
+ 2. NAS Calls, Ports, and Sessions . . . . . . . . . . . . . . . . 6
+ 2.1. Diameter Session Establishment . . . . . . . . . . . . . 7
+ 2.2. Diameter Session Reauthentication or Reauthorization . . 7
+ 2.3. Diameter Session Termination . . . . . . . . . . . . . . 8
+ 3. NAS Messages . . . . . . . . . . . . . . . . . . . . . . . . . 9
+ 3.1. AA-Request (AAR) Command . . . . . . . . . . . . . . . . 9
+ 3.2. AA-Answer (AAA) Command . . . . . . . . . . . . . . . . 11
+ 3.3. Re-Auth-Request (RAR) Command . . . . . . . . . . . . . 13
+ 3.4. Re-Auth-Answer (RAA) Command . . . . . . . . . . . . . . 14
+ 3.5. Session-Termination-Request (STR) Command . . . . . . . 15
+ 3.6. Session-Termination-Answer (STA) Command . . . . . . . . 15
+ 3.7. Abort-Session-Request (ASR) Command . . . . . . . . . . 16
+ 3.8. Abort-Session-Answer (ASA) Command . . . . . . . . . . . 17
+ 3.9. Accounting-Request (ACR) Command . . . . . . . . . . . . 17
+ 3.10. Accounting-Answer (ACA) Command. . . . . . . . . . . . . 19
+ 4. NAS Session AVPs . . . . . . . . . . . . . . . . . . . . . . . 20
+ 4.1. Call and Session Information . . . . . . . . . . . . . . 21
+ 4.2. NAS-Port AVP . . . . . . . . . . . . . . . . . . . . . . 22
+ 4.3. NAS-Port-Id AVP . . . . . . . . . . . . . . . . . . . . 22
+ 4.4. NAS-Port-Type AVP . . . . . . . . . . . . . . . . . . . 22
+ 4.5. Called-Station-Id AVP . . . . . . . . . . . . . . . . . 23
+ 4.6. Calling-Station-Id AVP . . . . . . . . . . . . . . . . . 23
+ 4.7. Connect-Info AVP . . . . . . . . . . . . . . . . . . . . 24
+ 4.8. Originating-Line-Info AVP . . . . . . . . . . . . . . . 24
+ 4.9. Reply-Message AVP . . . . . . . . . . . . . . . . . . . 25
+ 5. NAS Authentication AVPs . . . . . . . . . . . . . . . . . . . 26
+ 5.1. User-Password AVP . . . . . . . . . . . . . . . . . . . 26
+ 5.2. Password-Retry AVP . . . . . . . . . . . . . . . . . . . 27
+ 5.3. Prompt AVP . . . . . . . . . . . . . . . . . . . . . . . 27
+ 5.4. CHAP-Auth AVP . . . . . . . . . . . . . . . . . . . . . 27
+ 5.5. CHAP-Algorithm AVP . . . . . . . . . . . . . . . . . . . 28
+ 5.6. CHAP-Ident AVP . . . . . . . . . . . . . . . . . . . . . 28
+ 5.7. CHAP-Response AVP . . . . . . . . . . . . . . . . . . . 28
+ 5.8. CHAP-Challenge AVP . . . . . . . . . . . . . . . . . . . 28
+ 5.9. ARAP-Password AVP . . . . . . . . . . . . . . . . . . . 28
+ 5.10. ARAP-Challenge-Response AVP. . . . . . . . . . . . . . . 28
+ 5.11. ARAP-Security AVP. . . . . . . . . . . . . . . . . . . . 29
+ 5.12. ARAP-Security-Data AVP . . . . . . . . . . . . . . . . . 29
+ 6. NAS Authorization AVPs . . . . . . . . . . . . . . . . . . . . 29
+ 6.1. Service-Type AVP . . . . . . . . . . . . . . . . . . . . 30
+ 6.2. Callback-Number AVP . . . . . . . . . . . . . . . . . . 32
+ 6.3. Callback-Id AVP . . . . . . . . . . . . . . . . . . . . 32
+
+
+
+Calhoun, et al. Standards Track [Page 2]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ 6.4. Idle-Timeout AVP . . . . . . . . . . . . . . . . . . . . 32
+ 6.5. Port-Limit AVP . . . . . . . . . . . . . . . . . . . . . 32
+ 6.6. NAS-Filter-Rule AVP . . . . . . . . . . . . . . . . . . 32
+ 6.7. Filter-Id AVP . . . . . . . . . . . . . . . . . . . . . 33
+ 6.8. Configuration-Token AVP . . . . . . . . . . . . . . . . 33
+ 6.9. QoS-Filter-Rule AVP . . . . . . . . . . . . . . . . . . 33
+ 6.10. Framed Access Authorization AVPs . . . . . . . . . . . . 35
+ 6.10.1. Framed-Protocol AVP . . . . . . . . . . . . . . 35
+ 6.10.2. Framed-Routing AVP. . . . . . . . . . . . . . . 35
+ 6.10.3. Framed-MTU AVP. . . . . . . . . . . . . . . . . 35
+ 6.10.4. Framed-Compression AVP. . . . . . . . . . . . . 36
+ 6.11. IP Access Authorization AVPs.. . . . . . . . . . . . . . 36
+ 6.11.1. Framed-IP-Address AVP . . . . . . . . . . . . . 36
+ 6.11.2. Framed-IP-Netmask AVP . . . . . . . . . . . . . 36
+ 6.11.3. Framed-Route AVP. . . . . . . . . . . . . . . . 37
+ 6.11.4. Framed-Pool AVP . . . . . . . . . . . . . . . . 37
+ 6.11.5. Framed-Interface-Id AVP . . . . . . . . . . . . 37
+ 6.11.6. Framed-IPv6-Prefix AVP. . . . . . . . . . . . . 38
+ 6.11.7. Framed-IPv6-Route AVP . . . . . . . . . . . . . 38
+ 6.11.8. Framed-IPv6-Pool AVP. . . . . . . . . . . . . . 38
+ 6.12. IPX Access . . . . . . . . . . . . . . . . . . . . . . . 38
+ 6.12.1. Framed-IPX-Network AVP. . . . . . . . . . . . . 39
+ 6.13. AppleTalk Network Access . . . . . . . . . . . . . . . . 39
+ 6.13.1. Framed-AppleTalk-Link AVP . . . . . . . . . . . 39
+ 6.13.2. Framed-AppleTalk-Network AVP . . . . . . . . . 39
+ 6.13.3. Framed-AppleTalk-Zone AVP . . . . . . . . . . . 40
+ 6.14. AppleTalk Remote Access. . . . . . . . . . . . . . . . . 40
+ 6.14.1. ARAP-Features AVP . . . . . . . . . . . . . . . 40
+ 6.14.2. ARAP-Zone-Access AVP. . . . . . . . . . . . . . 40
+ 6.15. Non-Framed Access Authorization AVPs . . . . . . . . . . 40
+ 6.15.1. Login-IP-Host AVP . . . . . . . . . . . . . . . 40
+ 6.15.2. Login-IPv6-Host AVP . . . . . . . . . . . . . . 41
+ 6.15.3. Login-Service AVP . . . . . . . . . . . . . . . 41
+ 6.16. TCP Services . . . . . . . . . . . . . . . . . . . . . . 42
+ 6.16.1. Login-TCP-Port AVP . . . . . . . . . . . . . . 42
+ 6.17. LAT Services . . . . . . . . . . . . . . . . . . . . . . 42
+ 6.17.1. Login-LAT-Service AVP . . . . . . . . . . . . . 42
+ 6.17.2. Login-LAT-Node AVP. . . . . . . . . . . . . . . 43
+ 6.17.3. Login-LAT-Group AVP . . . . . . . . . . . . . . 43
+ 6.17.4. Login-LAT-Port AVP. . . . . . . . . . . . . . . 43
+ 7. NAS Tunneling . . . . . . . . . . . . . . . . . . . . . . . . 44
+ 7.1. Tunneling AVP . . . . . . . . . . . . . . . . . . . . . 44
+ 7.2. Tunnel-Type AVP . . . . . . . . . . . . . . . . . . . . 45
+ 7.3. Tunnel-Medium-Type AVP . . . . . . . . . . . . . . . . . 46
+ 7.4. Tunnel-Client-Endpoint AVP . . . . . . . . . . . . . . . 46
+ 7.5. Tunnel-Server-Endpoint AVP . . . . . . . . . . . . . . . 47
+ 7.6. Tunnel-Password AVP . . . . . . . . . . . . . . . . . . 48
+ 7.7. Tunnel-Private-Group-Id AVP . . . . . . . . . . . . . . 48
+
+
+
+Calhoun, et al. Standards Track [Page 3]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ 7.8. Tunnel-Assignment-Id AVP . . . . . . . . . . . . . . . . 48
+ 7.9. Tunnel-Preference AVP . . . . . . . . . . . . . . . . . 49
+ 7.10. Tunnel-Client-Auth-Id AVP. . . . . . . . . . . . . . . . 50
+ 7.11. Tunnel-Server-Auth-Id AVP. . . . . . . . . . . . . . . . 50
+ 8. NAS Accounting . . . . . . . . . . . . . . . . . . . . . . . . 50
+ 8.1. Accounting-Input-Octets AVP . . . . . . . . . . . . . . 51
+ 8.2. Accounting-Output-Octets AVP . . . . . . . . . . . . . . 52
+ 8.3. Accounting-Input-Packets AVP . . . . . . . . . . . . . . 52
+ 8.4. Accounting-Output-Packets AVP . . . . . . . . . . . . . 52
+ 8.5. Acct-Session-Time AVP . . . . . . . . . . . . . . . . . 52
+ 8.6. Acct-Authentic AVP . . . . . . . . . . . . . . . . . . . 52
+ 8.7. Accounting-Auth-Method AVP . . . . . . . . . . . . . . . 53
+ 8.8. Acct-Delay-Time . . . . . . . . . . . . . . . . . . . . 53
+ 8.9. Acct-Link-Count . . . . . . . . . . . . . . . . . . . . 54
+ 8.10. Acct-Tunnel-Connection AVP . . . . . . . . . . . . . . . 54
+ 8.11. Acct-Tunnel-Packets-Lost AVP . . . . . . . . . . . . . . 55
+ 9. RADIUS/Diameter Protocol Interactions . . . . . . . . . . . . 55
+ 9.1. RADIUS Request Forwarded as Diameter Request . . . . . . 55
+ 9.1.1. RADIUS Dynamic Authorization Considerations . . 59
+ 9.2. Diameter Request Forwarded as RADIUS Request . . . . . . 60
+ 9.2.1. RADIUS Dynamic Authorization Considerations . . 62
+ 9.3. AVPs Used Only for Compatibility . . . . . . . . . . . . 63
+ 9.3.1. NAS-Identifier AVP. . . . . . . . . . . . . . . 63
+ 9.3.2. NAS-IP-Address AVP. . . . . . . . . . . . . . . 64
+ 9.3.3. NAS-IPv6-Address AVP. . . . . . . . . . . . . . 65
+ 9.3.4. State AVP . . . . . . . . . . . . . . . . . . . 65
+ 9.3.5. Termination-Cause AVP Code Values . . . . . . . 66
+ 9.3.6. Origin-AAA-Protocol . . . . . . . . . . . . . . 68
+ 9.4. Prohibited RADIUS Attributes . . . . . . . . . . . . . . 69
+ 9.5. Translatable Diameter AVPs . . . . . . . . . . . . . . . 69
+ 9.6. RADIUS Vendor-Specific Attributes . . . . . . . . . . . 69
+ 9.6.1. Forwarding a Diameter Vendor Specific AVP as a
+ RADIUS VSA . . . . . . . . . . . . . . . . . . . 70
+ 9.6.2. Forwarding a RADIUS VSA as a Diameter Vendor
+ Specific AVP . . . . . . . . . . . . . . . . . . 70
+ 10. AVP Occurrence Tables. . . . . . . . . . . . . . . . . . . . . 71
+ 10.1. AA-Request/Answer AVP Table. . . . . . . . . . . . . . . 71
+ 10.2. Accounting AVP Tables. . . . . . . . . . . . . . . . . . 73
+ 10.2.1. Accounting Framed Access AVP Table. . . . . . . 74
+ 10.2.2. Accounting Non-Framed Access AVP Table. . . . . 76
+ 11. IANA Considerations. . . . . . . . . . . . . . . . . . . . . . 77
+ 11.1. Command Codes. . . . . . . . . . . . . . . . . . . . . . 77
+ 11.2. AVP Codes. . . . . . . . . . . . . . . . . . . . . . . . 78
+ 11.3. Application Identifier . . . . . . . . . . . . . . . . . 78
+ 11.4. CHAP-Algorithm AVP Values. . . . . . . . . . . . . . . . 78
+ 11.5. Accounting-Auth-Method AVP Values. . . . . . . . . . . . 78
+ 11.6. Origin-AAA-Protocol AVP Values . . . . . . . . . . . . . 78
+ 12. Security Considerations. . . . . . . . . . . . . . . . . . . . 78
+
+
+
+Calhoun, et al. Standards Track [Page 4]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ 13. References . . . . . . . . . . . . . . . . . . . . . . . . . . 79
+ 13.1. Normative References . . . . . . . . . . . . . . . . . . 79
+ 13.2. Informative References . . . . . . . . . . . . . . . . . 80
+ 14. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 83
+ Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . . 84
+ Full Copyright Statement . . . . . . . . . . . . . . . . . . . . . 85
+
+1. Introduction
+
+ This document describes the Diameter protocol application used for
+ AAA in the Network Access Server (NAS) environment. When combined
+ with the Diameter Base protocol [BASE], Transport Profile
+ [DiamTrans], and EAP [DiamEAP] specifications, this Diameter NAS
+ application specification satisfies NAS-related requirements defined
+ in RFC 2989 [AAACriteria] and RFC 3169 [NASCriteria].
+
+ Initial deployments of the Diameter protocol are expected to include
+ legacy systems. Therefore, this application has been carefully
+ designed to ease the burden of protocol conversion between RADIUS and
+ Diameter. This is achieved by including the RADIUS attribute space
+ to eliminate the need to perform many attribute translations.
+
+ The interactions specified in this document between Diameter
+ applications and RADIUS are to be applied to all Diameter
+ applications. In this sense, this document extends the Base Diameter
+ protocol [BASE].
+
+ First, this document describes the operation of a Diameter NAS
+ application. Then it defines the Diameter message Command-Codes.
+ The following sections list the AVPs used in these messages, grouped
+ by common usage. These are session identification, authentication,
+ authorization, tunneling, and accounting. The authorization AVPs are
+ further broken down by service type. Interaction and backward
+ compatibility issues with RADIUS are discussed in later sections.
+
+1.1. Terminology
+
+ The base Diameter [BASE] specification section 1.4 defines most of
+ the terminology used in this document. Additionally, the following
+ terms and acronyms are used in this application:
+
+ NAS (Network Access Server) - A device that provides an access
+ service for a user to a network. The service may be a network
+ connection or a value-added service such as terminal emulation
+ [NASModel].
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 5]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ PPP (Point-to-Point Protocol) - A multiprotocol serial datalink. PPP
+ is the primary IP datalink used for dial-in NAS connection service
+ [PPP].
+
+ CHAP (Challenge Handshake Authentication Protocol) - An
+ authentication process used in PPP [PPPCHAP].
+
+ PAP (Password Authentication Protocol) - A deprecated PPP
+ authentication process, but often used for backward compatibility
+ [PAP].
+
+ SLIP (Serial Line Interface Protocol) - A serial datalink that only
+ supports IP. A design prior to PPP.
+
+ ARAP (Appletalk Remote Access Protocol) - A serial datalink for
+ accessing Appletalk networks [ARAP].
+
+ IPX (Internet Packet Exchange) - The network protocol used by NetWare
+ networks [IPX].
+
+ LAT (Local Area Transport) - A Digital Equipment Corp. LAN protocol
+ for terminal services [LAT].
+
+ VPN (Virtual Private Network) - In this document, this term is used
+ to describe access services that use tunneling methods.
+
+1.2. Requirements Language
+
+ In this document, the key words "MAY", "MUST", "MUST NOT",
+ "OPTIONAL", "RECOMMENDED", "SHOULD", and "SHOULD NOT" are to be
+ interpreted as described in [Keywords].
+
+1.3. Advertising Application Support
+
+ Diameter applications conforming to this specification MUST advertise
+ support by including the value of one (1) in the Auth-Application-Id
+ of Capabilities-Exchange-Request (CER), AA-Request (AAR), and AA-
+ Answer (AAA) messages. All other messages are defined by [BASE] and
+ use the Base application id value.
+
+2. NAS Calls, Ports, and Sessions
+
+ The arrival of a new call or service connection at a port of a
+ Network Access Server (NAS) starts a Diameter NAS message exchange.
+ Information about the call, the identity of the user, and the user's
+ authentication information are packaged into a Diameter AA-Request
+ (AAR) message and sent to a server.
+
+
+
+
+Calhoun, et al. Standards Track [Page 6]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ The server processes the information and responds with a Diameter
+ AA-Answer (AAA) message that contains authorization information for
+ the NAS, or a failure code (Result-Code AVP). A value of
+ DIAMETER_MULTI_ROUND_AUTH indicates an additional authentication
+ exchange, and several AAR and AAA messages may be exchanged until the
+ transaction completes.
+
+ Depending on the Auth-Request-Type AVP, the Diameter protocol allows
+ authorization-only requests that contain no authentication
+ information from the client. This capability goes beyond the Call
+ Check capabilities described in section 5.6 of [RADIUS] in that no
+ access decision is requested. As a result, service cannot be started
+ as a result of a response to an authorization-only request without
+ introducing a significant security vulnerability.
+
+ Since no equivalent capability exists in RADIUS, authorization-only
+ requests from a NAS implementing Diameter may not be easily
+ translated to an equivalent RADIUS message by a Diameter/RADIUS
+ gateway. For example, when a Diameter authorization-only request
+ cannot be translated to a RADIUS Call Check, it would be necessary
+ for the Diameter/RADIUS gateway to add authentication information to
+ the RADIUS Access Request. On receiving the Access-Reply, the
+ Diameter/RADIUS gateway would need to discard the access decision
+ (Accept/Reject). It is not clear whether these translations can be
+ accomplished without adding significant security vulnerabilities.
+
+2.1. Diameter Session Establishment
+
+ When the authentication or authorization exchange completes
+ successfully, the NAS application SHOULD start a session context. If
+ the Result-Code of DIAMETER_MULTI_ROUND_AUTH is returned, the
+ exchange continues until a success or error is returned.
+
+ If accounting is active, the application MUST also send an Accounting
+ message [BASE]. An Accounting-Record-Type of START_RECORD is sent
+ for a new session. If a session fails to start, the EVENT_RECORD
+ message is sent with the reason for the failure described.
+
+ Note that the return of an unsupportable Accounting-Realtime-Required
+ value [BASE] would result in a failure to establish the session.
+
+2.2. Diameter Session Reauthentication or Reauthorization
+
+ The Diameter Base protocol allows users to be periodically
+ reauthenticated and/or reauthorized. In such instances, the
+ Session-Id AVP in the AAR message MUST be the same as the one present
+ in the original authentication/authorization message.
+
+
+
+
+Calhoun, et al. Standards Track [Page 7]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ A Diameter server informs the NAS of the maximum time allowed before
+ reauthentication or reauthorization via the Authorization-Lifetime
+ AVP [BASE]. A NAS MAY reauthenticate and/or reauthorize before the
+ end, but A NAS MUST reauthenticate and/or reauthorize at the end of
+ the period provided by the Authorization-Lifetime AVP. The failure
+ of a reauthentication exchange will terminate the service.
+
+ Furthermore, it is possible for Diameter servers to issue an
+ unsolicited reauthentication and/or reauthorization request (e.g.,
+ Re-Auth-Request (RAR) message [BASE]) to the NAS. Upon receipt of
+ such a message, the NAS MUST respond to the request with a Re-Auth-
+ Answer (RAA) message [BASE].
+
+ If the RAR properly identifies an active session, the NAS will
+ initiate a new local reauthentication or authorization sequence as
+ indicated by the Re-Auth-Request-Type value. This will cause the NAS
+ to send a new AAR message using the existing Session-Id. The server
+ will respond with an AAA message to specify the new service
+ parameters.
+
+ If accounting is active, every change of authentication or
+ authorization SHOULD generate an accounting message. If the NAS
+ service is a continuation of the prior user context, then an
+ Accounting-Record-Type of INTERIM_RECORD indicating the new session
+ attributes and cumulative status would be appropriate. If a new user
+ or a significant change in authorization is detected by the NAS, then
+ the service may send two messages of the types STOP_RECORD and
+ START_RECORD. Accounting may change the subsession identifiers
+ (Acct-Session-ID, or Acct-Sub-Session-Id) to indicate such sub-
+ sessions. A service may also use a different Session-Id value for
+ accounting (see [BASE] section 9.6).
+
+ However, the Diameter Session-ID AVP value used for the initial
+ authorization exchange MUST be used to generate an STR message when
+ the session context is terminated.
+
+2.3. Diameter Session Termination
+
+ When a NAS receives an indication that a user's session is being
+ disconnected by the client (e.g., LCP Terminate is received) or an
+ administrative command, the NAS MUST issue a Session-Termination-
+ Request (STR) [BASE] to its Diameter Server. This will ensure that
+ any resources maintained on the servers are freed appropriately.
+
+ Furthermore, a NAS that receives an Abort-Session-Request (ASR)
+ [BASE] MUST issue an ASA if the session identified is active and
+ disconnect the PPP (or tunneling) session.
+
+
+
+
+Calhoun, et al. Standards Track [Page 8]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ If accounting is active, an Accounting STOP_RECORD message [BASE]
+ MUST be sent upon termination of the session context.
+
+ More information on Diameter Session Termination is included in
+ [BASE] sections 8.4 and 8.5.
+
+3. NAS Messages
+
+ This section defines the Diameter message Command-Code [BASE] values
+ that MUST be supported by all Diameter implementations conforming to
+ this specification. The Command Codes are as follows:
+
+ Command-Name Abbrev. Code Reference
+ -------------------------------------------------------
+ AA-Request AAR 265 3.1
+ AA-Answer AAA 265 3.2
+ Re-Auth-Request RAR 258 3.3
+ Re-Auth-Answer RAA 258 3.4
+ Session-Termination-Request STR 275 3.5
+ Session-Termination-Answer STA 275 3.6
+ Abort-Session-Request ASR 274 3.7
+ Abort-Session-Answer ASA 274 3.8
+ Accounting-Request ACR 271 3.9
+ Accounting-Answer ACA 271 3.10
+
+3.1. AA-Request (AAR) Command
+
+ The AA-Request (AAR), which is indicated by setting the Command-Code
+ field to 265 and the 'R' bit in the Command Flags field, is used to
+ request authentication and/or authorization for a given NAS user.
+ The type of request is identified through the Auth-Request-Type AVP
+ [BASE]. The recommended value for most RADIUS interoperabily
+ situations is AUTHORIZE_AUTHENTICATE.
+
+ If Authentication is requested, the User-Name attribute SHOULD be
+ present, as well as any additional authentication AVPs that would
+ carry the password information. A request for authorization SHOULD
+ only include the information from which the authorization will be
+ performed, such as the User-Name, Called-Station-Id, or Calling-
+ Station-Id AVPs. All requests SHOULD contain AVPs uniquely
+ identifying the source of the call, such as Origin-Host and NAS-Port.
+ Certain networks MAY use different AVPs for authorization purposes.
+ A request for authorization will include some AVPs defined in section
+ 6.
+
+ It is possible for a single session to be authorized first and then
+ for an authentication request to follow.
+
+
+
+
+Calhoun, et al. Standards Track [Page 9]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ This AA-Request message MAY be the result of a multi-round
+ authentication exchange, which occurs when the AA-Answer message is
+ received with the Result-Code AVP set to DIAMETER_MULTI_ROUND_AUTH.
+ A subsequent AAR message SHOULD be sent, with the User-Password AVP
+ that includes the user's response to the prompt, and MUST include any
+ State AVPs that were present in the AAA message.
+
+ Message Format
+ <AA-Request> ::= < 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 ]
+
+
+
+Calhoun, et al. Standards Track [Page 10]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ * [ 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 ]
+
+3.2. AA-Answer (AAA) Command
+
+ The AA-Answer (AAA) message is indicated by setting the Command-Code
+ field to 265 and clearing the 'R' bit in the Command Flags field. It
+ is sent in response to the AA-Request (AAR) message. If
+ authorization was requested, a successful response will include the
+ authorization AVPs appropriate for the service being provided, as
+ defined in section 6.
+
+ For authentication exchanges requiring more than a single round trip,
+ the server MUST set the Result-Code AVP to DIAMETER_MULTI_ROUND_AUTH.
+ An AAA message with this result code MAY include one Reply-Message or
+ more and MAY include zero or one State AVPs.
+
+ If the Reply-Message AVP was present, the network access server
+ SHOULD send the text to the user's client to display to the user,
+ instructing the client to prompt the user for a response. For
+ example, this capability can be achieved in PPP via PAP. If the
+ access client is unable to prompt the user for a new response, it
+ MUST treat the AA-Answer (AAA) with the Reply-Message AVP as an error
+ and deny access.
+
+ Message Format
+
+ <AA-Answer> ::= < 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 ]
+
+
+
+Calhoun, et al. Standards Track [Page 11]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ [ 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 ]
+
+
+
+Calhoun, et al. Standards Track [Page 12]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ [ Login-TCP-Port ]
+ * [ NAS-Filter-Rule ]
+ * [ QoS-Filter-Rule ]
+ * [ Tunneling ]
+ * [ Redirect-Host ]
+ [ Redirect-Host-Usage ]
+ [ Redirect-Max-Cache-Time ]
+ * [ Proxy-Info ]
+ * [ AVP ]
+
+3.3. Re-Auth-Request (RAR) Command
+
+ A Diameter server may initiate a re-authentication and/or re-
+ authorization service for a particular session by issuing a Re-Auth-
+ Request (RAR) message [BASE].
+
+ For example, for pre-paid services, the Diameter server that
+ originally authorized a session may need some confirmation that the
+ user is still using the services.
+
+ If a NAS receives an RAR message with Session-Id equal to a currently
+ active session and a Re-Auth-Type that includes authentication, it
+ MUST initiate a re-authentication toward the user, if the service
+ supports this particular feature.
+
+ Message Format
+
+ <RA-Request> ::= < 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 ]
+
+
+
+Calhoun, et al. Standards Track [Page 13]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ [ 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 ]
+
+3.4. Re-Auth-Answer (RAA) Command
+
+ The Re-Auth-Answer (RAA) message [BASE] is sent in response to the
+ RAR. The Result-Code AVP MUST be present and indicates the
+ disposition of the request.
+
+ A successful RAA transaction MUST be followed by an AAR message.
+
+ Message Format
+
+ <RA-Answer> ::= < 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 ]
+ * [ Redirected-Host ]
+ [ Redirected-Host-Usage ]
+ [ Redirected-Host-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 ]
+
+
+
+Calhoun, et al. Standards Track [Page 14]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+3.5. Session-Termination-Request (STR) Command
+
+ The Session-Termination-Request (STR) message [BASE] is sent by the
+ NAS to inform the Diameter Server that an authenticated and/or
+ authorized session is being terminated.
+
+ Message Format
+
+ <ST-Request> ::= < 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 ]
+
+3.6. Session-Termination-Answer (STA) Command
+
+ The Session-Termination-Answer (STA) message [BASE] 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 the STR was being
+ serviced.
+
+ Upon sending or receiving 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
+
+ <ST-Answer> ::= < Diameter Header: 275, PXY >
+ < Session-Id >
+ { Result-Code }
+ { Origin-Host }
+ { Origin-Realm }
+ [ User-Name ]
+ * [ Class ]
+ [ Error-Message ]
+ [ Error-Reporting-Host ]
+
+
+
+Calhoun, et al. Standards Track [Page 15]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ * [ Failed-AVP ]
+ [ Origin-AAA-Protocol ]
+ [ Origin-State-Id ]
+ * [ Redirect-Host ]
+ [ Redirect-Host-Usase ]
+ [ Redirect-Max-Cache-Time ]
+ * [ Proxy-Info ]
+ * [ AVP ]
+
+3.7. Abort-Session-Request (ASR) Command
+
+ The Abort-Session-Request (ASR) message [BASE] may be sent by any
+ server to the NAS providing session service, to request that the
+ session identified by the Session-Id be stopped.
+
+ Message Format
+
+ <AS-Request> ::= < 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 ]
+
+
+
+Calhoun, et al. Standards Track [Page 16]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+3.8. Abort-Session-Answer (ASA) Command
+
+ The ASA message [BASE] is sent in response to 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
+ DIAMETER_UNKNOWN_SESSION_ID. If the access device does not stop the
+ session for any other reason, Result-Code is set to
+ DIAMETER_UNABLE_TO_COMPLY.
+
+ Message Format
+
+ <AS-Answer> ::= < 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 ]
+ * [ Redirected-Host ]
+ [ Redirected-Host-Usage ]
+ [ Redirected-Max-Cache-Time ]
+ * [ Proxy-Info ]
+ * [ AVP ]
+
+3.9. Accounting-Request (ACR) Command
+
+ The ACR message [BASE] is sent by the NAS to report its session
+ information to a target server downstream.
+
+ Either of Acct-Application-Id or Vendor-Specific-Application-Id AVPs
+ MUST be present. If the Vendor-Specific-Application-Id grouped AVP
+ is present, it must have an Acct-Application-Id inside.
+
+ The AVPs listed in the Base MUST be assumed to be present, as
+ appropriate. NAS service-specific accounting AVPs SHOULD be present
+ as described in section 8 and the rest of this specification.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 17]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Message Format
+
+ <AC-Request> ::= < 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 ]
+ * [ Connection-Info ]
+ [ Originating-Line-Info ]
+ [ Authorization-Lifetime ]
+ [ Session-Timeout ]
+ [ Idle-Timeout ]
+
+
+
+Calhoun, et al. Standards Track [Page 18]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ [ 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 ]
+
+3.10. Accounting-Answer (ACA) Command
+
+ The ACA message [BASE] is used to acknowledge an Accounting-Request
+ command. The Accounting-Answer command contains the same Session-Id
+ as the Request. If the Accounting-Request was protected by end-to-
+ end security, then the corresponding ACA message MUST be protected as
+ well.
+
+ Only the target Diameter Server or home Diameter Server SHOULD
+ respond with the Accounting-Answer command.
+
+ Either Acct-Application-Id or Vendor-Specific-Application-Id AVPs
+ MUST be present, as it was in the request.
+
+
+
+Calhoun, et al. Standards Track [Page 19]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ The AVPs listed in the Base MUST be assumed to be present, as
+ appropriate. NAS service-specific accounting AVPs SHOULD be present
+ as described in section 8 and the rest of this specification.
+
+ Message Format
+
+ <AC-Answer> ::= < 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 ]
+
+4. NAS Session AVPs
+
+ Diameter reserves the AVP Codes 0 - 255 for RADIUS functions that are
+ implemented in Diameter.
+
+ AVPs new to Diameter have code values of 256 and greater. A Diameter
+ message that includes one of these AVPs may represent functions not
+ present in the RADIUS environment and may cause interoperability
+
+
+
+Calhoun, et al. Standards Track [Page 20]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ issues, should the request traverse an AAA system that only supports
+ the RADIUS protocol.
+
+ Some RADIUS attributes are not allowed or supported directly in
+ Diameter. See section 9 for more information.
+
+4.1. Call and Session Information
+
+ This section contains the AVPs specific to NAS Diameter applications
+ that are needed to identify the call and session context and status
+ information. On a request, this information allows the server to
+ qualify the session.
+
+ These AVPs are used in addition to the Base AVPs of:
+
+ Session-Id
+ Auth-Application-Id
+ Origin-Host
+ Origin-Realm
+ Auth-Request-Type
+ Termination-Cause
+
+ The following table describes the session level AVPs; their AVP Code
+ values, types, and possible flag values; and whether the AVP MAY be
+ encrypted.
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST| |
+ Attribute Name Code Defined Value Type |MUST| MAY | NOT| NOT|Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ NAS-Port 5 4.2 Unsigned32 | M | P | | V | Y |
+ NAS-Port-Id 87 4.3 UTF8String | M | P | | V | Y |
+ NAS-Port-Type 61 4.4 Enumerated | M | P | | V | Y |
+ Called-Station-Id 30 4.5 UTF8String | M | P | | V | Y |
+ Calling-Station- 31 4.6 UTF8String | M | P | | V | Y |
+ Id | | | | | |
+ Connect-Info 77 4.7 UTF8String | M | P | | V | Y |
+ Originating-Line- 94 4.8 OctetString| | M,P | | V | Y |
+ Info | | | | | |
+ Reply-Message 18 4.9 UTF8String | M | P | | V | Y |
+ -----------------------------------------|----+-----+----+-----|----|
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 21]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+4.2. NAS-Port AVP
+
+ The NAS-Port AVP (AVP Code 5) is of type Unsigned32 and contains the
+ physical or virtual port number of the NAS which is authenticating
+ the user. Note that "port" is meant in its sense as a service
+ connection on the NAS, not as an IP protocol identifier.
+
+ Either NAS-Port or NAS-Port-Id (AVP Code 87) SHOULD be present in
+ AA-Request (AAR) commands if the NAS differentiates among its ports.
+
+4.3. NAS-Port-Id AVP
+
+ The NAS-Port-Id AVP (AVP Code 87) is of type UTF8String and consists
+ of ASCII text identifying the port of the NAS authenticating the
+ user. Note that "port" is meant in its sense as a service connection
+ on the NAS, not as an IP protocol identifier.
+
+ Either NAS-Port or NAS-Port-Id SHOULD be present in AA-Request (AAR)
+ commands if the NAS differentiates among its ports. NAS-Port-Id is
+ intended for use by NASes that cannot conveniently number their
+ ports.
+
+4.4. NAS-Port-Type AVP
+
+ The NAS-Port-Type AVP (AVP Code 61) is of type Enumerated and
+ contains the type of the port on which the NAS is authenticating the
+ user. This AVP SHOULD be present if the NAS uses the same NAS-Port
+ number ranges for different service types concurrently.
+
+ The supported values are defined in [RADIUSTypes]. The following
+ list is informational and subject to change by the IANA.
+
+ 0 Async
+ 1 Sync
+ 2 ISDN Sync
+ 3 ISDN Async V.120
+ 4 ISDN Async V.110
+ 5 Virtual
+ 6 PIAFS
+ 7 HDLC Clear Channel
+ 8 X.25
+ 9 X.75
+ 10 G.3 Fax
+ 11 SDSL - Symmetric DSL
+ 12 ADSL-CAP - Asymmetric DSL, Carrierless Amplitude Phase
+ Modulation
+ 13 ADSL-DMT - Asymmetric DSL, Discrete Multi-Tone
+ 14 IDSL - ISDN Digital Subscriber Line
+
+
+
+Calhoun, et al. Standards Track [Page 22]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ 15 Ethernet
+ 16 xDSL - Digital Subscriber Line of unknown type
+ 17 Cable
+ 18 Wireless - Other
+ 19 Wireless - IEEE 802.11
+ 20 Token-Ring [RAD802.1X]
+ 21 FDDI [RAD802.1X]
+ 22 Wireless - CDMA2000
+ 23 Wireless - UMTS
+ 24 Wireless - 1X-EV
+ 25 IAPP [IEEE 802.11f]
+
+4.5. Called-Station-Id AVP
+
+ The Called-Station-Id AVP (AVP Code 30) is of type UTF8String and
+ allows the NAS to send the ASCII string describing the layer 2
+ address the user contacted in the request. For dialup access, this
+ can be a phone number obtained by using Dialed Number Identification
+ (DNIS) or a similar technology. Note that this may be different from
+ the phone number the call comes in on. For use with IEEE 802 access,
+ the Called-Station-Id MAY contain a MAC address formatted as
+ described in [RAD802.1X]. It SHOULD only be present in
+ authentication and/or authorization requests.
+
+ If the Auth-Request-Type AVP is set to authorization-only and the
+ User-Name AVP is absent, the Diameter Server MAY perform
+ authorization based on this field. This can be used by a NAS to
+ request whether a call should be answered based on the DNIS.
+
+ The codification of this field's allowed usage range is outside the
+ scope of this specification.
+
+4.6. Calling-Station-Id AVP
+
+ The Calling-Station-Id AVP (AVP Code 31) is of type UTF8String and
+ allows the NAS to send the ASCII string describing the layer 2
+ address from which the user connected in the request. For dialup
+ access, this is the phone number the call came from, using Automatic
+ Number Identification (ANI) or a similar technology. For use with
+ IEEE 802 access, the Calling-Station-Id AVP MAY contain a MAC
+ address, formated as described in [RAD802.1X]. It SHOULD only be
+ present in authentication and/or authorization requests.
+
+ If the Auth-Request-Type AVP is set to authorization-only and the
+ User-Name AVP is absent, the Diameter Server MAY perform
+ authorization based on this field. This can be used by a NAS to
+ request whether a call should be answered based on the layer 2
+ address (ANI, MAC Address, etc.)
+
+
+
+Calhoun, et al. Standards Track [Page 23]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ The codification of this field's allowed usage range is outside the
+ scope of this specification.
+
+4.7. Connect-Info AVP
+
+ The Connect-Info AVP (AVP Code 77) is of type UTF8String and is sent
+ in the AA-Request message or ACR STOP message. When sent in the
+ Access-Request, it indicates the nature of the user's connection.
+ The connection speed SHOULD be included at the beginning of the first
+ Connect-Info AVP in the message. If the transmit and receive
+ connection speeds differ, both may be included in the first AVP with
+ the transmit speed listed first (the speed the NAS modem transmits
+ at), then a slash (/), then the receive speed, and then other
+ optional information.
+
+ For example: "28800 V42BIS/LAPM" or "52000/31200 V90"
+
+ More than one Connect-Info attribute may be present in an
+ Accounting-Request packet to accommodate expected efforts by the ITU
+ to have modems report more connection information in a standard
+ format that might exceed 252 octets.
+
+ If sent in the ACR STOP, this attribute may summarize statistics
+ relating to session quality. For example, in IEEE 802.11, the
+ Connect-Info attribute may contain information on the number of link
+ layer retransmissions. The exact format of this attribute is
+ implementation specific.
+
+4.8. Originating-Line-Info AVP
+
+ The Originating-Line-Info AVP (AVP Code 94) is of type OctetString
+ and is sent by the NAS system to convey information about the origin
+ of the call from an SS7 system.
+
+ The originating line information (OLI) element indicates the nature
+ and/or characteristics of the line from which a call originated
+ (e.g., pay phone, hotel, cellular). Telephone companies are starting
+ to offer OLI to their customers as an option over Primary Rate
+ Interface (PRI). Internet Service Providers (ISPs) can use OLI in
+ addition to Called-Station-Id and Calling-Station-Id attributes to
+ differentiate customer calls and to define different services.
+
+ The Value field contains two octets (00 - 99). ANSI T1.113 and
+ BELLCORE 394 can be used for additional information about these
+ values and their use. For more information on current assignment
+ values, see [ANITypes].
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 24]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Value Description
+ ------------------------------------------------------------
+ 00 Plain Old Telephone Service (POTS)
+ 01 Multiparty Line (more than 2)
+ 02 ANI Failure
+ 03 ANI Observed
+ 04 ONI Observed
+ 05 ANI Failure Observed
+ 06 Station Level Rating
+ 07 Special Operator Handling Required
+ 08 InterLATA Restricted
+ 10 Test Call
+ 20 Automatic Identified Outward Dialing (AIOD)
+ 23 Coin or Non-Coin
+ 24 Toll Free Service (Non-Pay Origination)
+ 25 Toll Free Service (Pay Origination)
+ 27 Toll Free Service (Coin Control Origination)
+ 29 Prison/Inmate Service
+ 30-32 Intercept
+ 30 Intercept (Blank)
+ 31 Intercept (Trouble)
+ 32 Intercept (Regular)
+ 34 Telco Operator Handled Call
+ 40-49 Unrestricted Use
+ 52 Outward Wide Area Telecommunications Service (OUTWATS)
+ 60 Telecommunications Relay Service (TRS)(Unrestricted)
+ 61 Cellular/Wireless PCS (Type 1)
+ 62 Cellular/Wireless PCS (Type 2)
+ 63 Cellular/Wireless PCS (Roaming)
+ 66 TRS (Hotel)
+ 67 TRS (Restricted)
+ 70 Pay Station, No Coin Control
+ 93 Access for Private Virtual Network Service
+
+4.9. Reply-Message AVP
+
+ The Reply-Message AVP (AVP Code 18) is of type UTF8String and
+ contains text that MAY be displayed to the user. When used in an
+ AA-Answer message with a successful Result-Code AVP, it indicates
+ success. When found in an AAA message with a Result-Code other than
+ DIAMETER_SUCCESS, the AVP contains a failure message.
+
+ The Reply-Message AVP MAY indicate dialog text to prompt the user
+ before another AA-Request attempt. When used in an AA-Answer with a
+ Result-Code of DIAMETER_MULTI_ROUND_AUTH or in an Re-Auth-Request
+ message, it MAY contain a dialog text to prompt the user for a
+ response.
+
+
+
+
+Calhoun, et al. Standards Track [Page 25]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Multiple Reply-Messages MAY be included, and if any are displayed,
+ they MUST be displayed in the same order as they appear in the
+ Diameter message.
+
+5. NAS Authentication AVPs
+
+ This section defines the AVPs necessary to carry the authentication
+ information in the Diameter protocol. The functionality defined here
+ provides a RADIUS-like AAA service over a more reliable and secure
+ transport, as defined in the base protocol [BASE].
+
+ The following table describes the AVPs; their AVP Code values, types,
+ and possible flag values, and whether the AVP MAY be encrypted.
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST| |
+ Attribute Name Code Defined Value Type |MUST| MAY | NOT| NOT|Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ User-Password 2 5.1 OctetString| M | P | | V | Y |
+ Password-Retry 75 5.2 Unsigned32 | M | P | | V | Y |
+ Prompt 76 5.3 Enumerated | M | P | | V | Y |
+ CHAP-Auth 402 5.4 Grouped | M | P | | V | Y |
+ CHAP-Algorithm 403 5.5 Enumerated | M | P | | V | Y |
+ CHAP-Ident 404 5.6 OctetString| M | P | | V | Y |
+ CHAP-Response 405 5.7 OctetString| M | P | | V | Y |
+ CHAP-Challenge 60 5.8 OctetString| M | P | | V | Y |
+ ARAP-Password 70 5.9 OctetString| M | P | | V | Y |
+ ARAP-Challenge- 84 5.10 OctetString| M | P | | V | Y |
+ Response | | | | | |
+ ARAP-Security 73 5.11 Unsigned32 | M | P | | V | Y |
+ ARAP-Security- 74 5.12 OctetString| M | P | | V | Y |
+ Data | | | | | |
+ -----------------------------------------|----+-----+----+-----|----|
+
+5.1. User-Password AVP
+
+ The User-Password AVP (AVP Code 2) is of type OctetString and
+ contains the password of the user to be authenticated, or the user's
+ input in a multi-round authentication exchange.
+
+ The User-Password AVP contains a user password or one-time password
+ and therefore represents sensitive information. As required in
+ [BASE], Diameter messages are encrypted by using IPsec or TLS.
+ Unless this AVP is used for one-time passwords, the User-Password AVP
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 26]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ SHOULD NOT be used in untrusted proxy environments without encrypting
+ it by using end-to-end security techniques, such as the proposed CMS
+ Security [DiamCMS].
+
+ The clear-text password (prior to encryption) MUST NOT be longer than
+ 128 bytes in length.
+
+5.2. Password-Retry AVP
+
+ The Password-Retry AVP (AVP Code 75) is of type Unsigned32 and MAY be
+ included in the AA-Answer if the Result-Code indicates an
+ authentication failure. The value of this AVP indicates how many
+ authentication attempts a user is permitted before being
+ disconnected. This AVP is primarily intended for use when the
+ Framed-Protocol AVP (see section 6.10.1) is set to ARAP.
+
+5.3. Prompt AVP
+
+ The Prompt AVP (AVP Code 76) is of type Enumerated and MAY be present
+ in the AA-Answer message. When present, it is used by the NAS to
+ determine whether the user's response, when entered, should be
+ echoed.
+
+ The supported values are listed in [RADIUSTypes]. The following list
+ is informational:
+
+ 0 No Echo
+ 1 Echo
+
+5.4. CHAP-Auth AVP
+
+ The CHAP-Auth AVP (AVP Code 402) is of type Grouped and contains the
+ information necessary to authenticate a user using the PPP
+ Challenge-Handshake Authentication Protocol (CHAP) [PPPCHAP]. If the
+ CHAP-Auth AVP is found in a message, the CHAP-Challenge AVP MUST be
+ present as well. The optional AVPs containing the CHAP response
+ depend upon the value of the CHAP-Algorithm AVP. The grouped AVP has
+ the following ABNF grammar:
+
+ CHAP-Auth ::= < AVP Header: 402 >
+ { CHAP-Algorithm }
+ { CHAP-Ident }
+ [ CHAP-Response ]
+ * [ AVP ]
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 27]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+5.5. CHAP-Algorithm AVP
+
+ The CHAP-Algorithm AVP (AVP Code 403) is of type Enumerated and
+ contains the algorithm identifier used in the computation of the CHAP
+ response [PPPCHAP]. The following values are currently supported:
+
+ CHAP with MD5 5
+ The CHAP response is computed by using the procedure described
+ in [PPPCHAP]. This algorithm requires that the CHAP-Response
+ AVP MUST be present in the CHAP-Auth AVP.
+
+5.6. CHAP-Ident AVP
+
+ The CHAP-Ident AVP (AVP Code 404) is of type OctetString and contains
+ the 1 octet CHAP Identifier used in the computation of the CHAP
+ response [PPPCHAP].
+
+5.7. CHAP-Response AVP
+
+ The CHAP-Response AVP (AVP Code 405) is of type OctetString and
+ contains the 16 octet authentication data provided by the user in
+ response to the CHAP challenge [PPPCHAP].
+
+5.8. CHAP-Challenge AVP
+
+ The CHAP-Challenge AVP (AVP Code 60) is of type OctetString and
+ contains the CHAP Challenge sent by the NAS to the CHAP peer
+ [PPPCHAP].
+
+5.9. ARAP-Password AVP
+
+ The ARAP-Password AVP (AVP Code 70) is of type OctetString and is
+ only present when the Framed-Protocol AVP (see section 6.10.1) is
+ included in the message and is set to ARAP. This AVP MUST NOT be
+ present if either the User-Password or the CHAP-Auth AVP is present.
+ See [RADIUSExt] for more information on the contents of this AVP.
+
+5.10. ARAP-Challenge-Response AVP
+
+ The ARAP-Challenge-Response AVP (AVP Code 84) is of type OctetString
+ and is only present when the Framed-Protocol AVP (see section 6.10.1)
+ is included in the message and is set to ARAP. This AVP contains an
+ 8 octet response to the dial-in client's challenge. The RADIUS
+ server calculates this value by taking the dial-in client's challenge
+ from the high-order 8 octets of the ARAP-Password AVP and performing
+ DES encryption on this value with the authenticating user's password
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 28]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ as the key. If the user's password is fewer than 8 octets in length,
+ the password is padded at the end with NULL octets to a length of 8
+ before it is used as a key.
+
+5.11. ARAP-Security AVP
+
+ The ARAP-Security AVP (AVP Code 73) is of type Unsigned32 and MAY be
+ present in the AA-Answer message if the Framed-Protocol AVP (see
+ section 6.10.1) is set to the value of ARAP, and the Result-Code AVP
+ is set to DIAMETER_MULTI_ROUND_AUTH. See [RADIUSExt] for more
+ information on the format of this AVP.
+
+5.12. ARAP-Security-Data AVP
+
+ The ARAP-Security AVP (AVP Code 74) is of type OctetString and MAY be
+ present in the AA-Request or AA-Answer message if the Framed-Protocol
+ AVP is set to the value of ARAP, and the Result-Code AVP is set to
+ DIAMETER_MULTI_ROUND_AUTH. This AVP contains the security module
+ challenge or response associated with the ARAP Security Module
+ specified in ARAP-Security.
+
+6. NAS Authorization AVPs
+
+ This section contains the authorization AVPs supported in the NAS
+ Application. The Service-Type AVP SHOULD be present in all messages,
+ and, based on its value, additional AVPs defined in this section and
+ in section 7 MAY be present.
+
+ Due to space constraints, the short-form IPFltrRule is used to
+ represent IPFilterRule, and QoSFltrRule is used for QoSFilterRule.
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST| |
+ Attribute Name Code Defined Value Type |MUST| MAY | NOT| NOT|Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ Service-Type 6 6.1 Enumerated | M | P | | V | Y |
+ Callback-Number 19 6.2 UTF8String | M | P | | V | Y |
+ Callback-Id 20 6.3 UTF8String | M | P | | V | Y |
+ Idle-Timeout 28 6.4 Unsigned32 | M | P | | V | Y |
+ Port-Limit 62 6.5 Unsigned32 | M | P | | V | Y |
+ NAS-Filter-Rule 400 6.6 IPFltrRule | M | P | | V | Y |
+ Filter-Id 11 6.7 UTF8String | M | P | | V | Y |
+ Configuration- 78 6.8 OctetString| M | | | P,V | |
+ Token | | | | | |
+ QoS-Filter-Rule 407 6.9 QoSFltrRule| | | | | |
+ Framed-Protocol 7 6.10.1 Enumerated | M | P | | V | Y |
+
+
+
+Calhoun, et al. Standards Track [Page 29]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Framed-Routing 10 6.10.2 Enumerated | M | P | | V | Y |
+ Framed-MTU 12 6.10.3 Unsigned32 | M | P | | V | Y |
+ Framed- 13 6.10.4 Enumerated | M | P | | V | Y |
+ Compression | | | | | |
+ Framed-IP-Address 8 6.11.1 OctetString| M | P | | V | Y |
+ Framed-IP-Netmask 9 6.11.2 OctetString| M | P | | V | Y |
+ Framed-Route 22 6.11.3 UTF8String | M | P | | V | Y |
+ Framed-Pool 88 6.11.4 OctetString| M | P | | V | Y |
+ Framed- 96 6.11.5 Unsigned64 | M | P | | V | Y |
+ Interface-Id | | | | | |
+ Framed-IPv6- 97 6.11.6 OctetString| M | P | | V | Y |
+ Prefix | | | | | |
+ Framed-IPv6- 99 6.11.7 UTF8String | M | P | | V | Y |
+ Route | | | | | |
+ Framed-IPv6-Pool 100 6.11.8 OctetString| M | P | | V | Y |
+ Framed-IPX- 23 6.12.1 UTF8String | M | P | | V | Y |
+ Network | | | | | |
+ Framed-Appletalk- 37 6.13.1 Unsigned32 | M | P | | V | Y |
+ Link | | | | | |
+ Framed-Appletalk- 38 6.13.2 Unsigned32 | M | P | | V | Y |
+ Network | | | | | |
+ Framed-Appletalk- 39 6.13.3 OctetString| M | P | | V | Y |
+ Zone | | | | | |
+ ARAP-Features 71 6.14.1 OctetString| M | P | | V | Y |
+ ARAP-Zone-Access 72 6.14.2 Enumerated | M | P | | V | Y |
+ Login-IP-Host 14 6.15.1 OctetString| M | P | | V | Y |
+ Login-IPv6-Host 98 6.15.2 OctetString| M | P | | V | Y |
+ Login-Service 15 6.15.3 Enumerated | M | P | | V | Y |
+ Login-TCP-Port 16 6.16.1 Unsigned32 | M | P | | V | Y |
+ Login-LAT-Service 34 6.17.1 OctetString| M | P | | V | Y |
+ Login-LAT-Node 35 6.17.2 OctetString| M | P | | V | Y |
+ Login-LAT-Group 36 6.17.3 OctetString| M | P | | V | Y |
+ Login-LAT-Port 63 6.17.4 OctetString| M | P | | V | Y |
+ -----------------------------------------|----+-----+----+-----|----|
+
+6.1. Service-Type AVP
+
+ The Service-Type AVP (AVP Code 6) is of type Enumerated and contains
+ the type of service the user has requested or the type of service to
+ be provided. One such AVP MAY be present in an authentication and/or
+ authorization request or response. A NAS is not required to
+ implement all of these service types. It MUST treat unknown or
+ unsupported Service-Types received in a response as a failure and end
+ the session with a DIAMETER_INVALID_AVP_VALUE Result-Code.
+
+ When used in a request, the Service-Type AVP SHOULD be considered a
+ hint to the server that the NAS believes the user would prefer the
+ kind of service indicated. The server is not required to honor the
+
+
+
+Calhoun, et al. Standards Track [Page 30]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ hint. Furthermore, if the service specified by the server is
+ supported, but not compatible with the current mode of access, the
+ NAS MUST fail to start the session. The NAS MUST also generate the
+ appropriate error message(s).
+
+ The following values have been defined for the Service-Type AVP. The
+ complete list of defined values can be found in [RADIUS] and
+ [RADIUSTypes]. The following list is informational:
+
+ 1 Login
+ 2 Framed
+ 3 Callback Login
+ 4 Callback Framed
+ 5 Outbound
+ 6 Administrative
+ 7 NAS Prompt
+ 8 Authenticate Only
+ 9 Callback NAS Prompt
+ 10 Call Check
+ 11 Callback Administrative
+ 12 Voice
+ 13 Fax
+ 14 Modem Relay
+ 15 IAPP-Register [IEEE 802.11f]
+ 16 IAPP-AP-Check [IEEE 802.11f]
+ 17 Authorize Only [RADDynAuth]
+
+ The following values are further qualified:
+
+ Login 1
+ The user should be connected to a host. The message MAY
+ include additional AVPs defined in sections 6.16 or 6.17.
+
+ Framed 2
+ A Framed Protocol, such as PPP or SLIP, should be started for
+ the User. The message MAY include additional AVPs defined in
+ section 6.10, or section 7 for tunneling services.
+
+ Callback Login 3
+ The user should be disconnected and called back, then connected
+ to a host. The message MAY include additional AVPs defined in
+ this section.
+
+ Callback Framed 4
+ The user should be disconnected and called back, and then a
+ Framed Protocol, such as PPP or SLIP, should be started for the
+ User. The message MAY include additional AVPs defined in
+ section 6.10, or in section 7 for tunneling services.
+
+
+
+Calhoun, et al. Standards Track [Page 31]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.2. Callback-Number AVP
+
+ The Callback-Number AVP (AVP Code 19) is of type UTF8String and
+ contains a dialing string to be used for callback. It MAY be used in
+ an authentication and/or authorization request as a hint to the
+ server that a Callback service is desired, but the server is not
+ required to honor the hint in the corresponding response.
+
+ The codification of this field's allowed usage range is outside the
+ scope of this specification.
+
+6.3. Callback-Id AVP
+
+ The Callback-Id AVP (AVP Code 20) is of type UTF8String and contains
+ the name of a place to be called, to be interpreted by the NAS. This
+ AVP MAY be present in an authentication and/or authorization
+ response.
+
+ This AVP is not roaming-friendly as it assumes that the Callback-Id
+ is configured on the NAS. Using the Callback-Number AVP therefore
+ preferable.
+
+6.4. Idle-Timeout AVP
+
+ The Idle-Timeout AVP (AVP Code 28) is of type Unsigned32 and sets the
+ maximum number of consecutive seconds of idle connection allowable to
+ the user before termination of the session or before a prompt is
+ issued. The default is none, or system specific.
+
+6.5. Port-Limit AVP
+
+ The Port-Limit AVP (AVP Code 62) is of type Unsigned32 and sets the
+ maximum number of ports the NAS provides to the user. It MAY be used
+ in an authentication and/or authorization request as a hint to the
+ server that multilink PPP [PPPMP] service is desired, but the server
+ is not required to honor the hint in the corresponding response.
+
+6.6. NAS-Filter-Rule AVP
+
+ The NAS-Filter-Rule AVP (AVP Code 400) is of type IPFilterRule and
+ provides filter rules that need to be configured on the NAS for the
+ user. One or more of these AVPs MAY be present in an authorization
+ response.
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 32]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.7. Filter-Id AVP
+
+ The Filter-Id AVP (AVP Code 11) is of type UTF8String and contains
+ the name of the filter list for this user. Zero or more Filter-Id
+ AVPs MAY be sent in an authorization answer.
+
+ Identifying a filter list by name allows the filter to be used on
+ different NASes without regard to filter-list implementation details.
+ However, this AVP is not roaming friendly, as filter naming differs
+ from one service provider to another.
+
+ In non-RADIUS environments, it is RECOMMENDED that the NAS-Filter-
+ Rule AVP be used instead.
+
+6.8. Configuration-Token AVP
+
+ The Configuration-Token AVP (AVP Code 78) is of type OctetString and
+ is sent by a Diameter Server to a Diameter Proxy Agent or Translation
+ Agent in an AA-Answer command to indicate a type of user profile to
+ be used. It should not be sent to a Diameter Client (NAS).
+
+ The format of the Data field of this AVP is site specific.
+
+6.9. QoS-Filter-Rule AVP
+
+ The QoS-Filter-Rule AVP (AVP Code 407) is of type QoSFilterRule and
+ provides QoS filter rules that need to be configured on the NAS for
+ the user. One or more such AVPs MAY be present in an authorization
+ response.
+
+ Note: Due to an editorial mistake in [BASE], only the AVP format is
+ discussed. The complete QoSFilterRule definition was not included.
+ It is reprinted here for clarification.
+
+ QoSFilterRule
+
+ The QosFilterRule format is derived from the OctetString AVP Base
+ Format. It uses the ASCII charset. Packets may be marked or
+ metered based on the following information:
+
+ Direction (in or out)
+ Source and destination IP address (possibly masked)
+ Protocol
+ Source and destination port (lists or ranges)
+ DSCP values (no mask or range)
+
+ Rules for the appropriate direction are evaluated in order; the
+ first matched rule terminates the evaluation. Each packet is
+
+
+
+Calhoun, et al. Standards Track [Page 33]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ evaluated once. If no rule matches, the packet is treated as best
+ effort. An access device unable to interpret or apply a QoS rule
+ SHOULD NOT terminate the session.
+
+ QoSFilterRule filters MUST follow the following format:
+
+ action dir proto from src to dst [options]
+
+ tag - Mark packet with a specific DSCP
+ [DIFFSERV]. The DSCP option MUST be
+ included.
+ meter - Meter traffic. The metering options
+ MUST be included.
+
+ dir The format is as described under IPFilterRule.
+
+ proto The format is as described under IPFilterRule.
+
+ src and dst The format is as described under IPFilterRule.
+
+ options:
+
+ DSCP <color>
+ Color values as defined in [DIFFSERV]. Exact
+ matching of DSCP values is required (no masks or
+ ranges).
+
+ metering <rate> <color_under> <color_over>
+ The metering option provides Assured Forwarding,
+ as defined in [DIFFSERVAF], and MUST be present
+ if the action is set to meter. The rate option is
+ the throughput, in bits per second, used
+ by the access device to mark packets. Traffic
+ over the rate is marked with the color_over
+ codepoint, and traffic under the rate is marked
+ with the color_under codepoint. The color_under
+ and color_over options contain the drop
+ preferences and MUST conform to the recommended
+ codepoint keywords described in [DIFFSERVAF]
+ (e.g., AF13).
+
+ The metering option also supports the strict
+ limit on traffic required by Expedited
+ Forwarding, as defined in [DIFFSERVEF]. The
+ color_over option may contain the keyword "drop"
+ to prevent forwarding of traffic that exceeds the
+ rate parameter.
+
+
+
+
+Calhoun, et al. Standards Track [Page 34]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ The rule syntax is a modified subset of ipfw(8) from FreeBSD,
+ and the ipfw.c code may provide a useful base for
+ implementations.
+
+6.10. Framed Access Authorization AVPs
+
+ This section lists the authorization AVPs necessary to
+ support framed access, such as PPP and SLIP. AVPs defined in this
+ section MAY be present in a message if the Service-Type AVP was set
+ to "Framed" or "Callback Framed".
+
+6.10.1. Framed-Protocol AVP
+
+ The Framed-Protocol AVP (AVP Code 7) is of type Enumerated and
+ contains the framing to be used for framed access. This AVP MAY be
+ present in both requests and responses. The supported values are
+ listed in [RADIUSTypes]. The following list is informational:
+
+ 1 PPP
+ 2 SLIP
+ 3 AppleTalk Remote Access Protocol (ARAP)
+ 4 Gandalf proprietary SingleLink/MultiLink protocol
+ 5 Xylogics proprietary IPX/SLIP
+ 6 X.75 Synchronous
+
+6.10.2. Framed-Routing AVP
+
+ The Framed-Routing AVP (AVP Code 10) is of type Enumerated and
+ contains the routing method for the user when the user is a router to
+ a network. This AVP SHOULD only be present in authorization
+ responses. The supported values are listed in [RADIUSTypes]. The
+ following list is informational:
+
+ 0 None
+ 1 Send routing packets
+ 2 Listen for routing packets
+ 3 Send and Listen
+
+6.10.3. Framed-MTU AVP
+
+ The Framed-MTU AVP (AVP Code 12) is of type Unsigned32 and contains
+ the Maximum Transmission Unit to be configured for the user, when it
+ is not negotiated by some other means (such as PPP). This AVP SHOULD
+ only be present in authorization responses. The MTU value MUST be in
+ the range from 64 to 65535.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 35]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.10.4. Framed-Compression AVP
+
+ The Framed-Compression AVP (AVP Code 13) is of type Enumerated and
+ contains the compression protocol to be used for the link. It MAY be
+ used in an authorization request as a hint to the server that a
+ specific compression type is desired, but the server is not required
+ to honor the hint in the corresponding response.
+
+ More than one compression protocol AVP MAY be sent. The NAS is
+ responsible for applying the proper compression protocol to the
+ appropriate link traffic.
+
+ The supported values are listed in [RADIUSTypes]. The following list
+ is informational:
+
+ 0 None
+ 1 VJ TCP/IP header compression
+ 2 IPX header compression
+ 3 Stac-LZS compression
+
+6.11. IP Access Authorization AVPs
+
+ The AVPs defined in this section are used when the user requests, or
+ is being granted, access service to IP.
+
+6.11.1. Framed-IP-Address AVP
+
+ The Framed-IP-Address AVP (AVP Code 8) [RADIUS] is of type
+ OctetString and contains an IPv4 address of the type specified in the
+ attribute value to be configured for the user. It MAY be used in an
+ authorization request as a hint to the server that a specific address
+ is desired, but the server is not required to honor the hint in the
+ corresponding response.
+
+ Two values have special significance: 0xFFFFFFFF and 0xFFFFFFFE. The
+ value 0xFFFFFFFF indicates that the NAS should allow the user to
+ select an address (i.e., negotiated). The value 0xFFFFFFFE indicates
+ that the NAS should select an address for the user (e.g., assigned
+ from a pool of addresses kept by the NAS).
+
+6.11.2. Framed-IP-Netmask AVP
+
+ The Framed-IP-Netmask AVP (AVP Code 9) is of type OctetString and
+ contains the four octets of the IPv4 netmask to be configured for the
+ user when the user is a router to a network. It MAY be used in an
+ authorization request as a hint to the server that a specific netmask
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 36]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ is desired, but the server is not required to honor the hint in the
+ corresponding response. This AVP MUST be present in a response if
+ the request included this AVP with a value of 0xFFFFFFFF.
+
+6.11.3. Framed-Route AVP
+
+ The Framed-Route AVP (AVP Code 22) is of type UTF8String and contains
+ the ASCII routing information to be configured for the user on the
+ NAS. Zero or more of these AVPs MAY be present in an authorization
+ response.
+
+ The string MUST contain a destination prefix in dotted quad form
+ optionally followed by a slash and a decimal length specifier stating
+ how many high-order bits of the prefix should be used. This is
+ followed by a space, a gateway address in dotted quad form, a space,
+ and one or more metrics separated by spaces; for example,
+
+ "192.168.1.0/24 192.168.1.1 1".
+
+ The length specifier may be omitted, in which case it should default
+ to 8 bits for class A prefixes, to 16 bits for class B prefixes, and
+ to 24 bits for class C prefixes; for example,
+
+ "192.168.1.0 192.168.1.1 1".
+
+ Whenever the gateway address is specified as "0.0.0.0" the IP address
+ of the user SHOULD be used as the gateway address.
+
+6.11.4. Framed-Pool AVP
+
+ The Framed-Pool AVP (AVP Code 88) is of type OctetString and contains
+ the name of an assigned address pool that SHOULD be used to assign an
+ address for the user. If a NAS does not support multiple address
+ pools, the NAS SHOULD ignore this AVP. Address pools are usually
+ used for IP addresses but can be used for other protocols if the NAS
+ supports pools for those protocols.
+
+ Although specified as type OctetString for compatibility with RADIUS
+ [RADIUSExt], the encoding of the Data field SHOULD also conform to
+ the rules for the UTF8String Data Format.
+
+6.11.5. Framed-Interface-Id AVP
+
+ The Framed-Interface-Id AVP (AVP Code 96) is of type Unsigned64 and
+ contains the IPv6 interface identifier to be configured for the user.
+ It MAY be used in authorization requests as a hint to the server that
+ a specific interface id is desired, but the server is not required to
+ honor the hint in the corresponding response.
+
+
+
+Calhoun, et al. Standards Track [Page 37]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.11.6. Framed-IPv6-Prefix AVP
+
+ The Framed-IPv6-Prefix AVP (AVP Code 97) is of type OctetString and
+ contains the IPv6 prefix to be configured for the user. One or more
+ AVPs MAY be used in authorization requests as a hint to the server
+ that specific IPv6 prefixes are desired, but the server is not
+ required to honor the hint in the corresponding response.
+
+6.11.7. Framed-IPv6-Route AVP
+
+ The Framed-IPv6-Route AVP (AVP Code 99) is of type UTF8String and
+ contains the ASCII routing information to be configured for the user
+ on the NAS. Zero or more of these AVPs MAY be present in an
+ authorization response.
+
+ The string MUST contain an IPv6 address prefix followed by a slash
+ and a decimal length specifier stating how many high order bits of
+ the prefix should be used. This is followed by a space, a gateway
+ address in hexadecimal notation, a space, and one or more metrics
+ separated by spaces; for example,
+
+ "2000:0:0:106::/64 2000::106:a00:20ff:fe99:a998 1".
+
+ Whenever the gateway address is the IPv6 unspecified address, the IP
+ address of the user SHOULD be used as the gateway address, such as
+ in:
+
+ "2000:0:0:106::/64 :: 1".
+
+6.11.8. Framed-IPv6-Pool AVP
+
+ The Framed-IPv6-Pool AVP (AVP Code 100) is of type OctetString and
+ contains the name of an assigned pool that SHOULD be used to assign
+ an IPv6 prefix for the user. If the access device does not support
+ multiple prefix pools, it MUST ignore this AVP.
+
+ Although specified as type OctetString for compatibility with RADIUS
+ [RADIUSIPv6], the encoding of the Data field SHOULD also conform to
+ the rules for the UTF8String Data Format.
+
+6.12. IPX Access
+
+ The AVPs defined in this section are used when the user requests, or
+ is being granted, access to an IPX network service.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 38]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.12.1. Framed-IPX-Network AVP
+
+ The Framed-IPX-Network AVP (AVP Code 23) is of type Unsigned32 and
+ contains the IPX Network number to be configured for the user. It
+ MAY be used in an authorization request as a hint to the server that
+ a specific address is desired, but the server is not required to
+ honor the hint in the corresponding response.
+
+ Two addresses have special significance: 0xFFFFFFFF and 0xFFFFFFFE.
+ The value 0xFFFFFFFF indicates that the NAS should allow the user to
+ select an address (i.e., Negotiated). The value 0xFFFFFFFE indicates
+ that the NAS should select an address for the user (e.g., assign it
+ from a pool of one or more IPX networks kept by the NAS).
+
+6.13. AppleTalk Network Access
+
+ The AVPs defined in this section are used when the user requests, or
+ is being granted, access to an AppleTalk network [AppleTalk].
+
+6.13.1. Framed-AppleTalk-Link AVP
+
+ The Framed-AppleTalk-Link AVP (AVP Code 37) is of type Unsigned32 and
+ contains the AppleTalk network number that should be used for the
+ serial link to the user, which is another AppleTalk router. This AVP
+ MUST only be present in an authorization response and is never used
+ when the user is not another router.
+
+ Despite the size of the field, values range from 0 to 65,535. The
+ special value of 0 indicates an unnumbered serial link. A value of 1
+ to 65,535 means that the serial line between the NAS and the user
+ should be assigned that value as an AppleTalk network number.
+
+6.13.2. Framed-AppleTalk-Network AVP
+
+ The Framed-AppleTalk-Network AVP (AVP Code 38) is of type Unsigned32
+ and contains the AppleTalk Network number that the NAS should probe
+ to allocate an AppleTalk node for the user. This AVP MUST only be
+ present in an authorization response and is never used when the user
+ is not another router. Multiple instances of this AVP indicate that
+ the NAS may probe, using any of the network numbers specified.
+
+ Despite the size of the field, values range from 0 to 65,535. The
+ special value 0 indicates that the NAS should assign a network for
+ the user, using its default cable range. A value between 1 and
+ 65,535 (inclusive) indicates to the AppleTalk Network that the NAS
+ should probe to find an address for the user.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 39]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.13.3. Framed-AppleTalk-Zone AVP
+
+ The Framed-AppleTalk-Zone AVP (AVP Code 39) is of type OctetString
+ and contains the AppleTalk Default Zone to be used for this user.
+ This AVP MUST only be present in an authorization response. Multiple
+ instances of this AVP in the same message are not allowed.
+
+ The codification of this field's allowed range is outside the scope
+ of this specification.
+
+6.14. AppleTalk Remote Access
+
+ The AVPs defined in this section are used when the user requests, or
+ is being granted, access to the AppleTalk network via the AppleTalk
+ Remote Access Protocol [ARAP]. They are only present if the Framed-
+ Protocol AVP (see section 6.10.1) is set to ARAP. Section 2.2 of RFC
+ 2869 [RADIUSExt] describes the operational use of these attributes.
+
+6.14.1. ARAP-Features AVP
+
+ The ARAP-Features AVP (AVP Code 71) is of type OctetString and MAY be
+ present in the AA-Accept message if the Framed-Protocol AVP is set to
+ the value of ARAP. See [RADIUSExt] for more information about the
+ format of this AVP.
+
+6.14.2. ARAP-Zone-Access AVP
+
+ The ARAP-Zone-Access AVP (AVP Code 72) is of type Enumerated and MAY
+ be present in the AA-Accept message if the Framed-Protocol AVP is set
+ to the value of ARAP.
+
+ The supported values are listed in [RADIUSTypes] and defined in
+ [RADIUSExt].
+
+6.15. Non-Framed Access Authorization AVPs
+
+ This section contains the authorization AVPs that are needed to
+ support terminal server functionality. AVPs defined in this section
+ MAY be present in a message if the Service-Type AVP was set to
+ "Login" or "Callback Login".
+
+6.15.1. Login-IP-Host AVP
+
+ The Login-IP-Host AVP (AVP Code 14) [RADIUS] is of type OctetString
+ and contains the IPv4 address of a host with which to connect the
+ user when the Login-Service AVP is included. It MAY be used in an
+ AA-Request command as a hint to the Diameter Server that a specific
+
+
+
+
+Calhoun, et al. Standards Track [Page 40]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ host is desired, but the Diameter Server is not required to honor the
+ hint in the AA-Answer.
+
+ Two addresses have special significance: all ones and 0. The value
+ of all ones indicates that the NAS SHOULD allow the user to select an
+ address. The value 0 indicates that the NAS SHOULD select a host to
+ connect the user to.
+
+6.15.2. Login-IPv6-Host AVP
+
+ The Login-IPv6-Host AVP (AVP Code 98) [RADIUSIPv6] is of type
+ OctetString and contains the IPv6 address of a host with which to
+ connect the user when the Login-Service AVP is included. It MAY be
+ used in an AA-Request command as a hint to the Diameter Server that a
+ specific host is desired, but the Diameter Server is not required to
+ honor the hint in the AA-Answer.
+
+ Two addresses have special significance:
+
+ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF and 0. The value
+ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF indicates that the NAS SHOULD
+ allow the user to select an address. The value 0 indicates that the
+ NAS SHOULD select a host to connect the user to.
+
+6.15.3. Login-Service AVP
+
+ The Login-Service AVP (AVP Code 15) is of type Enumerated and
+ contains the service that should be used to connect the user to the
+ login host. This AVP SHOULD only be present in authorization
+ responses.
+
+ The supported values are listed in [RADIUSTypes]. The following list
+ is informational:
+
+ 0 Telnet
+ 1 Rlogin
+ 2 TCP Clear
+ 3 PortMaster (proprietary)
+ 4 LAT
+ 5 X25-PAD
+ 6 X25-T3POS
+ 8 TCP Clear Quiet (suppresses any NAS-generated connect
+ string)
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 41]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.16. TCP Services
+
+ The AVPs described in this section MAY be present if the Login-
+ Service AVP is set to Telnet, Rlogin, TCP Clear, or TCP Clear Quiet.
+
+6.16.1. Login-TCP-Port AVP
+
+ The Login-TCP-Port AVP (AVP Code 16) is of type Unsigned32 and
+ contains the TCP port with which the user is to be connected when the
+ Login-Service AVP is also present. This AVP SHOULD only be present
+ in authorization responses. The value MUST NOT be greater than
+ 65,535.
+
+6.17. LAT Services
+
+ The AVPs described in this section MAY be present if the Login-
+ Service AVP is set to LAT [LAT].
+
+6.17.1. Login-LAT-Service AVP
+
+ The Login-LAT-Service AVP (AVP Code 34) is of type OctetString and
+ contains the system with which the user is to be connected by LAT.
+ It MAY be used in an authorization request as a hint to the server
+ that a specific service is desired, but the server is not required to
+ honor the hint in the corresponding response. This AVP MUST only be
+ present in the response if the Login-Service AVP states that LAT is
+ desired.
+
+ Administrators use this service attribute when dealing with clustered
+ systems, such as a VAX or Alpha cluster. In these environments,
+ several different time-sharing hosts share the same resources (disks,
+ printers, etc.), and administrators often configure each host to
+ offer access (service) to each of the shared resources. In this
+ case, each host in the cluster advertises its services through LAT
+ broadcasts.
+
+ Sophisticated users often know which service providers (machines) are
+ faster and tend to use a node name when initiating a LAT connection.
+ Some administrators want particular users to use certain machines as
+ a primitive form of load balancing (although LAT knows how to do load
+ balancing itself).
+
+ The String field contains the identity of the LAT service to use.
+ The LAT Architecture allows this string to contain $ (dollar), -
+ (hyphen), . (period), _ (underscore), numerics, upper- and lowercase
+ alphabetics, and the ISO Latin-1 character set extension [ISOLatin].
+ All LAT string comparisons are case insensitive.
+
+
+
+
+Calhoun, et al. Standards Track [Page 42]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+6.17.2. Login-LAT-Node AVP
+
+ The Login-LAT-Node AVP (AVP Code 35) is of type OctetString and
+ contains the Node with which the user is to be automatically
+ connected by LAT. It MAY be used in an authorization request as a
+ hint to the server that a specific LAT node is desired, but the
+ server is not required to honor the hint in the corresponding
+ response. This AVP MUST only be present in a response if the Login-
+ Service-Type AVP is set to LAT.
+
+ The String field contains the identity of the LAT service to use.
+ The LAT Architecture allows this string to contain $ (dollar), -
+ (hyphen), . (period), _ (underscore), numerics, upper- and lowercase
+ alphabetics, and the ISO Latin-1 character set extension [ISOLatin].
+ All LAT string comparisons are case insensitive.
+
+6.17.3. Login-LAT-Group AVP
+
+ The Login-LAT-Group AVP (AVP Code 36) is of type OctetString and
+ contains a string identifying the LAT group codes this user is
+ authorized to use. It MAY be used in an authorization request as a
+ hint to the server that a specific group is desired, but the server
+ is not required to honor the hint in the corresponding response.
+ This AVP MUST only be present in a response if the Login-Service-Type
+ AVP is set to LAT.
+
+ LAT supports 256 different group codes, which LAT uses as a form of
+ access rights. LAT encodes the group codes as a 256-bit bitmap.
+
+ Administrators can assign one or more of the group code bits at the
+ LAT service provider; it will only accept LAT connections that have
+ these group codes set in the bitmap. The administrators assign a
+ bitmap of authorized group codes to each user. LAT gets these from
+ the operating system and uses them in its requests to the service
+ providers.
+
+ The codification of the range of allowed usage of this field is
+ outside the scope of this specification.
+
+6.17.4. Login-LAT-Port AVP
+
+ The Login-LAT-Port AVP (AVP Code 63) is of type OctetString and
+ contains the Port with which the user is to be connected by LAT. It
+ MAY be used in an authorization request as a hint to the server that
+ a specific port is desired, but the server is not required to honor
+ the hint in the corresponding response. This AVP MUST only be
+ present in a response if the Login-Service-Type AVP is set to LAT.
+
+
+
+
+Calhoun, et al. Standards Track [Page 43]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ The String field contains the identity of the LAT service to use.
+ The LAT Architecture allows this string to contain $ (dollar), -
+ (hyphen), . (period), _ (underscore), numerics, upper- and lower-case
+ alphabetics, and the ISO Latin-1 character set extension [ISOLatin].
+ All LAT string comparisons are case insensitive.
+
+7. NAS Tunneling
+
+ Some NASes support compulsory tunnel services in which the incoming
+ connection data is conveyed by an encapsulation method to a gateway
+ elsewhere in the network. This is typically transparent to the
+ service user, and the tunnel characteristics may be described by the
+ remote AAA server, based on the user's authorization information.
+ Several tunnel characteristics may be returned, and the NAS
+ implementation may choose one [RADTunnels], [RADTunlAcct].
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST| |
+ Attribute Name Code Defined Value Type |MUST| MAY | NOT| NOT |Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ Tunneling 401 7.1 Grouped | M | P | | V | N |
+ Tunnel-Type 64 7.2 Enumerated | M | P | | V | Y |
+ Tunnel-Medium- 65 7.3 Enumerated | M | P | | V | Y |
+ Type | | | | | |
+ Tunnel-Client- 66 7.4 UTF8String | M | P | | V | Y |
+ Endpoint | | | | | |
+ Tunnel-Server- 67 7.5 UTF8String | M | P | | V | Y |
+ Endpoint | | | | | |
+ Tunnel-Password 69 7.6 OctetString| M | P | | V | Y |
+ Tunnel-Private- 81 7.7 OctetString| M | P | | V | Y |
+ Group-Id | | | | | |
+ Tunnel- 82 7.8 OctetString| M | P | | V | Y |
+ Assignment-Id | | | | | |
+ Tunnel-Preference 83 7.9 Unsigned32 | M | P | | V | Y |
+ Tunnel-Client- 90 7.10 UTF8String | M | P | | V | Y |
+ Auth-Id | | | | | |
+ Tunnel-Server- 91 7.11 UTF8String | M | P | | V | Y |
+ Auth-Id | | | | | |
+ -----------------------------------------|----+-----+----+-----|----|
+
+7.1. Tunneling AVP
+
+ The Tunneling AVP (AVP Code 401) is of type Grouped and contains the
+ following AVPs, used to describe a compulsory tunnel service:
+ [RADTunnels], [RADTunlAcct]. Its data field has the following ABNF
+ grammar:
+
+
+
+Calhoun, et al. Standards Track [Page 44]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ 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 ]
+
+7.2. Tunnel-Type AVP
+
+ The Tunnel-Type AVP (AVP Code 64) is of type Enumerated and contains
+ the tunneling protocol(s) to be used (in the case of a tunnel
+ initiator) or in use (in the case of a tunnel terminator). It MAY be
+ used in an authorization request as a hint to the server that a
+ specific tunnel type is desired, but the server is not required to
+ honor the hint in the corresponding response.
+
+ The Tunnel-Type AVP SHOULD also be included in Accounting-Request
+ messages.
+
+ A tunnel initiator is not required to implement any of these tunnel
+ types. If a tunnel initiator receives a response that contains only
+ unknown or unsupported Tunnel-Types, the tunnel initiator MUST behave
+ as though a response were received with the Result-Code indicating a
+ failure.
+
+ The supported values are listed in [RADIUSTypes]. The following list
+ is informational:
+
+ 1 Point-to-Point Tunneling Protocol (PPTP)
+ 2 Layer Two Forwarding (L2F)
+ 3 Layer Two Tunneling Protocol (L2TP)
+ 4 Ascend Tunnel Management Protocol (ATMP)
+ 5 Virtual Tunneling Protocol (VTP)
+ 6 IP Authentication Header in the Tunnel-mode (AH)
+ 7 IP-in-IP Encapsulation (IP-IP)
+ 8 Minimal IP-in-IP Encapsulation (MIN-IP-IP)
+ 9 IP Encapsulating Security Payload in the Tunnel-mode (ESP)
+ 10 Generic Route Encapsulation (GRE)
+ 11 Bay Dial Virtual Services (DVS)
+ 12 IP-in-IP Tunneling
+ 13 Virtual LANs (VLAN)
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 45]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+7.3. Tunnel-Medium-Type AVP
+
+ The Tunnel-Medium-Type AVP (AVP Code 65) is of type Enumerated and
+ contains the transport medium to use when creating a tunnel for
+ protocols (such as L2TP) that can operate over multiple transports.
+ It MAY be used in an authorization request as a hint to the server
+ that a specific medium is desired, but the server is not required to
+ honor the hint in the corresponding response.
+
+ The supported values are listed in [RADIUSTypes]. The following list
+ is informational:
+
+ 1 IPv4 (IP version 4)
+ 2 IPv6 (IP version 6)
+ 3 NSAP
+ 4 HDLC (8-bit multidrop)
+ 5 BBN 1822
+ 6 802 (includes all 802 media plus Ethernet "canonical
+ format")
+ 7 E.163 (POTS)
+ 8 E.164 (SMDS, Frame Relay, ATM)
+ 9 F.69 (Telex)
+ 10 X.121 (X.25, Frame Relay)
+ 11 IPX
+ 12 Appletalk
+ 13 Decnet IV
+ 14 Banyan Vines
+ 15 E.164 with NSAP format subaddress
+
+7.4. Tunnel-Client-Endpoint AVP
+
+ The Tunnel-Client-Endpoint AVP (AVP Code 66) is of type UTF8String
+ and contains the address of the initiator end of the tunnel. It MAY
+ be used in an authorization request as a hint to the server that a
+ specific endpoint is desired, but the server is not required to honor
+ the hint in the corresponding response.
+
+ This AVP SHOULD be included in the corresponding Accounting-Request
+ messages, in which case it indicates the address from which the
+ tunnel was initiated. This AVP, along with the Tunnel-Server-
+ Endpoint and Session-Id AVP [BASE], MAY be used to provide a globally
+ unique means to identify a tunnel for accounting and auditing
+ purposes.
+
+ If Tunnel-Medium-Type is IPv4 (1), then this string is either the
+ fully qualified domain name (FQDN) of the tunnel client machine, or a
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 46]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ "dotted-decimal" IP address. Implementations MUST support the
+ dotted-decimal format and SHOULD support the FQDN format for IP
+ addresses.
+
+ If Tunnel-Medium-Type is IPv6 (2), then this string is either the
+ FQDN of the tunnel client machine, or a text representation of the
+ address in either the preferred or alternate form [IPv6Addr].
+ Conforming implementations MUST support the preferred form and SHOULD
+ support both the alternate text form and the FQDN format for IPv6
+ addresses.
+
+ If Tunnel-Medium-Type is neither IPv4 nor IPv6, then this string is a
+ tag referring to configuration data local to the Diameter client that
+ describes the interface or medium-specific client address to use.
+
+7.5. Tunnel-Server-Endpoint AVP
+
+ The Tunnel-Server-Endpoint AVP (AVP Code 67) is of type UTF8String
+ and contains the address of the server end of the tunnel. It MAY be
+ used in an authorization request as a hint to the server that a
+ specific endpoint is desired, but the server is not required to honor
+ the hint in the corresponding response.
+
+ This AVP SHOULD be included in the corresponding Accounting-Request
+ messages, in which case it indicates the address from which the
+ tunnel was initiated. This AVP, along with the Tunnel-Client-
+ Endpoint and Session-Id AVP [BASE], MAY be used to provide a globally
+ unique means to identify a tunnel for accounting and auditing
+ purposes.
+
+ If Tunnel-Medium-Type is IPv4 (1), then this string is either the
+ fully qualified domain name (FQDN) of the tunnel server machine, or a
+ "dotted-decimal" IP address. Implementations MUST support the
+ dotted-decimal format and SHOULD support the FQDN format for IP
+ addresses.
+
+ If Tunnel-Medium-Type is IPv6 (2), then this string is either the
+ FQDN of the tunnel server machine, or a text representation of the
+ address in either the preferred or alternate form [IPv6Addr].
+ Implementations MUST support the preferred form and SHOULD support
+ both the alternate text form and the FQDN format for IPv6 addresses.
+
+ If Tunnel-Medium-Type is not IPv4 or IPv6, this string is a tag
+ referring to configuration data local to the Diameter client that
+ describes the interface or medium-specific server address to use.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 47]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+7.6. Tunnel-Password AVP
+
+ The Tunnel-Password AVP (AVP Code 69) is of type OctetString and may
+ contain a password to be used to authenticate to a remote server.
+ The Tunnel-Password AVP contains sensitive information. This value
+ is not protected in the same manner as RADIUS [RADTunnels].
+
+ As required in [BASE], Diameter messages are encrypted by using IPsec
+ or TLS. The Tunnel-Password AVP SHOULD NOT be used in untrusted
+ proxy environments without encrypting it by using end-to-end security
+ techniques, such as CMS Security [DiamCMS].
+
+7.7. Tunnel-Private-Group-Id AVP
+
+ The Tunnel-Private-Group-Id AVP (AVP Code 81) is of type OctetString
+ and contains the group Id for a particular tunneled session. The
+ Tunnel-Private-Group-Id AVP MAY be included in an authorization
+ request if the tunnel initiator can predetermine the group resulting
+ from a particular connection. It SHOULD be included in the
+ authorization response if this tunnel session is to be treated as
+ belonging to a particular private group. Private groups may be used
+ to associate a tunneled session with a particular group of users.
+ For example, it MAY be used to facilitate routing of unregistered IP
+ addresses through a particular interface. This AVP SHOULD be
+ included in the Accounting-Request messages that pertain to the
+ tunneled session.
+
+7.8. Tunnel-Assignment-Id AVP
+
+ The Tunnel-Assignment-Id AVP (AVP Code 82) is of type OctetString and
+ is used to indicate to the tunnel initiator the particular tunnel to
+ which a session is to be assigned. Some tunneling protocols, such as
+ [PPTP] and [L2TP], allow for sessions between the same two tunnel
+ endpoints to be multiplexed over the same tunnel and also for a given
+ session to use its own dedicated tunnel. This attribute provides a
+ mechanism for Diameter to inform the tunnel initiator (e.g., PAC,
+ LAC) whether to assign the session to a multiplexed tunnel or to a
+ separate tunnel. Furthermore, it allows for sessions sharing
+ multiplexed tunnels to be assigned to different multiplexed tunnels.
+
+ A particular tunneling implementation may assign differing
+ characteristics to particular tunnels. For example, different
+ tunnels may be assigned different QoS parameters. Such tunnels may
+ be used to carry either individual or multiple sessions. The
+ Tunnel-Assignment-Id attribute thus allows the Diameter server to
+ indicate that a particular session is to be assigned to a tunnel
+ providing an appropriate level of service. It is expected that any
+ QoS-related Diameter tunneling attributes defined in the future
+
+
+
+Calhoun, et al. Standards Track [Page 48]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ accompanying this one will be associated by the tunnel initiator with
+ the Id given by this attribute. In the meantime, any semantic given
+ to a particular Id string is a matter left to local configuration in
+ the tunnel initiator.
+
+ The Tunnel-Assignment-Id AVP is of significance only to Diameter and
+ the tunnel initiator. The Id it specifies is only intended to be of
+ local use to Diameter and the tunnel initiator. The Id assigned by
+ the tunnel initiator is not conveyed to the tunnel peer.
+
+ This attribute MAY be included in authorization responses. The
+ tunnel initiator receiving this attribute MAY choose to ignore it and
+ to assign the session to an arbitrary multiplexed or non-multiplexed
+ tunnel between the desired endpoints. This AVP SHOULD also be
+ included in the Accounting-Request messages pertaining to the
+ tunneled session.
+
+ If a tunnel initiator supports the Tunnel-Assignment-Id AVP, then it
+ should assign a session to a tunnel in the following manner:
+
+ - If this AVP is present and a tunnel exists between the
+ specified endpoints with the specified Id, then the session
+ should be assigned to that tunnel.
+
+ - If this AVP is present and no tunnel exists between the
+ specified endpoints with the specified Id, then a new tunnel
+ should be established for the session and the specified Id
+ should be associated with the new tunnel.
+
+ - If this AVP is not present, then the session is assigned to an
+ unnamed tunnel. If an unnamed tunnel does not yet exist
+ between the specified endpoints, then it is established and
+ used for this session and for subsequent ones established
+ without the Tunnel-Assignment-Id attribute. A tunnel initiator
+ MUST NOT assign a session for which a Tunnel-Assignment-Id AVP
+ was not specified to a named tunnel (i.e., one that was
+ initiated by a session specifying this AVP).
+
+ Note that the same Id may be used to name different tunnels if these
+ tunnels are between different endpoints.
+
+7.9. Tunnel-Preference AVP
+
+ The Tunnel-Preference AVP (AVP Code 83) is of type Unsigned32 and is
+ used to identify the relative preference assigned to each tunnel when
+ more than one set of tunneling AVPs is returned within separate
+ Grouped-AVP AVPs. It MAY be used in an authorization request as a
+ hint to the server that a specific preference is desired, but the
+
+
+
+Calhoun, et al. Standards Track [Page 49]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ server is not required to honor the hint in the corresponding
+ response.
+
+ For example, suppose that AVPs describing two tunnels are returned by
+ the server, one with a Tunnel-Type of PPTP and the other with a
+ Tunnel-Type of L2TP. If the tunnel initiator supports only one of
+ the Tunnel-Types returned, it will initiate a tunnel of that type.
+ If, however, it supports both tunnel protocols, it SHOULD use the
+ value of the Tunnel-Preference AVP to decide which tunnel should be
+ started. The tunnel with the lowest numerical value in the Value
+ field of this AVP SHOULD be given the highest preference. The values
+ assigned to two or more instances of the Tunnel-Preference AVP within
+ a given authorization response MAY be identical. In this case, the
+ tunnel initiator SHOULD use locally configured metrics to decide
+ which set of AVPs to use.
+
+7.10. Tunnel-Client-Auth-Id AVP
+
+ The Tunnel-Client-Auth-Id AVP (AVP Code 90) is of type UTF8String and
+ specifies the name used by the tunnel initiator during the
+ authentication phase of tunnel establishment. It MAY be used in an
+ authorization request as a hint to the server that a specific
+ preference is desired, but the server is not required to honor the
+ hint in the corresponding response. This AVP MUST be present in the
+ authorization response if an authentication name other than the
+ default is desired. This AVP SHOULD be included in the Accounting-
+ Request messages pertaining to the tunneled session.
+
+7.11. Tunnel-Server-Auth-Id AVP
+
+ The Tunnel-Server-Auth-Id AVP (AVP Code 91) is of type UTF8String and
+ specifies the name used by the tunnel terminator during the
+ authentication phase of tunnel establishment. It MAY be used in an
+ authorization request as a hint to the server that a specific
+ preference is desired, but the server is not required to honor the
+ hint in the corresponding response. This AVP MUST be present in the
+ authorization response if an authentication name other than the
+ default is desired. This AVP SHOULD be included in the Accounting-
+ Request messages pertaining to the tunneled session.
+
+8. NAS Accounting
+
+ Applications implementing this specification use Diameter Accounting,
+ as defined in [BASE], and the AVPs in the following section.
+ Service-specific AVP usage is defined in the tables in section 10.
+
+ If accounting is active, Accounting Request (ACR) messages SHOULD be
+ sent after the completion of any Authentication or Authorization
+
+
+
+Calhoun, et al. Standards Track [Page 50]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ transaction and at the end of a Session. The Accounting-Record-Type
+ value indicates the type of event. All other AVPs identify the
+ session and provide additional information relevant to the event.
+
+ The successful completion of the first Authentication or
+ Authorization transaction SHOULD cause a START_RECORD to be sent. If
+ additional Authentications or Authorizations occur in later
+ transactions, the first exchange should generate a START_RECORD, and
+ the later an INTERIM_RECORD. For a given session, there MUST only be
+ one set of matching START and STOP records, with any number of
+ INTERIM_RECORDS in between, or one EVENT_RECORD indicating the reason
+ a session wasn't started.
+
+ The following table describes the AVPs; their AVP Code values, types,
+ and possible flag values; and whether the AVP MAY be encrypted.
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST| |
+ Attribute Name Code Defined Value Type |MUST| MAY | NOT| NOT|Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ Accounting- 363 8.1 Unsigned64 | M | P | | V | Y |
+ Input-Octets | | | | | |
+ Accounting- 364 8.2 Unsigned64 | M | P | | V | Y |
+ Output-Octets | | | | | |
+ Accounting- 365 8.3 Unsigned64 | M | P | | V | Y |
+ Input-Packets | | | | | |
+ Accounting- 366 8.4 Unsigned64 | M | P | | V | Y |
+ Output-Packets | | | | | |
+ Acct-Session-Time 46 8.5 Unsigned32 | M | P | | V | Y |
+ Acct-Authentic 45 8.6 Enumerated | M | P | | V | Y |
+ Acounting-Auth- 406 8.7 Enumerated | M | P | | V | Y |
+ Method | | | | | |
+ Acct-Delay-Time 41 8.8 Unsigned32 | M | P | | V | Y |
+ Acct-Link-Count 51 8.9 Unsigned32 | M | P | | V | Y |
+ Acct-Tunnel- 68 8.10 OctetString| M | P | | V | Y |
+ Connection | | | | | |
+ Acct-Tunnel- 86 8.11 Unsigned32 | M | P | | V | Y |
+ Packets-Lost | | | | | |
+ -----------------------------------------|----+-----+----+-----|----|
+
+8.1. Accounting-Input-Octets AVP
+
+ The Accounting-Input-Octets AVP (AVP Code 363) is of type Unsigned64
+ and contains the number of octets received from the user.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 51]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ For NAS usage, this AVP indicates how many octets have been received
+ from the port in the course of this session. It can only be present
+ in ACR messages with an Accounting-Record-Type of INTERIM_RECORD or
+ STOP_RECORD.
+
+8.2. Accounting-Output-Octets AVP
+
+ The Accounting-Output-Octets AVP (AVP Code 364) is of type Unsigned64
+ and contains the number of octets sent to the user.
+
+ For NAS usage, this AVP indicates how many octets have been sent to
+ the port in the course of this session. It can only be present in
+ ACR messages with an Accounting-Record-Type of INTERIM_RECORD or
+ STOP_RECORD.
+
+8.3. Accounting-Input-Packets AVP
+
+ The Accounting-Input-Packets (AVP Code 365) is of type Unsigned64 and
+ contains the number of packets received from the user.
+
+ For NAS usage, this AVP indicates how many packets have been received
+ from the port over the course of a session being provided to a Framed
+ User. It can only be present in ACR messages with an Accounting-
+ Record-Type of INTERIM_RECORD or STOP_RECORD.
+
+8.4. Accounting-Output-Packets AVP
+
+ The Accounting-Output-Packets (AVP Code 366) is of type Unsigned64
+ and contains the number of IP packets sent to the user.
+
+ For NAS usage, this AVP indicates how many packets have been sent to
+ the port over the course of a session being provided to a Framed
+ User. It can only be present in ACR messages with an Accounting-
+ Record-Type of INTERIM_RECORD or STOP_RECORD.
+
+8.5. Acct-Session-Time AVP
+
+ The Acct-Session-Time AVP (AVP Code 46) is of type Unsigned32 and
+ indicates the length of the current session in seconds. It can only
+ be present in ACR messages with an Accounting-Record-Type of
+ INTERIM_RECORD or STOP_RECORD.
+
+8.6. Acct-Authentic AVP
+
+ The Acct-Authentic AVP (AVP Code 45) is of type Enumerated and
+ specifies how the user was authenticated. The supported values are
+ listed in [RADIUSTypes]. The following list is informational:
+
+
+
+
+Calhoun, et al. Standards Track [Page 52]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ 1 RADIUS
+ 2 Local
+ 3 Remote
+ 4 Diameter
+
+8.7. Accounting-Auth-Method AVP
+
+ The Accounting-Auth-Method AVP (AVP Code 406) is of type Enumerated.
+ A NAS MAY include this AVP in an Accounting-Request message to
+ indicate the method used to authenticate the user. (Note that this
+ is equivalent to the RADIUS MS-Acct-Auth-Type VSA attribute).
+
+ The following values are defined:
+
+ 1 PAP
+ 2 CHAP
+ 3 MS-CHAP-1
+ 4 MS-CHAP-2
+ 5 EAP
+ 7 None
+
+8.8. Acct-Delay-Time
+
+ The Acct-Delay-Time AVP (AVP Code 41) is of type Unsigned32 and
+ indicates the number of seconds the Diameter client has been trying
+ to send the Accounting-Request (ACR). The accounting server may
+ subtract this value from the time when the ACR arrives at the server
+ to calculate the approximate time of the event that caused the ACR to
+ be generated.
+
+ This AVP is not used for retransmissions at the transport level (TCP
+ or SCTP). Rather, it may be used when an ACR command cannot be
+ transmitted because there is no appropriate peer to transmit it to or
+ was rejected because it could not be delivered. In these cases, the
+ command MAY be buffered and transmitted later, when an appropriate
+ peer-connection is available or after sufficient time has passed that
+ the destination-host may be reachable and operational. If the ACR is
+ resent in this way, the Acct-Delay-Time AVP SHOULD be included. The
+ value of this AVP indicates the number of seconds that elapsed
+ between the time of the first attempt at transmission and the current
+ attempt.
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 53]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+8.9. Acct-Link-Count
+
+ The Acct-Link-Count AVP (AVP Code 51) is of type Unsigned32 and
+ indicates the total number of links that have been active (current or
+ closed) in a given multilink session at the time the accounting
+ record is generated. This AVP MAY be included in Accounting-Requests
+ for any session that may be part of a multilink service.
+
+ The Acct-Link-Count AVP may be used to make it easier for an
+ accounting server to know when it has all the records for a given
+ multilink service. When the number of Accounting-Requests received
+ with Accounting-Record-Type = STOP_RECORD and with the same Acct-
+ Multi-Session-Id and unique Session-Ids equals the largest value of
+ Acct-Link-Count seen in those Accounting-Requests, all STOP_RECORD
+ Accounting-Requests for that multilink service have been received.
+
+ The following example, showing eight Accounting-Requests, illustrates
+ how the Acct-Link-Count AVP is used. In the table below, only the
+ relevant AVPs are shown, although additional AVPs containing
+ accounting information will be present in the Accounting-Requests.
+
+ Acct-Multi- Accounting- Acct-
+ Session-Id Session-Id Record-Type Link-Count
+ --------------------------------------------------------
+ "...10" "...10" START_RECORD 1
+ "...10" "...11" START_RECORD 2
+ "...10" "...11" STOP_RECORD 2
+ "...10" "...12" START_RECORD 3
+ "...10" "...13" START_RECORD 4
+ "...10" "...12" STOP_RECORD 4
+ "...10" "...13" STOP_RECORD 4
+ "...10" "...10" STOP_RECORD 4
+
+8.10. Acct-Tunnel-Connection AVP
+
+ The Acct-Tunnel-Connection AVP (AVP Code 68) is of type OctetString
+ and contains the identifier assigned to the tunnel session. This
+ AVP, along with the Tunnel-Client-Endpoint and Tunnel-Server-Endpoint
+ AVPs, may be used to provide a means to uniquely identify a tunnel
+ session for auditing purposes.
+
+ The format of the identifier in this AVP depends upon the value of
+ the Tunnel-Type AVP. For example, to identify an L2TP tunnel
+ connection fully, the L2TP Tunnel Id and Call Id might be encoded in
+ this field. The exact encoding of this field is implementation
+ dependent.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 54]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+8.11. Acct-Tunnel-Packets-Lost AVP
+
+ The Acct-Tunnel-Packets-Lost AVP (AVP Code 86) is of type Unsigned32
+ and contains the number of packets lost on a given link.
+
+9. RADIUS/Diameter Protocol Interactions
+
+ This section describes some basic guidelines that servers acting as
+ AAA Translation Agents may use. A complete description of all the
+ differences between RADIUS and Diameter is beyond the scope of this
+ section and document. Note that this document does not restrict
+ implementations from creating additional translation methods, as long
+ as the translation function doesn't violate the RADIUS or the
+ Diameter protocols.
+
+ Although the Diameter protocol is in many ways a superset of RADIUS
+ functions, a number of RADIUS representations are not allowed, so
+ that new capabilities can be used without the old problems.
+
+ There are primarily two different situations that must be handled:
+ one in which a RADIUS request is received that must be forwarded as a
+ Diameter request, and another in which the inverse is true. RADIUS
+ does not support a peer-to-peer architecture, and server-initiated
+ operations are generally not supported. See [RADDynAuth] for an
+ alternative.
+
+ Some RADIUS attributes are encrypted. RADIUS security and encryption
+ techniques are applied on a hop-per-hop basis. A Diameter agent will
+ have to decrypt RADIUS attribute data entering the Diameter system,
+ and if that information is forwarded, the agent MUST secure it by
+ using Diameter specific techniques.
+
+ Note that this section uses the two terms, "AVP" and "attribute", in
+ a concise and specific manner. The former is used to signify a
+ Diameter AVP, and the latter to signify a RADIUS attribute.
+
+9.1. RADIUS Request Forwarded as Diameter Request
+
+ This section describes the actions that should be taken when a
+ Translation Agent receives a RADIUS message to be translated to a
+ Diameter message.
+
+ Note that RADIUS servers are assumed to be stateless. It is also
+ quite possible for the RADIUS messages that comprise the session
+ (i.e., authentication and accounting messages) to be handled by
+ different Translation Agents in the proxy network. Therefore, a
+ RADIUS/Diameter Translation Agent SHOULD NOT be assumed to have an
+ accurate track on session-state information.
+
+
+
+Calhoun, et al. Standards Track [Page 55]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ When a Translation Agent receives a RADIUS message, the following
+ steps should be taken:
+
+ - If a Message-Authenticator attribute is present, the value MUST
+ be checked but not included in the Diameter message. If it is
+ incorrect, the RADIUS message should be silently discarded.
+ The gateway system SHOULD generate and include a Message-
+ Authenticator in returned RADIUS responses.
+
+ - The transport address of the sender MUST be checked against the
+ NAS identifying attributes. See the description of NAS-
+ Identifier and NAS-IP-Address below.
+
+ - The Translation Agent must maintain transaction state
+ information relevant to the RADIUS request, such as the
+ Identifier field in the RADIUS header, any existing RADIUS
+ Proxy-State attribute, and the source IP address and port
+ number of the UDP packet. These may be maintained locally in a
+ state table or saved in a Proxy-Info AVP group. A Diameter
+ Session-Id AVP value must be created using a session state
+ mapping mechanism.
+
+ - If the RADIUS request contained a State attribute and the
+ prefix of the data is "Diameter/", the data following the
+ prefix contains the Diameter Origin-Host/Origin-Realm/Session-
+ Id. If no such attributes are present and the RADIUS command
+ is an Access-Request, a new Session-Id is created. The
+ Session-Id is included in the Session-Id AVP.
+
+ - The Diameter Origin-Host and Origin-Realm AVPs MUST be created
+ and added by using the information from an FQDN corresponding
+ to the NAS-IP-Address attribute (preferred if available),
+ and/or to the NAS-Identifier attribute. (Note that the RADIUS
+ NAS-Identifier is not required to be an FQDN.)
+
+ - The response MUST have an Origin-AAA-Protocol AVP added,
+ indicating the protocol of origin of the message.
+
+ - The Proxy-Info group SHOULD be added, with the local server's
+ identity specified in the Proxy-Host AVP. This should ensure
+ that the response is returned to this system.
+
+ - The Destination-Realm AVP is created from the information found
+ in the RADIUS User-Name attribute.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 56]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ - If the RADIUS User-Password attribute is present, the password
+ must be unencrypted by using the link's RADIUS shared secret.
+ The unencrypted value must be forwarded in a User-Password AVP
+ using Diameter security.
+
+ - If the RADIUS CHAP-Password attribute is present, the Ident and
+ Data portion of the attribute are used to create the CHAP-Auth
+ grouped AVP.
+
+ - If the RADIUS message contains an address attribute, it MUST be
+ converted to the appropriate Diameter AVP and type.
+
+ - If the RADIUS message contains Tunnel information [RADTunnels],
+ the attributes or tagged groups should each be converted to a
+ Diameter Tunneling Grouped AVP set. If the tunnel information
+ contains a Tunnel-Password attribute, the RADIUS encryption
+ must be resolved, and the password forwarded, by using Diameter
+ security methods.
+
+ - If the RADIUS message received is an Accounting-Request, the
+ Acct-Status-Type attribute value must be converted to a
+ Accounting-Record-Type AVP value. If the Acct-Status-Type
+ attribute value is STOP, the local server MUST issue a
+ Session-Termination-Request message once the Diameter
+ Accounting-Answer message has been received.
+
+ - If the Accounting message contains an Acct-Termination-Cause
+ attribute, it should be translated to the equivalent
+ Termination-Cause AVP value. (see below)
+
+ - If the RADIUS message contains the Accounting-Input-Octets,
+ Accounting-Input-Packets, Accounting-Output-Octets, or
+ Accounting-Output-Packets, these attributes must be converted
+ to the Diameter equivalents. Further, if the Acct-Input-
+ Gigawords or Acct-Output-Gigawords attributes are present,
+ these must be used to properly compute the Diameter accounting
+ AVPs.
+
+ The corresponding Diameter response is always guaranteed to be
+ received by the same Translation Agent that translated the original
+ request, due to the contents of the Proxy-Info AVP group in the
+ Diameter request. The following steps are applied to the response
+ message during the Diameter-to-RADIUS translation:
+
+ - If the Diameter Command-Code is set to AA-Answer and the
+ Result-Code AVP is set to DIAMETER_MULTI_ROUND_AUTH, the
+ gateway must send a RADIUS Access-Challenge. This must have
+ the Origin-Host, Origin-Realm, and Diameter Session-Id AVPs
+
+
+
+Calhoun, et al. Standards Track [Page 57]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ encapsulated in the RADIUS State attribute, with the prefix
+ "Diameter/", concatenated in the above order separated with "/"
+ characters, in UTF-8 [UTF-8]. This is necessary to ensure that
+ the Translation Agent receiving the subsequent RADIUS Access-
+ Request will have access to the Session Identifier and be able
+ to set the Destination-Host to the correct value. If the
+ Multi-Round-Time-Out AVP is present, the value of the AVP MUST
+ be inserted in the RADIUS Session-Timeout AVP.
+
+ - If the Command-Code is set to AA-Answer, the Diameter Session-
+ Id AVP is saved in a new RADIUS Class attribute whose format
+ consists of the string "Diameter/" followed by the Diameter
+ Session Identifier. This will ensure that the subsequent
+ Accounting messages, which could be received by any Translation
+ Agent, would have access to the original Diameter Session
+ Identifier.
+ - If a Proxy-State attribute was present in the RADIUS request,
+ the same attribute is added in the response. This information
+ may be found in the Proxy-Info AVP group, or in a local state
+ table.
+
+ - If state information regarding the RADIUS request was saved in
+ a Proxy-Info AVP or local state table, the RADIUS Identifier
+ and UDP IP Address and port number are extracted and used in
+ issuing the RADIUS reply.
+
+ When translating a Diameter AA-Answer (with successful result code)
+ to RADIUS Access-Accept that contains a Session-Timeout or
+ Authorization-Lifetime AVP, take the following steps:
+
+ - If the Diameter message contains a Session-Timeout AVP but no
+ Authorization-Lifetime AVP, translate it to a Session-Timeout
+ attribute (not a Termination-Action).
+
+ - If the Diameter message contains an Authorization-Lifetime AVP
+ but no Session-Timeout AVP, translate it to a Session-Timeout
+ attribute and a Termination-Action set to AA-REQUEST. (Remove
+ Authorization-Lifetime and Re-Auth-Request-Type.)
+
+ - If the Diameter message has both, the Session-Timeout must be
+ greater than or equal to the Authorization-Lifetime (required
+ by [BASE]). Translate it to a Session-Timeout value (with
+ value from Authorization-Lifetime AVP, the smaller one) and
+ with the Termination-Action set to AA-REQUEST. (Remove the
+ Authorization-Lifetime and Re-Auth-Request-Type.)
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 58]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+9.1.1. RADIUS Dynamic Authorization Considerations
+
+ A Diameter/RADIUS gateway may communicate with a server that
+ implements RADIUS Dynamic Authorization [RADDynAuth]. If the server
+ supports these functions, it MUST be listening on the assigned port
+ and would receive RADIUS CoA-Request and Disconnect-Request messages.
+ These can be mapped into the Diameter Re-Auth-Request (RAR) and
+ Abort-Session-Request (ASR) message exchanges, respectively [BASE].
+
+ If the [RADDynAuth] is not supported, the port would not be active
+ and the RADIUS server would receive an ICMP Port Unreachable
+ indication. Alternatively, if the messages are received but with an
+ inappropriate Service-Type, the gateway can respond with the
+ appropriate NAK message and an Error-Cause attribute with the value
+ of 405, "Unsupported Service".
+
+ The RADIUS CoA-Request and Disconnect-Request messages will not
+ contain a Diameter Session-Id. Diameter requires that this value
+ match an active session context. The gateway MUST have a session Id
+ cache (or other means) to identify the sessions these functions
+ pertain to. If unable to identify the session, the gateway (or NAS)
+ should return an Error-Cause value 503, "Session Context Not Found".
+
+ The RADIUS CoA-Request message only supports a change of
+ authorization attributes, and the received CoA-Request SHOULD include
+ a Service-Type of "Authorize-Only". This indicates an extended
+ exchange request by the rules given in [RADDynAuth] section 3.2, note
+ 6. This is the only type of exchange supported by Diameter [BASE].
+
+ For the CoA-Request, the translated RAR message will have a Re-Auth-
+ Type of AUTHORIZE_ONLY. The returned RAA will be translated into a
+ CoA-NAK with Error-Cause "Request Initiated". The gateway's Diameter
+ client SHOULD also start a reauthorization sequence by sending an AAR
+ message, which will be translated into an Access-Request message.
+ The RADIUS server will use the Access-Accept (or Access-Reject)
+ message to convey the new authorization attributes, which the gateway
+ will pass back in an AAA message.
+
+ Any attributes included in the COA-Request or Access-Accept message
+ are to be considered mandatory in Diameter. If they cannot be
+ supported, they MUST result in an error message return to the RADIUS
+ server, with an Error-Cause of "Unsupported Attribute". The Diameter
+ NAS will attempt to apply all the attributes supplied in the AA
+ message to the session.
+
+ A RADIUS Disconnect-Request message received by the gateway would be
+ translated to a Diameter Abort-Session-Request (ASR) message [BASE].
+ The results will be returned by the Diameter client in an Abort-
+
+
+
+Calhoun, et al. Standards Track [Page 59]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Session-Answer (ASA) message. A success indication would translate
+ to a RADIUS Disconnect-ACK, and a failure would generate a
+ Disconnect-NAK.
+
+9.2. Diameter Request Forwarded as RADIUS Request
+
+ When a server receives a Diameter request to be forwarded to a RADIUS
+ entity, the following are examples of the steps that may be taken:
+
+ - The Origin-Host AVP's value is inserted into the NAS-Identifier
+ attribute.
+
+ - The following information MUST be present in the corresponding
+ Diameter response and therefore MUST be saved, either in a
+ local state table or encoded in a RADIUS Proxy-State attribute:
+
+ 1. Origin-Host AVP
+ 2. Session-Id AVP
+ 3. Proxy-Info AVP
+ 4. Any other AVP that MUST be present in the response and
+ has no corresponding RADIUS attribute.
+
+ - If the CHAP-Auth AVP is present, the grouped AVPs are used to
+ create the RADIUS CHAP-Password attribute data.
+
+ - If the User-Password AVP is present, the data should be
+ encrypted and forwarded by using RADIUS rules. The same is
+ true for any other RADIUS-encrypted attribute values.
+
+ - AVPs of the type Address must be translated to the
+ corresponding RADIUS attribute.
+
+ - If the Accounting-Input-Octets, Accounting-Input-Packets,
+ Accounting-Output-Octets, or Accounting-Output-Packets AVPs are
+ present, they must be translated to the corresponding RADIUS
+ attributes. If the value of the Diameter AVPs do not fit
+ within a 32-bit RADIUS attribute, the RADIUS Acct-Input-
+ Gigawords and Acct-Output-Gigawords must be used.
+
+ - If the RADIUS link supports the Message-Authenticator attribute
+ [RADIUSExt], it SHOULD be generated and added to the request.
+
+ When the corresponding response is received by the Translation Agent,
+ which is guaranteed in the RADIUS protocol, the following steps may
+ be taken:
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 60]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ - If the RADIUS code is set to Access-Challenge, a Diameter AA-
+ Answer message is created with the Result-Code set to
+ DIAMETER_MULTI_ROUND_AUTH. If the Session-Timeout AVP is
+ present in the RADIUS message, its value is inserted into the
+ Multi-Round-Time-Out AVP.
+
+ - If a Proxy-State attribute is present, extract the encoded
+ information; otherwise, retrieve the original Proxy-Info AVP
+ group information from the local state table.
+
+ - The response's Origin-Host information is created from the FQDN
+ of the RADIUS message's source IP address. The same FQDN is
+ also stored to a Route-Record AVP.
+
+ - The response's Destination-Host AVP is copied from the saved
+ request's Origin-Host information.
+
+ - The Session-Id information can be recovered from local state,
+ or from the constructed State or Proxy-State attribute, as
+ above.
+
+ - If a Proxy-Info AVP was present in the request, the same AVP
+ MUST be added to the response.
+
+ - If the RADIUS State attributes are present, they must be
+ present in the Diameter response, minus those added by the
+ gateway.
+
+ - Any other AVPs that were saved at request time, and that MUST
+ be present in the response, are added to the message.
+
+ When translating a RADIUS Access-Accept to Diameter AA-Answer that
+ contains a Session-Timeout attribute, do the following:
+
+ - If the RADIUS message contains a Session-Timeout attribute and
+ a Termination-Action attribute set to DEFAULT (or no
+ Termination-Action attribute at all), translate it to AA-Answer
+ with a Session-Timeout AVP and remove the Termination-Action
+ attribute.
+
+ - If the RADIUS message contains a Session-Timeout attribute and
+ a Termination-Action attribute set to AA-REQUEST, translate it
+ to AA-Answer with Authorization-Lifetime AVP and with Re-Auth-
+ Request-Type set to AUTHORIZE_AUTHENTICATE and remove the
+ Session-Timeout attribute.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 61]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+9.2.1. RADIUS Dynamic Authorization Considerations
+
+ A RADIUS/Diameter gateway communicating with a RADIUS client that
+ implements RADIUS Dynamic Authorization [RADDynAuth] may translate
+ Diameter Re-Auth-Request (RAR) messages and Abort-Session-Request
+ (ASR) messages [BASE] into RADIUS CoA-Request and Disconnect-Request
+ messages respectively.
+
+ If the RADIUS client does not support the capability, the gateway
+ will receive an ICMP Port Unreachable indication when it transmits
+ the RADIUS message. Even if the NAS supports [RADDynAuth], it may
+ not support the Service-Type in the request message. In this case it
+ will respond with a NAK message and (optionally) an Error-Cause
+ attribute with value 405, "Unsupported Service". If the gateway
+ encounters these error conditions, or if it does not support
+ [RADDynAuth], it sends a Diameter Answer message with an Result-Code
+ AVP of "DIAMETER_COMMAND_UNSUPPORTED" to the AAA server.
+
+ When encoding the RADIUS messages, the gateway MUST include the
+ Diameter Session-ID in the RADIUS State attribute value, as mentioned
+ above. The RADIUS client should return it in the response.
+
+ A Diameter Re-Auth-Request (RAR) message [BASE] received by the
+ gateway will be translated into a RADIUS CoA-Request and sent to the
+ RADIUS client. The RADIUS client should respond with a CoA-ACK or
+ CoA-NAK message, which the gateway should translate into a Re-Auth-
+ Answer (RAA) message.
+
+ If the gateway receives a RADIUS CoA-NAK response containing a
+ Service-Type Attribute with value "Authorize Only" and an Error-Cause
+ Attribute with value "Request Initiated", this indicates an extended
+ exchange request per [RADDynAuth] section 3.2, note 6.
+
+ The response is translated to a Diameter Re-Auth-Answer (RAA) with a
+ Result-Code AVP of "DIAMETER_LIMITED_SUCCESS" sent to the AAA server.
+
+ Subsequently, the gateway should receive a RADIUS Access-Request from
+ the NAS, with a Service-Type of "Authorize Only". This is translated
+ into a Diameter AA-Request with an Auth-Request-Type AVP of
+ AUTHORIZE_ONLY and sent to the AAA server. The AAA server will then
+ reply with a Diameter AA-Answer, which is translated into a RADIUS
+ Access-Accept or Access-Reject, depending on the value of the
+ Result-Code AVP.
+
+ A Diameter Abort-Session-Request (ASR) message [BASE] received by the
+ gateway will be translated into a RADIUS Disconnect-Request and sent
+ to the RADIUS client. The RADIUS client should respond with a
+
+
+
+
+Calhoun, et al. Standards Track [Page 62]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Disconnect-ACK or Disconnect-NAK message, which the gateway should
+ translate into an Abort-Session-Answer (ASA) message.
+
+ If the gateway receives a RADIUS Disconnect-NAK response containing a
+ Service-Type Attribute with value "Authorize Only" and an Error-Cause
+ Attribute with value "Request Initiated", the Disconnect-NAK response
+ is translated into a Diameter Abort-Session-Answer (ASA) with a
+ Result-Code AVP of "DIAMETER_LIMITED_SUCCESS" sent to the AAA server.
+
+ Subsequently, the gateway should receive a RADIUS Access-Request from
+ the NAS, with a Service-Type of "Authorize Only". This is translated
+ into a Diameter AA-Request with an Auth-Request-Type AVP of
+ AUTHORIZE_ONLY and sent to the AAA server. The AAA server will then
+ reply with a Diameter AA-Answer, which is translated into a RADIUS
+ Access-Accept or Access-Reject, depending on the value of the
+ Result-Code AVP.
+
+9.3. AVPs Used Only for Compatibility
+
+ The AVPs defined in this section SHOULD only be used for backwards
+ compatibility when a Diameter/RADIUS translation function is invoked
+ and are not typically originated by Diameter systems during normal
+ operations.
+
+ +---------------------+
+ | AVP Flag rules |
+ |----+-----+----+-----|----+
+ AVP Section | | |SHLD| MUST| |
+ Attribute Name Code Defined Value Type |MUST| MAY | NOT| NOT|Encr|
+ -----------------------------------------|----+-----+----+-----|----|
+ NAS-Identifier 32 9.3.1 UTF8String | M | P | | V | Y |
+ NAS-IP-Address 4 9.3.2 OctetString| M | P | | V | Y |
+ NAS-IPv6-Address 95 9.3.3 OctetString| M | P | | V | Y |
+ State 24 9.3.4 OctetString| M | P | | V | Y |
+ Termination- 295 9.3.5 Enumerated | M | P | | V | Y |
+ Cause | | | | | |
+ Origin-AAA- 408 9.3.6 Enumerated | M | P | | V | Y |
+ Protocol | | | | | |
+ -----------------------------------------|----+-----+----+-----|----|
+
+9.3.1. NAS-Identifier AVP
+
+ The NAS-Identifier AVP (AVP Code 32) [RADIUS] is of type UTF8String
+ and contains the identity of the NAS providing service to the user.
+ This AVP SHOULD only be added by a RADIUS/Diameter Translation Agent.
+ When this AVP is present, the Origin-Host AVP identifies the NAS
+ providing service to the user.
+
+
+
+
+Calhoun, et al. Standards Track [Page 63]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ In RADIUS it would be possible for a rogue NAS to forge the NAS-
+ Identifier attribute. Diameter/RADIUS translation agents SHOULD
+ attempt to check a received NAS-Identifier attribute against the
+ source address of the RADIUS packet, by doing an A/AAAA RR query. If
+ the NAS-Identifier attribute contains an FQDN, then such a query
+ would resolve to an IP address matching the source address. However,
+ the NAS-Identifier attribute is not required to contain an FQDN, so
+ such a query could fail. If it fails, an error should be logged, but
+ no action should be taken, other than a reverse lookup on the source
+ address and insert the resulting FQDN into the Route-Record AVP.
+
+ Diameter agents and servers SHOULD check whether a NAS-Identifier AVP
+ corresponds to an entry in the Route-Record AVP. If no match is
+ found, then an error is logged, but no other action is taken.
+
+9.3.2. NAS-IP-Address AVP
+
+ The NAS-IP-Address AVP (AVP Code 4) [RADIUS] is of type OctetString
+ and contains the IP Address of the NAS providing service to the user.
+ This AVP SHOULD only be added by a RADIUS/Diameter Translation Agent.
+ When this AVP is present, the Origin-Host AVP identifies the NAS
+ providing service to the user.
+
+ In RADIUS it would be possible for a rogue NAS to forge the NAS-IP-
+ Address attribute value. Diameter/RADIUS translation agents MUST
+ check a received NAS-IP-Address or NAS-IPv6-Address attribute against
+ the source address of the RADIUS packet. If they do not match and
+ the Diameter/RADIUS translation agent does not know whether the
+ packet was sent by a RADIUS proxy or NAS (e.g., no Proxy-State
+ attribute), then by default it is assumed that the source address
+ corresponds to a RADIUS proxy, and that the NAS Address is behind
+ that proxy, potentially with some additional RADIUS proxies in
+ between. The Diameter/RADIUS translation agent MUST insert entries
+ in the Route-Record AVP corresponding to the apparent route. This
+ implies doing a reverse lookup on the source address and NAS-IP-
+ Address or NAS-IPv6-Address attributes to determine the corresponding
+ FQDNs.
+
+ If the source address and the NAS-IP-Address or NAS-IPv6-Address do
+ not match, and the Diameter/RADIUS translation agent knows that it is
+ talking directly to the NAS (e.g., there are no RADIUS proxies
+ between it and the NAS), then the error should be logged, and the
+ packet MUST be discarded.
+
+ Diameter agents and servers MUST check whether the NAS-IP-Address AVP
+ corresponds to an entry in the Route-Record AVP. This is done by
+ doing a reverse lookup (PTR RR) for the NAS-IP-Address to retrieve
+ the corresponding FQDN, and by checking for a match with the Route-
+
+
+
+Calhoun, et al. Standards Track [Page 64]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Record AVP. If no match is found, then an error is logged, but no
+ other action is taken.
+
+9.3.3. NAS-IPv6-Address AVP
+
+ The NAS-IPv6-Address AVP (AVP Code 95) [RADIUSIPv6] is of type
+ OctetString and contains the IPv6 Address of the NAS providing
+ service to the user. This AVP SHOULD only be added by a
+ RADIUS/Diameter Translation Agent. When this AVP is present, the
+ Origin-Host AVP identifies the NAS providing service to the user.
+
+ In RADIUS it would be possible for a rogue NAS to forge the NAS-
+ IPv6-Address attribute. Diameter/RADIUS translation agents MUST
+ check a received NAS-IPv6-Address attribute against the source
+ address of the RADIUS packet. If they do not match and the
+ Diameter/RADIUS translation agent does not know whether the packet
+ was sent by a RADIUS proxy or NAS (e.g., no Proxy-State attribute),
+ then by default it is assumed that the source address corresponds to
+ a RADIUS proxy, and that the NAS-IPv6-Address is behind that proxy,
+ potentially with some additional RADIUS proxies in between. The
+ Diameter/RADIUS translation agent MUST insert entries in the Route-
+ Record AVP corresponding to the apparent route. This implies doing a
+ reverse lookup on the source address and NAS-IPv6-Address attributes
+ to determine the corresponding FQDNs.
+
+ If the source address and the NAS-IPv6-Address do not match, and the
+ Diameter/RADIUS translation agent knows that it is talking directly
+ to the NAS (e.g., there are no RADIUS proxies between it and the
+ NAS), then the error should be logged, and the packet MUST be
+ discarded.
+
+ Diameter agents and servers MUST check whether the NAS-IPv6-Address
+ AVP corresponds to an entry in the Route-Record AVP. This is done by
+ doing a reverse lookup (PTR RR) for the NAS-IPv6-Address to retrieve
+ the corresponding FQDN, and by checking for a match with the Record-
+ Route AVP. If no match is found, then an error is logged, but no
+ other action is taken.
+
+9.3.4. State AVP
+
+ The State AVP (AVP Code 24) [RADIUS] is of type OctetString and has
+ two uses in the Diameter NAS application.
+
+ The State AVP MAY be sent by a Diameter Server to a NAS in an AA-
+ Response command that contains a Result-Code of
+ DIAMETER_MULTI_ROUND_AUTH. If so, the NAS MUST return it unmodified
+ in the subsequent AA-Request command.
+
+
+
+
+Calhoun, et al. Standards Track [Page 65]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ The State AVP MAY also be sent by a Diameter Server to a NAS in an
+ AA-Response command that also includes a Termination-Action AVP with
+ the value of AA-REQUEST. If the NAS performs the Termination-Action
+ by sending a new AA-Request command upon termination of the current
+ service, it MUST return the State AVP unmodified in the new request
+ command.
+
+ In either usage, the NAS MUST NOT interpret the AVP locally. Usage
+ of the State AVP is implementation dependent.
+
+9.3.5. Termination-Cause AVP Code Values
+
+ This section defines a mapping between Termination-Cause AVP code
+ values and RADIUS Acct-Terminate-Cause attribute code values from RFC
+ 2866 [RADIUSAcct] and [RADIUSTypes], thereby allowing a
+ RADIUS/Diameter Translation Agent to convert between the attribute
+ and AVP values. This section thus extends the definitions in the
+ "Termination-Cause AVP" section of the Base Diameter specification.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 66]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ The table in this section defines the mapping between Termination-
+ Cause AVP and RADIUS Acct-Terminate-Cause causes.
+
+ +-----------------------+
+ | Value |
+ +-----------+-----------+
+ Cause Value Name | RADIUS | Diameter |
+ ------------------------------|-----------+-----------+
+ User Request | 1 | 11 |
+ Lost Carrier | 2 | 12 |
+ Lost Service | 3 | 13 |
+ Idle Timeout | 4 | 14 |
+ Session Timeout | 5 | 15 |
+ Admin Reset | 6 | 16 |
+ Admin Reboot | 7 | 17 |
+ Port Error | 8 | 18 |
+ NAS Error | 9 | 19 |
+ NAS Request | 10 | 20 |
+ NAS Reboot | 11 | 21 |
+ Port Unneeded | 12 | 22 |
+ Port Preempted | 13 | 23 |
+ Port Suspended | 14 | 24 |
+ Service Unavailable | 15 | 25 |
+ Callback | 16 | 26 |
+ User Error | 17 | 27 |
+ Host Request | 18 | 28 |
+ Supplicant Restart | 19 | 29 | [RAD802.1X]
+ Reauthentication Failure | 20 | 30 | [RAD802.1X]
+ Port Reinit | 21 | 31 | [RAD802.1X]
+ Port Disabled | 22 | 32 | [RAD802.1X]
+ ------------------------------|-----------+-----------+
+
+ From RFC 2866, the termination causes are as follows:
+
+ User Request User requested termination of service, for
+ example with LCP Terminate or by logging out.
+
+ Lost Carrier DCD was dropped on the port.
+
+ Lost Service Service can no longer be provided; for
+ example, user's connection to a host was
+ interrupted.
+
+ Idle Timeout Idle timer expired.
+
+ Session Timeout Maximum session length timer expired.
+
+ Admin Reset Administrator reset the port or session.
+
+
+
+Calhoun, et al. Standards Track [Page 67]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ Admin Reboot Administrator is ending service on the NAS,
+ for example, prior to rebooting the NAS.
+
+ Port Error NAS detected an error on the port that
+ required ending the session.
+
+ NAS Error NAS detected an error (other than on the
+ port) that required ending the session.
+
+ NAS Request NAS ended the session for a non-error reason not
+ otherwise listed here.
+
+ NAS Reboot NAS ended the session to reboot
+ non-administratively ("crash").
+
+ Port Unneeded NAS ended the session because resource usage
+ fell below a low-water mark (for example, if
+ a bandwidth-on-demand algorithm decided that
+ the port was no longer needed).
+
+ Port Preempted NAS ended the session to allocate the
+ port to a higher priority use.
+
+ Port Suspended NAS ended the session to suspend a virtual
+ session.
+
+ Service Unavailable NAS was unable to provide requested service.
+
+ Callback NAS is terminating the current session
+ to perform callback for a new session.
+
+ User Error Input from user is in error, causing
+ session termination.
+
+ Host Request Login Host terminated session normally.
+
+9.3.6. Origin-AAA-Protocol
+
+ The Origin-AAA-Protocol AVP (AVP Code 408) is of the type Enumerated
+ and should be inserted in a Diameter message translated by a gateway
+ system from another AAA protocol, such as RADIUS. It identifies the
+ source protocol of the message to the Diameter system receiving the
+ message.
+
+ The supported values are:
+
+ 1 RADIUS
+
+
+
+
+Calhoun, et al. Standards Track [Page 68]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+9.4. Prohibited RADIUS Attributes
+
+ The following RADIUS attributes MUST NOT appear in a Diameter
+ message. Instead, they are translated to other Diameter AVPs or
+ handled in some special manner. The rules for the treatment of the
+ attributes are discussed in sections 9.1, 9.2, and 9.6.
+
+ Attribute Description Defined Nearest Diameter AVP
+ -----------------------------------------------------------------
+ 3 CHAP-Password RFC 2865 CHAP-Auth Group
+ 26 Vendor-Specific RFC 2865 Vendor Specific AVP
+ 29 Termination-Action RFC 2865 Authorization-Lifetime
+ 40 Acct-Status-Type RFC 2866 Accounting-Record-Type
+ 42 Acct-Input-Octets RFC 2866 Accounting-Input-Octets
+ 43 Acct-Output-Octets RFC 2866 Accounting-Output-Octets
+ 47 Acct-Input-Packets RFC 2866 Accounting-Input-Packets
+ 48 Acct-Output-Packets RFC 2866 Accounting-Output-Packets
+ 49 Acct-Terminate-Cause RFC 2866 Termination-Cause
+ 52 Acct-Input-Gigawords RFC 2869 Accounting-Input-Octets
+ 53 Acct-Output-Gigawords RFC 2869 Accounting-Output-Octets
+ 80 Message-Authenticator RFC 2869 none - check and discard
+
+9.5. Translatable Diameter AVPs
+
+ In general, Diameter AVPs that are not RADIUS compatible have code
+ values greater than 255. The table in the section above shows the
+ AVPs that can be converted into RADIUS attributes.
+
+ Another problem may occur with Diameter AVP values that may be more
+ than 253 octets in length. Some RADIUS attributes (including but not
+ limited to (8)Reply-Message, (79)EAP-Message, and (77)Connect-Info)
+ allow concatenation of multiple instances to overcome this
+ limitation. If this is not possible, a Result-Code of
+ DIAMETER_INVALID_AVP_LENGTH should be returned.
+
+9.6. RADIUS Vendor Specific Attributes
+
+ RADIUS supports the inclusion of Vendor Specific Attributes (VSAs)
+ through the use of attribute 26. The recommended format [RADIUS] of
+ the attribute data field includes a 4 octet vendor code followed by a
+ one octet vendor type field and a one octet length field. The last
+ two fields MAY be repeated.
+
+ A system communicating between Diameter and RADIUS MAY have specific
+ knowledge of vendor formats, and MAY be able to translate between the
+ two formats. However, given the deployment of many RADIUS vendor
+ formats that do not follow the example format in RFC 2865 [RADIUS],
+ (e.g., those that use a longer vendor type code) the translations in
+
+
+
+Calhoun, et al. Standards Track [Page 69]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ the next two sections will not work in general for those VSAs. RFC
+ 2865 states that a robust implementation SHOULD support the field as
+ undistinguished octets.
+
+ Systems that don't have vendor format knowledge MAY discard such
+ attributes without knowing a suitable translation. An alternative
+ format is under consideration [VSA], which proposes encodings that
+ would preserve the native information and not require vendor
+ knowledge in the gateway system.
+
+ The following sections are an example for translating RADIUS VSAs
+ that use the example RADIUS format, and Diameter VSAs that have type
+ codes less than 255, and value field lengths less than 252.
+
+9.6.1. Forwarding a Diameter Vendor Specific AVP as a RADIUS VSA
+
+ For Type codes less than 255, the value field length MUST be less
+ than 252 or the AVP will be discarded. The RADIUS VSA attribute
+ should consist of the following fields;
+
+ RADIUS Type = 26, Vendor Specific Attribute
+ RADIUS Length = total length of attribute (header + data)
+ RADIUS Vendor code = Diameter Vendor code
+ RADIUS Vendor type code = low order byte of Diameter AVP code
+ RADIUS Vendor data length = length of Diameter data
+
+ If the Diameter AVP code is greater than 255, then the RADIUS
+ speaking code may use a Vendor specific field coding, if it knows one
+ for that vendor. Otherwise, the AVP will be ignored. If it is
+ flagged as Mandatory, a "DIAMETER_AVP_UNSUPPORTED" Result-Code will
+ be returned, and the RADIUS message will not be sent.
+
+9.6.2. Forwarding a RADIUS VSA as a Diameter Vendor Specific AVP
+
+ The Diameter AVP will consist of the following fields:
+
+ Diameter Flags: V=1, M=0, P=0
+ Diameter Vendor code = RADIUS VSA Vendor code
+ Diameter AVP code = RADIUS VSA Vendor type code
+ Diameter AVP length = length of AVP (header + data)
+ Diameter Data = RADIUS VSA vendor data
+
+ Note that the VSAs are considered optional by RADIUS rules, and this
+ specification does not set the Mandatory flag. If an implementor
+ desires a VSA be made mandatory because it represents a required
+ service policy, the RADIUS gateway should have a process to set the
+ bit on the Diameter side.
+
+
+
+
+Calhoun, et al. Standards Track [Page 70]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ If the RADIUS receiving code knows of vendor specific field
+ interpretations for the specific vendor, it may employ them to parse
+ an extended AVP code or data length. Otherwise the recommended
+ standard fields will be used.
+
+ Nested Multiple vendor data fields MUST be expanded into multiple
+ Diameter AVPs.
+
+10. AVP Occurrence Tables
+
+ The following tables present the AVPs used by NAS applications in NAS
+ messages and specify in which Diameter messages they MAY or MAY NOT
+ be present. [BASE] messages and AVPs are not described in this
+ document. Note that AVPs that can only be present within a Grouped
+ AVP are not represented in this table.
+
+ The table uses 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.
+ 0-1 Zero or one instance of the AVP MAY be present in the
+ message.
+ 1 One instance of the AVP MUST be present in the message.
+
+10.1. AA-Request/Answer AVP Table
+
+ The table in this section is limited to the Command Codes defined in
+ this specification.
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | AAR | AAA |
+ ------------------------------|-----+-----+
+ Acct-Interim-Interval | 0 | 0-1 |
+ ARAP-Challenge-Response | 0 | 0-1 |
+ ARAP-Features | 0 | 0-1 |
+ ARAP-Password | 0-1 | 0 |
+ ARAP-Security | 0-1 | 0-1 |
+ ARAP-Security-Data | 0+ | 0+ |
+ ARAP-Zone-Access | 0 | 0-1 |
+ Auth-Application-Id | 1 | 1 |
+ Auth-Grace-Period | 0-1 | 0-1 |
+ Auth-Request-Type | 1 | 1 |
+ Auth-Session-State | 0-1 | 0-1 |
+ Authorization-Lifetime | 0-1 | 0-1 |
+ ------------------------------|-----+-----+
+
+
+
+Calhoun, et al. Standards Track [Page 71]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | AAR | AAA |
+ ------------------------------|-----+-----+
+ Callback-Id | 0 | 0-1 |
+ Callback-Number | 0-1 | 0-1 |
+ Called-Station-Id | 0-1 | 0 |
+ Calling-Station-Id | 0-1 | 0 |
+ CHAP-Auth | 0-1 | 0 |
+ CHAP-Challenge | 0-1 | 0 |
+ Class | 0 | 0+ |
+ Configuration-Token | 0 | 0+ |
+ Connect-Info | 0+ | 0 |
+ Destination-Host | 0-1 | 0 |
+ Destination-Realm | 1 | 0 |
+ Error-Message | 0 | 0-1 |
+ Error-Reporting-Host | 0 | 0-1 |
+ Failed-AVP | 0+ | 0+ |
+ Filter-Id | 0 | 0+ |
+ Framed-Appletalk-Link | 0 | 0-1 |
+ Framed-Appletalk-Network | 0 | 0+ |
+ Framed-Appletalk-Zone | 0 | 0-1 |
+ Framed-Compression | 0+ | 0+ |
+ Framed-Interface-Id | 0-1 | 0-1 |
+ Framed-IP-Address | 0-1 | 0-1 |
+ Framed-IP-Netmask | 0-1 | 0-1 |
+ Framed-IPv6-Prefix | 0+ | 0+ |
+ Framed-IPv6-Pool | 0 | 0-1 |
+ Framed-IPv6-Route | 0 | 0+ |
+ Framed-IPX-Network | 0 | 0-1 |
+ Framed-MTU | 0-1 | 0-1 |
+ Framed-Pool | 0 | 0-1 |
+ Framed-Protocol | 0-1 | 0-1 |
+ Framed-Route | 0 | 0+ |
+ Framed-Routing | 0 | 0-1 |
+ Idle-Timeout | 0 | 0-1 |
+ Login-IP-Host | 0+ | 0+ |
+ Login-IPv6-Host | 0+ | 0+ |
+ Login-LAT-Group | 0-1 | 0-1 |
+ Login-LAT-Node | 0-1 | 0-1 |
+ Login-LAT-Port | 0-1 | 0-1 |
+ Login-LAT-Service | 0-1 | 0-1 |
+ Login-Service | 0 | 0-1 |
+ Login-TCP-Port | 0 | 0-1 |
+ Multi-Round-Time-Out | 0 | 0-1 |
+ ------------------------------|-----+-----+
+
+
+
+
+Calhoun, et al. Standards Track [Page 72]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | AAR | AAA |
+ ------------------------------|-----+-----+
+ NAS-Filter-Rule | 0 | 0+ |
+ NAS-Identifier | 0-1 | 0 |
+ NAS-IP-Address | 0-1 | 0 |
+ NAS-IPv6-Address | 0-1 | 0 |
+ NAS-Port | 0-1 | 0 |
+ NAS-Port-Id | 0-1 | 0 |
+ NAS-Port-Type | 0-1 | 0 |
+ Origin-AAA-Protocol | 0-1 | 0-1 |
+ Origin-Host | 1 | 1 |
+ Origin-Realm | 1 | 1 |
+ Origin-State-Id | 0-1 | 0-1 |
+ Originating-Line-Info | 0-1 | 0 |
+ Password-Retry | 0 | 0-1 |
+ Port-Limit | 0-1 | 0-1 |
+ Prompt | 0 | 0-1 |
+ Proxy-Info | 0+ | 0+ |
+ QoS-Filter-Rule | 0 | 0+ |
+ Re-Auth-Request-Type | 0 | 0-1 |
+ Redirect-Host | 0 | 0+ |
+ Redirect-Host-Usage | 0 | 0-1 |
+ Redirect-Max-Cache-Time | 0 | 0-1 |
+ Reply-Message | 0 | 0+ |
+ Result-Code | 0 | 1 |
+ Route-Record | 0+ | 0+ |
+ Service-Type | 0-1 | 0-1 |
+ Session-Id | 1 | 1 |
+ Session-Timeout | 0 | 0-1 |
+ State | 0-1 | 0-1 |
+ Tunneling | 0+ | 0+ |
+ User-Name | 0-1 | 0-1 |
+ User-Password | 0-1 | 0 |
+ ------------------------------|-----+-----+
+
+10.2. Accounting AVP Tables
+
+ The tables in this section are used to show which AVPs defined in
+ this document are to be present and used in NAS application
+ Accounting messages. These AVPs are defined in this document, as
+ well as in [BASE] and [RADIUSAcct].
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 73]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+10.2.1. Accounting Framed Access AVP Table
+
+ The table in this section is used when the Service-Type specifies
+ Framed Access.
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | ACR | ACA |
+ ---------------------------------------|-----+-----+
+ Accounting-Auth-Method | 0-1 | 0 |
+ Accounting-Input-Octets | 1 | 0 |
+ Accounting-Input-Packets | 1 | 0 |
+ Accounting-Output-Octets | 1 | 0 |
+ Accounting-Output-Packets | 1 | 0 |
+ Accounting-Record-Number | 0-1 | 0-1 |
+ Accounting-Record-Type | 1 | 1 |
+ Accounting-Realtime-Required | 0-1 | 0-1 |
+ Accounting-Sub-Session-Id | 0-1 | 0-1 |
+ Acct-Application-Id | 0-1 | 0-1 |
+ Acct-Session-Id | 1 | 0-1 |
+ Acct-Multi-Session-Id | 0-1 | 0-1 |
+ Acct-Authentic | 1 | 0 |
+ Acct-Delay-Time | 0-1 | 0 |
+ Acct-Interim-Interval | 0-1 | 0-1 |
+ Acct-Link-Count | 0-1 | 0 |
+ Acct-Session-Time | 1 | 0 |
+ Acct-Tunnel-Connection | 0-1 | 0 |
+ Acct-Tunnel-Packets-Lost | 0-1 | 0 |
+ Authorization-Lifetime | 0-1 | 0 |
+ Callback-Id | 0-1 | 0 |
+ Callback-Number | 0-1 | 0 |
+ Called-Station-Id | 0-1 | 0 |
+ Calling-Station-Id | 0-1 | 0 |
+ Class | 0+ | 0+ |
+ Connection-Info | 0+ | 0 |
+ Destination-Host | 0-1 | 0 |
+ Destination-Realm | 1 | 0 |
+ Event-Timestamp | 0-1 | 0-1 |
+ Error-Message | 0 | 0-1 |
+ Error-Reporting-Host | 0 | 0-1 |
+ Failed-AVP | 0 | 0+ |
+ ---------------------------------------|-----+-----+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 74]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | ACR | ACA |
+ ---------------------------------------|-----+-----+
+ Framed-AppleTalk-Link | 0-1 | 0 |
+ Framed-AppleTalk-Network | 0-1 | 0 |
+ Framed-AppleTalk-Zone | 0-1 | 0 |
+ Framed-Compression | 0-1 | 0 |
+ Framed-IP-Address | 0-1 | 0 |
+ Framed-IP-Netmask | 0-1 | 0 |
+ Framed-IPv6-Prefix | 0+ | 0 |
+ Framed-IPv6-Pool | 0-1 | 0 |
+ Framed-IPX-Network | 0-1 | 0 |
+ Framed-MTU | 0-1 | 0 |
+ Framed-Pool | 0-1 | 0 |
+ Framed-Protocol | 0-1 | 0 |
+ Framed-Route | 0-1 | 0 |
+ Framed-Routing | 0-1 | 0 |
+ NAS-Filter-Rule | 0+ | 0 |
+ NAS-Identifier | 0-1 | 0-1 |
+ NAS-IP-Address | 0-1 | 0-1 |
+ NAS-IPv6-Address | 0-1 | 0-1 |
+ NAS-Port | 0-1 | 0-1 |
+ NAS-Port-Id | 0-1 | 0-1 |
+ NAS-Port-Type | 0-1 | 0-1 |
+ Origin-AAA-Protocol | 0-1 | 0-1 |
+ Origin-Host | 1 | 1 |
+ Origin-Realm | 1 | 1 |
+ Origin-State-Id | 0-1 | 0-1 |
+ Originating-Line-Info | 0-1 | 0 |
+ Proxy-Info | 0+ | 0+ |
+ QoS-Filter-Rule | 0+ | 0 |
+ Route-Record | 0+ | 0+ |
+ Result-Code | 0 | 1 |
+ Service-Type | 0-1 | 0-1 |
+ Session-Id | 1 | 1 |
+ Termination-Cause | 0-1 | 0-1 |
+ Tunnel-Assignment-Id | 0-1 | 0 |
+ Tunnel-Client-Endpoint | 0-1 | 0 |
+ Tunnel-Medium-Type | 0-1 | 0 |
+ Tunnel-Private-Group-Id | 0-1 | 0 |
+ Tunnel-Server-Endpoint | 0-1 | 0 |
+ Tunnel-Type | 0-1 | 0 |
+ User-Name | 0-1 | 0-1 |
+ Vendor-Specific-Application-Id | 0-1 | 0-1 |
+ ---------------------------------------|-----+-----+
+
+
+
+
+Calhoun, et al. Standards Track [Page 75]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+10.2.2. Accounting Non-Framed Access AVP Table
+
+ The table in this section is used when the Service-Type specifies
+ Non-Framed Access.
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | ACR | ACA |
+ ---------------------------------------|-----+-----+
+ Accounting-Auth-Method | 0-1 | 0 |
+ Accounting-Input-Octets | 1 | 0 |
+ Accounting-Output-Octets | 1 | 0 |
+ Accounting-Record-Type | 1 | 1 |
+ Accounting-Record-Number | 0-1 | 0-1 |
+ Accounting-Realtime-Required | 0-1 | 0-1 |
+ Accounting-Sub-Session-Id | 0-1 | 0-1 |
+ Acct-Application-Id | 0-1 | 0-1 |
+ Acct-Session-Id | 1 | 0-1 |
+ Acct-Multi-Session-Id | 0-1 | 0-1 |
+ Acct-Authentic | 1 | 0 |
+ Acct-Delay-Time | 0-1 | 0 |
+ Acct-Interim-Interval | 0-1 | 0-1 |
+ Acct-Link-Count | 0-1 | 0 |
+ Acct-Session-Time | 1 | 0 |
+ Authorization-Lifetime | 0-1 | 0 |
+ Callback-Id | 0-1 | 0 |
+ Callback-Number | 0-1 | 0 |
+ Called-Station-Id | 0-1 | 0 |
+ Calling-Station-Id | 0-1 | 0 |
+ Class | 0+ | 0+ |
+ Connection-Info | 0+ | 0 |
+ Destination-Host | 0-1 | 0 |
+ Destination-Realm | 1 | 0 |
+ Event-Timestamp | 0-1 | 0-1 |
+ Error-Message | 0 | 0-1 |
+ Error-Reporting-Host | 0 | 0-1 |
+ Failed-AVP | 0 | 0+ |
+ Login-IP-Host | 0+ | 0 |
+ Login-IPv6-Host | 0+ | 0 |
+ Login-LAT-Service | 0-1 | 0 |
+ Login-LAT-Node | 0-1 | 0 |
+ Login-LAT-Group | 0-1 | 0 |
+ Login-LAT-Port | 0-1 | 0 |
+ Login-Service | 0-1 | 0 |
+ Login-TCP-Port | 0-1 | 0 |
+ ---------------------------------------|-----+-----+
+
+
+
+
+Calhoun, et al. Standards Track [Page 76]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | ACR | ACA |
+ ---------------------------------------|-----+-----+
+ NAS-Identifier | 0-1 | 0-1 |
+ NAS-IP-Address | 0-1 | 0-1 |
+ NAS-IPv6-Address | 0-1 | 0-1 |
+ NAS-Port | 0-1 | 0-1 |
+ NAS-Port-Id | 0-1 | 0-1 |
+ NAS-Port-Type | 0-1 | 0-1 |
+ Origin-AAA-Protocol | 0-1 | 0-1 |
+ Origin-Host | 1 | 1 |
+ Origin-Realm | 1 | 1 |
+ Origin-State-Id | 0-1 | 0-1 |
+ Originating-Line-Info | 0-1 | 0 |
+ Proxy-Info | 0+ | 0+ |
+ QoS-Filter-Rule | 0+ | 0 |
+ Route-Record | 0+ | 0+ |
+ Result-Code | 0 | 1 |
+ Session-Id | 1 | 1 |
+ Service-Type | 0-1 | 0-1 |
+ Termination-Cause | 0-1 | 0-1 |
+ User-Name | 0-1 | 0-1 |
+ 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 BCP 26 [IANAConsid].
+
+ This document defines values in the namespaces that have been created
+ and defined in the Diameter Base [BASE]. The IANA Considerations
+ section of that document details the assignment criteria. Values
+ assigned in this document, or by future IANA action, must be
+ coordinated within this shared namespace.
+
+11.1. Command Codes
+
+ This specification assigns the value 265 from the Command Code
+ namespace defined in [BASE]. See sections 3.1 and 3.2 for the
+ assignment of the namespace in this specification.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 77]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+11.2. AVP Codes
+
+ This specification assigns the values 363 - 366 and 400 - 408 from
+ the AVP Code namespace defined in [BASE]. See sections 4 and 5 for
+ the assignment of the namespace in this specification. Note that the
+ values 363 - 366 are jointly, but consistently, assigned in
+ [DiamMIP]. This document also creates one new namespace to be
+ managed by IANA, as described in section 11.5.
+
+ This specification also specifies the use of AVPs in the 0 - 255
+ range, which are defined in [RADIUSTypes]. These values are assigned
+ by the policy in RFC 2865 section 6 [RADIUS] and are amended by RFC
+ 3575 [RADIUSIANA].
+
+11.3. Application Identifier
+
+ This specification uses the value one (1) in the Application
+ Identifier namespace as assigned in [BASE]. See section 1.2 above
+ for more information.
+
+11.4. CHAP-Algorithm AVP Values
+
+ As defined in section 5.5, the CHAP-Algorithm AVP (AVP Code 403) uses
+ the values of the "PPP AUTHENTICATION ALGORITHMS" namespace defined
+ in [PPPCHAP].
+
+11.5. Accounting-Auth-Method AVP Values
+
+ As defined in section 8.6, the Accounting-Auth-Method AVP (AVP Code
+ 406) defines the values 1 - 5. All remaining values are available
+ for assignment via IETF Consensus [IANA].
+
+11.6. Origin-AAA-Protocol AVP Values
+
+ As defined in section 9.3.6, the Origin-AAA-Protocol AVP (AVP Code
+ 408) defines the value 1. All remaining values are available for
+ assignment with a "Specification Required" policy [IANAConsid].
+
+12. Security Considerations
+
+ This document describes the extension of Diameter for the NAS
+ application. The security considerations of the Diameter protocol
+ itself have been discussed in [BASE]. Use of this application of
+ Diameter MUST take into consideration the security issues and
+ requirements of the Base protocol.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 78]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ This document does not contain a security protocol but does discuss
+ how PPP authentication protocols can be carried within the Diameter
+ protocol. The PPP authentication protocols described are PAP and
+ CHAP.
+
+ The use of PAP SHOULD be discouraged, as it exposes users' passwords
+ to possibly non-trusted entities. However, PAP is also frequently
+ used for use with One-Time Passwords, which do not expose a security
+ risk.
+
+ This document also describes how CHAP can be carried within the
+ Diameter protocol, which is required for RADIUS backward
+ compatibility. The CHAP protocol, as used in a RADIUS environment,
+ facilitates authentication replay attacks.
+
+ The use of the EAP authentication protocols described in [DiamEAP]
+ can offer better security, given a method suitable for the
+ circumstances.
+
+13. References
+
+13.1. Normative References
+
+ [BASE] Calhoun, P., Loughney, J., Guttman, E., Zorn, G., and
+ J. Arkko, "Diameter Base Protocol", RFC 3588,
+ September 2003.
+
+ [DiamTrans] Aboba, B. and J. Wood, "Authentication, Authorization
+ and Accounting (AAA) Transport Profile", RFC 3539,
+ June 2003.
+
+ [RADIUS] Rigney, C., Willens, S., Rubens, A., and W. Simpson,
+ "Remote Authentication Dial In User Service (RADIUS)",
+ RFC 2865, June 2000.
+
+ [RADIUSTypes] IANA, "RADIUS Types", URL:
+ <http://www.iana.org/assignments/radius-types>
+
+ [RADIUSIPv6] Aboba, B., Zorn, G., and D. Mitton, "RADIUS and IPv6",
+ RFC 3162, August 2001.
+
+ [IPv6Addr] Nerenberg, L., "IMAP4 Binary Content Extension", RFC
+ 3516, April 2003.
+
+ [PPPCHAP] Simpson, W., "PPP Challenge Handshake Authentication
+ Protocol (CHAP)", RFC 1994, August 1996.
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 79]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ [IANAConsid] Narten, T. and H. Alvestrand, "Guidelines for Writing
+ an IANA Considerations Section in RFCs", BCP 26, RFC
+ 2434, October 1998.
+
+ [IANA] IANA Assigned Numbers Database, URL:
+ <http://www.iana.org/numbers.html>
+
+ [Keywords] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+ [ANITypes] NANPA Number Resource Info, ANI Assignments, URL:
+ <http://www.nanpa.com/number_resource_info/
+ ani_ii_assignments.html>
+
+13.2. Informative References
+
+ [RADIUSAcct] Rigney, C., "RADIUS Accounting", RFC 2866, June 2000.
+
+ [RADIUSExt] Rigney, C., Willats, W., and P. Calhoun, "RADIUS
+ Extensions", RFC 2869, June 2000.
+
+ [RADTunnels] Zorn, G., Leifer, D., Rubens, A., Shriver, J.,
+ Holdrege, M., and I. Goyret, "RADIUS Attributes for
+ Tunnel Protocol Support", RFC 2868, June 2000.
+
+ [RADTunlAcct] Zorn, G., Aboba, B., and D. Mitton, "RADIUS Accounting
+ Modifications for Tunnel Protocol Support", RFC 2867,
+ June 2000.
+
+ [RADDynAuth] Chiba, M., Dommety, G., Eklund, M., Mitton, D., and B.
+ Aboba, "Dynamic Authorization Extensions to Remote
+ Authentication Dial In User Service (RADIUS)", RFC
+ 3576, July 2003.
+
+ [RADIUSIANA] Aboba, B., "IANA Considerations for RADIUS (Remote
+ Authentication Dial In User Service)", RFC 3575, July
+ 2003.
+
+ [NASModel] Mitton, D. and M. Beadles, "Network Access Server
+ Requirements Next Generation (NASREQNG) NAS Model",
+ RFC 2881, July 2000.
+
+ [NASCriteria] Beadles, M. and D. Mitton, "Criteria for Evaluating
+ Network Access Server Protocols", RFC 3169, September
+ 2001.
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 80]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ [AAACriteria] Aboba, B., Calhoun, P., Glass, S., Hiller, T., McCann,
+ P., Shiino, H., Zorn, G., Dommety, G., Perkins, C.,
+ Patil, B., Mitton, D., Manning, S., Beadles, M.,
+ Walsh, P., Chen, X., Sivalingham, S., Hameed, A.,
+ Munson, M., Jacobs, S., Lim, B., Hirschman, B., Hsu,
+ R., Xu, Y., Campbell, E., Baba, S., and E. Jaques,
+ "Criteria for Evaluating AAA Protocols for Network
+ Access", RFC 2989, November 2000.
+
+ [DiamEAP] Eronen, P., "Diameter EAP Application", Work in
+ Progress, May 2004.
+
+ [DiamCMS] Calhoun, P., Bulley, W., and S. Farrell, "Diameter CMS
+ Security Application", Work in Progress, March 2002.
+
+ [DiamMIP] Calhoun, P., Johansson, T., Perkins, C., Hiller, T.,
+ and P. McCann "Diameter Mobile IPv4 Application", RFC
+ 4004, August 2005.
+
+ [VSA] Mitton, D., "Diameter/RADIUS Vendor Specific AVP
+ Translation", Work in Progress, April 2005.
+
+ [RAD802.1X] Congdon, P., Aboba, B., Smith, A., Zorn, G., and J.
+ Roese, "IEEE 802.1X Remote Authentication Dial In User
+ Service (RADIUS) Usage Guidelines", RFC 3580,
+ September 2003.
+
+ [CDMA2000] 3GPP2 "P.S0001-B", Wireless IP Network Standard,
+ October 2002.
+ http://www.3gpp2.com/Public_html/specs/P.S0001-
+ B_v1.0.pdf
+
+ [AppleTalk] Sidhu, Gursharan; Andrews, Richard F. & Oppenheimer,
+ Alan B. "Inside AppleTalk", Second Edition, Apple
+ Computer., 1990
+
+ [ARAP] Apple Remote Access Protocol (ARAP) Version 2.0
+ External Reference Specification", Apple Computer,
+ September 1994, R0612LL/B
+
+ [IPX] Novell, Inc., "NetWare System Technical Interface
+ Overview", June 1989, # 883-000780-001
+
+ [LAT] Local Area Transport (LAT) Specification V5.0, Digital
+ Equipment Corp., AA-NL26A-TE, June 1989
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 81]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+ [DIFFSERV] Nichols, K., Blake, S., Baker, F., and D. Black,
+ "Definition of the Differentiated Services Field (DS
+ Field) in the IPv4 and IPv6 Headers", RFC 2474,
+ December 1998.
+
+ [DIFFSERVAF] Heinanen, J., Baker, F., Weiss, W., and J. Wroclawski,
+ "Assured Forwarding PHB Group", RFC 2597, June 1999.
+
+ [DIFFSERVEF] Davie, B., Charny, A., Bennet, J.C., Benson, K., Le
+ Boudec, J., Courtney, W., Davari, S., Firoiu, V., and
+ D. Stiliadis, "An Expedited Forwarding PHB (Per-Hop
+ Behavior)", RFC 3246, March 2002.
+
+ [UTF-8] Yergeau, F., "UTF-8, a transformation format of ISO
+ 10646", STD 63, RFC 3629, November 2003.
+
+ [ISOLatin] ISO 8859. International Standard -- Information
+ Processing -- 8-bit Single-Byte Coded Graphic
+ Character Sets -- Part 1: Latin Alphabet No. 1, ISO
+ 8859-1:1987. URL:
+ <http://www.iso.ch/cate/d16338.html>
+
+ [PPP] Simpson, W., "The Point-to-Point Protocol (PPP)", STD
+ 51, RFC 1661, July 1994.
+
+ [PAP] Lloyd, B. and W. Simpson, "PPP Authentication
+ Protocols", RFC 1334, October 1992.
+
+ [L2TP] Townsley, W., Valencia, A., Rubens, A., Pall, G.,
+ Zorn, G., and B. Palter, "Layer Two Tunneling Protocol
+ "L2TP"", RFC 2661, August 1999.
+
+ [PPPMP] Sklower, K., Lloyd, B., McGregor, G., Carr, D., and T.
+ Coradetti, "The PPP Multilink Protocol (MP)", RFC
+ 1990, August 1996.
+
+ [PPTP] Hamzeh, K., Pall, G., Verthein, W., Taarud, J.,
+ Little, W., and G. Zorn, "Point-to-Point Tunneling
+ Protocol", RFC 2637, July 1999.
+
+ [IEEE 802.11F] IEEE, "Trial-Use Recommended Practice for Multi-Vendor
+ Access Point Interoperability via an Inter-Access
+ Point Protocol Across Distribution Systems Supporting
+ IEEE 802.11 Operation", IEEE 802.11F-2003, June 2003.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 82]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+14. Acknowledgements
+
+ The authors would like to thank Carl Rigney, Allan C. Rubens, William
+ Allen Simpson, and Steve Willens for their work on the original
+ RADIUS [RADIUS], from which many of the concepts in this
+ specification were derived. Thanks, also, to Carl Rigney for
+ [RADIUSAcct] and [RADIUSExt]; Ward Willats for [RADIUSExt]; Glen
+ Zorn, Bernard Aboba, and Dave Mitton for [RADTunlAcct] and
+ [RADIUSIPv6]; and Dory Leifer, John Shriver, Matt Holdrege, and
+ Ignacio Goyret for their work on [RADTunnels]. This document stole
+ text and concepts from both [RADTunnels] and [RADIUSExt]. Thanks go
+ to Carl Williams for providing IPv6-specific text.
+
+ The authors would also like to acknowledge the following people for
+ their contributions in the development of the Diameter protocol:
+ Bernard Aboba, Jari Arkko, William Bulley, Kuntal Chowdhury, Daniel
+ C. Fox, Lol Grant, Nancy Greene, Jeff Hagg, Peter Heitman, Paul
+ Krumviede, Fergal Ladley, Ryan Moats, Victor Muslin, Kenneth Peirce,
+ Sumit Vakil, John R. Vollbrecht, and Jeff Weisberg.
+
+ Finally, Pat Calhoun would like to thank Sun Microsystems, as most of
+ the effort put into this document was done while he was in their
+ employ.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 83]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+Authors' Addresses
+
+ Pat Calhoun
+ Cisco Systems, Inc.
+ 170 West Tasman Drive
+ San Jose, CA 95134
+ USA
+
+ Phone: +1 408-853-5269
+
+
+ Glen Zorn
+ Cisco Systems, Inc.
+ 500 108th Avenue N.E., Suite 500
+ Bellevue, WA 98004
+ USA
+
+ Phone: 1 425-471-4861
+
+
+ David Spence
+ 3259 Bluett Rd.
+ Ann Arbor, MI 48105
+ USA
+
+ Phone: +1 734 834 6481
+
+
+ David Mitton
+ Circular Networks
+ 733 Turnpike St #154
+ North Andover, MA 01845
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 84]
+
+RFC 4005 Diameter Network Access Server Application August 2005
+
+
+Full Copyright Statement
+
+ Copyright (C) The Internet Society (2005).
+
+ This document is subject to the rights, licenses and restrictions
+ contained in BCP 78, and except as set forth therein, the authors
+ retain all their rights.
+
+ This document and the information contained herein are provided on an
+ "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS
+ OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET
+ ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED,
+ INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
+ INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED
+ WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+Intellectual Property
+
+ The IETF takes no position regarding the validity or scope of any
+ Intellectual Property Rights or other rights that might be claimed to
+ pertain to the implementation or use of the technology described in
+ this document or the extent to which any license under such rights
+ might or might not be available; nor does it represent that it has
+ made any independent effort to identify any such rights. Information
+ on the procedures with respect to rights in RFC documents can be
+ found in BCP 78 and BCP 79.
+
+ Copies of IPR disclosures made to the IETF Secretariat and any
+ assurances of licenses to be made available, or the result of an
+ attempt made to obtain a general license or permission for the use of
+ such proprietary rights by implementers or users of this
+ specification can be obtained from the IETF on-line IPR repository at
+ http://www.ietf.org/ipr.
+
+ The IETF invites any interested party to bring to its attention any
+ copyrights, patents or patent applications, or other proprietary
+ rights that may cover technology that may be required to implement
+ this standard. Please address the information to the IETF at ietf-
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+
+
+
+
+
+
+Calhoun, et al. Standards Track [Page 85]
+
diff --git a/lib/diameter/doc/standard/rfc4006.txt b/lib/diameter/doc/standard/rfc4006.txt
new file mode 100644
index 0000000000..3f3e5e1d1b
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc4006.txt
@@ -0,0 +1,6387 @@
+
+
+
+
+
+
+Network Working Group H. Hakala
+Request for Comments: 4006 L. Mattila
+Category: Standards Track Ericsson
+ J-P. Koskinen
+ M. Stura
+ J. Loughney
+ Nokia
+ August 2005
+
+
+ Diameter Credit-Control Application
+
+Status of This Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The Internet Society (2005).
+
+Abstract
+
+ This document specifies a Diameter application that can be used to
+ implement real-time credit-control for a variety of end user services
+ such as network access, Session Initiation Protocol (SIP) services,
+ messaging services, and download services.
+
+Table of Contents
+
+ 1. Introduction................................................. 4
+ 1.1. Requirements Language................................. 5
+ 1.2. Terminology........................................... 5
+ 1.3. Advertising Application Support....................... 7
+ 2. Architecture Models.......................................... 7
+ 3. Credit-Control Messages...................................... 9
+ 3.1. Credit-Control-Request (CCR) Command.................. 9
+ 3.2. Credit-Control-Answer (CCA) Command................... 11
+ 4. Credit-Control Application Overview.......................... 11
+ 4.1. Service-Specific Rating Input and Interoperability.... 13
+ 5. Session Based Credit-Control................................. 15
+ 5.1. General Principles.................................... 15
+ 5.2. First Interrogation................................... 21
+ 5.3. Intermediate Interrogation............................ 27
+ 5.4. Final Interrogation................................... 29
+
+
+
+Hakala, et al. Standards Track [Page 1]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ 5.5. Server-Initiated Credit Re-Authorization.............. 30
+ 5.6. Graceful Service Termination.......................... 32
+ 5.7. Failure Procedures.................................... 38
+ 6. One Time Event............................................... 41
+ 6.1. Service Price Enquiry................................. 42
+ 6.2. Balance Check......................................... 42
+ 6.3. Direct Debiting....................................... 43
+ 6.4. Refund................................................ 44
+ 6.5. Failure Procedure..................................... 44
+ 7. Credit-Control Application State Machine..................... 46
+ 8. Credit-Control AVPs.......................................... 55
+ 8.1. CC-Correlation-Id AVP................................. 58
+ 8.2. CC-Request-Number AVP................................. 58
+ 8.3. CC-Request-Type AVP................................... 58
+ 8.4. CC-Session-Failover AVP............................... 59
+ 8.5. CC-Sub-Session-Id AVP................................. 59
+ 8.6. Check-Balance-Result AVP.............................. 60
+ 8.7. Cost-Information AVP.................................. 60
+ 8.8. Unit-Value AVP........................................ 61
+ 8.9. Exponent AVP.......................................... 61
+ 8.10. Value-Digits AVP...................................... 61
+ 8.11. Currency-Code AVP..................................... 62
+ 8.12. Cost-Unit AVP......................................... 62
+ 8.13. Credit-Control AVP.................................... 62
+ 8.14. Credit-Control-Failure-Handling AVP................... 62
+ 8.15. Direct-Debiting-Failure-Handling AVP.................. 63
+ 8.16. Multiple-Services-Credit-Control AVP.................. 64
+ 8.17. Granted-Service-Unit AVP.............................. 65
+ 8.18. Requested-Service-Unit AVP............................ 66
+ 8.19. Used-Service-Unit AVP................................. 66
+ 8.20. Tariff-Time-Change AVP................................ 67
+ 8.21. CC-Time AVP........................................... 67
+ 8.22. CC-Money AVP.......................................... 67
+ 8.23. CC-Total-Octets AVP................................... 68
+ 8.24. CC-Input-Octets AVP................................... 68
+ 8.25. CC-Output-Octets AVP.................................. 68
+ 8.26. CC-Service-Specific-Units AVP......................... 68
+ 8.27. Tariff-Change-Usage AVP............................... 68
+ 8.28. Service-Identifier AVP................................ 69
+ 8.29. Rating-Group AVP...................................... 69
+ 8.30. G-S-U-Pool-Reference AVP.............................. 69
+ 8.31. G-S-U-Pool-Identifier AVP............................. 70
+ 8.32. CC-Unit-Type AVP...................................... 70
+ 8.33. Validity-Time AVP..................................... 70
+ 8.34. Final-Unit-Indication AVP............................. 71
+ 8.35. Final-Unit-Action AVP................................. 72
+ 8.36. Restriction-Filter-Rule AVP........................... 72
+ 8.37. Redirect-Server AVP................................... 73
+
+
+
+Hakala, et al. Standards Track [Page 2]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ 8.38. Redirect-Address-Type AVP............................. 73
+ 8.39. Redirect-Server-Address AVP........................... 74
+ 8.40. Multiple-Services-Indicator AVP....................... 74
+ 8.41. Requested-Action AVP.................................. 74
+ 8.42. Service-Context-Id AVP................................ 75
+ 8.43. Service-Parameter-Info AVP............................ 76
+ 8.44. Service-Parameter-Type AVP............................ 76
+ 8.45. Service-Parameter-Value AVP........................... 77
+ 8.46. Subscription-Id AVP................................... 77
+ 8.47. Subscription-Id-Type AVP.............................. 77
+ 8.48. Subscription-Id-Data AVP.............................. 78
+ 8.49. User-Equipment-Info AVP............................... 78
+ 8.50. User-Equipment-Info-Type AVP.......................... 78
+ 8.50. User-Equipment-Info-Value AVP......................... 79
+ 9. Result Code AVP Values....................................... 79
+ 9.1. Transient Failures.................................... 79
+ 9.2. Permanent Failures.................................... 80
+ 10. AVP Occurrence Table......................................... 80
+ 10.1. Credit-Control AVP Table.............................. 81
+ 10.2. Re-Auth-Request/Answer AVP Table...................... 82
+ 11. RADIUS/Diameter Credit-Control Interworking Model............ 82
+ 12. IANA Considerations.......................................... 85
+ 12.1. Application Identifier................................ 86
+ 12.2. Command Codes......................................... 86
+ 12.3. AVP Codes............................................. 86
+ 12.4. Result-Code AVP Values................................ 86
+ 12.5. CC-Request-Type AVP................................... 86
+ 12.6. CC-Session-Failover AVP............................... 86
+ 12.7. CC-Unit-Type AVP...................................... 87
+ 12.8. Check-Balance-Result AVP.............................. 87
+ 12.9. Credit-Control AVP.................................... 87
+ 12.10. Credit-Control-Failure-Handling AVP................... 87
+ 12.11. Direct-Debiting-Failure-Handling AVP.................. 87
+ 12.12. Final-Unit-Action AVP................................. 87
+ 12.13. Multiple-Services-Indicator AVP....................... 87
+ 12.14. Redirect-Address-Type AVP............................. 88
+ 12.15. Requested-Action AVP.................................. 88
+ 12.16. Subscription-Id-Type AVP.............................. 88
+ 12.17. Tariff-Change-Usage AVP............................... 88
+ 12.18. User-Equipment-Info-Type AVP.......................... 88
+ 13. Credit-Control Application Related Parameters................ 88
+ 14. Security Considerations...................................... 89
+ 14.1. Direct Connection with Redirects...................... 90
+ 15. References................................................... 91
+ 15.1. Normative References.................................. 91
+ 15.2. Informative References................................ 92
+ 16. Acknowledgements............................................. 93
+ Appendix A Credit-Control Sequences.............................. 94
+
+
+
+Hakala, et al. Standards Track [Page 3]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ A.1. Flow I................................................ 94
+ A.2. Flow II............................................... 96
+ A.3. Flow III.............................................. 98
+ A.4. Flow IV............................................... 99
+ A.5. Flow V................................................ 100
+ A.6. Flow VI............................................... 102
+ A.7. Flow VII.............................................. 103
+ A.8. Flow VIII............................................. 105
+ A.9. Flow IX............................................... 107
+ Authors' Addresses............................................... 112
+ Full Copyright Statement......................................... 114
+
+1. Introduction
+
+ This document specifies a Diameter application that can be used to
+ implement real-time credit-control for a variety of end user services
+ such as network access, Session Initiation Protocol (SIP) services,
+ messaging services, and download services. It provides a general
+ solution to real-time cost and credit-control.
+
+ The prepaid model has been shown to be very successful, for instance,
+ in GSM networks, where network operators offering prepaid services
+ have experienced a substantial growth of their customer base and
+ revenues. Prepaid services are now cropping up in many other
+ wireless and wire line based networks.
+
+ In next generation wireless networks, additional functionality is
+ required beyond that specified in the Diameter base protocol. For
+ example, the 3GPP Charging and Billing requirements [3GPPCHARG] state
+ that an application must be able to rate service information in
+ real-time. In addition, it is necessary to check that the end user's
+ account provides coverage for the requested service prior to
+ initiation of that service. When an account is exhausted or expired,
+ the user must be denied the ability to compile additional chargeable
+ events.
+
+ A mechanism has to be provided to allow the user to be informed of
+ the charges to be levied for a requested service. In addition, there
+ are services such as gaming and advertising that may credit as well
+ as debit a user account.
+
+ The other Diameter applications provide service specific
+ authorization, and they do not provide credit authorization for
+ prepaid users. The credit authorization shall be generic and
+ applicable to all the service environments required to support
+ prepaid services.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 4]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ To fulfill these requirements, it is necessary to facilitate credit-
+ control communication between the network element providing the
+ service (e.g., Network Access Server, SIP Proxy, and Application
+ Server) and a credit-control server.
+
+ The scope of this specification is the credit authorization. Service
+ specific authorization and authentication is out of the scope.
+
+1.1. Requirements Language
+
+ In this document, the key words "MAY", "MUST, "MUST NOT", "OPTIONAL",
+ "RECOMMENDED", "SHOULD", and "SHOULD NOT", are to be interpreted as
+ described in [KEYWORDS].
+
+1.2. Terminology
+
+ AAA
+
+ Authentication, Authorization, and Accounting
+
+ AA answer
+
+ AA answer generically refers to a service specific authorization and
+ authentication answer. AA answer commands are defined in service
+ specific authorization applications, e.g., [NASREQ] and [DIAMMIP].
+
+ AA request
+
+ AA request generically refers to a service specific authorization and
+ authentication request. AA request commands are defined in service
+ specific authorization applications e.g., [NASREQ] and [DIAMMIP].
+
+ Credit-control
+
+ Credit-control is a mechanism that directly interacts in real-time
+ with an account and controls or monitors the charges related to the
+ service usage. Credit-control is a process of checking whether
+ credit is available, credit-reservation, deduction of credit from the
+ end user account when service is completed and refunding of reserved
+ credit that is not used.
+
+ Diameter Credit-control Server
+
+ A Diameter credit-control server acts as a prepaid server, performing
+ real-time rating and credit-control. It is located in the home
+ domain and is accessed by service elements or Diameter AAA servers in
+
+
+
+
+
+Hakala, et al. Standards Track [Page 5]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ real-time for purpose of price determination and credit-control
+ before the service event is delivered to the end-user. It may also
+ interact with business support systems.
+
+ Diameter Credit-control Client
+
+ A Diameter credit-control client is an entity that interacts with a
+ credit-control server. It monitors the usage of the granted quota
+ according to instructions returned by credit-control server.
+
+ Interrogation
+
+ The Diameter credit-control client uses interrogation to initiate a
+ session based credit-control process. During the credit-control
+ process, it is used to report the used quota and request a new one.
+ An interrogation maps to a request/answer transaction.
+
+ One-time event
+
+ Basically, a request/answer transaction of type event.
+
+ Rating
+
+ The act of determining the cost of the service event.
+
+ Service
+
+ A type of task performed by a service element for an end user.
+
+ Service Element
+
+ A network element that provides a service to the end users. The
+ Service Element may include the Diameter credit-control client, or
+ another entity (e.g., RADIUS AAA server) that can act as a Credit-
+ control client on behalf of the Service Element. In the latter case,
+ the interface between the Service Element and the Diameter credit-
+ control client is outside the scope of this specification. Examples
+ of the Service Elements include Network Access Server (NAS), SIP
+ Proxy, and Application Servers such as messaging server, content
+ server, and gaming server.
+
+ Service Event
+
+ An event relating to a service provided to the end user.
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 6]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Session based credit-control
+
+ A credit-control process that makes use of several interrogations:
+ the first, a possible intermediate, and the final. The first
+ interrogation is used to reserve money from the user's account and to
+ initiate the process. The intermediate interrogations may be needed
+ to request new quota while the service is being rendered. The final
+ interrogation is used to exit the process. The credit-control server
+ is required to maintain session state for session-based credit-
+ control.
+
+1.3. Advertising Application Support
+
+ Diameter nodes conforming to this specification MUST advertise
+ support by including the value of 4 in the Auth-Application-Id of the
+ Capabilities-Exchange-Request and Capabilities-Exchange-Answer
+ command [DIAMBASE].
+
+2. Architecture Models
+
+ The current accounting models specified in the Radius Accounting
+ [RFC2866] and Diameter base [DIAMBASE] are not sufficient for real-
+ time credit-control, where credit-worthiness is to be determined
+ prior to service initiation. Also, the existing Diameter
+ authorization applications, [NASREQ] and [DIAMMIP], only provide
+ service authorization, but do not provide credit authorization for
+ prepaid users. In order to support real-time credit-control, a new
+ type of server is needed in the AAA infrastructure: Diameter credit-
+ control server. The Diameter credit-control server is the entity
+ responsible for credit authorization for prepaid subscribers.
+
+ A service element may authenticate and authorize the end user with
+ the AAA server by using AAA protocols; e.g., RADIUS or a Diameter
+ base protocol with a possible Diameter application.
+
+ Accounting protocols such as RADIUS accounting and the Diameter base
+ accounting protocol can be used to provide accounting data to the
+ accounting server after service is initiated, and to provide possible
+ interim reports until service completion. However, for real-time
+ credit-control, these authorization and accounting models are not
+ sufficient.
+
+ When real-time credit-control is required, the credit-control client
+ contacts the credit-control server with information about a possible
+ service event. The credit-control process is performed to determine
+ potential charges and to verify whether the end user's account
+ balance is sufficient to cover the cost of the service being
+ rendered.
+
+
+
+Hakala, et al. Standards Track [Page 7]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Figure 1 illustrates the typical credit-control architecture, which
+ consists of a Service Element with an embedded Diameter credit-
+ control client, a Diameter credit-control server, and an AAA server.
+ A Business Support System is usually deployed; it includes at least
+ the billing functionality. The credit-control server and AAA server
+ in this architecture model are logical entities. The real
+ configuration can combine them into a single host. The credit-
+ control protocol is the Diameter base protocol with the Diameter
+ credit-control application.
+
+ When an end user requests services such as SIP or messaging, the
+ request is typically forwarded to a service element (e.g., SIP Proxy)
+ in the user's home domain. In some cases it might be possible that
+ the service element in the visited domain can offer services to the
+ end user; however, a commercial agreement must exist between the
+ visited domain and the home domain. Network access is an example of
+ a service offered in the visited domain where the NAS, through an AAA
+ infrastructure, authenticates and authorizes the user with the user's
+ home network.
+
+ Service Element AAA and CC
+ +----------+ +---------+ Protocols+-----------+ +--------+
+ | End |<---->|+-------+|<------------>| AAA | |Business|
+ | User | +->|| CC || | Server |->|Support |
+ | | | || Client||<-----+ | | |System |
+ +----------+ | |+-------+| | +-----------+ | |
+ | +---------+ | ^ +--------+
+ +----------+ | | CC Protocol | ^
+ | End |<--+ | +-----v----+ |
+ | User | +------>|Credit- | |
+ +----------+ Credit-Control |Control |--------+
+ Protocol |Server |
+ +----------+
+
+ Figure 1: Typical credit-control architecture
+
+ There can be multiple credit-control servers in the system for
+ redundancy and load balancing. The system can also contain separate
+ rating server(s), and accounts can be located in a centralized
+ database. To ensure that the end user's account is not debited or
+ credited multiple times for the same service event, only one place in
+ the credit-control system should perform duplicate detection. System
+ internal interfaces can exist to relay messages between servers and
+ an account manager. However, the detailed architecture of the
+ credit-control system and its interfaces are implementation specific
+ and are out of scope of this specification.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 8]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Protocol transparent Diameter relays can exist between the credit-
+ control client and credit-control server. Also, Diameter Redirect
+ agents that refer credit-control clients to credit-control servers
+ and allow them to communicate directly can exist. These agents
+ transparently support the Diameter credit-control application. The
+ different roles of Diameter Agents are defined in Diameter base
+ [DIAMBASE], section 2.8.
+
+ If Diameter credit-control proxies exist between the credit-control
+ client and the credit-control server, they MUST advertise the
+ Diameter credit-control application support.
+
+3. Credit-Control Messages
+
+ This section defines new Diameter message Command-Code values that
+ MUST be supported by all Diameter implementations that conform to
+ this specification. The Command Codes are as follows:
+
+ Command-Name Abbrev. Code Reference
+ -----------------------------------------------------------
+ Credit-Control-Request CCR 272 3.1
+ Credit-Control-Answer CCA 272 3.2
+
+ Diameter Base [DIAMBASE] defines in the section 3.2 the Command Code
+ ABNF specification. These formats are observed in Credit-Control
+ messages.
+
+3.1. Credit-Control-Request (CCR) Command
+
+ The Credit-Control-Request message (CCR) is indicated by the
+ command-code field being set to 272 and the 'R' bit being set in the
+ Command Flags field. It is used between the Diameter credit-control
+ client and the credit-control server to request credit authorization
+ for a given service.
+
+ The Auth-Application-Id MUST be set to the value 4, indicating the
+ Diameter credit-control application.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 9]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Message Format
+
+ <Credit-Control-Request> ::= < 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 ]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 10]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+3.2. Credit-Control-Answer (CCA) Command
+
+ The Credit-Control-Answer message (CCA) is indicated by the command-
+ code field being set to 272 and the 'R' bit being cleared in the
+ Command Flags field. It is used between the credit-control server
+ and the Diameter credit-control client to acknowledge a Credit-
+ Control-Request command.
+
+ Message Format
+
+ <Credit-Control-Answer> ::= < 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 ]
+
+4. Credit-Control Application Overview
+
+ The credit authorization process takes place before and during
+ service delivery to the end user and generally requires the user's
+ authentication and authorization before any request is sent to the
+ credit-control server. The credit-control application defined in
+ this specification supports two different credit authorization
+ models: credit authorization with money reservation and credit
+
+
+
+Hakala, et al. Standards Track [Page 11]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ authorization with direct debiting. In both models, the credit-
+ control client requests credit authorization from the credit-control
+ server prior to allowing any service to be delivered to the end user.
+
+ In the first model, the credit-control server rates the request,
+ reserves a suitable amount of money from the user's account, and
+ returns the corresponding amount of credit resources. Note that
+ credit resources may not imply actual monetary credit; credit
+ resources may be granted to the credit control client in the form of
+ units (e.g., data volume or time) to be metered.
+
+ Upon receipt of a successful credit authorization answer with a
+ certain amount of credit resources, the credit-control client allows
+ service delivery to the end user and starts monitoring the usage of
+ the granted resources. When the credit resources granted to the user
+ have been consumed or the service has been successfully delivered or
+ terminated, the credit-control client reports back to the server the
+ used amount. The credit-control server deducts the used amount from
+ the end user's account; it may perform rating and make a new credit
+ reservation if the service delivery is continuing. This process is
+ accomplished with session based credit-control that includes the
+ first interrogation, possible intermediate interrogations, and the
+ final interrogation. For session based credit-control, both the
+ credit control client and the credit-control server are required to
+ maintain credit-control session state. Session based credit-control
+ is described in more detail, with more variations, in section 5.
+
+ In contrast, credit authorization with direct debiting is a single
+ transaction process wherein the credit-control server directly
+ deducts a suitable amount of money from the user's account as soon as
+ the credit authorization request is received. Upon receipt of a
+ successful credit authorization answer, the credit-control client
+ allows service delivery to the end user. This process is
+ accomplished with the one-time event. Session state is not
+ maintained.
+
+ In a multi-service environment, an end user can issue an additional
+ service request (e.g., data service) during an ongoing service (e.g.,
+ voice call) toward the same account. Alternatively, during an active
+ multimedia session, an additional media type is added to the session,
+ causing a new simultaneous request toward same account.
+ Consequently, this needs to be considered when credit resources are
+ granted to the services.
+
+ The credit-control application also supports operations such as
+ service price enquiry, user's balance check, and refund of credit on
+ the user's account. These operations are accomplished with the one-
+ time event. Session state is not maintained.
+
+
+
+Hakala, et al. Standards Track [Page 12]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ A flexible credit-control application specific failure handling is
+ defined in which the home service provider can model the credit-
+ control client behavior according to its own credit risk management
+ policy.
+
+ The Credit-Control-Failure-Handling AVP and the Direct-Debiting-
+ Failure-Handling AVP are defined to determine what is done if the
+ sending of credit-control messages to the credit-control server has
+ been temporarily prevented. The usage of the Credit-Control-
+ Failure-Handling AVP and the Direct-Debiting-Failure-Handling AVP
+ allows flexibility, as failure handling for the credit-control
+ session and one time event direct debiting may be different.
+
+4.1. Service-Specific Rating Input and Interoperability
+
+ The Diameter credit-control application defines the framework for
+ credit-control; it provides generic credit-control mechanisms
+ supporting multiple service applications. The credit-control
+ application, therefore, does not define AVPs that could be used as
+ input in the rating process. Listing the possible services that
+ could use this Diameter application is out of scope for this generic
+ mechanism.
+
+ It is reasonable to expect that a service level agreement will exist
+ between providers of the credit-control client and the credit-control
+ server covering the charging, services offered, roaming agreements,
+ agreed rating input (i.e., AVPs), and so on.
+
+ Therefore, it is assumed that a Diameter credit-control server will
+ provide service only for Diameter credit-control clients that have
+ agreed beforehand as to the content of credit-control messages.
+ Naturally, it is possible that any arbitrary Diameter credit-control
+ client can interchange credit-control messages with any Diameter
+ credit-control server, but with a higher likelihood that unsupported
+ services/AVPs could be present in the credit-control message, causing
+ the server to reject the request with an appropriate result-code.
+
+4.1.1. Specifying Rating Input AVPs
+
+ There are two ways to provide rating input to the credit-control
+ server: either by using AVPs or by including them in the Service-
+ Parameter-Info AVP. The general principles for sending rating
+ parameters are as follows:
+
+ 1a. The service SHOULD re-use existing AVPs if it can use AVPs
+ defined in existing Diameter applications (e.g., NASREQ for network
+ access services). Re-use of existing AVPs is strongly recommended in
+ [DIAMBASE].
+
+
+
+Hakala, et al. Standards Track [Page 13]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ For AVPs of type Enumerated, the service may require a new value to
+ be defined. Allocation of new AVP values is done as specified in
+ [DIAMBASE], section 1.2.
+
+ 1b. New AVPs can be defined if the existing AVPs do not provide
+ sufficient rating information. In this case, the procedures defined
+ in [DIAMBASE] for creating new AVPs MUST be followed.
+
+ 1c. For services specific only to one vendor's implementation, a
+ Vendor-Specific AVP code for Private use can be used. Where a
+ Vendor-Specific AVP is implemented by more than one vendor,
+ allocation of global AVPs is encouraged instead; refer to [DIAMBASE].
+
+ 2. The Service-Parameter-Info AVP MAY be used as a container to pass
+ legacy rating information in its original encoded form (e.g., ASN.1
+ BER). This method can be used to avoid unnecessary conversions from
+ an existing data format to an AVP format. In this case, the rating
+ input is embedded in the Service-Parameter-Info AVP as defined in
+ section 8.43.
+
+ New service applications SHOULD favor the use of explicitly defined
+ AVPs as described in items 1a and 1b, to simplify interoperability.
+
+4.1.2. Service-Specific Documentation
+
+ The service specific rating input AVPs, the contents of the Service-
+ Parameter-Info AVP or Service-Context-Id AVP (defined in section
+ 8.42) are not within the scope of this document. To facilitate
+ interoperability, it is RECOMMENDED that the rating input and the
+ values of the Service-Context-Id be coordinated via an informational
+ RFC or other permanent and readily available reference. The
+ specification of another cooperative standardization body (e.g.,
+ 3GPP, OMA, and 3GPP2) SHOULD be used. However, private services may
+ be deployed that are subject to agreements between providers of the
+ credit-control server and client. In this case, vendor specific AVPs
+ can be used.
+
+ This specification, together with the above service specific
+ documents, governs the credit-control message. Service specific
+ documents define which existing AVPs or new AVPs are used as input to
+ the rating process (i.e., those that do not define new credit-control
+ applications), and thus have to be included in the Credit-Control-
+ Request command by a Diameter credit-control client supporting a
+ given service as *[AVP]. Should Service-Parameter-Info be used, then
+ the service specific document MUST specify the exact content of this
+ grouped AVP.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 14]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The Service-Context-Id AVP MUST be included at the command level of a
+ Credit-Control Request to identify the service specific document that
+ applies to the request. The specific service or rating group the
+ request relates to is uniquely identified by the combination of
+ Service-Context-Id and Service-Identifier or Rating-Group.
+
+4.1.3. Handling of Unsupported/Incorrect Rating Input
+
+ Diameter credit-control implementations are required to support the
+ Mandatory rating AVPs defined in service specific documentation of
+ the services they support, according to the 'M' bit rules in
+ [DIAMBASE].
+
+ If a rating input required for the rating process is incorrect in the
+ Credit-control request, or if the credit-control server does not
+ support the requested service context (identified by the Service-
+ Context-Id AVP at command level), the Credit-control answer MUST
+ contain the error code DIAMETER_RATING_FAILED. A CCA message with
+ this error MUST contain one or more Failed-AVP AVPs containing the
+ missing and/or unsupported AVPs that caused the failure. A Diameter
+ credit-control client that receives the error code
+ DIAMETER_RATING_FAILED in response to a request MUST NOT send similar
+ requests in the future.
+
+4.1.4. RADIUS Vendor-Specific Rating Attributes
+
+ When service specific documents include RADIUS vendor specific
+ attributes that could be used as input in the rating process, the
+ rules described in [NASREQ] for formatting the Diameter AVP MUST be
+ followed.
+
+ For example, if the AVP code used is the vendor attribute type code,
+ the Vendor-Specific flag MUST be set to 1 and the Vendor-ID MUST be
+ set to the IANA Vendor identification value. The Diameter AVP data
+ field contains only the attribute value of the RADIUS attribute.
+
+5. Session Based Credit-Control
+
+5.1. General Principles
+
+ For a session-based credit-control, several interrogations are
+ needed: the first, intermediate (optional) and the final
+ interrogations. This is illustrated in Figures 2 and 3.
+
+ If the credit-control client performs credit-reservation before
+ granting service to the end user, it MUST use several interrogations
+ toward the credit-control server (i.e., session based credit-
+
+
+
+
+Hakala, et al. Standards Track [Page 15]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ control). In this case, the credit-control server MUST maintain the
+ credit-control session state.
+
+ Each credit-control session MUST have a globally unique Session-Id as
+ defined in [DIAMBASE], which MUST NOT be changed during the lifetime
+ of a credit-control session.
+
+ Certain applications require multiple credit-control sub-sessions.
+ These applications would send messages with a constant Session-Id
+ AVP, but with a different CC-Sub-Session-Id AVP. If several credit
+ sub-sessions will be used, all sub-sessions MUST be closed separately
+ before the main session is closed so that units per sub-session may
+ be reported. The absence of this AVP implies that no sub-sessions
+ are in use.
+
+ Note that the service element might send a service specific re-
+ authorization message to the AAA server due to expiration of the
+ authorization-lifetime during an ongoing credit-control session.
+ However, the service specific re-authorization does not influence the
+ credit authorization that is ongoing between the credit-control
+ client and credit-control server, as credit authorization is
+ controlled by the burning rate of the granted quota.
+
+ If service specific re-authorization fails, the user will be
+ disconnected, and the credit-control client MUST send a final
+ interrogation to the credit-control server.
+
+ The Diameter credit-control server may seek to control the validity
+ time of the granted quota and/or the production of intermediate
+ interrogations. Thus, it MAY include the Validity-Time AVP in the
+ answer message to the credit-control client. Upon expiration of the
+ Validity-Time, the credit-control client MUST generate a credit-
+ control update request and report the used quota to the credit-
+ control server. It is up to the credit-control server to determine
+ the value of the Validity-Time to be used for consumption of the
+ granted service units. If the Validity-Time is used, its value
+ SHOULD be given as input to set the session supervision timer Tcc
+ (the session supervision timer MAY be set to two times the value of
+ the Validity-Time, as defined in section 13). Since credit-control
+ update requests are also produced at the expiry of granted service
+ units and/or for mid-session service events, the omission of
+ Validity-Time does not mean that intermediate interrogation for the
+ purpose of credit-control is not performed.
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 16]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+5.1.1. Basic Tariff-Time Change Support
+
+ The Diameter credit-control server and client MAY optionally support
+ a tariff change mechanism. The Diameter credit-control server may
+ include a Tariff-Time-Change AVP in the answer message. Note that
+ the granted units should be allocated based on the worst-case
+ scenario in case of forthcoming tariff change, so that the overall
+ reported used units would never exceed the credit reservation.
+
+ When the Diameter credit-control client reports the used units and a
+ tariff change has occurred during the reporting period, the Diameter
+ credit-control client MUST separately itemize the units used before
+ and after the tariff change. If the client is unable to distinguish
+ whether units straddling the tariff change were used before or after
+ the tariff change, the credit-control client MUST itemize those units
+ in a third category.
+
+ If a client does not support the tariff change mechanism and it
+ receives a CCA message carrying the Tariff-Time-Change AVP, it MUST
+ terminate the credit-control session, giving a reason of
+ DIAMETER_BAD_ANSWER in the Termination-Cause AVP.
+
+ For time based services, the quota is continuously consumed at the
+ regular rate of 60 seconds per minute. At the time when credit
+ resources are allocated, the server already knows how many units will
+ be consumed before the tariff time change and how many units will be
+ consumed afterward. Similarly, the server can determine the units
+ consumed at the before rate and the units consumed at the rate
+ afterward in the event that the end-user closes the session before
+ the consumption of the allotted quota. There is no need for
+ additional traffic between client and server in the case of tariff
+ time changes for continuous time based service. Therefore, the
+ tariff change mechanism is not used for such services. For time-
+ based services in which the quota is NOT continuously consumed at a
+ regular rate, the tariff change mechanism described for volume and
+ event units MAY be used.
+
+5.1.2. Credit-Control for Multiple Services within a (sub-)Session
+
+ When multiple services are used within the same user session and each
+ service or group of services is subject to different cost, it is
+ necessary to perform credit-control for each service independently.
+ Making use of credit-control sub-sessions to achieve independent
+ credit-control will result in increased signaling load and usage of
+ resources in both the credit-control client and the credit-control
+ server. For instance, during one network access session the end user
+ may use several http-services subject to different access cost. The
+ network access specific attributes such as the quality of service
+
+
+
+Hakala, et al. Standards Track [Page 17]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ (QoS) are common to all the services carried within the access
+ bearer, but the cost of the bearer may vary depending on its content.
+
+ To support these scenarios optimally, the credit-control application
+ enables independent credit-control of multiple services in a single
+ credit-control (sub-)session. This is achieved by including the
+ optional Multiple-Services-Credit-Control AVP in Credit-Control-
+ Request/Answer messages. It is possible to request and allocate
+ resources as a credit pool shared between multiple services. The
+ services can be grouped into rating groups in order to achieve even
+ further aggregation of credit allocation. It is also possible to
+ request and allocate quotas on a per service basis. Where quotas are
+ allocated to a pool by means of the Multiple-Services-Credit-Control
+ AVP, the quotas remain independent objects that can be re-authorized
+ independently at any time. Quotas can also be given independent
+ result codes, validity times, and Final-Unit-Indications.
+
+ A Rating-Group gathers a set of services, identified by a Service-
+ Identifier, and subject to the same cost and rating type (e.g.,
+ $0.1/minute). It is assumed that the service element is provided
+ with Rating-Groups, Service-Identifiers, and their associated
+ parameters that define what has to be metered by means outside the
+ scope of this specification. (Examples of parameters associated to
+ Service-Identifiers are IP 5-tuple and HTTP URL.) Service-Identifiers
+ enable authorization on a per-service based credit as well as
+ itemized reporting of service usage. It is up to the credit-control
+ server whether to authorize credit for one or more services or for
+ the whole rating-group. However, the client SHOULD always report
+ used units at the finest supported level of granularity. Where quota
+ is allocated to a rating-group, all the services belonging to that
+ group draw from the allotted quota. The following is a graphical
+ representation of the relationship between service-identifiers,
+ rating-groups, credit pools, and credit-control (sub-)session.
+
+ DCC (Sub-)Session
+ |
+ +------------+-----------+-------------+--------------- +
+ | | | | |
+ Service-Id a Service-Id b Service-Id c Service-Id d.....Service-Id z
+ \ / \ / /
+ \ / \ / /
+ \ / Rating-Group 1.......Rating-Group n
+ \ / | |
+ Quota ---------------Quota Quota
+ | / |
+ | / |
+ Credit-Pool Credit-Pool
+
+
+
+
+Hakala, et al. Standards Track [Page 18]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ If independent credit-control of multiple services is used, the
+ validity-time and final-unit-indication SHOULD be present either in
+ the Multiple-Services-Credit-Control AVP(s) or at command level as
+ single AVPs. However, the Result-Code AVP MAY be present both on the
+ command level and within the Multiple-Services-Credit-Control AVP.
+ If the Result-Code on the command level indicates a value other than
+ SUCCESS, then the Result-Code on command level takes precedence over
+ any included in the Multiple-Services-Credit-Control AVP.
+
+ The credit-control client MUST indicate support for independent
+ credit-control of multiple services within a (sub-)session by
+ including the Multiple-Services-Indicator AVP in the first
+ interrogation. A credit-control server not supporting this feature
+ MUST treat the Multiple-Services-Indicator AVP and any received
+ Multiple-Services-Credit-Control AVPs as invalid AVPs.
+
+ If the client indicated support for independent credit-control of
+ multiple services, a credit-control server that wishes to use the
+ feature MUST return the granted units within the Multiple-Services-
+ Credit-Control AVP associated to the corresponding service-identifier
+ and/or rating-group.
+
+ To avoid a situation where several parallel (and typically also
+ small) credit reservations must be made on the same account (i.e.,
+ credit fragmentation), and also to avoid unnecessary load on the
+ credit-control server, it is possible to provide service units as a
+ pool that applies to multiple services or rating groups. This is
+ achieved by providing the service units in the form of a quota for a
+ particular service or rating group in the Multiple-Services-Credit-
+ Control AVP, and also by including a reference to a credit pool for
+ that unit type.
+
+ The reference includes a multiplier derived from the rating
+ parameter, which translates from service units of a specific type to
+ the abstract service units in the pool. For instance, if the rating
+ parameter for service 1 is $1/MB and the rating parameter for service
+ 2 is $0.5/MB, the multipliers could be 10 and 5 for services 1 and 2,
+ respectively.
+
+ If S is the total service units within the pool, M1, M2, ..., Mn are
+ the multipliers provided for services 1, 2, ..., n, and C1, C2, ...,
+ Cn are the used resources within the session, then the pool credit is
+ exhausted and re-authorization MUST be sought when:
+
+ C1*M1 + C2*M2 + ... + Cn*Mn >= S
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 19]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The total credit in the pool, S, is calculated from the quotas, which
+ are currently allocated to the pool as follows:
+
+ S = Q1*M1 + Q2*M2 + ... + Qn*Mn
+
+ If services or rating groups are added to or removed from the pool,
+ then the total credit is adjusted appropriately. Note that when the
+ total credit is adjusted because services or rating groups are
+ removed from the pool, the value that need to be removed is the
+ consumed one (i.e., Cx*Mx).
+
+ Re-authorizations for an individual service or rating group may be
+ sought at any time; for example, if a 'non-pooled' quota is used up
+ or the Validity-Time expires.
+
+ Where multiple G-S-U-Pool-Reference AVPs (section 8.30) with the same
+ G-S-U-Pool-Identifier are provided within a Multiple-Services-
+ Credit-Control AVP (section 8.16) along with the Granted-Service-Unit
+ AVP, then these MUST have different CC-Unit-Type values, and they all
+ draw from the credit pool separately. For instance, if one
+ multiplier for time (M1t) and one multiplier for volume (M1v) are
+ given, then the used resources from the pool is the sum C1t*M1t +
+ C1v*M1v, where C1t is the time unit and C1v is the volume unit.
+
+ Where service units are provided within a Multiple-Services-Credit-
+ Control AVP without a corresponding G-S-U-Pool-Reference AVP, then
+ these are handled independently from any credit pool and from any
+ other services or rating groups within the session.
+
+ The credit pool concept is an optimal tool to avoid the over-
+ reservation effect of the basic single quota tariff time change
+ mechanism (the mechanism described in section 5.1.1). Therefore,
+ Diameter credit-control clients and servers implementing the
+ independent credit-control of multiple services SHOULD leverage the
+ credit pool concept when supporting the tariff time change. The
+ Diameter credit-control server SHOULD include both the Tariff-Time-
+ Change and Tariff-Change-Usage AVPs in two quota allocations in the
+ answer message (i.e., two instances of the Multiple-Services-Credit-
+ Control AVP). One of the granted units is allocated to be used
+ before the potential tariff change, while the second granted units
+ are for use after a tariff change. Both granted unit quotas MUST
+ contain the same Service-Identifier and/or Rating-Group. This dual
+ quota mechanism ensures that the overall reported used units would
+ never exceed the credit reservation. The Diameter credit-control
+ client reports both the used units before and after the tariff change
+ in a single instance of the Multiple-Services-Credit-Control AVP.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 20]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The failure handling for credit-control sessions is defined in
+ section 5.7 and reflected in the basic credit-control state machine
+ in section 7. Credit-control clients and servers implementing the
+ independent credit-control of multiple services in a (sub-)session
+ functionality MUST ensure failure handling and general behavior fully
+ consistent with the above mentioned sections, while maintaining the
+ ability to handle parallel ongoing credit re-authorization within a
+ (sub-)session. Therefore, it is RECOMMENDED that Diameter credit-
+ control clients maintain a PendingU message queue and restart the Tx
+ timer (section 13) every time a CCR message with the value
+ UPDATE_REQUEST is sent while they are in PendingU state. When
+ answers to all pending messages are received, the state machine moves
+ to OPEN state, and Tx is stopped. Naturally, the action performed
+ when a problem for the session is detected according to section 5.7
+ affects all the ongoing services (e.g., failover to a backup server
+ if possible affect all the CCR messages with the value UPDATE_REQUEST
+ in the PendingU queue).
+
+ Since the client may send CCR messages with the value UPDATE_REQUEST
+ while in PendingU (i.e., without waiting for an answer to ongoing
+ credit re-authorization), the time space between these requests may
+ be very short, and the server may not have received the previous
+ request(s) yet. Therefore, in this situation the server may receive
+ out of sequence requests and SHOULD NOT consider this an error
+ condition. A proper answer is to be returned to each of those
+ requests.
+
+5.2. First Interrogation
+
+ When session based credit-control is required (e.g., the
+ authentication server indicated a prepaid user), the first
+ interrogation MUST be sent before the Diameter credit-control client
+ allows any service event to the end user. The CC-Request-Type is set
+ to the value INITIAL_REQUEST in the request message.
+
+ If the Diameter credit-control client knows the cost of the service
+ event (e.g., a content server delivering ringing tones may know their
+ cost) the monetary amount to be charged is included in the
+ Requested-Service-Unit AVP. If the Diameter credit-control client
+ does not know the cost of the service event, the Requested-Service-
+ Unit AVP MAY contain the number of requested service events. Where
+ the Multiple-Services-Credit-Control AVP is used, it MUST contain the
+ Requested-Service-Unit AVP to indicate that the quota for the
+ associated service/rating-group is requested. In the case of
+ multiple services, the Service-Identifier AVP or the Rating-Group AVP
+ within the Multiple-Services-Credit-Control AVP always indicates the
+ service concerned. Additional service event information to be rated
+
+
+
+
+Hakala, et al. Standards Track [Page 21]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ MAY be sent as service specific AVPs or MAY be sent within the
+ Service-Parameter-Info AVP at command level. The Service-Context-Id
+ AVP indicates the service specific document applicable to the
+ request.
+
+ The Event-Timestamp AVP SHOULD be included in the request and
+ contains the time when the service event is requested in the service
+ element. The Subscription-Id AVP SHOULD be included to identify the
+ end user in the credit-control server. The credit-control client MAY
+ include the User-Equipment-Info AVP so that the credit-control server
+ has some indication of the type and capabilities of the end user
+ access device. How the credit-control server uses this information
+ is outside the scope of this document.
+
+ The credit-control server SHOULD rate the service event and make a
+ credit-reservation from the end user's account that covers the cost
+ of the service event. If the type of the Requested-Service-Unit AVP
+ is money, no rating is needed, but the corresponding monetary amount
+ is reserved from the end user's account.
+
+ The credit-control server returns the Granted-Service-Unit AVP in the
+ Answer message to the Diameter credit-control client. The Granted-
+ Service-Unit AVP contains the amount of service units that the
+ Diameter credit-control client can provide to the end user until a
+ new Credit-Control-Request MUST be sent to the credit-control server.
+ If several unit types are sent in the Answer message, the credit-
+ control client MUST handle each unit type separately. The type of
+ the Granted-Service-Unit AVP can be time, volume, service specific,
+ or money, depending on the type of service event. The unit type(s)
+ SHOULD NOT be changed within an ongoing credit-control session.
+
+ There MUST be a maximum of one instance of the same unit type in one
+ Answer message. However, if multiple quotas are conveyed to the
+ credit-control client in the Multiple-Services-Credit-Control AVPs,
+ it is possible to carry two instances of the same unit type
+ associated to a service-identifier/rating-group. This is typically
+ the case when a tariff time change is expected and the credit-control
+ server wants to make a distinction between the granted quota before
+ and after tariff change.
+
+ If the credit-control server determines that no further control is
+ needed for the service, it MAY include the result code indicating
+ that the credit-control is not applicable (e.g., if the service is
+ free of charge). This result code at command level implies that the
+ credit-control session is to be terminated.
+
+ The Credit-Control-Answer message MAY also include the Final-Unit-
+ Indication AVP to indicate that the answer message contains the final
+
+
+
+Hakala, et al. Standards Track [Page 22]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ units for the service. After the end user has consumed these units,
+ the Diameter credit-control-client MUST behave as described in
+ section 5.6.
+
+ This document defines two different approaches to perform the first
+ interrogation to be used in different network architectures. The
+ first approach uses credit-control messages after the user's
+ authorization and authentication takes place. The second approach
+ uses service specific authorization messages to perform the first
+ interrogation during the user's authorization/authentication phase,
+ and credit-control messages for the intermediate and final
+ interrogations. If an implementation of the credit-control client
+ supports both the methods, determining which method to use SHOULD be
+ configurable.
+
+ In service environments such as the Network Access Server (NAS), it
+ is desired to perform the first interrogation as part of the
+ authorization/authentication process for the sake of protocol
+ efficiency. Further credit authorizations after the first
+ interrogation are performed with credit-control commands defined in
+ this specification. Implementations of credit-control clients
+ operating in the mentioned environments SHOULD support this method.
+ If the credit-control server and AAA server are separate physical
+ entities, the service element sends the request messages to the AAA
+ server, which then issues an appropriate request or proxies the
+ received request forward to the credit-control server.
+
+ In other service environments, such as the 3GPP network and some SIP
+ scenarios, there is a substantial decoupling between
+ registration/access to the network and the actual service request
+ (i.e., the authentication/authorization is executed once at
+ registration/access to the network and is not executed for every
+ service event requested by the subscriber). In these environments,
+ it is more appropriate to perform the first interrogation after the
+ user has been authenticated and authorized. The first, the
+ intermediate, and the final interrogations are executed with credit-
+ control commands defined in this specification.
+
+ Other IETF standards or standards developed by other standardization
+ bodies may define the most suitable method in their architectures.
+
+5.2.1. First Interrogation after Authorization and Authentication
+
+ The Diameter credit-control client in the service element may get
+ information from the authorization server as to whether credit-
+ control is required, based on its knowledge of the end user. If
+ credit-control is required the credit-control server needs to be
+ contacted prior to initiating service delivery to the end user. The
+
+
+
+Hakala, et al. Standards Track [Page 23]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ accounting protocol and the credit-control protocol can be used in
+ parallel. The authorization server may also determine whether the
+ parallel accounting stream is required.
+
+ The following diagram illustrates the case where both protocols are
+ used in parallel and the service element sends credit-control
+ messages directly to the credit-control server. More credit-control
+ sequence examples are given in Annex A.
+
+ Diameter
+ End User Service Element AAA Server CC Server
+ (CC Client)
+ | Registration | AA request/answer(accounting,cc or both)|
+ |<----------------->|<------------------>| |
+ | : | | |
+ | : | | |
+ | Service Request | | |
+ |------------------>| | |
+ | | CCR(Initial,Credit-Control AVPs) |
+ | +|---------------------------------------->|
+ | CC stream|| | CCA(Granted-Units)|
+ | +|<----------------------------------------|
+ | Service Delivery | | |
+ |<----------------->| ACR(start,Accounting AVPs) |
+ | : |------------------->|+ |
+ | : | ACA || Accounting stream |
+ | |<-------------------|+ |
+ | : | | |
+ | : | | |
+ | | CCR(Update,Used-Units) |
+ | |---------------------------------------->|
+ | | | CCA(Granted-Units)|
+ | |<----------------------------------------|
+ | : | | |
+ | : | | |
+ | End of Service | | |
+ |------------------>| CCR(Termination, Used-Units) |
+ | |---------------------------------------->|
+ | | | CCA |
+ | |<----------------------------------------|
+ | | ACR(stop) | |
+ | |------------------->| |
+ | | ACA | |
+ | |<-------------------| |
+
+ Figure 2: Protocol example with first interrogation after user's
+ authorization/authentication
+
+
+
+
+Hakala, et al. Standards Track [Page 24]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+5.2.2. Authorization Messages for First Interrogation
+
+ The Diameter credit-control client in the service element MUST
+ actively co-operate with the authorization/authentication client in
+ the construction of the AA request by adding appropriate credit-
+ control AVPs. The credit-control client MUST add the Credit-Control
+ AVP to indicate credit-control capabilities and MAY add other
+ relevant credit-control specific AVPs to the proper
+ authorization/authentication command to perform the first
+ interrogation toward the home Diameter AAA server. The Auth-
+ Application-Id is set to the appropriate value, as defined in the
+ relevant service specific authorization/authentication application
+ document (e.g., [NASREQ], [DIAMMIP]). The home Diameter AAA server
+ authenticates/authorizes the subscriber and determines whether
+ credit-control is required.
+
+ If credit-control is not required for the subscriber, the home
+ Diameter AAA server will respond as usual, with an appropriate AA
+ answer message. If credit-control is required for the subscriber and
+ the Credit-Control AVP with the value set to CREDIT_AUTHORIZATION was
+ present in the authorization request, the home AAA server MUST
+ contact the credit-control server to perform the first interrogation.
+ If credit-control is required for the subscriber and the Credit-
+ Control AVP was not present in the authorization request, the home
+ AAA server MUST send an authorization reject answer message.
+
+ The Diameter AAA server supporting credit-control is required to send
+ the Credit-Control-Request command (CCR) defined in this document to
+ the credit-control server. The Diameter AAA server populates the CCR
+ based on service specific AVPs used for input to the rating process,
+ and possibly on credit-control AVPs received in the AA request. The
+ credit-control server will reserve money from the user's account,
+ will rate the request and will send a Credit-Control-Answer message
+ to the home Diameter AAA server. The answer message includes the
+ Granted-Service-Unit AVP(s) and MAY include other credit-control
+ specific AVPs, as appropriate. Additionally, the credit-control
+ server MAY set the Validity-Time and MAY include the Credit-Control-
+ Failure-Handling AVP and the Direct-Debiting-Failure-Handling AVP to
+ determine what to do if the sending of credit-control messages to the
+ credit-control server has been temporarily prevented.
+
+ Upon receiving the Credit-Control-Answer message from the credit-
+ control server, the home Diameter AAA server will populate the AA
+ answer with the received credit-control AVPs and with the appropriate
+ service attributes according to the authorization/authentication
+ specific application (e.g., [NASREQ], [DIAMMIP]). It will then
+ forward the packet to the credit-control client. If the home
+ Diameter AAA server receives a credit-control reject message, it will
+
+
+
+Hakala, et al. Standards Track [Page 25]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ simply generate an appropriate authorization reject message to the
+ credit-control client, including the credit-control specific error
+ code.
+
+ In this model, the credit-control client sends further credit-control
+ messages to the credit-control server via the home Diameter AAA
+ server. Upon receiving a successful authorization answer message
+ with the Granted-Service-Unit AVP(s), the credit-control client will
+ grant the service to the end user and will generate an intermediate
+ credit-control request, as required by using credit-control commands.
+ The CC-Request-Number of the first UPDATE_REQUEST MUST be set to 1
+ (for how to produce unique value for the CC-Request-Number AVP, see
+ section 8.2).
+
+ If service specific re-authorization is performed (i.e.,
+ authorization-lifetime expires), the credit-control client MUST add
+ to the service specific re-authorization request the Credit-Control
+ AVP with a value set to RE_AUTHORIZATION to indicate that the
+ credit-control server MUST NOT be contacted. When session based
+ credit-control is used for the subscriber, a constant credit-control
+ message stream flows through the home Diameter AAA server. The home
+ Diameter AAA server can make use of this credit-control message flow
+ to deduce that the user's activity is ongoing; therefore, it is
+ recommended to set the authorization-lifetime to a reasonably high
+ value when credit-control is used for the subscriber.
+
+ In this scenario, the home Diameter AAA server MUST advertise support
+ for the credit-control application to its peers during the capability
+ exchange process.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 26]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The following diagram illustrates the use of
+ authorization/authentication messages to perform the first
+ interrogation. The parallel accounting stream is not shown in the
+ figure.
+
+ Service Element Diameter
+ End User (CC Client) AAA Server CC Server
+ | Service Request | AA Request (CC AVPs) |
+ |------------------>|------------------->| |
+ | | | CCR(Initial, CC AVPs)
+ | | |------------------->|
+ | | | CCA(Granted-Units)
+ | | |<-------------------|
+ | | AA Answer(Granted-Units) |
+ | Service Delivery |<-------------------| |
+ |<----------------->| | |
+ | : | | |
+ | : | | |
+ | : | | |
+ | | | |
+ | | CCR(Update,Used-Units) |
+ | |------------------->| CCR(Update,Used-Units)
+ | | |------------------->|
+ | | | CCA(Granted-Units)|
+ | | CCA(Granted-Units)|<-------------------|
+ | |<-------------------| |
+ | : | | |
+ | : | | |
+ | End of Service | | |
+ |------------------>| CCR(Termination,Used-Units) |
+ | |------------------->| CCR(Term.,Used-Units)
+ | | |------------------->|
+ | | | CCA |
+ | | CCA |<-------------------|
+ | |<-------------------| |
+
+ Figure 3: Protocol example with use of the
+ authorization messages for the first interrogation
+
+5.3. Intermediate Interrogation
+
+ When all the granted service units for one unit type are spent by the
+ end user or the Validity-Time is expired, the Diameter credit-control
+ client MUST send a new Credit-Control-Request to the credit-control
+ server. In the event that credit-control for multiple services is
+ applied in one credit-control session (i.e., units associated to
+ Service-Identifier(s) or Rating-Group are granted), a new Credit-
+ Control-Request MUST be sent to the credit-control server when the
+
+
+
+Hakala, et al. Standards Track [Page 27]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ credit reservation has been wholly consumed, or upon expiration of
+ the Validity-Time. It is always up to the Diameter credit-control
+ client to send a new request well in advance of the expiration of the
+ previous request in order to avoid interruption in the service
+ element. Even if the granted service units reserved by the credit-
+ control server have not been spent upon expiration of the Validity-
+ Time, the Diameter credit-control client MUST send a new Credit-
+ Control-Request to the credit-control server.
+
+ There can also be mid-session service events, which might affect the
+ rating of the current service events. In this case, a spontaneous
+ updating (a new Credit-Control-Request) SHOULD be sent including
+ information related to the service event even if all the granted
+ service units have not been spent or the Validity-Time has not
+ expired.
+
+ When the used units are reported to the credit-control server, the
+ credit-control client will not have any units in its possession
+ before new granted units are received from the credit-control server.
+ When the new granted units are received, these units apply from the
+ point where the measurement of the reported used units stopped.
+ Where independent credit-control of multiple services is supported,
+ this process may be executed for one or more services, a single
+ rating-group, or a pool within the (sub)session.
+
+ The CC-Request-Type AVP is set to the value UPDATE_REQUEST in the
+ intermediate request message. The Subscription-Id AVP SHOULD be
+ included in the intermediate message to identify the end user in the
+ credit-control server. The Service-Context-Id AVP indicates the
+ service specific document applicable to the request.
+
+ The Requested-Service-Unit AVP MAY contain the new amount of
+ requested service units. Where the Multiple-Services-Credit-Control
+ AVP is used, it MUST contain the Requested-Service-Unit AVP if a new
+ quota is requested for the associated service/rating-group. The
+ Used-Service-Unit AVP contains the amount of used service units
+ measured from the point when the service became active or, if interim
+ interrogations are used during the session, from the point when the
+ previous measurement ended. The same unit types used in the previous
+ message SHOULD be used. If several unit types were included in the
+ previous answer message, the used service units for each unit type
+ MUST be reported.
+
+ The Event-Timestamp AVP SHOULD be included in the request and
+ contains the time of the event that triggered the sending of the new
+ Credit-Control-Request.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 28]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The credit-control server MUST deduct the used amount from the end
+ user's account. It MAY rate the new request and make a new credit-
+ reservation from the end user's account that covers the cost of the
+ requested service event.
+
+ A Credit-Control-Answer message with the CC-Request-Type AVP set to
+ the value UPDATE_REQUEST MAY include the Cost-Information AVP
+ containing the accumulated cost estimation for the session, without
+ taking any credit-reservation into account.
+
+ The Credit-Control-Answer message MAY also include the Final-Unit-
+ Indication AVP to indicate that the answer message contains the final
+ units for the service. After the end user has consumed these units,
+ the Diameter credit-control-client MUST behave as described in
+ section 5.6.
+
+ There can be several intermediate interrogations within a session.
+
+5.4. Final Interrogation
+
+ When the end user terminates the service session, or when the
+ graceful service termination described in section 5.6 takes place,
+ the Diameter credit-control client MUST send a final Credit-Control-
+ Request message to the credit-control server. The CC-Request-Type
+ AVP is set to the value TERMINATION_REQUEST. The Service-Context-Id
+ AVP indicates the service specific document applicable to the
+ request.
+
+ The Event-Timestamp AVP SHOULD be included in the request and
+ contains the time when the session was terminated.
+
+ The Used-Service-Unit AVP contains the amount of used service units
+ measured from the point when the service became active or, if interim
+ interrogations are used during the session, from the point when the
+ previous measurement ended. If several unit types were included in
+ the previous answer message, the used service units for each unit
+ type MUST be reported.
+
+ After final interrogation, the credit-control server MUST refund the
+ reserved credit amount not used to the end user's account and deduct
+ the used monetary amount from the end user's account.
+
+ A Credit-Control-Answer message with the CC-Request-Type set to the
+ value TERMINATION_REQUEST MAY include the Cost-Information AVP
+ containing the estimated total cost for the session in question.
+
+ If the user logs off during an ongoing credit-control session, or if
+ some other reason causes the user to become logged off (e.g., final-
+
+
+
+Hakala, et al. Standards Track [Page 29]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ unit indication causes user logoff according to local policy), the
+ service element, according to application specific policy, may send a
+ Session-Termination-Request (STR) to the home Diameter AAA server as
+ usual [DIAMBASE]. Figure 4 illustrates the case when the final-unit
+ indication causes user logoff upon consumption of the final granted
+ units and the generation of STR.
+
+ Service Element AAA Server CC Server
+ End User (CC Client)
+ | Service Delivery | | |
+ |<----------------->| | |
+ | : | | |
+ | : | | |
+ | : | | |
+ | | | |
+ | | CCR(Update,Used-Units) |
+ | |------------------->| CCR(Update,Used-Units)
+ | | |------------------->|
+ | | CCA(Final-Unit, Terminate)
+ | CCA(Final-Unit, Terminate)|<-------------------|
+ | |<-------------------| |
+ | : | | |
+ | : | | |
+ | Disconnect user | | |
+ |<------------------| CCR(Termination,Used-Units) |
+ | |------------------->| CCR(Term.,Used-Units)
+ | | |------------------->|
+ | | | CCA |
+ | | CCA |<-------------------|
+ | |<-------------------| |
+ | | STR | |
+ | |------------------->| |
+ | | STA | |
+ | |<-------------------| |
+
+ Figure 4: User disconnected due to exhausted account
+
+5.5. Server-Initiated Credit Re-Authorization
+
+ The Diameter credit-control application supports server-initiated
+ re-authorization. The credit-control server MAY optionally initiate
+ the credit re-authorization by issuing a Re-Auth-Request (RAR) as
+ defined in the Diameter base protocol [DIAMBASE]. The Auth-
+ Application-Id in the RAR message is set to 4 to indicate Diameter
+ Credit Control, and the Re-Auth-Request-Type is set to
+ AUTHORIZE_ONLY.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 30]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Section 5.1.2 defines the feature to enable credit-control for
+ multiple services within a single (sub-)session where the server can
+ authorize credit usage at a different level of granularity. Further,
+ the server may provide credit resources to multiple services or
+ rating groups as a pool (see section 5.1.2 for details and
+ definitions). Therefore, the server, based on its service logic and
+ its knowledge of the ongoing session, can decide to request credit
+ re-authorization for a whole (sub-)session, a single credit pool, a
+ single service, or a single rating-group. To request credit re-
+ authorization for a credit pool, the server includes in the RAR
+ message the G-S-U-Pool-Identifier AVP indicating the affected pool.
+ To request credit re-authorization for a service or a rating-group,
+ the server includes in the RAR message the Service-Identifier AVP or
+ the Rating-Group AVP, respectively. To request credit re-
+ authorization for all the ongoing services within the (sub-)session,
+ the server includes none of the above mentioned AVPs in the RAR
+ message.
+
+ If a credit re-authorization is not already ongoing (i.e., the
+ credit-control session is in Open state), a credit control client
+ that receives an RAR message with Session-Id equal to a currently
+ active credit-control session MUST acknowledge the request by sending
+ the Re-Auth-Answer (RAA) message and MUST initiate the credit re-
+ authorization toward the server by sending a Credit-Control-Request
+ message with the CC-Request-Type AVP set to the value UPDATE_REQUEST.
+ The Result-Code 2002 (DIAMETER_LIMITED_SUCCESS) SHOULD be used in the
+ RAA message to indicate that an additional message (i.e., CCR message
+ with the value UPDATE_REQUEST) is required to complete the procedure.
+ If a quota was allocated to the service, the credit-control client
+ MUST report the used quota in the Credit-Control-Request. Note that
+ the end user does not need to be prompted for the credit re-
+ authorization, since the credit re-authorization is transparent to
+ the user (i.e., it takes place exclusively between the credit-control
+ client and the credit-control server).
+
+ Where multiple services in a user's session are supported, the
+ procedure in the above paragraph will be executed at the granularity
+ requested by the server in the RAR message.
+
+ If credit re-authorization is ongoing at the time when the RAR
+ message is received (i.e., RAR-CCR collision), the credit-control
+ client successfully acknowledges the request but does not initiate a
+ new credit re-authorization. The Result-Code 2001 (DIAMETER_SUCCESS)
+ SHOULD be used in the RAA message to indicate that a credit re-
+ authorization procedure is already ongoing (i.e., the client was in
+ PendingU state when the RAR was received). The credit-control server
+ SHOULD process the Credit-Control-Request as if it was received in
+ answer to the server initiated credit re-authorization, and should
+
+
+
+Hakala, et al. Standards Track [Page 31]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ consider the server initiated credit re-authorization process
+ successful upon reception of the Re-Auth-Answer message.
+
+ When multiple services are supported in a user's session, the server
+ may request credit re-authorization for a credit pool (or for the
+ (sub-)session) while a credit re-authorization is already ongoing for
+ some of the services or rating-groups. In this case, the client
+ acknowledges the server request with an RAA message and MUST send a
+ new Credit-Control-Request message to perform re-authorization for
+ the remaining services/rating-groups. The Result-Code 2002
+ (DIAMETER_LIMITED_SUCCESS) SHOULD be used in the RAA message to
+ indicate that an additional message (i.e., CCR message with value
+ UPDATE_REQUEST) is required to complete the procedure. The server
+ processes the received requests and returns an appropriate answer to
+ both requests.
+
+ The above-defined procedures are enabled for each of the possibly
+ active Diameter credit-control sub-sessions. The server MAY request
+ re-authorization for an active sub-session by including the CC-Sub-
+ Session-Id AVP in the RAR message in addition to the Session-Id AVP.
+
+5.6. Graceful Service Termination
+
+ When the user's account runs out of money, the user may not be
+ allowed to compile additional chargeable events. However, the home
+ service provider may offer some services; for instance, access to a
+ service portal where it is possible to refill the account, for which
+ the user is allowed to benefit for a limited time. The length of
+ this time is usually dependent on the home service provider policy.
+
+ This section defines the optional graceful service termination
+ feature that MAY be supported by the credit-control server. Credit-
+ control client implementations MUST support the Final-Unit-Indication
+ with at least the teardown of the ongoing service session once the
+ subscriber has consumed all the final granted units.
+
+ Where independent credit-control of multiple services in a single
+ credit-control (sub-)session is supported, it is possible to use the
+ graceful service termination for each of the services/rating-groups
+ independently. Naturally, the graceful service termination process
+ defined in the following sub-sections will apply to the specific
+ service/rating-group as requested by the server.
+
+ In some service environments (e.g., NAS), the graceful service
+ termination may be used to redirect the subscriber to a service
+ portal for online balance refill or other services offered by the
+ home service provider. In this case, the graceful termination
+ process installs a set of packet filters to restrict the user's
+
+
+
+Hakala, et al. Standards Track [Page 32]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ access capability only to/from the specified destinations. All the
+ IP packets not matching the filters will be dropped or, possibly,
+ re-directed to the service portal. The user may also be sent an
+ appropriate notification as to why the access has been limited.
+ These actions may be communicated explicitly from the server to the
+ client or may be configured per-service at the client. Explicitly
+ signaled redirect or restrict instructions always take precedence
+ over configured ones.
+
+ It is also possible use the graceful service termination to connect
+ the prepaid user to a top-up server that plays an announcement and
+ prompts the user to replenish the account. In this case, the
+ credit-control server sends only the address of the top-up server
+ where the prepaid user shall be connected after the final granted
+ units have been consumed. An example of this is given in Appendix A
+ (Flow VII).
+
+ The credit-control server MAY initiate the graceful service
+ termination by including the Final-Unit-Indication AVP in the
+ Credit-Control-Answer to indicate that the message contains the final
+ units for the service.
+
+ When the credit-control client receives the Final-Unit-Indication AVP
+ in the answer from the server, its behavior depends on the value
+ indicated in the Final-Unit-Action AVP. The server may request the
+ following actions: TERMINATE, REDIRECT, or RESTRICT_ACCESS.
+
+ A following figure illustrates the graceful service termination
+ procedure described in the following sub-sections.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 33]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Diameter
+ End User Service Element AAA Server CC Server
+ (CC Client)
+ | Service Delivery | | |
+ |<----------------->| | |
+ | |CCR(Update,Used-Units) |
+ | |------------------->|CCR(Update,Used-Units)
+ | : | |------------------->|
+ | : | |CCA(Final-Unit,Action)
+ | : | |<-------------------|
+ | |CCA(Final-Unit,Action) |
+ | |<-------------------| |
+ | | | |
+ | : | | |
+ | : | | |
+ | : | | |
+ | /////////////// |CCR(Update,Used-Units) |
+ |/Final Units End/->|------------------->|CCR(Update,Used-Units)
+ |/Action and // | |------------------->|
+ |/Restrictions // | | CCA(Validity-Time)|
+ |/Start // | CCA(Validity-Time)|<-------------------|
+ | ///////////// |<-------------------| |
+ | : | | |
+ | : | | |
+ | Replenish Account +-------+ |
+ |<-------------------------------------------->|Account| |
+ | | | +-------+ |
+ | | | RAR |
+ | + | RAR |<===================|
+ | | |<===================| |
+ | | | RAA | |
+ | ///////////// | |===================>| RAA |
+ | /If supported / | | CCR(Update) |===================>|
+ | /by CC Server/ | |===================>| CCR(Update) |
+ | ///////////// | | |===================>|
+ | | | | CCA(Granted-Unit)|
+ | | | CCA(Granted-Unit)|<===================|
+ | Restrictions ->+ |<===================| |
+ | removed | | |
+ | : | | |
+ | OR | CCR(Update) | |
+ | Validity-Time ->|------------------->| CCR(Update) |
+ | expires | |------------------->|
+ | | | CCA(Granted-Unit)|
+ | | CCA(Granted-Unit)|<-------------------|
+ | Restrictions ->|<-------------------| |
+ | removed | | |
+
+
+
+
+Hakala, et al. Standards Track [Page 34]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Figure 5: Optional graceful service termination procedure
+
+5.6.1. Terminate Action
+
+ The Final-Unit-Indication AVP with Final-Unit-Action TERMINATE does
+ not include any other information. When the subscriber has consumed
+ the final granted units, the service element MUST terminate the
+ service. This is the default handling applicable whenever the
+ credit-control client receives an unsupported Final-Unit-Action value
+ and MUST be supported by all the Diameter credit-control client
+ implementations conforming to this specification. A final Credit-
+ Control-Request message to the credit-control server MUST be sent if
+ the Final-Unit-Indication AVP indicating action TERMINATE was present
+ at command level. The CC-Request-Type AVP in the request is set to
+ the value TERMINATION_REQUEST.
+
+5.6.2. Redirect Action
+
+ The Final-Unit-Indication AVP with Final-Unit-Action REDIRECT
+ indicates to the service element supporting this action that, upon
+ consumption of the final granted units, the user MUST be re-directed
+ to the address specified in the Redirect-Server AVP as follows.
+
+ The credit-control server sends the Redirect-Server AVP in the
+ Credit-Control-Answer message. In such a case, the service element
+ MUST redirect or connect the user to the destination specified in the
+ Redirect-Server AVP, if possible. When the end user is redirected
+ (by using protocols others than Diameter) to the specified server or
+ connected to the top-up server, an additional authorization (and
+ possibly authentication) may be needed before the subscriber can
+ replenish the account; however, this is out of the scope of this
+ specification.
+
+ In addition to the Redirect-Server AVP, the credit-control server MAY
+ include one or more Restriction-Filter-Rule AVPs or one or more
+ Filter-Id AVPs in the Credit-Control-Answer message to enable the
+ user to access other services (for example, zero-rated services). In
+ such a case, the access device MUST drop all the packets not matching
+ the IP filters specified in the Credit-Control-Answer message and, if
+ possible, redirect the user to the destination specified in the
+ Redirect-Server AVP.
+
+ An entity other than the credit-control server may provision the
+ access device with appropriate IP packet filters to be used in
+ conjunction with the Diameter credit-control application. This case
+ is considered in section 5.6.3.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 35]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ When the final granted units have been consumed, the credit-control
+ client MUST perform an intermediate interrogation. The purpose of
+ this interrogation is to indicate to the credit-control server that
+ the specified action started and to report the used units. The
+ credit-control server MUST deduct the used amount from the end user's
+ account but MUST NOT make a new credit reservation. The credit-
+ control client, however, may send intermediate interrogations before
+ all the final granted units have been consumed for which rating and
+ money reservation may be needed; for instance, upon Validity-Time
+ expires or upon mid-session service events that affect the rating of
+ the current service. Therefore, the credit-control client MUST NOT
+ include any rating related AVP in the request sent once all the final
+ granted units have been consumed as an indication to the server that
+ the requested final unit action started, rating and money reservation
+ are not required (when the Multiple-Services-Credit-Control AVP is
+ used, the Service-Identifier or Rating-Group AVPs is included to
+ indicate the concerned services). Naturally, the Credit-Control-
+ Answer message does not contain any granted service unit and MUST
+ include the Validity-Time AVP to indicate to the credit-control
+ client how long the subscriber is allowed to use network resources
+ before a new intermediate interrogation is sent to the server.
+
+ At the expiry of Validity-Time, the credit-control client sends a
+ Credit-Control-Request (UPDATE_REQUEST) as usual. This message does
+ not include the Used-Service-Unit AVP, as there is no allotted quota
+ to report. The credit-control server processes the request and MUST
+ perform the credit reservation. If during this time the subscriber
+ did not replenish his/her account, whether he/she will be
+ disconnected or will be granted access to services not controlled by
+ a credit-control server for an unlimited time is dependent on the
+ home service provider policy (note: the latter option implies that
+ the service element should not remove the restriction filters upon
+ termination of the credit-control). The server will return the
+ appropriate Result-Code (see section 9.1) in the Credit-Control-
+ Answer message in order to implement the policy-defined action.
+ Otherwise, new quota will be returned, the service element MUST
+ remove all the possible restrictions activated by the graceful
+ service termination process and continue the credit-control session
+ and service session as usual.
+
+ The credit-control client may not wait until the expiration of the
+ Validity-Time and may send a spontaneous update (a new Credit-
+ Control-Request) if the service element can determine, for instance,
+ that communication between the end user and the top-up server took
+ place. An example of this is given in Appendix A (Figure A.8).
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 36]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Note that the credit-control server may already have initiated the
+ above-described process for the first interrogation. However, the
+ user's account might be empty when this first interrogation is
+ performed. In this case, the subscriber can be offered a chance to
+ replenish the account and continue the service. The credit-control
+ client receives a Credit-Control-Answer or service specific
+ authorization answer with the Final-Unit-Indication and Validity-Time
+ AVPs but no Granted-Service-Unit. It immediately starts the graceful
+ service termination without sending any message to the server. An
+ example of this case is illustrated in Appendix A.
+
+5.6.3. Restrict Access Action
+
+ A Final-Unit-Indication AVP with the Final-Unit-Action
+ RESTRICT_ACCESS indicates to the device supporting this action that
+ the user's access MUST be restricted according to the IP packet
+ filters given in the Restriction-Filter-Rule AVP(s) or according to
+ the IP packet filters identified by the Filter-Id AVP(s). The
+ credit-control server SHOULD include either the Restriction-Filter-
+ Rule AVP or the Filter-Id AVP in the Credit-Control-Answer message.
+
+ An entity other than the credit-control server may provision the
+ access device with appropriate IP packet filters to be used in
+ conjunction with the Diameter credit-control application. Such an
+ entity may, for instance, configure the access device with IP flows
+ to be passed when the Diameter credit-control application indicates
+ RESTRICT_ACCESS or REDIRECT. The access device passes IP packets
+ according to the filter rules that may have been received in the
+ Credit-Control-Answer message in addition to those that may have been
+ configured by the other entity. However, when the user's account
+ cannot cover the cost of the requested service, the action taken is
+ the responsibility of the credit-control server that controls the
+ prepaid subscriber.
+
+ If another entity working in conjunction with the Diameter credit-
+ control application already provisions the access device with all the
+ required filter rules for the end user, the credit-control server
+ presumably need not send any additional filter. Therefore, it is
+ RECOMMENDED that credit-control server implementations supporting the
+ graceful service termination be configurable for sending the
+ Restriction-Filter-Rule AVP, the Filter-Id AVP, or none of the above.
+
+ When the final granted units have been consumed, the credit-control
+ client MUST perform an intermediate interrogation. The credit-
+ control client and the credit-control server process this
+ intermediate interrogation and execute subsequent procedures, as
+ specified in the previous section for the REDIRECT action.
+
+
+
+
+Hakala, et al. Standards Track [Page 37]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The credit-control server may initiate the graceful service
+ termination with action RESTRICT_ACCESS already for the first
+ interrogation, as specified in the previous section for the REDIRECT
+ action.
+
+5.6.4. Usage of the Server-Initiated Credit Re-Authorization
+
+ Once the subscriber replenishes the account, she presumably expects
+ all the restrictions placed by the graceful termination procedure to
+ be removed immediately and unlimited service' access to be resumed.
+ For the best user experience, the credit-control server
+ implementation MAY support the server-initiated credit re-
+ authorization (see section 5.5). In such a case, upon the successful
+ account top-up, the credit-control server sends the Re-Auth-Request
+ (RAR) message to solicit the credit re-authorization. The credit-
+ control client initiates the credit re-authorization by sending the
+ Credit-Control-Request message with the CC-Request-Type AVP set to
+ the value UPDATE_REQUEST. The Used-Service-Unit AVP is not included
+ in the request, as there is no allotted quota to report. The
+ Requested-Service-Unit AVP MAY be included in the request. After the
+ credit-control client successfully receives the Credit-Control-Answer
+ with new Granted-Service-Unit, all the possible restrictions
+ activated for the purpose of the graceful service termination MUST be
+ removed in the service element. The credit-control session and the
+ service session continue as usual.
+
+5.7. Failure Procedures
+
+ The Credit-Control-Failure-Handling AVP (CCFH), as described in this
+ section, determines the behavior of the credit-control client in
+ fault situations. The CCFH may be received from the Diameter home
+ AAA server, from the credit-control server, or may be configured
+ locally. The CCFH value received from the home AAA server overrides
+ the locally configured value. The CCFH value received from the
+ credit-control server in the Credit-Control-Answer message always
+ overrides any existing value.
+
+ The authorization server MAY include the Accounting-Realtime-Required
+ AVP to determine what to do if the sending of accounting records to
+ the accounting server has been temporarily prevented, as defined in
+ [DIAMBASE]. It is RECOMMENDED that the client complement the
+ credit-control failure procedures with backup accounting flow toward
+ an accounting server. By using different combinations of
+ Accounting-Realtime-Required and Credit-Control-Failure-Handling
+ AVPs, different safety levels can be built. For example, by choosing
+ a Credit-Control-Failure-Handling AVP equal to CONTINUE for the
+ credit-control flow and a Accounting-Realtime-Required AVP equal to
+ DELIVER_AND_GRANT for the accounting flow, the service can be granted
+
+
+
+Hakala, et al. Standards Track [Page 38]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ to the end user even if the connection to the credit-control server
+ is down, as long as the accounting server is able to collect the
+ accounting information and information exchange is taking place
+ between the accounting server and credit-control server.
+
+ As the credit-control application is based on real-time bi-
+ directional communication between the credit-control client and the
+ credit-control server, the usage of alternative destinations and the
+ buffering of messages may not be sufficient in the event of
+ communication failures. Because the credit-control server has to
+ maintain session states, moving the credit-control message stream to
+ a backup server requires a complex context transfer solution.
+ Whether the credit-control message stream is moved to a backup
+ credit-control server during an ongoing credit-control session
+ depends on the value of the CC-Session-Failover AVP. However,
+ failover may occur at any point in the path between the credit-
+ control client and the credit-control server if a transport failure
+ is detected with a peer, as described in [DIAMBASE]. As a
+ consequence, the credit-control server might receive duplicate
+ messages. These duplicates or out of sequence messages can be
+ detected in the credit-control server based on the credit-control
+ server session state machine (section 7), Session-Id AVP, and CC-
+ Request-Number AVP.
+
+ If a failure occurs during an ongoing credit-control session, the
+ credit-control client may move the credit-control message stream to
+ an alternative server if the CC-server indicated FAILOVER_SUPPORTED
+ in the CC-Session-Failover AVP. A secondary credit-control server
+ name, either received from the home Diameter AAA server or configured
+ locally, can be used as an address of the backup server. If the CC-
+ Session-Failover AVP is set to FAILOVER_NOT_SUPPORTED, the credit-
+ control message stream MUST NOT be moved to a backup server.
+
+ For new credit-control sessions, failover to an alternative credit-
+ control server SHOULD be performed if possible. For instance, if an
+ implementation of the credit-control client can determine primary
+ credit-control server unavailability, it can establish the new
+ credit-control sessions with a possibly available secondary credit-
+ control server.
+
+ The AAA transport profile [AAATRANS] defines the application layer
+ watchdog algorithm that enables failover from a peer that has failed
+ and is controlled by a watchdog timer (Tw) defined in [AAATRANS].
+ The recommended default initial value for Tw (Twinit) is 30 seconds.
+ Twinit may be set as low as 6 seconds; however, according to
+ [AAATRANS], setting too low a value for Twinit is likely to result in
+ an increased probability of duplicates, as well as an increase in
+ spurious failover and failback attempts. The Diameter base protocol
+
+
+
+Hakala, et al. Standards Track [Page 39]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ is common to several different types of Diameter AAA applications
+ that may be run in the same service element. Therefore, tuning the
+ timer Twinit to a lower value in order to satisfy the requirements of
+ real-time applications, such as the Diameter credit-control
+ application, will certainly cause the above mentioned problems. For
+ prepaid services, however, the end user expects an answer from the
+ network in a reasonable time. Thus, the Diameter credit-control
+ client will react faster than would the underlying base protocol.
+ Therefore this specification defines the timer Tx that is used by the
+ credit-control client (as defined in section 13) to supervise the
+ communication with the credit-control server. When the timer Tx
+ elapses, the credit-control client takes an action to the end user
+ according to the Credit-Control-Failure-Handling AVP.
+
+ When Tx expires, the Diameter credit-control client always terminates
+ the service if the Credit-Control-Failure-Handling (CCFH) AVP is set
+ to the value TERMINATE. The credit-control session may be moved to
+ an alternative server only if a protocol error DIAMETER_TOO_BUSY or
+ DIAMETER_UNABLE_TO_DELIVER is received before Tx expires. Therefore,
+ the value TERMINATE is not appropriate if proper failover behavior is
+ desired.
+
+ If the Credit-Control-Failure-Handling AVP is set to the value
+ CONTINUE or RETRY_AND_TERMINATE, the service will be granted to the
+ end user when the timer Tx expires. An answer message with granted-
+ units may arrive later if the base protocol transport failover
+ occurred in the path to the credit-control server. (The Twinit
+ default value is 3 times more than the Tx recommended value.) The
+ credit-control client SHOULD grant the service to the end user, start
+ monitoring the resource usage, and wait for the possible late answer
+ until the timeout of the request (e.g., 120 seconds). If the request
+ fails and the CC-Session-Failover AVP is set to
+ FAILOVER_NOT_SUPPORTED, the credit-control client terminates or
+ continues the service depending on the value set in the CCFH and MUST
+ free all the reserved resources for the credit-control session. If
+ the protocol error DIAMETER_UNABLE_TO_DELIVER or DIAMETER_TOO_BUSY is
+ received or the request times out and the CC-Session-Failover AVP is
+ set to FAILOVER_SUPPORTED, the credit-control client MAY send the
+ request to a backup server, if possible. If the credit-control
+ client receives a successful answer from the backup server, it
+ continues the credit-control session with such a server. If the re-
+ transmitted request also fails, the credit-control client terminates
+ or continues the service depending on the value set in the CCFH and
+ MUST free all the reserved resources for the credit-control session.
+
+ If a communication failure occurs during the graceful service
+ termination procedure, the service element SHOULD always terminate
+ the ongoing service session.
+
+
+
+Hakala, et al. Standards Track [Page 40]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ If the credit-control server detects a failure during an ongoing
+ credit-control session, it will terminate the credit-control session
+ and return the reserved units back to the end user's account.
+
+ The supervision session timer Tcc (as defined in section 13) is used
+ in the credit-control server to supervise the credit-control session.
+
+ In order to support failover between credit-control servers,
+ information transfer about the credit-control session and account
+ state SHOULD take place between the primary and the secondary
+ credit-control server. Implementations supporting the credit-control
+ session failover MUST also ensure proper detection of duplicate or
+ out of sequence messages. The communication between the servers is
+ regarded as an implementation issue and is outside of the scope of
+ this specification.
+
+6. One Time Event
+
+ The one-time event is used when there is no need to maintain any
+ state in the Diameter credit-control server; for example, enquiring
+ about the price of the service. The use of a one-time event implies
+ that the user has been authenticated and authorized beforehand.
+
+ The one time event can be used when the credit-control client wants
+ to know the cost of the service event or to check the account balance
+ without any credit-reservation. It can also be used for refunding
+ service units on the user's account or for direct debiting without
+ any credit-reservation. The one time event is shown in Figure 6.
+
+ Diameter
+ End User Service Element AAA Server CC Server
+ (CC Client)
+ | Service Request | | |
+ |------------------>| | |
+ | | CCR(Event) | |
+ | |------------------->| CCR(Event) |
+ | | |------------------->|
+ | | | CCA(Granted-Units)|
+ | | CCA(Granted-Units)|<-------------------|
+ | Service Delivery |<-------------------| |
+ |<----------------->| | |
+
+ Figure 6: One time event
+
+ In environments such as the 3GPP architecture, the one time event can
+ be sent from the service element directly to the credit-control
+ server.
+
+
+
+
+Hakala, et al. Standards Track [Page 41]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+6.1. Service Price Enquiry
+
+ The credit-control client may need to know the price of the service
+ event. Services offered by application service providers whose
+ prices are not known in the credit-control client might exist. The
+ end user might also want to get an estimation of the price of a
+ service event before requesting it.
+
+ A Diameter credit-control client requesting the cost information MUST
+ set the CC-Request-Type AVP equal to EVENT_REQUEST, include the
+ Requested-Action AVP set to PRICE_ENQUIRY, and set the requested
+ service event information into the Service-Identifier AVP in the
+ Credit-Control-Request message. Additional service event information
+ may be sent as service specific AVPs or within the Service-
+ Parameter-Info AVP. The Service-Context-Id AVP indicates the service
+ specific document applicable to the request.
+
+ The credit-control server calculates the cost of the requested
+ service event, but it does not perform any account balance check or
+ credit-reservation from the account.
+
+ The estimated cost of the requested service event is returned to the
+ credit-control client in the Cost-Information AVP in the Credit-
+ Control-Answer message.
+
+6.2. Balance Check
+
+ The Diameter credit-control client may only have to verify that the
+ end user's account balance covers the cost of a certain service
+ without reserving any units from the account at the time of the
+ inquiry. This method does not guarantee that credit would be left
+ when the Diameter credit-control client requests the debiting of the
+ account with a separate request.
+
+ A Diameter credit-control client requesting the balance check MUST
+ set the CC-Request-Type AVP equal to EVENT_REQUEST, include a
+ Requested-Action AVP set to CHECK_BALANCE, and include the
+ Subscription-Id AVP in order to identify the end user in the credit-
+ control server. The Service-Context-Id AVP indicates the service
+ specific document applicable to the request.
+
+ The credit-control server makes the balance check, but it does not
+ make any credit-reservation from the account.
+
+ The result of balance check (ENOUGH_CREDIT/NO_CREDIT) is returned to
+ the credit-control client in the Check-Balance-Result AVP in the
+ Credit-Control-Answer message.
+
+
+
+
+Hakala, et al. Standards Track [Page 42]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+6.3. Direct Debiting
+
+ There are certain service events for which service execution is
+ always successful in the service environment. The delay between the
+ service invocation and the actual service delivery to the end user
+ can be sufficiently long that the use of the session-based credit-
+ control would lead to unreasonably long credit-control sessions. In
+ these cases, the Diameter credit-control client can use the one-time
+ event scenario for direct debiting. The Diameter credit-control
+ client SHOULD be sure that the requested service event execution
+ would be successful when this scenario is used.
+
+ In the Credit-Control-Request message, the CC-Request-Type is set to
+ the value EVENT_REQUEST and the Requested-Action AVP is set to
+ DIRECT_DEBITING. The Subscription-Id AVP SHOULD be included to
+ identify the end user in the credit-control server. The Event-
+ Timestamp AVP SHOULD be included in the request and contain the time
+ when the service event is requested in the service element. The
+ Service-Context-Id AVP indicates the service specific document
+ applicable to the request.
+
+ The Diameter credit-control client MAY include the monetary amount to
+ be charged in the Requested-Service-Unit AVP, if it knows the cost of
+ the service event. If the Diameter credit-control client does not
+ know the cost of the service event, the Requested-Service-Unit AVP
+ MAY contain the number of requested service events. The Service-
+ Identifier AVP always indicates the service concerned. Additional
+ service event information to be rated MAY be sent as service specific
+ AVPs or within the Service-Parameter-Info AVP.
+
+ The credit-control server SHOULD rate the service event and deduct
+ the corresponding monetary amount from the end user's account. If
+ the type of the Requested-Service-Unit AVP is money, no rating is
+ needed, but the corresponding monetary amount is deducted from the
+ end user's account.
+
+ The credit-control server returns the Granted-Service-Unit AVP in the
+ Credit-Control-Answer message to the Diameter credit-control client.
+ The Granted-Service-Unit AVP contains the amount of service units
+ that the Diameter credit-control client can provide to the end user.
+ The type of the Granted-Service-Unit can be time, volume, service
+ specific, or money, depending on the type of service event.
+
+ If the credit-control server determines that no credit-control is
+ needed for the service, it can include the result code indicating
+ that the credit-control is not applicable (e.g., service is free of
+ charge).
+
+
+
+
+Hakala, et al. Standards Track [Page 43]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ For informative purposes, the Credit-Control-Answer message MAY also
+ include the Cost-Information AVP containing the estimated total cost
+ of the requested service.
+
+6.4. Refund
+
+ Some services may refund service units to the end user's account; for
+ example, gaming services.
+
+ The credit-control client MUST set CC-Request-Type to the value
+ EVENT_REQUEST and the Requested-Action AVP to REFUND_ACCOUNT in the
+ Credit-Control-Request message. The Subscription-Id AVP SHOULD be
+ included to identify the end user in the credit-control server. The
+ Service-Context-Id AVP indicates the service specific document
+ applicable to the request.
+
+ The Diameter credit-control client MAY include the monetary amount to
+ be refunded in the Requested-Service-Unit AVP. The Service-
+ Identifier AVP always indicates the concerned service. If the
+ Diameter credit-control client does not know the monetary amount to
+ be refunded, in addition to the Service-Identifier AVP it MAY send
+ service specific AVPs or the Service-Parameter-Info AVP containing
+ additional service event information to be rated.
+
+ For informative purposes, the Credit-Control-Answer message MAY also
+ include the Cost-Information AVP containing the estimated monetary
+ amount of refunded unit.
+
+6.5. Failure Procedure
+
+ Failover to an alternative credit-control server is allowed for a one
+ time event, as the server is not maintaining session states. For
+ instance, if the credit-control client receives a protocol error
+ DIAMETER_UNABLE_TO_DELIVER or DIAMETER_TOO_BUSY, it can re-send the
+ request to an alternative server, if possible. There MAY be protocol
+ transparent Diameter relays and redirect agents or Diameter credit-
+ control proxies between the credit-control client and credit-control
+ server. Failover may occur at any point in the path between the
+ credit-control client and the credit-control server if a transport
+ failure is detected with a peer, as described in [DIAMBASE]. Because
+ there can be duplicate requests for various reasons, the credit-
+ control server is responsible for real time duplicate detection.
+ Implementation issues for duplicate detection are discussed in
+ [DIAMBASE], Appendix C.
+
+ When the credit-control client detects a communication failure with
+ the credit-control server, its behavior depends on the requested
+ action. The timer Tx (as defined in section 13) is used in the
+
+
+
+Hakala, et al. Standards Track [Page 44]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ credit-control client to supervise the communication with the
+ credit-control server.
+
+ If the requested action is PRICE_ENQUIRY or CHECK_BALANCE and
+ communication failure is detected, the credit-control client SHOULD
+ forward the request messages to an alternative credit-control server,
+ if possible. The secondary credit-control server name, if received
+ from the home Diameter AAA server, can be used as an address of
+ backup server.
+
+ If the requested action is DIRECT_DEBITING, the Direct-Debiting-
+ Failure-Handling AVP (DDFH) controls the credit-control client's
+ behavior. The DDFH may be received from the home Diameter AAA server
+ or may be locally configured. The credit-control server may also
+ send the DDFH in any CCA message to be used for direct debiting
+ events compiled thereafter. The DDFH value received from the home
+ Diameter AAA server overrides the locally configured value, and the
+ DDFH value received from the credit-control server in a Credit-
+ Control-Answer message always overrides any existing value.
+
+ If the DDFH is set to TERMINATE_OR_BUFFER, the credit-control client
+ SHOULD NOT grant the service if it can determine, eventually after a
+ possible re-transmission attempt to an alternative credit-control
+ server, from the result code or error code in the answer message that
+ units have not been debited. Otherwise, the credit-control client
+ SHOULD grant the service to the end user and store the request in the
+ credit-control application level non-volatile storage. (Note that
+ re-sending the request at a later time is not a guarantee that the
+ service will be debited, as the user's account may be empty when the
+ server successfully processes the request.) The credit-control
+ client MUST mark these request messages as possible duplicates by
+ setting the T-flag in the command header as described in [DIAMBASE],
+ section 3.
+
+ If the Direct-Debiting-Failure-Handling AVP is set to CONTINUE, the
+ service SHOULD be granted, even if credit-control messages cannot be
+ delivered and messages are not buffered.
+
+ If the timer Tx expires, the credit-control client MUST continue the
+ service and wait for a possible late answer. If the request times
+ out, the credit-control client re-transmits the request (marked with
+ T-flag) to a backup credit-control server, if possible. If the re-
+ transmitted request also times out, or if a temporary error is
+ received in answer, the credit-control client buffers the request if
+ the value of the Direct-Debiting-Failure-Handling AVP is set to
+ TERMINATE_OR_BUFFER. If a failed answer is received for the
+
+
+
+
+
+Hakala, et al. Standards Track [Page 45]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ re-transmitted request, the credit-control client frees all the
+ resources reserved for the event message and deletes the request
+ regardless of the value of the DDFH.
+
+ The Credit-Control-Request with the requested action REFUND_ACCOUNT
+ should always be stored in the credit-control application level non-
+ volatile storage in case of temporary failure. The credit-control
+ client MUST mark the re-transmitted request message as a possible
+ duplicate by setting the T-flag in the command header as described in
+ [DIAMBASE], section 3.
+
+ For stored requests, the implementation may choose to limit the
+ number of re-transmission attempts and to define a re-transmission
+ interval.
+
+ Note that only one place in the credit-control system SHOULD be
+ responsible for duplicate detection. If there is only one credit-
+ control server within the given realm, the credit-control server may
+ perform duplicate detection. If there is more than one credit-
+ control server in a given realm, only one entity in the credit-
+ control system should be responsible, to ensure that the end user's
+ account is not debited or credited multiple times for the same
+ service event.
+
+7. Credit-Control Application State Machine
+
+ This section defines the credit-control application state machine.
+
+ The first four state machines are to be observed by credit-control
+ clients. The first one describes the session-based credit-control
+ when the first interrogation is executed as part of the
+ authorization/authentication process. The second describes the
+ session-based credit-control when the first interrogation is executed
+ after the authorization/authentication process. The requirements as
+ to what state machines have to be supported are discussed in section
+ 5.2.
+
+ The third state machine describes the session-based credit-control
+ for the intermediate and final interrogations. The fourth one
+ describes the event-based credit-control. These latter state
+ machines are to be observed by all implementations that conform to
+ this specification.
+
+ The fifth state machine describes the credit-control session from a
+ credit-control server perspective.
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 46]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Any event not listed in the state machines MUST be considered 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
+ Diameter credit-control client is unable to communicate with the
+ desired destination or, if failover procedure is supported, with a
+ possibly defined alternative destination (e.g., the request times out
+ and the answer message is not received). This could be due to the
+ peer being down, or due to a physical link failure in the path to or
+ from the credit-control server.
+
+ The event 'Temporary error' means that the Diameter credit-control
+ client received a protocol error notification (DIAMETER_TOO_BUSY,
+ DIAMETER_UNABLE_TO_DELIVER, or DIAMETER_LOOP_DETECTED) in the
+ Result-Code AVP of the Credit-Control-Answer command. The above
+ protocol error notification may ultimately be received in answer to
+ the re-transmitted request to a defined alternative destination, if
+ failover is supported.
+
+ The event 'Failed answer' means that the Diameter credit-control
+ client received non-transient failure (permanent failure)
+ notification in the Credit-Control-Answer command. The above
+ permanent failure notification may ultimately be received in answer
+ to the re-transmitted request to a defined alternative destination,
+ if failover is supported.
+
+ The action 'store request' means that a request is stored in the
+ credit-control application level non-volatile storage.
+
+ The event 'Not successfully processed' means that the credit-control
+ server could not process the message; e.g., due to an unknown end
+ user, account being empty, or errors defined in [DIAMBASE].
+
+ The event 'User service terminated' can be triggered by various
+ reasons, e.g., normal user termination, network failure, and ASR
+ (Abort-Session-Request). The Termination-Cause AVP contains
+ information about the termination reason, as specified in [DIAMBASE].
+
+ The Tx timer, which is used to control the waiting time in the
+ credit-control client in the Pending state, is stopped upon exit of
+ the Pending state. The stopping of the Tx timer is omitted in the
+ state machine when the new state is Idle, as moving to Idle state
+ implies the clearing of the session and all the variables associated
+ to it.
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 47]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The states PendingI, PendingU, PendingT, PendingE, and PendingB stand
+ for pending states to wait for an answer to a credit-control request
+ related to Initial, Update, Termination, Event, or Buffered request,
+ respectively.
+
+ The acronyms CCFH and DDFH stand for Credit-Control-Failure-Handling
+ and Direct-Debiting-Failure-Handling, respectively.
+
+ In the following state machine table, the failover to a secondary
+ server upon 'Temporary error' or 'Failure to send' is not explicitly
+ described. Moving an ongoing credit-control message stream to an
+ alternative server is, however, possible if the CC-Session-Failover
+ AVP is set to FAILOVER_SUPPORTED, as described in section 5.7.
+
+ Re-sending a credit-control event to an alternative server is
+ supported as described in section 6.5.
+
+ CLIENT, SESSION BASED for the first interrogation with AA request
+
+ State Event Action New State
+ ---------------------------------------------------------------
+ Idle Client or device requests Send PendingI
+ access/service AA request
+ with added
+ CC AVPs,
+ start Tx
+
+ PendingI Successful AA req. Grant Open
+ answer received service to
+ end user,
+ stop Tx
+
+ PendingI Tx expired Disconnect Idle
+ user/dev
+
+ PendingI Failed AA answer received Disconnect Idle
+ user/dev
+
+ PendingI AA answer Grant Idle
+ received with result code service
+ equal to CREDIT_CONTROL_ to end user
+ NOT_APPLICABLE
+
+ PendingI User service terminated Queue PendingI
+ termination
+ event
+
+
+
+
+
+Hakala, et al. Standards Track [Page 48]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ PendingI Change in rating condition Queue PendingI
+ changed
+ rating
+ condition
+ event
+
+ CLIENT, SESSION BASED for the first interrogation with CCR
+
+ State Event Action New State
+ ----------------------------------------------------------------
+
+
+ Idle Client or device requests Send PendingI
+ access/service CC initial
+ req.,
+ start Tx
+
+ PendingI Successful CC initial Stop Tx Open
+ answer received
+
+ PendingI Failure to send, or Grant Idle
+ temporary error and service to
+ CCFH equal to CONTINUE end user
+
+ PendingI Failure to send, or Terminate Idle
+ temporary error and end user's
+ CCFH equal to TERMINATE service
+ or to RETRY_AND_TERMINATE
+
+ PendingI Tx expired and CCFH Terminate Idle
+ equal to TERMINATE end user's
+ service
+
+ PendingI Tx expired and CCFH equal Grant PendingI
+ to CONTINUE or to service to
+ RETRY_AND_TERMINATE end user
+
+ PendingI CC initial answer Terminate Idle
+ received with result code end user's
+ END_USER_SERVICE_DENIED or service
+ USER_UNKNOWN
+
+ PendingI CC initial answer Grant Idle
+ received with result code service
+ equal to CREDIT_CONTROL_ to end user
+ NOT_APPLICABLE
+
+
+
+
+
+Hakala, et al. Standards Track [Page 49]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ PendingI Failed CC initial answer Grant Idle
+ received and CCFH equal to service to
+ CONTINUE end user
+
+ PendingI Failed CC initial answer Terminate Idle
+ received and CCFH equal end user's
+ to TERMINATE or to service
+ RETRY_AND_TERMINATE
+
+ PendingI User service terminated Queue PendingI
+ termination
+ event
+
+ PendingI Change in rating condition Queue PendingI
+ changed
+ rating
+ condition
+ event
+
+ CLIENT, SESSION BASED for intermediate and final interrogations
+
+ State Event Action New State
+ ----------------------------------------------------------------
+
+ Open Granted unit elapses Send PendingU
+ and no final unit CC update
+ indication received req.,
+ start Tx
+
+ Open Granted unit elapses Terminate PendingT
+ and final unit action end user's
+ equal to TERMINATE service, send
+ received CC termination
+ req.
+
+ Open Change in rating condition Send PendingU
+ in queue CC update
+ req.,
+ Start Tx
+
+ Open Service terminated in queue Send PendingT
+ CC termination
+ req.
+
+ Open Change in rating condition Send PendingU
+ or Validity-Time elapses CC update
+ req.,
+ Start Tx
+
+
+
+Hakala, et al. Standards Track [Page 50]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Open User service terminated Send PendingT
+ CC termination
+ req.
+
+ Open RAR received Send RAA PendingU
+ followed by
+ CC update req.,
+ start Tx
+
+ PendingU Successful CC update Stop Tx Open
+ answer received
+
+ PendingU Failure to send, or Grant Idle
+ temporary error and service to
+ CCFH equal to CONTINUE end user
+
+ PendingU Failure to send, or Terminate Idle
+ temporary error and end user's
+ CCFH equal to TERMINATE service
+ or to RETRY_AND_TERMINATE
+
+ PendingU Tx expired and CCFH Terminate Idle
+ equal to TERMINATE end user's
+ service
+
+ PendingU Tx expired and CCFH equal Grant PendingU
+ to CONTINUE or to service to
+ RETRY_AND_TERMINATE end user
+
+ PendingU CC update answer Terminate Idle
+ received with result code end user's
+ END_USER_SERVICE_DENIED service
+
+ PendingU CC update answer Grant Idle
+ received with result code service
+ equal to CREDIT_CONTROL_ to end user
+ NOT_APPLICABLE
+
+ PendingU Failed CC update Grant Idle
+ answer received and service to
+ CCFH equal to CONTINUE end user
+
+ PendingU Failed CC update Terminate Idle
+ answer received and CCFH end user's
+ equal to TERMINATE or service
+ to RETRY_AND_TERMINATE
+
+
+
+
+
+Hakala, et al. Standards Track [Page 51]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ PendingU User service terminated Queue PendingU
+ termination
+ event
+
+ PendingU Change in rating Queue PendingU
+ condition changed
+ rating
+ condition
+ event
+
+ PendingU RAR received Send RAA PendingU
+
+ PendingT Successful CC Idle
+ termination answer received
+
+ PendingT Failure to send, temporary Idle
+ error, or failed answer
+
+ PendingT Change in rating condition PendingT
+
+ CLIENT, EVENT BASED
+
+ State Event Action New State
+ ----------------------------------------------------------------
+ Idle Client or device requests Send PendingE
+ a one-time service CC event
+ req.,
+ Start Tx
+
+ Idle Request in storage Send PendingB
+ stored
+ request
+
+ PendingE Successful CC event Grant Idle
+ answer received service to
+ end user
+
+ PendingE Failure to send, temporary Indicate Idle
+ error, failed CC event service
+ answer received, or error
+ Tx expired; requested
+ action CHECK_BALANCE or
+ PRICE_ENQUIRY
+
+ PendingE CC event answer Terminate Idle
+ received with result code end user's
+ END_USER_SERVICE_DENIED or service
+ USER_UNKNOWN and Tx running
+
+
+
+Hakala, et al. Standards Track [Page 52]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ PendingE CC event answer Grant Idle
+ received with result code service
+ CREDIT_CONTROL_NOT_APPLICABLE; to end
+ requested action user
+ DIRECT_DEBITING
+
+ PendingE Failure to send, temporary Grant Idle
+ error, or failed CC event service
+ answer received; requested to end
+ action DIRECT_DEBITING; user
+ DDFH equal to CONTINUE
+
+ PendingE Failed CC event Terminate Idle
+ answer received or temporary end user's
+ error; requested action service
+ DIRECT_DEBITING;
+ DDFH equal to
+ TERMINATE_OR_BUFFER and
+ Tx running
+
+ PendingE Tx expired; requested Grant PendingE
+ action DIRECT_DEBITING service
+ to end
+ user
+
+ PendingE Failure to send; requested Store Idle
+ action DIRECT_DEBITING; request with
+ DDFH equal to T-flag
+ TERMINATE_OR_BUFFER
+
+ PendingE Temporary error; requested Store Idle
+ action DIRECT_DEBITING; request
+ DDFH equal to
+ TERMINATE_OR_BUFFER;
+ Tx expired
+
+ PendingE Failed answer or answer Idle
+ received with result code
+ END_USER_SERVICE DENIED or
+ USER_UNKNOWN; requested action
+ DIRECT_DEBITING; Tx expired
+
+ PendingE Failed CC event answer Indicate Idle
+ received; requested service
+ action REFUND_ACCOUNT error and
+ delete request
+
+
+
+
+
+Hakala, et al. Standards Track [Page 53]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ PendingE Failure to send or Store Idle
+ Tx expired; requested request
+ action REFUND_ACCOUNT with T-flag
+
+ PendingE Temporary error, Store Idle
+ and requested action request
+ REFUND_ACCOUNT
+
+ PendingB Successful CC answer Delete Idle
+ received request
+
+ PendingB Failed CC answer Delete Idle
+ received request
+
+ PendingB Failure to send or Idle
+ temporary error
+
+ SERVER, SESSION AND EVENT BASED
+
+ State Event Action New State
+ ----------------------------------------------------------------
+
+ Idle CC initial request Send Open
+ received and successfully CC initial
+ processed answer,
+ reserve units,
+ start Tcc
+
+ Idle CC initial request Send Idle
+ received but not CC initial
+ successfully processed answer with
+ Result-Code
+ != SUCCESS
+
+ Idle CC event request Send Idle
+ received and successfully CC event
+ processed answer
+
+ Idle CC event request Send Idle
+ received but not CC event
+ successfully processed answer with
+ Result-Code
+ != SUCCESS
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 54]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Open CC update request Send CC Open
+ received and successfully update answer,
+ processed debit used
+ units,
+ reserve
+ new units,
+ restart Tcc
+
+ Open CC update request Send Idle
+ received but not CC update
+ successfully processed answer with
+ Result-Code
+ != SUCCESS,
+ debit used
+ units
+
+ Open CC termination request Send Idle
+ received and successfully CC termin.
+ processed answer,
+ Stop Tcc,
+ debit used
+ units
+
+ Open CC termination request Send Idle
+ received but not CC termin.
+ successfully processed answer with
+ Result-Code
+ != SUCCESS,
+ debit used
+ units
+
+ Open Session supervision timer Tcc Release Idle
+ expired reserved
+ units
+
+8. Credit-Control AVPs
+
+ This section defines the credit-control AVPs that are specific to
+ Diameter credit-control application and that MAY be included in the
+ Diameter credit-control messages.
+
+ The AVPs defined in this section MAY also be included in
+ authorization commands defined in authorization-specific
+ applications, such as [NASREQ] and [DIAMMIP], if the first
+ interrogation is performed as part of the
+ authorization/authentication process, as described in section 5.2.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 55]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The Diameter AVP rules are defined in the Diameter Base [DIAMBASE],
+ section 4. These AVP rules are observed in AVPs defined in this
+ section.
+
+ The following table describes the Diameter AVPs defined in the
+ credit-control application, their AVP Code values, types, possible
+ flag values, and whether the AVP MAY be encrypted. The Diameter base
+ [DIAMBASE] specifies the AVP Flag rules for AVPs in section 4.5.
+
+ +--------------------+
+ | AVP Flag rules |
+ |----+-----+----+----|----+
+ AVP Section | | |SHLD|MUST| |
+ Attribute Name Code Defined Data Type |MUST| MAY | NOT|NOT |Encr|
+ -----------------------------------------|----+-----+----+----|----|
+ CC-Correlation-Id 411 8.1 OctetString| | P,M | | V | Y |
+ CC-Input-Octets 412 8.24 Unsigned64 | M | P | | V | Y |
+ CC-Money 413 8.22 Grouped | M | P | | V | Y |
+ CC-Output-Octets 414 8.25 Unsigned64 | M | P | | V | Y |
+ CC-Request-Number 415 8.2 Unsigned32 | M | P | | V | Y |
+ CC-Request-Type 416 8.3 Enumerated | M | P | | V | Y |
+ CC-Service- 417 8.26 Unsigned64 | M | P | | V | Y |
+ Specific-Units | | | | | |
+ CC-Session- 418 8.4 Enumerated | M | P | | V | Y |
+ Failover | | | | | |
+ CC-Sub-Session-Id 419 8.5 Unsigned64 | M | P | | V | Y |
+ CC-Time 420 8.21 Unsigned32 | M | P | | V | Y |
+ CC-Total-Octets 421 8.23 Unsigned64 | M | P | | V | Y |
+ CC-Unit-Type 454 8.32 Enumerated | M | P | | V | Y |
+ Check-Balance- 422 8.6 Enumerated | M | P | | V | Y |
+ Result | | | | | |
+ Cost-Information 423 8.7 Grouped | M | P | | V | Y |
+ Cost-Unit 424 8.12 UTF8String | M | P | | V | Y |
+ Credit-Control 426 8.13 Enumerated | M | P | | V | Y |
+ Credit-Control- 427 8.14 Enumerated | M | P | | V | Y |
+ Failure-Handling | | | | | |
+ Currency-Code 425 8.11 Unsigned32 | M | P | | V | Y |
+ Direct-Debiting- 428 8.15 Enumerated | M | P | | V | Y |
+ Failure-Handling | | | | | |
+ Exponent 429 8.9 Integer32 | M | P | | V | Y |
+ Final-Unit-Action 449 8.35 Enumerated | M | P | | V | Y |
+ Final-Unit- 430 8.34 Grouped | M | P | | V | Y |
+ Indication | | | | | |
+ Granted-Service- 431 8.17 Grouped | M | P | | V | Y |
+ Unit | | | | | |
+ G-S-U-Pool- 453 8.31 Unsigned32 | M | P | | V | Y |
+ Identifier | | | | | |
+
+
+
+
+Hakala, et al. Standards Track [Page 56]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ G-S-U-Pool- 457 8.30 Grouped | M | P | | V | Y |
+ Reference | | | | | |
+ Multiple-Services 456 8.16 Grouped | M | P | | V | Y |
+ -Credit-Control | | | | | |
+ Multiple-Services 455 8.40 Enumerated | M | P | | V | Y |
+ -Indicator | | | | | |
+ Rating-Group 432 8.29 Unsigned32 | M | P | | V | Y |
+ Redirect-Address 433 8.38 Enumerated | M | P | | V | Y |
+ -Type | | | | | |
+ Redirect-Server 434 8.37 Grouped | M | P | | V | Y |
+ Redirect-Server 435 8.39 UTF8String | M | P | | V | Y |
+ -Address | | | | | |
+ Requested-Action 436 8.41 Enumerated | M | P | | V | Y |
+ Requested-Service 437 8.18 Grouped | M | P | | V | Y |
+ -Unit | | | | | |
+ Restriction 438 8.36 IPFiltrRule| M | P | | V | Y |
+ -Filter-Rule | | | | | |
+ Service-Context 461 8.42 UTF8String | M | P | | V | Y |
+ -Id | | | | | |
+ Service- 439 8.28 Unsigned32 | M | P | | V | Y |
+ Identifier | | | | | |
+ Service-Parameter 440 8.43 Grouped | | P,M | | V | Y |
+ -Info | | | | | |
+ Service- 441 8.44 Unsigned32 | | P,M | | V | Y |
+ Parameter-Type | | | | | |
+ Service- 442 8.45 OctetString| | P,M | | V | Y |
+ Parameter-Value | | | | | |
+ Subscription-Id 443 8.46 Grouped | M | P | | V | Y |
+ Subscription-Id 444 8.48 UTF8String | M | P | | V | Y |
+ -Data | | | | | |
+ Subscription-Id 450 8.47 Enumerated | M | P | | V | Y |
+ -Type | | | | | |
+ Tariff-Change 452 8.27 Enumerated | M | P | | V | Y |
+ -Usage | | | | | |
+ Tariff-Time 451 8.20 Time | M | P | | V | Y |
+ -Change | | | | | |
+ Unit-Value 445 8.8 Grouped | M | P | | V | Y |
+ Used-Service-Unit 446 8.19 Grouped | M | P | | V | Y |
+ User-Equipment 458 8.49 Grouped | | P,M | | V | Y |
+ -Info | | | | | |
+ User-Equipment 459 8.50 Enumerated | | P,M | | V | Y |
+ -Info-Type | | | | | |
+ User-Equipment 460 8.51 OctetString| | P,M | | V | Y |
+ -Info-Value | | | | | |
+ Value-Digits 447 8.10 Integer64 | M | P | | V | Y |
+ Validity-Time 448 8.33 Unsigned32 | M | P | | V | Y |
+
+
+
+
+
+Hakala, et al. Standards Track [Page 57]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+8.1. CC-Correlation-Id AVP
+
+ The CC-Correlation-Id AVP (AVP Code 411) is of type OctetString and
+ contains information to correlate credit-control requests generated
+ for different components of the service; e.g., transport and service
+ level. The one who allocates the Service-Context-Id (i.e., unique
+ identifier of a service specific document) is also responsible for
+ defining the content and encoding of the CC-Correlation-Id AVP.
+
+8.2. CC-Request-Number AVP
+
+ The CC-Request-Number AVP (AVP Code 415) is of type Unsigned32 and
+ identifies this request within one session. As Session-Id AVPs are
+ globally unique, the combination of Session-Id and CC-Request-Number
+ AVPs is also globally unique and can be used in matching credit-
+ control messages with confirmations. An easy way to produce unique
+ numbers is to set the value to 0 for a credit-control request of type
+ INITIAL_REQUEST and EVENT_REQUEST and to set the value to 1 for the
+ first UPDATE_REQUEST, to 2 for the second, and so on until the value
+ for TERMINATION_REQUEST is one more than for the last UPDATE_REQUEST.
+
+8.3. CC-Request-Type AVP
+
+ The CC-Request-Type AVP (AVP Code 416) is of type Enumerated and
+ contains the reason for sending the credit-control request message.
+ It MUST be present in all Credit-Control-Request messages. The
+ following values are defined for the CC-Request-Type AVP:
+
+ INITIAL_REQUEST 1
+ An Initial request is used to initiate a credit-control session,
+ and contains credit control information that is relevant to the
+ initiation.
+
+ UPDATE_REQUEST 2
+ An Update request contains credit-control information for an
+ existing credit-control session. Update credit-control requests
+ SHOULD be sent every time a credit-control re-authorization is
+ needed at the expiry of the allocated quota or validity time.
+ Further, additional service-specific events MAY trigger a
+ spontaneous Update request.
+
+ TERMINATION_REQUEST 3
+ A Termination request is sent to terminate a credit-control
+ session and contains credit-control information relevant to the
+ existing session.
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 58]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ EVENT_REQUEST 4
+ An Event request is used when there is no need to maintain any
+ credit-control session state in the credit-control server. This
+ request contains all information relevant to the service, and is
+ the only request of the service. The reason for the Event request
+ is further detailed in the Requested-Action AVP. The Requested-
+ Action AVP MUST be included in the Credit-Control-Request message
+ when CC-Request-Type is set to EVENT_REQUEST.
+
+8.4. CC-Session-Failover AVP
+
+ The CC-Session-Failover AVP (AVP Code 418) is type of Enumerated and
+ contains information as to whether moving the credit-control message
+ stream to a backup server during an ongoing credit-control session is
+ supported. In communication failures, the credit-control message
+ streams can be moved to an alternative destination if the credit-
+ control server supports failover to an alternative server. The
+ secondary credit-control server name, if received from the home
+ Diameter AAA server, can be used as an address of the backup server.
+ An implementation is not required to support moving a credit-control
+ message stream to an alternative server, as this also requires moving
+ information related to the credit-control session to backup server.
+
+ The following values are defined for the CC-Session-Failover AVP:
+
+ FAILOVER_NOT_SUPPORTED 0
+ When the CC-Session-Failover AVP is set to FAILOVER_NOT_SUPPORTED,
+ the credit-control message stream MUST NOT to be moved to an
+ alternative destination in the case of communication failure.
+
+ This is the default behavior if the AVP isn't included in the
+ reply from the authorization or credit-control server.
+
+ FAILOVER_SUPPORTED 1
+ When the CC-Session-Failover AVP is set to FAILOVER_SUPPORTED, the
+ credit-control message stream SHOULD be moved to an alternative
+ destination in the case of communication failure. Moving the
+ credit-control message stream to a backup server MAY require that
+ information related to the credit-control session should also be
+ forwarded to alternative server.
+
+8.5. CC-Sub-Session-Id AVP
+
+ The CC-Sub-Session-Id AVP (AVP Code 419) is of type Unsigned64 and
+ contains the credit-control sub-session identifier. The combination
+ of the Session-Id and this AVP MUST be unique per sub-session, and
+
+
+
+
+
+Hakala, et al. Standards Track [Page 59]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ the value of this AVP MUST be monotonically increased by one for all
+ new sub-sessions. The absence of this AVP implies that no sub-
+ sessions are in use.
+
+8.6. Check-Balance-Result AVP
+
+ The Check Balance Result AVP (AVP Code 422) is of type Enumerated and
+ contains the result of the balance check. This AVP is applicable
+ only when the Requested-Action AVP indicates CHECK_BALANCE in the
+ Credit-Control-Request command.
+
+ The following values are defined for the Check-Balance-Result AVP.
+
+ ENOUGH_CREDIT 0
+ There is enough credit in the account to cover the requested
+ service.
+
+ NO_CREDIT 1
+ There isn't enough credit in the account to cover the requested
+ service.
+
+8.7. Cost-Information AVP
+
+ The Cost-Information AVP (AVP Code 423) is of type Grouped, and it is
+ used to return the cost information of a service, which the credit-
+ control client can transfer transparently to the end user. The
+ included Unit-Value AVP contains the cost estimate (always type of
+ money) of the service, in the case of price enquiry, or the
+ accumulated cost estimation, in the case of credit-control session.
+
+ The Currency-Code specifies in which currency the cost was given.
+ The Cost-Unit specifies the unit when the service cost is a cost per
+ unit (e.g., cost for the service is $1 per minute).
+
+ When the Requested-Action AVP with value PRICE_ENQUIRY is included in
+ the Credit-Control-Request command, the Cost-Information AVP sent in
+ the succeeding Credit-Control-Answer command contains the cost
+ estimation of the requested service, without any reservation being
+ made.
+
+ The Cost-Information AVP included in the Credit-Control-Answer
+ command with the CC-Request-Type set to UPDATE_REQUEST contains the
+ accumulated cost estimation for the session, without taking any
+ credit reservation into account.
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 60]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The Cost-Information AVP included in the Credit-Control-Answer
+ command with the CC-Request-Type set to EVENT_REQUEST or
+ TERMINATION_REQUEST contains the estimated total cost for the
+ requested service.
+
+ It is defined as follows (per the grouped-avp-def of
+ RFC 3588 [DIAMBASE]):
+
+ Cost-Information ::= < AVP Header: 423 >
+ { Unit-Value }
+ { Currency-Code }
+ [ Cost-Unit ]
+
+8.8. Unit-Value AVP
+
+ Unit-Value AVP is of type Grouped (AVP Code 445) and specifies the
+ units as decimal value. The Unit-Value is a value with an exponent;
+ i.e., Unit-Value = Value-Digits AVP * 10^Exponent. This
+ representation avoids unwanted rounding off. For example, the value
+ of 2,3 is represented as Value-Digits = 23 and Exponent = -1. The
+ absence of the exponent part MUST be interpreted as an exponent equal
+ to zero.
+
+ It is defined as follows (per the grouped-avp-def of
+ RFC 3588 [DIAMBASE]):
+
+ Unit-Value ::= < AVP Header: 445 >
+ { Value-Digits }
+ [ Exponent ]
+
+8.9. Exponent AVP
+
+ Exponent AVP is of type Integer32 (AVP Code 429) and contains the
+ exponent value to be applied for the Value-Digit AVP within the
+ Unit-Value AVP.
+
+8.10. Value-Digits AVP
+
+ The Value-Digits AVP is of type Integer64 (AVP Code 447) and contains
+ the significant digits of the number. If decimal values are needed
+ to present the units, the scaling MUST be indicated with the related
+ Exponent AVP. For example, for the monetary amount $ 0.05 the value
+ of Value-Digits AVP MUST be set to 5, and the scaling MUST be
+ indicated with the Exponent AVP set to -2.
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 61]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+8.11. Currency-Code AVP
+
+ The Currency-Code AVP (AVP Code 425) is of type Unsigned32 and
+ contains a currency code that specifies in which currency the values
+ of AVPs containing monetary units were given. It is specified by
+ using the numeric values defined in the ISO 4217 standard [ISO4217].
+
+8.12. Cost-Unit AVP
+
+ The Cost-Unit AVP (AVP Code 424) is of type UTF8String, and it is
+ used to display a human readable string to the end user. It
+ specifies the applicable unit to the Cost-Information when the
+ service cost is a cost per unit (e.g., cost of the service is $1 per
+ minute). The Cost-Unit can be minutes, hours, days, kilobytes,
+ megabytes, etc.
+
+8.13. Credit-Control AVP
+
+ The Credit-Control AVP (AVP Code 426) is of type Enumerated and MUST
+ be included in AA requests when the service element has credit-
+ control capabilities.
+
+ CREDIT_AUTHORIZATION 0
+ If the home Diameter AAA server determines that the user has
+ prepaid subscription, this value indicates that the credit-control
+ server MUST be contacted to perform the first interrogation. The
+ value of the Credit-Control AVP MUST always be set to 0 in an AA
+ request sent to perform the first interrogation and to initiate a
+ new credit-control session.
+
+ RE_AUTHORIZATION 1
+ This value indicates to the Diameter AAA server that a credit-
+ control session is ongoing for the subscriber and that the
+ credit-control server MUST not be contacted. The Credit-Control
+ AVP set to the value of 1 is to be used only when the first
+ interrogation has been successfully performed and the credit-
+ control session is ongoing (i.e., re-authorization triggered by
+ Authorization-Lifetime). This value MUST NOT be used in an AA
+ request sent to perform the first interrogation.
+
+8.14. Credit-Control-Failure-Handling AVP
+
+ The Credit-Control-Failure-Handling AVP (AVP Code 427) is of type
+ Enumerated. The credit-control client uses information in this AVP
+ to decide what to do if sending credit-control messages to the
+ credit-control server has been, for instance, temporarily prevented
+ due to a network problem. Depending on the service logic, the
+ credit-control server can order the client to terminate the service
+
+
+
+Hakala, et al. Standards Track [Page 62]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ immediately when there is a reason to believe that the service cannot
+ be charged, or to try failover to an alternative server, if possible.
+ Then the server could either terminate or grant the service, should
+ the alternative connection also fail.
+
+ TERMINATE 0
+ When the Credit-Control-Failure-Handling AVP is set to TERMINATE,
+ the service MUST only be granted for as long as there is a
+ connection to the credit-control server. If the credit-control
+ client does not receive any Credit-Control-Answer message within
+ the Tx timer (as defined in section 13), the credit-control
+ request is regarded as failed, and the end user's service session
+ is terminated.
+
+ This is the default behavior if the AVP isn't included in the
+ reply from the authorization or credit-control server.
+
+ CONTINUE 1
+ When the Credit-Control-Failure-Handling AVP is set to CONTINUE,
+ the credit-control client SHOULD re-send the request to an
+ alternative server in the case of transport or temporary failures,
+ provided that a failover procedure is supported in the credit-
+ control server and the credit-control client, and that an
+ alternative server is available. Otherwise, the service SHOULD be
+ granted, even if credit-control messages can't be delivered.
+
+ RETRY_AND_TERMINATE 2
+ When the Credit-Control-Failure-Handling AVP is set to
+ RETRY_AND_TERMINATE, the credit-control client SHOULD re-send the
+ request to an alternative server in the case of transport or
+ temporary failures, provided that a failover procedure is
+ supported in the credit-control server and the credit-control
+ client, and that an alternative server is available. Otherwise,
+ the service SHOULD not be granted when the credit-control messages
+ can't be delivered.
+
+8.15. Direct-Debiting-Failure-Handling AVP
+
+ The Direct-Debiting-Failure-Handling AVP (AVP Code 428) is of type
+ Enumerated. The credit-control client uses information in this AVP
+ to decide what to do if sending credit-control messages (Requested-
+ Action AVP set to DIRECT_DEBITING) to the credit-control server has
+ been, for instance, temporarily prevented due to a network problem.
+
+ TERMINATE_OR_BUFFER 0
+ When the Direct-Debiting-Failure-Handling AVP is set to
+ TERMINATE_OR_BUFFER, the service MUST be granted for as long as
+ there is a connection to the credit-control server. If the
+
+
+
+Hakala, et al. Standards Track [Page 63]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ credit-control client does not receive any Credit-Control-Answer
+ message within the Tx timer (as defined in section 13) the
+ credit-control request is regarded as failed. The client SHOULD
+ terminate the service if it can determine from the failed answer
+ that units have not been debited. Otherwise the credit-control
+ client SHOULD grant the service, store the request in application
+ level non-volatile storage, and try to re-send the request. These
+ requests MUST be marked as possible duplicates by setting the T-
+ flag in the command header as described in [DIAMBASE] section 3.
+
+ This is the default behavior if the AVP isn't included in the
+ reply from the authorization server.
+
+ CONTINUE 1
+ When the Direct-Debiting-Failure-Handling AVP is set to CONTINUE,
+ the service SHOULD be granted, even if credit-control messages
+ can't be delivered, and the request should be deleted.
+
+8.16. Multiple-Services-Credit-Control AVP
+
+ Multiple-Services-Credit-Control AVP (AVP Code 456) is of type
+ Grouped and contains the AVPs related to the independent credit-
+ control of multiple services feature. Note that each instance of
+ this AVP carries units related to one or more services or related to
+ a single rating group.
+
+ The Service-Identifier and the Rating-Group AVPs are used to
+ associate the granted units to a given service or rating group. If
+ both the Service-Identifier and the Rating-Group AVPs are included,
+ the target of the service units is always the service(s) indicated by
+ the value of the Service-Identifier AVP(s). If only the Rating-
+ Group-Id AVP is present, the Multiple-Services-Credit-Control AVP
+ relates to all the services that belong to the specified rating
+ group.
+
+ The G-S-U-Pool-Reference AVP allows the server to specify a G-S-U-
+ Pool-Identifier identifying a credit pool within which the units of
+ the specified type are considered pooled. If a G-S-U-Pool-Reference
+ AVP is present, then actual service units of the specified type MUST
+ also be present. For example, if the G-S-U-Pool-Reference AVP
+ specifies Unit-Type TIME, then the CC-Time AVP MUST be present.
+
+ The Requested-Service-Unit AVP MAY contain the amount of requested
+ service units or the requested monetary value. It MUST be present in
+ the initial interrogation and within the intermediate interrogations
+ in which new quota is requested. If the credit-control client does
+ not include the Requested-Service-Unit AVP in a request command,
+ because for instance, it has determined that the end-user terminated
+
+
+
+Hakala, et al. Standards Track [Page 64]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ the service, the server MUST debit the used amount from the user's
+ account but MUST NOT return a new quota in the corresponding answer.
+ The Validity-Time, Result-Code, and Final-Unit-Indication AVPs MAY be
+ present in an answer command as defined in sections 5.1.2 and 5.6 for
+ the graceful service termination.
+
+ When both the Tariff-Time-Change and Tariff-Change-Usage AVPs are
+ present, the server MUST include two separate instances of the
+ Multiple-Services-Credit-Control AVP with the Granted-Service-Unit
+ AVP associated to the same service-identifier and/or rating-group.
+ Where the two quotas are associated to the same pool or to different
+ pools, the credit pooling mechanism defined in section 5.1.2 applies.
+ The Tariff-Change-Usage AVP MUST NOT be included in request commands
+ to report used units before, and after tariff time change the Used-
+ Service-Unit AVP MUST be used.
+
+ A server not implementing the independent credit-control of multiple
+ services functionality MUST treat the Multiple-Services-Credit-
+ Control AVP as an invalid AVP.
+
+ The Multiple-Services-Control AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [DIAMBASE]):
+
+ 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 ]
+
+8.17. Granted-Service-Unit AVP
+
+ Granted-Service-Unit AVP (AVP Code 431) is of type Grouped and
+ contains the amount of units that the Diameter credit-control client
+ can provide to the end user until the service must be released or the
+ new Credit-Control-Request must be sent. A client is not required to
+ implement all the unit types, and it must treat unknown or
+ unsupported unit types in the answer message as an incorrect CCA
+ answer. In this case, the client MUST terminate the credit-control
+ session and indicate in the Termination-Cause AVP reason
+ DIAMETER_BAD_ANSWER.
+
+
+
+
+Hakala, et al. Standards Track [Page 65]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The Granted-Service-Unit AVP is defined as follows (per the grouped-
+ avp-def of RFC 3588 [DIAMBASE]):
+
+ 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 ]
+
+8.18. Requested-Service-Unit AVP
+
+ The Requested-Service-Unit AVP (AVP Code 437) is of type Grouped and
+ contains the amount of requested units specified by the Diameter
+ credit-control client. A server is not required to implement all the
+ unit types, and it must treat unknown or unsupported unit types as
+ invalid AVPs.
+
+ The Requested-Service-Unit AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [DIAMBASE]):
+
+ Requested-Service-Unit ::= < AVP Header: 437 >
+ [ CC-Time ]
+ [ CC-Money ]
+ [ CC-Total-Octets ]
+ [ CC-Input-Octets ]
+ [ CC-Output-Octets ]
+ [ CC-Service-Specific-Units ]
+ *[ AVP ]
+
+8.19. Used-Service-Unit AVP
+
+ The Used-Service-Unit AVP is of type Grouped (AVP Code 446) and
+ contains the amount of used units measured from the point when the
+ service became active or, if interim interrogations are used during
+ the session, from the point when the previous measurement ended.
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 66]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The Used-Service-Unit AVP is defined as follows (per the grouped-
+ avp-def of RFC 3588 [DIAMBASE]):
+
+ 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 ]
+
+8.20. Tariff-Time-Change AVP
+
+ The Tariff-Time-Change AVP (AVP Code 451) is of type Time. It is
+ sent from the server to the client and includes the time in seconds
+ since January 1, 1900, 00:00 UTC, when the tariff of the service will
+ be changed.
+
+ The tariff change mechanism is optional for the client and server,
+ and it is not used for time-based services defined in section 5. If
+ a client does not support the tariff time change mechanism, it MUST
+ treat Tariff-Time-Change AVP in the answer message as an incorrect
+ CCA answer. In this case, the client terminates the credit-control
+ session and indicates in the Termination-Cause AVP reason
+ DIAMETER_BAD_ANSWER.
+
+ Omission of this AVP means that no tariff change is to be reported.
+
+8.21. CC-Time AVP
+
+ The CC-Time AVP (AVP Code 420) is of type Unsigned32 and indicates
+ the length of the requested, granted, or used time in seconds.
+
+8.22. CC-Money AVP
+
+ The CC-Money AVP (AVP Code 413) is of type Grouped and specifies the
+ monetary amount in the given currency. The Currency-Code AVP SHOULD
+ be included. It is defined as follows (per the grouped-avp-def of
+ RFC 3588 [DIAMBASE]):
+
+ CC-Money ::= < AVP Header: 413 >
+ { Unit-Value }
+ [ Currency-Code ]
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 67]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+8.23. CC-Total-Octets AVP
+
+ The CC-Total-Octets AVP (AVP Code 421) is of type Unsigned64 and
+ contains the total number of requested, granted, or used octets
+ regardless of the direction (sent or received).
+
+8.24. CC-Input-Octets AVP
+
+ The CC-Input-Octets AVP (AVP Code 412) is of type Unsigned64 and
+ contains the number of requested, granted, or used octets that can
+ be/have been received from the end user.
+
+8.25. CC-Output-Octets AVP
+
+ The CC-Output-Octets AVP (AVP Code 414) is of type Unsigned64 and
+ contains the number of requested, granted, or used octets that can
+ be/have been sent to the end user.
+
+8.26. CC-Service-Specific-Units AVP
+
+ The CC-Service-Specific-Units AVP (AVP Code 417) is of type
+ Unsigned64 and specifies the number of service-specific units (e.g.,
+ number of events, points) given in a selected service. The service-
+ specific units always refer to the service identified in the
+ Service-Identifier AVP (or Rating-Group AVP when the Multiple-
+ Services-Credit-Control AVP is used).
+
+8.27. Tariff-Change-Usage AVP
+
+ The Tariff-Change-Usage AVP (AVP Code 452) is of type Enumerated and
+ defines whether units are used before or after a tariff change, or
+ whether the units straddled a tariff change during the reporting
+ period. Omission of this AVP means that no tariff change has
+ occurred.
+
+ In addition, when present in answer messages as part of the
+ Multiple-Services-Credit-Control AVP, this AVP defines whether units
+ are allocated to be used before or after a tariff change event.
+
+ When the Tariff-Time-Change AVP is present, omission of this AVP in
+ answer messages means that the single quota mechanism applies.
+
+ Tariff-Change-Usage can be one of the following:
+
+ UNIT_BEFORE_TARIFF_CHANGE 0
+ When present in the Multiple-Services-Credit-Control AVP, this
+ value indicates the amount of the units allocated for use before a
+ tariff change occurs.
+
+
+
+Hakala, et al. Standards Track [Page 68]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ When present in the Used-Service-Unit AVP, this value indicates
+ the amount of resource units used before a tariff change had
+ occurred.
+
+ UNIT_AFTER_TARIFF_CHANGE 1
+ When present in the Multiple-Services-Credit-Control AVP, this
+ value indicates the amount of the units allocated for use after a
+ tariff change occurs.
+
+ When present in the Used-Service-Unit AVP, this value indicates
+ the amount of resource units used after tariff change had
+ occurred.
+
+ UNIT_INDETERMINATE 2
+ The used unit contains the amount of units that straddle the
+ tariff change (e.g., the metering process reports to the credit-
+ control client in blocks of n octets, and one block straddled the
+ tariff change). This value is to be used only in the Used-
+ Service-Unit AVP.
+
+8.28. Service-Identifier AVP
+
+ The Service-Identifier AVP is of type Unsigned32 (AVP Code 439) and
+ contains the identifier of a service. The specific service the
+ request relates to is uniquely identified by the combination of
+ Service-Context-Id and Service-Identifier AVPs.
+
+ A usage example of this AVP is illustrated in Appendix A (Flow IX).
+
+8.29. Rating-Group AVP
+
+ The Rating-Group AVP is of type Unsigned32 (AVP Code 432) and
+ contains the identifier of a rating group. All the services subject
+ to the same rating type are part of the same rating group. The
+ specific rating group the request relates to is uniquely identified
+ by the combination of Service-Context-Id and Rating-Group AVPs.
+
+ A usage example of this AVP is illustrated in Appendix A (Flow IX).
+
+8.30. G-S-U-Pool-Reference AVP
+
+ The G-S-U-Pool-Reference AVP (AVP Code 457) is of type Grouped. It
+ is used in the Credit-Control-Answer message, and associates the
+ Granted-Service-Unit AVP within which it appears with a credit pool
+ within the session.
+
+ The G-S-U-Pool-Identifier AVP specifies the credit pool from which
+ credit is drawn for this unit type.
+
+
+
+Hakala, et al. Standards Track [Page 69]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The CC-Unit-Type AVP specifies the type of units for which credit is
+ pooled.
+
+ The Unit-Value AVP specifies the multiplier, which converts between
+ service units of type CC-Unit-Type and abstract service units within
+ the credit pool (and thus to service units of any other service or
+ rating group associated with the same pool).
+
+ The G-S-U-Pool-Reference AVP is defined as follows (per the grouped-
+ avp-def of RFC 3588 [DIAMBASE]):
+
+ G-S-U-Pool-Reference ::= < AVP Header: 457 >
+ { G-S-U-Pool-Identifier }
+ { CC-Unit-Type }
+ { Unit-Value }
+
+8.31. G-S-U-Pool-Identifier AVP
+
+ The G-S-U-Pool-Identifier AVP (AVP Code 453) is of type Unsigned32
+ and identifies a credit pool within the session.
+
+8.32. CC-Unit-Type AVP
+
+ The CC-Unit-Type AVP (AVP Code 454) is of type Enumerated and
+ specifies the type of units considered to be pooled into a credit
+ pool.
+
+ The following values are defined for the CC-Unit-Type AVP:
+
+ TIME 0
+ MONEY 1
+ TOTAL-OCTETS 2
+ INPUT-OCTETS 3
+ OUTPUT-OCTETS 4
+ SERVICE-SPECIFIC-UNITS 5
+
+8.33. Validity-Time AVP
+
+ The Validity-Time AVP is of type Unsigned32 (AVP Code 448). It is
+ sent from the credit-control server to the credit-control client.
+ The AVP contains the validity time of the granted service units. The
+ measurement of the Validity-Time is started upon receipt of the
+ Credit-Control-Answer Message containing this AVP. If the granted
+ service units have not been consumed within the validity time
+ specified in this AVP, the credit-control client MUST send a Credit-
+ Control-Request message to the server, with CC-Request-Type set to
+ UPDATE_REQUEST. The value field of the Validity-Time AVP is given in
+ seconds.
+
+
+
+Hakala, et al. Standards Track [Page 70]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The Validity-Time AVP is also used for the graceful service
+ termination (see section 5.6) to indicate to the credit-control
+ client how long the subscriber is allowed to use network resources
+ after the specified action (i.e., REDIRECT or RESTRICT_ACCESS)
+ started. When the Validity-Time elapses, a new intermediate
+ interrogation is sent to the server.
+
+8.34. Final-Unit-Indication AVP
+
+ The Final-Unit-Indication AVP (AVP Code 430) is of type Grouped and
+ indicates that the Granted-Service-Unit AVP in the Credit-Control-
+ Answer, or in the AA answer, contains the final units for the
+ service. After these units have expired, the Diameter credit-control
+ client is responsible for executing the action indicated in the
+ Final-Unit-Action AVP (see section 5.6).
+
+ If more than one unit type is received in the Credit-Control-Answer,
+ the unit type that first expired SHOULD cause the credit-control
+ client to execute the specified action.
+
+ In the first interrogation, the Final-Unit-Indication AVP with
+ Final-Unit-Action REDIRECT or RESTRICT_ACCESS can also be present
+ with no Granted-Service-Unit AVP in the Credit-Control-Answer or in
+ the AA answer. This indicates to the Diameter credit-control client
+ to execute the specified action immediately. If the home service
+ provider policy is to terminate the service, naturally, the server
+ SHOULD return the appropriate transient failure (see section 9.1) in
+ order to implement the policy-defined action.
+
+ The Final-Unit-Action AVP defines the behavior of the service element
+ when the user's account cannot cover the cost of the service and MUST
+ always be present if the Final-Unit-Indication AVP is included in a
+ command.
+
+ If the Final-Unit-Action AVP is set to TERMINATE, no other AVPs MUST
+ be present.
+
+ If the Final-Unit-Action AVP is set to REDIRECT at least the
+ Redirect-Server AVP MUST be present. The Restriction-Filter-Rule AVP
+ or the Filter-Id AVP MAY be present in the Credit-Control-Answer
+ message if the user is also allowed to access other services that are
+ not accessible through the address given in the Redirect-Server AVP.
+
+ If the Final-Unit-Action AVP is set to RESTRICT_ACCESS, either the
+ Restriction-Filter-Rule AVP or the Filter-Id AVP SHOULD be present.
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 71]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The Filter-Id AVP is defined in [NASREQ]. The Filter-Id AVP can be
+ used to reference an IP filter list installed in the access device by
+ means other than the Diameter credit-control application, e.g.,
+ locally configured or configured by another entity.
+
+ The Final-Unit-Indication AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [DIAMBASE]):
+
+ Final-Unit-Indication ::= < AVP Header: 430 >
+ { Final-Unit-Action }
+ *[ Restriction-Filter-Rule ]
+ *[ Filter-Id ]
+ [ Redirect-Server ]
+
+8.35. Final-Unit-Action AVP
+
+ The Final-Unit-Action AVP (AVP Code 449) is of type Enumerated and
+ indicates to the credit-control client the action to be taken when
+ the user's account cannot cover the service cost.
+
+ The Final-Unit-Action can be one of the following:
+
+ TERMINATE 0
+ The credit-control client MUST terminate the service session.
+ This is the default handling, applicable whenever the credit-
+ control client receives an unsupported Final-Unit-Action value,
+ and it MUST be supported by all the Diameter credit-control client
+ implementations conforming to this specification.
+
+ REDIRECT 1
+ The service element MUST redirect the user to the address
+ specified in the Redirect-Server-Address AVP. The redirect action
+ is defined in section 5.6.2.
+
+ RESTRICT_ACCESS 2
+ The access device MUST restrict the user access according to the
+ IP packet filters defined in the Restriction-Filter-Rule AVP or
+ according to the IP packet filters identified by the Filter-Id
+ AVP. All the packets not matching the filters MUST be dropped
+ (see section 5.6.3).
+
+8.36. Restriction-Filter-Rule AVP
+
+ The Restriction-Filter-Rule AVP (AVP Code 438) is of type
+ IPFilterRule and provides filter rules corresponding to services that
+ are to remain accessible even if there are no more service units
+ granted. The access device has to configure the specified filter
+
+
+
+
+Hakala, et al. Standards Track [Page 72]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ rules for the subscriber and MUST drop all the packets not matching
+ these filters. Zero, one, or more such AVPs MAY be present in a
+ Credit-Control-Answer message or in an AA answer message.
+
+8.37. Redirect-Server AVP
+
+ The Redirect-Server AVP (AVP Code 434) is of type Grouped and
+ contains the address information of the redirect server (e.g., HTTP
+ redirect server, SIP Server) with which the end user is to be
+ connected when the account cannot cover the service cost. It MUST be
+ present when the Final-Unit-Action AVP is set to REDIRECT.
+
+ It is defined as follows (per the grouped-avp-def of RFC 3588
+ [DIAMBASE]):
+
+ Redirect-Server ::= < AVP Header: 434 >
+ { Redirect-Address-Type }
+ { Redirect-Server-Address }
+
+8.38. Redirect-Address-Type AVP
+
+ The Redirect-Address-Type AVP (AVP Code 433) is of type Enumerated
+ and defines the address type of the address given in the Redirect-
+ Server-Address AVP.
+
+ The address type can be one of the following:
+
+ IPv4 Address 0
+ The address type is in the form of "dotted-decimal" IPv4 address,
+ as defined in [IPv4].
+
+ IPv6 Address 1
+ The address type is in the form of IPv6 address, as defined in
+ [IPv6Addr]. The address is a text representation of the address
+ in either the preferred or alternate text form [IPv6Addr].
+ Conformant implementations MUST support the preferred form and
+ SHOULD support the alternate text form for IPv6 addresses.
+
+ URL 2
+ The address type is in the form of Uniform Resource Locator, as
+ defined in [URL].
+
+ SIP URI 3
+ The address type is in the form of SIP Uniform Resource
+ Identifier, as defined in [SIP].
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 73]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+8.39. Redirect-Server-Address AVP
+
+ The Redirect-Server-Address AVP (AVP Code 435) is of type UTF8String
+ and defines the address of the redirect server (e.g., HTTP redirect
+ server, SIP Server) with which the end user is to be connected when
+ the account cannot cover the service cost.
+
+8.40. Multiple-Services-Indicator AVP
+
+ The Multiple-Services-Indicator AVP (AVP Code 455) is of type
+ Enumerated and indicates whether the Diameter credit-control client
+ is capable of handling multiple services independently within a
+ (sub-) session. The absence of this AVP means that independent
+ credit-control of multiple services is not supported.
+
+ A server not implementing the independent credit-control of multiple
+ services MUST treat the Multiple-Services-Indicator AVP as an invalid
+ AVP.
+
+ The following values are defined for the Multiple-Services-Indicator
+ AVP:
+
+ MULTIPLE_SERVICES_NOT_SUPPORTED 0
+ Client does not support independent credit-control of multiple
+ services within a (sub-)session.
+
+ MULTIPLE_SERVICES_SUPPORTED 1
+ Client supports independent credit-control of multiple services
+ within a (sub-)session.
+
+8.41. Requested-Action AVP
+
+ The Requested-Action AVP (AVP Code 436) is of type Enumerated and
+ contains the requested action being sent by Credit-Control-Request
+ command where the CC-Request-Type is set to EVENT_REQUEST. The
+ following values are defined for the Requested-Action AVP:
+
+ DIRECT_DEBITING 0
+ This indicates a request to decrease the end user's account
+ according to information specified in the Requested-Service-Unit
+ AVP and/or Service-Identifier AVP (additional rating information
+ may be included in service-specific AVPs or in the Service-
+ Parameter-Info AVP). The Granted-Service-Unit AVP in the Credit-
+ Control-Answer command contains the debited units.
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 74]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ REFUND_ACCOUNT 1
+ This indicates a request to increase the end user's account
+ according to information specified in the Requested-Service-Unit
+ AVP and/or Service-Identifier AVP (additional rating information
+ may be included in service-specific AVPs or in the Service-
+ Parameter-Info AVP). The Granted-Service-Unit AVP in the Credit-
+ Control-Answer command contains the refunded units.
+
+ CHECK_BALANCE 2
+ This indicates a balance check request. In this case, the
+ checking of the account balance is done without any credit
+ reservation from the account. The Check-Balance-Result AVP in the
+ Credit-Control-Answer command contains the result of the balance
+ check.
+
+ PRICE_ENQUIRY 3
+ This indicates a price enquiry request. In this case, neither
+ checking of the account balance nor reservation from the account
+ will be done; only the price of the service will be returned in
+ the Cost-Information AVP in the Credit-Control-Answer Command.
+
+8.42. Service-Context-Id AVP
+
+ The Service-Context-Id AVP is of type UTF8String (AVP Code 461) and
+ contains a unique identifier of the Diameter credit-control service
+ specific document that applies to the request (as defined in section
+ 4.1.2). This is an identifier allocated by the service provider, by
+ the service element manufacturer, or by a standardization body, and
+ MUST uniquely identify a given Diameter credit-control service
+ specific document. The format of the Service-Context-Id is:
+
+ "service-context" "@" "domain"
+
+ service-context = Token
+
+ The Token is an arbitrary string of characters and digits.
+
+ 'domain' represents the entity that allocated the Service-Context-Id.
+ It can be ietf.org, 3gpp.org, etc., if the identifier is allocated by
+ a standardization body, or it can be the FQDN of the service provider
+ (e.g., provider.example.com) or of the vendor (e.g.,
+ vendor.example.com) if the identifier is allocated by a private
+ entity.
+
+ This AVP SHOULD be placed as close to the Diameter header as
+ possible.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 75]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Service-specific documents that are for private use only (i.e., to
+ one provider's own use, where no interoperability is deemed useful)
+ may define private identifiers without need of coordination.
+ However, when interoperability is wanted, coordination of the
+ identifiers via, for example, publication of an informational RFC is
+ RECOMMENDED in order to make Service-Context-Id globally available.
+
+8.43. Service-Parameter-Info AVP
+
+ The Service-Parameter-Info AVP (AVP Code 440) is of type Grouped and
+ contains service-specific information used for price calculation or
+ rating. The Service-Parameter-Type AVP defines the service parameter
+ type, and the Service-Parameter-Value AVP contains the parameter
+ value. The actual contents of these AVPs are not within the scope of
+ this document and SHOULD be defined in another Diameter application,
+ in standards written by other standardization bodies, or in service-
+ specific documentation.
+
+ In the case of an unknown service request (e.g., unknown Service-
+ Parameter-Type), the corresponding answer message MUST contain the
+ error code DIAMETER_RATING_FAILED. A Credit-Control-Answer message
+ with this error MUST contain one or more Failed-AVP AVPs containing
+ the Service-Parameter-Info AVPs that caused the failure.
+
+ It is defined as follows (per the grouped-avp-def of RFC 3588
+ [DIAMBASE]):
+
+ Service-Parameter-Info ::= < AVP Header: 440 >
+ { Service-Parameter-Type }
+ { Service-Parameter-Value }
+
+8.44. Service-Parameter-Type AVP
+
+ The Service-Parameter-Type AVP is of type Unsigned32 (AVP Code 441)
+ and defines the type of the service event specific parameter (e.g.,
+ it can be the end-user location or service name). The different
+ parameters and their types are service specific, and the meanings of
+ these parameters are not defined in this document. Whoever allocates
+ the Service-Context-Id (i.e., unique identifier of a service-specific
+ document) is also responsible for assigning Service-Parameter-Type
+ values for the service and ensuring their uniqueness within the given
+ service. The Service-Parameter-Value AVP contains the value
+ associated with the service parameter type.
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 76]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+8.45. Service-Parameter-Value AVP
+
+ The Service-Parameter-Value AVP is of type OctetString (AVP Code 442)
+ and contains the value of the service parameter type.
+
+8.46. Subscription-Id AVP
+
+ The Subscription-Id AVP (AVP Code 443) is used to identify the end
+ user's subscription and is of type Grouped. The Subscription-Id AVP
+ includes a Subscription-Id-Data AVP that holds the identifier and a
+ Subscription-Id-Type AVP that defines the identifier type.
+
+ It is defined as follows (per the grouped-avp-def of RFC 3588
+ [DIAMBASE]):
+
+ Subscription-Id ::= < AVP Header: 443 >
+ { Subscription-Id-Type }
+ { Subscription-Id-Data }
+
+8.47. Subscription-Id-Type AVP
+
+ The Subscription-Id-Type AVP (AVP Code 450) is of type Enumerated,
+ and it is used to determine which type of identifier is carried by
+ the Subscription-Id AVP.
+
+ This specification defines the following subscription identifiers.
+ However, new Subscription-Id-Type values can be assigned by an IANA
+ designated expert, as defined in section 12. A server MUST implement
+ all the Subscription-Id-Types required to perform credit
+ authorization for the services it supports, including possible future
+ values. Unknown or unsupported Subscription-Id-Types MUST be treated
+ according to the 'M' flag rule, as defined in [DIAMBASE].
+
+ END_USER_E164 0
+ The identifier is in international E.164 format (e.g., MSISDN),
+ according to the ITU-T E.164 numbering plan defined in [E164] and
+ [CE164].
+
+ END_USER_IMSI 1
+ The identifier is in international IMSI format, according to the
+ ITU-T E.212 numbering plan as defined in [E212] and [CE212].
+
+ END_USER_SIP_URI 2
+ The identifier is in the form of a SIP URI, as defined in [SIP].
+
+ END_USER_NAI 3
+ The identifier is in the form of a Network Access Identifier, as
+ defined in [NAI].
+
+
+
+Hakala, et al. Standards Track [Page 77]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ END_USER_PRIVATE 4
+ The Identifier is a credit-control server private identifier.
+
+8.48. Subscription-Id-Data AVP
+
+ The Subscription-Id-Data AVP (AVP Code 444) is used to identify the
+ end user and is of type UTF8String. The Subscription-Id-Type AVP
+ defines which type of identifier is used.
+
+8.49. User-Equipment-Info AVP
+
+ The User-Equipment-Info AVP (AVP Code 458) is of type Grouped and
+ allows the credit-control client to indicate the identity and
+ capability of the terminal the subscriber is using for the connection
+ to network.
+
+ It is defined as follows (per the grouped-avp-def of RFC 3588
+ [DIAMBASE]):
+
+ User-Equipment-Info ::= < AVP Header: 458 >
+ { User-Equipment-Info-Type }
+ { User-Equipment-Info-Value }
+
+8.50. User-Equipment-Info-Type AVP
+
+ The User-Equipment-Info-Type AVP is of type Enumerated (AVP Code
+ 459) and defines the type of user equipment information contained in
+ the User-Equipment-Info-Value AVP.
+
+ This specification defines the following user equipment types.
+ However, new User-Equipment-Info-Type values can be assigned by an
+ IANA designated expert, as defined in section 12.
+
+ IMEISV 0
+ The identifier contains the International Mobile Equipment
+ Identifier and Software Version in the international IMEISV format
+ according to 3GPP TS 23.003 [3GPPIMEI].
+
+ MAC 1
+ The 48-bit MAC address is formatted as described in [RAD802.1X].
+
+ EUI64 2
+ The 64-bit identifier used to identify hardware instance of the
+ product, as defined in [EUI64].
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 78]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ MODIFIED_EUI64 3
+ There are a number of types of terminals that have identifiers
+ other than IMEI, IEEE 802 MACs, or EUI-64. These identifiers can
+ be converted to modified EUI-64 format as described in [IPv6Addr]
+ or by using some other methods referred to in the service-specific
+ documentation.
+
+8.51. User-Equipment-Info-Value AVP
+
+ The User-Equipment-Info-Value AVP (AVP Code 460) is of type
+ OctetString. The User-Equipment-Info-Type AVP defines which type of
+ identifier is used.
+
+9. Result Code AVP Values
+
+ This section defines new Result-Code AVP [DIAMBASE] values that must
+ be supported by all Diameter implementations that conform to this
+ specification.
+
+ The Credit-Control-Answer message includes the Result-Code AVP, which
+ may indicate that an error was present in the Credit-Control-Request
+ message. A rejected Credit-Control-Request message SHOULD cause the
+ user's session to be terminated.
+
+9.1. 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 that the request MAY be able to be satisfied in the
+ future.
+
+ DIAMETER_END_USER_SERVICE_DENIED 4010
+ The credit-control server denies the service request due to
+ service restrictions. If the CCR contained used-service-units,
+ they are deducted, if possible.
+
+ DIAMETER_CREDIT_CONTROL_NOT_APPLICABLE 4011
+ The credit-control server determines that the service can be
+ granted to the end user but that no further credit-control is
+ needed for the service (e.g., service is free of charge).
+
+ DIAMETER_CREDIT_LIMIT_REACHED 4012
+ The credit-control server denies the service request because the
+ end user's account could not cover the requested service. If the
+ CCR contained used-service-units they are deducted, if possible.
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 79]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+9.2. Permanent Failures
+
+ Errors that fall within the permanent failure category are used to
+ inform the peer that the request failed and should not be attempted
+ again.
+
+ DIAMETER_USER_UNKNOWN 5030
+ The specified end user is unknown in the credit-control server.
+
+ DIAMETER_RATING_FAILED 5031
+ This error code is used to inform the credit-control client that
+ the credit-control server cannot rate the service request due to
+ insufficient rating input, an incorrect AVP combination, or an AVP
+ or an AVP value that is not recognized or supported in the rating.
+ The Failed-AVP AVP MUST be included and contain a copy of the
+ entire AVP(s) that could not be processed successfully or an
+ example of the missing AVP complete with the Vendor-Id if
+ applicable. The value field of the missing AVP should be of
+ correct minimum length and contain zeros.
+
+10. AVP Occurrence Table
+
+ The following table presents the AVPs defined in this document and
+ specifies in which Diameter messages they MAY or MAY NOT be present.
+ Note that AVPs that can only be present within a Grouped AVP are not
+ represented in this table.
+
+ The table uses 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.
+ 0-1 Zero or one instance of the AVP MAY be present in the
+ message. It is considered an error if there is 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.
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 80]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+10.1. Credit-Control AVP Table
+
+ The table in this section is used to represent which credit-control
+ applications specific AVPs defined in this document are to be present
+ in the credit-control messages.
+
+ +-----------+
+ | Command |
+ | Code |
+ |-----+-----+
+ Attribute Name | CCR | CCA |
+ ------------------------------|-----+-----+
+ Acct-Multi-Session-Id | 0-1 | 0-1 |
+ Auth-Application-Id | 1 | 1 |
+ CC-Correlation-Id | 0-1 | 0 |
+ CC-Session-Failover | 0 | 0-1 |
+ CC-Request-Number | 1 | 1 |
+ CC-Request-Type | 1 | 1 |
+ CC-Sub-Session-Id | 0-1 | 0-1 |
+ Check-Balance-Result | 0 | 0-1 |
+ Cost-Information | 0 | 0-1 |
+ Credit-Control-Failure- | 0 | 0-1 |
+ Handling | | |
+ Destination-Host | 0-1 | 0 |
+ Destination-Realm | 1 | 0 |
+ Direct-Debiting-Failure- | 0 | 0-1 |
+ Handling | | |
+ Event-Timestamp | 0-1 | 0-1 |
+ Failed-AVP | 0 | 0+ |
+ Final-Unit-Indication | 0 | 0-1 |
+ Granted-Service-Unit | 0 | 0-1 |
+ Multiple-Services-Credit- | 0+ | 0+ |
+ Control | | |
+ Multiple-Services-Indicator | 0-1 | 0 |
+ Origin-Host | 1 | 1 |
+ Origin-Realm | 1 | 1 |
+ Origin-State-Id | 0-1 | 0-1 |
+ Proxy-Info | 0+ | 0+ |
+ Redirect-Host | 0 | 0+ |
+ Redirect-Host-Usage | 0 | 0-1 |
+ Redirect-Max-Cache-Time | 0 | 0-1 |
+ Requested-Action | 0-1 | 0 |
+ Requested-Service-Unit | 0-1 | 0 |
+ Route-Record | 0+ | 0+ |
+ Result-Code | 0 | 1 |
+ Service-Context-Id | 1 | 0 |
+ Service-Identifier | 0-1 | 0 |
+ Service-Parameter-Info | 0+ | 0 |
+
+
+
+Hakala, et al. Standards Track [Page 81]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Session-Id | 1 | 1 |
+ Subscription-Id | 0+ | 0 |
+ Termination-Cause | 0-1 | 0 |
+ User-Equipment-Info | 0-1 | 0 |
+ Used-Service-Unit | 0+ | 0 |
+ User-Name | 0-1 | 0-1 |
+ Validity-Time | 0 | 0-1 |
+ ------------------------------|-----+-----+
+
+10.2. Re-Auth-Request/Answer AVP Table
+
+ This section defines AVPs that are specific to the Diameter credit-
+ control application and that MAY be included in the Diameter Re-
+ Auth-Request/Answer (RAR/RAA) message [DIAMBASE].
+
+ Re-Auth-Request/Answer command MAY include the following additional
+ AVPs:
+
+ +---------------+
+ | Command Code |
+ |-------+-------+
+ Attribute Name | RAR | RAA |
+ ------------------------------+-------+-------+
+ CC-Sub-Session-Id | 0-1 | 0-1 |
+ G-S-U-Pool-Identifier | 0-1 | 0-1 |
+ Service-Identifier | 0-1 | 0-1 |
+ Rating-Group | 0-1 | 0-1 |
+ ------------------------------+-------+-------+
+
+11. RADIUS/Diameter Credit-Control Interworking Model
+
+ This section defines the basic principles for the Diameter credit-
+ control/RADIUS prepaid inter-working model; that is, a message
+ translation between a RADIUS based prepaid solution and a Diameter
+ credit-control application. A complete description of the protocol
+ translations between RADIUS and the Diameter credit-control
+ application is beyond the scope of this specification and SHOULD be
+ addressed in another appropriate document, such as the RADIUS prepaid
+ specification.
+
+ The Diameter credit-control architecture may have a Translation Agent
+ capable of translation between RADIUS prepaid and Diameter credit-
+ control protocols. An AAA server (usually the home AAA server) may
+ act as a Translation Agent and as a Diameter credit-control client
+ for service elements that use credit-control mechanisms other than
+ Diameter credit control for instance, RADIUS prepaid. In this case,
+ the home AAA server contacts the Diameter credit-control server as
+ part of the authorization process. The interworking architecture is
+
+
+
+Hakala, et al. Standards Track [Page 82]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ illustrated in Figure 7, and interworking flow in Figure 8. In a
+ roaming situation the service element (e.g., the NAS) may be located
+ in the visited network, and a visited AAA server is usually
+ contacted. The visited AAA server connects then to the home AAA
+ server.
+
+ RADIUS Prepaid
+ +--------+ +---------+ protocol +------------+ +--------+
+ | End |<----->| Service |<---------->| Home AAA | |Business|
+ | User | | Element | | Server | |Support |
+ +--------+ +-->| | |+----------+|->|System |
+ | +---------+ ||CC Client || | |
+ | |+----------+| | |
+ +--------+ | +------^-----+ +----^---+
+ | End |<--+ Credit-Control | |
+ | User | Protocol | |
+ +--------+ +-------V--------+ |
+ |Credit-Control |----+
+ | Server |
+ +----------------+
+
+ Figure 7: Credit-control architecture with service element
+ containing translation agent, translating RADIUS
+ prepaid to Diameter credit-control protocol
+
+ When the AAA server acting as a Translation Agent receives an initial
+ RADIUS Access-Request message from service element (e.g., NAS
+ access), it performs regular authentication and authorization. If
+ the RADIUS Access-Request message indicates that the service element
+ is capable of credit-control, and if the home AAA server finds that
+ the subscriber is a prepaid subscriber, then a Diameter credit-
+ control request SHOULD be sent toward the credit-control server to
+ perform credit authorization and to establish a credit-control
+ session. After the Diameter credit-control server checks the end
+ user's account balance, rates the service, and reserves credit from
+ the end user's account, the reserved quota is returned to the home
+ AAA server in the Diameter Credit-Control-Answer. Then the home AAA
+ server sends the reserved quota to the service element in the RADIUS
+ Access-Accept.
+
+ At the expiry of the allocated quota, the service element sends a new
+ RADIUS Access-Request containing the units used this far to the home
+ AAA server. The home AAA server shall map a RADIUS Access-Request
+ containing the reported units to the Diameter credit-control server
+ in a Diameter Credit-Control-Request (UPDATE_REQUEST). The Diameter
+ credit-control server debits the used units from the end user's
+ account and allocates a new quota that is returned to the home AAA
+ server in the Diameter Credit-Control-Answer. The quota is
+
+
+
+Hakala, et al. Standards Track [Page 83]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ transferred to the service element in the RADIUS Access-Accept. When
+ the end user terminates the service, or when the entire quota has
+ been used, the service element sends a RADIUS Access-Request. To
+ debit the used units from the end user's account and to stop the
+ credit-control session, the home AAA server sends a Diameter Credit-
+ Control-Request (TERMINATION_REQUEST) to the credit-control server.
+ The Diameter credit-control server acknowledges the session
+ termination by sending a Diameter Credit-Control-Answer to the home
+ AAA server. The RADIUS Access-Accept is sent to the NAS.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 84]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ A following diagram illustrates a RADIUS prepaid - Diameter credit-
+ control interworking sequence.
+
+ Service Element Translation Agent
+ (e.g., NAS) (CC Client) CC Server
+ | Access-Request | |
+ |----------------------->| |
+ | | CCR (initial) |
+ | |----------------------->|
+ | | CCA (Granted-Units) |
+ | |<-----------------------|
+ | Access-Accept | |
+ | (Granted-Units) | |
+ |<-----------------------| |
+ : : :
+ | Access-Request | |
+ | (Used-Units) | |
+ |----------------------->| |
+ | | CCR (update, |
+ | | Used-Units) |
+ | |----------------------->|
+ | | CCA (Granted-Units) |
+ | |<-----------------------|
+ | Access-Accept | |
+ | (Granted-Units) | |
+ |<-----------------------| |
+ : : :
+ | Access-Request | |
+ |----------------------->| |
+ | | CCR (terminate, |
+ | | Used-Units) |
+ | |----------------------->|
+ | | CCA |
+ | |<-----------------------|
+ | Access-Accept | |
+ |<-----------------------| |
+ | | |
+
+ Figure 8: Message flow example with RADIUS prepaid -
+ Diameter credit-control interworking
+
+12. IANA Considerations
+
+ This section contains the namespaces that have either been created in
+ this specification, or the values assigned to existing namespaces
+ managed by IANA.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 85]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ In the subsections below, when we speak about review by a Designated
+ Expert, please note that the designated expert will be assigned by
+ the IESG. Initially, such Expert discussions take place on the AAA
+ WG mailing list.
+
+12.1. Application Identifier
+
+ This specification assigns the value 4, 'Diameter Credit Control', to
+ the Application Identifier namespace defined in [DIAMBASE]. See
+ section 1.3 for more information.
+
+12.2. Command Codes
+
+ This specification uses the value 272 from the Command code namespace
+ defined in [DIAMBASE] for the Credit-Control-Request (CCR) and
+ Credit-Control-Answer (CCA) commands.
+
+12.3. AVP Codes
+
+ This specification assigns the values 411 - 461 from the AVP code
+ namespace defined in [DIAMBASE]. See section 8 for the assignment of
+ the namespace in this specification.
+
+12.4. Result-Code AVP Values
+
+ This specification assigns the values 4010, 4011, 4012, 5030, 5031
+ from the Result-Code AVP value namespace defined in [DIAMBASE]. See
+ section 9 for the assignment of the namespace in this specification.
+
+12.5. CC-Request-Type AVP
+
+ As defined in section 8.3, the CC-Request-Type AVP includes
+ Enumerated type values 1 - 4. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.6. CC-Session-Failover AVP
+
+ As defined in section 8.4, the CC-Failover-Supported AVP includes
+ Enumerated type values 0 - 1. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 86]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+12.7. CC-Unit-Type AVP
+
+ As defined in section 8.32, the CC-Unit-Type AVP includes Enumerated
+ type values 0 - 5. IANA has created and is maintaining a namespace
+ for this AVP. All remaining values are available for assignment by a
+ Designated Expert [IANA].
+
+12.8. Check-Balance-Result AVP
+
+ As defined in section 8.6, the Check-Balance-Result AVP includes
+ Enumerated type values 0 - 1. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.9. Credit-Control AVP
+
+ As defined in section 8.13, the Credit-Control AVP includes
+ Enumerated type values 0 - 1. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.10. Credit-Control-Failure-Handling AVP
+
+ As defined in section 8.14, the Credit-Control-Failure-Handling AVP
+ includes Enumerated type values 0 - 2. IANA has created and is
+ maintaining a namespace for this AVP. All remaining values are
+ available for assignment by a Designated Expert [IANA].
+
+12.11. Direct-Debiting-Failure-Handling AVP
+
+ As defined in section 8.15, the Direct-Debiting-Failure-Handling AVP
+ includes Enumerated type values 0 - 1. IANA has created and is
+ maintaining a namespace for this AVP. All remaining values are
+ available for assignment by a Designated Expert [IANA].
+
+12.12. Final-Unit-Action AVP
+
+ As defined in section 8.35, the Final-Unit-Action AVP includes
+ Enumerated type values 0 - 2. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.13. Multiple-Services-Indicator AVP
+
+ As defined in section 8.40, the Multiple-Services-Indicator AVP
+ includes Enumerated type values 0 - 1. IANA has created and is
+ maintaining a namespace for this AVP. All remaining values are
+ available for assignment by a Designated Expert [IANA].
+
+
+
+Hakala, et al. Standards Track [Page 87]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+12.14. Redirect-Address-Type AVP
+
+ As defined in section 8.38, the Redirect-Address-Type AVP includes
+ Enumerated type values 0 - 3. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.15. Requested-Action AVP
+
+ As defined in section 8.41, the Requested-Action AVP includes
+ Enumerated type values 0 - 3. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.16. Subscription-Id-Type AVP
+
+ As defined in section 8.47, the Subscription-Id-Type AVP includes
+ Enumerated type values 0 - 4. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.17. Tariff-Change-Usage AVP
+
+ As defined in section 8.27, the Tariff-Change-Usage AVP includes
+ Enumerated type values 0 - 2. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+12.18. User-Equipment-Info-Type AVP
+
+ As defined in section 8.50, the User-Equipment-Info-Type AVP includes
+ Enumerated type values 0 - 3. IANA has created and is maintaining a
+ namespace for this AVP. All remaining values are available for
+ assignment by a Designated Expert [IANA].
+
+13. Credit-Control Application Related Parameters
+
+ Tx timer
+
+ When real-time credit-control is required, the credit-control
+ client contacts the credit-control server before and while the
+ service is provided to an end user. Due to the real-time nature
+ of the application, the communication delays SHOULD be minimized;
+ e.g., to avoid an overly long service setup time experienced by
+ the end user. The Tx timer is introduced to control the waiting
+ time in the client in the Pending state. When the Tx timer
+ elapses, the credit-control client takes an action to the end user
+ according to the value of the Credit-Control-Failure-Handling AVP
+
+
+
+Hakala, et al. Standards Track [Page 88]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ or Direct-Debiting-Failure-Handling AVP. The recommended value is
+ 10 seconds.
+
+ Tcc timer
+
+ The Tcc timer supervises an ongoing credit-control session in the
+ credit-control server. It is RECOMMENDED to use the Validity-Time
+ as input to set the Tcc timer value. In case of transient
+ failures in the network, the Diameter credit-control server might
+ change to Idle state. To avoid this, the Tcc timer MAY be set so
+ that Tcc equals to 2 x Validity-Time.
+
+ Credit-Control-Failure-Handling and Direct-Debiting-Failure-Handling
+
+ Client implementations may offer the possibility of locally
+ configuring these AVPs. In such a case their value and behavior
+ is defined in section 5.7 for the Credit-Control-Failure-Handling
+ and in section 6.5 for the Direct-Debiting-Failure-Handling.
+
+14. Security Considerations
+
+ The Diameter base protocol [DIAMBASE] requires that each Diameter
+ implementation use underlying security; i.e., IPsec or TLS. These
+ mechanisms are believed to provide sufficient protection under the
+ normal Internet threat model; that is, assuming that the authorized
+ nodes engaging in the protocol have not been compromised, but that
+ the attacker has complete control over the communication channels
+ between them. This includes eavesdropping, message modification,
+ insertion, and man-in-the-middle and replay attacks. Note also that
+ this application includes a mechanism for application layer replay
+ protection by means of the Session-Id from [DIAMBASE] and CC-
+ Request-Number, which is specified in this document. The Diameter
+ credit-control application is often used within one domain, and there
+ may be a single hop between the peers. In these environments, the
+ use of TLS or IPsec is sufficient. The details of TLS and IPsec
+ related security considerations are discussed in the [DIAMBASE].
+
+ Because this application handles monetary transactions (directly or
+ indirectly), it increases the interest for various security attacks.
+ Therefore, all parties communicating with each other MUST be
+ authenticated, including, for instance, TLS client-side
+ authentication. In addition, authorization of the client SHOULD be
+ emphasized; i.e., that the client is allowed to perform credit-
+ control for a certain user. The specific means of authorization are
+ outside of the scope of this specification but can be, for instance,
+ manual configuration.
+
+
+
+
+
+Hakala, et al. Standards Track [Page 89]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Another kind of threat is malicious modification, injection, or
+ deletion of AVPs or complete credit-control messages. The credit-
+ control messages contain sensitive billing related information (such
+ as subscription Id, granted units, used units, cost information)
+ whose malicious modification can have financial consequences.
+ Sometimes simply delaying the credit-control messages can cause
+ disturbances in the credit-control client or server.
+
+ Even without any modification to the messages, an adversary can
+ invite a security threat by eavesdropping, as the transactions
+ contain private information about the user. Also, by monitoring the
+ credit-control messages one can collect information about the
+ credit-control server's billing models and business relationships.
+
+ When third-party relays or proxy are involved, the hop-by-hop
+ security does not necessarily provide sufficient protection for
+ Diameter user session. In some cases, it may be inappropriate to
+ send Diameter messages, such as CCR and CCA, containing sensitive
+ AVPs via untrusted Diameter proxy agents, as there are no assurances
+ that third-party proxies will not modify the credit-control commands
+ or AVP values.
+
+14.1. Direct Connection with Redirects
+
+ A Diameter credit-control agent cannot always know whether agents
+ between it and the end user's Diameter credit-control server are
+ reliable. In this case, the Diameter credit-control agent doesn't
+ have a routing entry in its Diameter Routing Table (defined in
+ [DIAMBASE], section 2.7) for the realm of the credit-control server
+ in the end user's home domain. The Diameter credit-control agent can
+ have a default route configured to a local Redirect agent, and it
+ redirects the CCR message to the redirect agent. The local Redirect
+ agent then returns a redirect notification (Result-code 3006,
+ DIAMETER_REDIRECT_INDICATION) to the credit-control agent, as well as
+ Diameter credit-control server(s) information (Redirect-Host AVP) and
+ information (Redirect-Host-Usage AVP) about how the routing entry
+ resulting from the Redirect-Host is to be used. The Diameter
+ credit-control agent then forwards the CCR message directly to one of
+ the hosts identified by the CCA message from the redirect agent. If
+ the value of the Redirect-Host-Usage AVP is unequal to zero, all
+ following messages are sent to the host specified in the Redirect-
+ Host AVP until the time specified by the Redirect-Max-Cache-Time AVP
+ is expired.
+
+ There are some authorization issues even with redirects. There may
+ be attacks toward nodes that have been properly authorized, but that
+ abuse their authorization or have been compromised. These issues are
+ discussed more widely in [DIAMEAP], section 8.
+
+
+
+Hakala, et al. Standards Track [Page 90]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+15. References
+
+15.1. Normative References
+
+ [DIAMBASE] Calhoun, P., Loughney, J., Guttman, E., Zorn, G., and J.
+ Arkko, "Diameter Base Protocol", RFC 3588, September
+ 2003.
+
+ [3GPPCHARG] 3rd Generation Partnership Project; Technical
+ Specification Group Services and System Aspects, Service
+ aspects; Charging and Billing, (release 5), 3GPP TS
+ 22.115 v. 5.2.1, 2002-03.
+
+ [SIP] Rosenberg, J., Schulzrinne, H., Camarillo, G., Johnston,
+ A., Peterson, J., Sparks, R., Handley, M., and E.
+ Schooler, "SIP: Session Initiation Protocol", RFC 3261,
+ June 2002.
+
+ [NAI] Aboba, B. and M. Beadles, "The Network Access
+ Identifier", RFC 2486, January 1999.
+
+ [E164] Recommendation E.164/I.331 (05/97): The International
+ Public Telecommunication Numbering Plan. 1997.
+
+ [CE164] Complement to ITU-T Recommendation E.164 (05/1997):"List
+ of ITU-T Recommendation E.164 assigned country codes",
+ June 2000.
+
+ [E212] Recommendation E.212 (11/98): The international
+ identification plan for mobile terminals and mobile
+ users. 1998.
+
+ [CE212] Complement to ITU-T Recommendation E.212 (11/1997):" List
+ of mobile country or geographical area codes", February
+ 1999.
+
+ [IANA] Narten, T. and H. Alvestrand, "Guidelines for Writing an
+ IANA Considerations Section in RFCs", BCP 26, RFC 2434,
+ October 1998.
+
+ [IPv4] Postel, J., "Internet Protocol", STD 5, RFC 791,
+ September 1981.
+
+ [IPv6Addr] Hinden, R. and S. Deering, "Internet Protocol Version 6
+ (IPv6) Addressing Architecture", RFC 3513, April 2003.
+
+ [KEYWORDS] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+
+
+Hakala, et al. Standards Track [Page 91]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ [ISO4217] Codes for the representation of currencies and funds,
+ International Standard ISO 4217,2001
+
+ [NASREQ] Calhoun, P., Zorn, G., Spence, D., and D. Mitton,
+ "Diameter Network Access Server Application", RFC 4005,
+ August 2005.
+
+ [AAATRANS] Aboba, B. and J. Wood, "Authentication, Authorization and
+ Accounting (AAA) Transport Profile", RFC 3539, June 2003.
+
+ [URL] Berners-Lee, T., Masinter, L., and M. McCahill, "Uniform
+ Resource Locators (URL)", RFC 1738, December 1994.
+
+ [RAD802.1X] Congdon, P., Aboba, B., Smith, A., Zorn, G., and J.
+ Roese, "IEEE 802.1X Remote Authentication Dial In User
+ Service (RADIUS) Usage Guidelines", RFC 3580, September
+ 2003.
+
+ [EUI64] IEEE, "Guidelines for 64-bit Global Identifier (EUI-64)
+ Registration Authority",
+ http://standards.ieee.org/regauth/oui/tutorials/
+ EUI64.html March 1997.
+
+ [3GPPIMEI] 3rd Generation Partnership Project; Technical
+ Specification Group Core Network, Numbering, addressing
+ and identification, (release 5), 3GPP TS 23.003 v. 5.8.0,
+ 2003-12
+
+15.2. Informative References
+
+ [RFC2866] Rigney, C., "RADIUS Accounting", RFC 2866, June 2000.
+
+ [DIAMMIP] Calhoun, P., Johansson, T., Perkins, C., Hiller, T., and
+ P. McCann, "Diameter Mobile IPv4 Application", RFC 4004,
+ August 2005.
+
+ [DIAMEAP] Eronen, P., Hiller, T., and G. Zorn, "Diameter Extensible
+ Authentication Protocol (EAP) Application", Work in
+ Progress.
+
+ [RFC3725] Rosenberg, J., Peterson, J., Schulzrinne, H., and G.
+ Camarillo, "Best Current Practices for Third Party Call
+ Control (3pcc) in the Session Initiation Protocol (SIP)",
+ BCP 85, RFC 3725, April 2004.
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 92]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+16. Acknowledgements
+
+ The authors would like to thank Bernard Aboba, Jari Arkko, Robert
+ Ekblad, Pasi Eronen, Benny Gustafsson, Robert Karlsson, Avi Lior,
+ Paco Marin, Jussi Maki, Jeff Meyer, Anne Narhi, John Prudhoe,
+ Christopher Richards, Juha Vallinen, and Mark Watson for their
+ comments and suggestions.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 93]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+Appendix A. Credit-Control Sequences
+
+A.1. Flow I
+
+ NAS
+ End User (CC Client) AAA Server CC Server
+ |(1)User Logon |(2)AA Request (CC AVPs) |
+ |------------------>|------------------->| |
+ | | |(3)CCR(initial, CC AVPs)
+ | | |------------------->|
+ | | | (4)CCA(Granted-Units)
+ | | |<-------------------|
+ | |(5)AA Answer(Granted-Units) |
+ |(6)Access granted |<-------------------| |
+ |<----------------->| | |
+ | | | |
+ : : : :
+ | |(7)CCR(update,Used-Units) |
+ | |------------------->|(8)CCR |
+ | | | (update,Used-Units)
+ | | |------------------->|
+ | | |(9)CCA(Granted-Units)
+ | |(10)CCA(Granted-Units)<------------------|
+ | |<-------------------| |
+ : : : :
+ | (Auth. lifetime expires) | |
+ | |(11) AAR (CC AVP) | |
+ | |------------------->| |
+ | | (12) AAA | |
+ | |<-------------------| |
+ : : : :
+ : : : :
+ |(13) User logoff | | |
+ |------------------>|(14)CCR(term.,Used-Units) |
+ | |------------------->|(15)CCR |
+ | | | (term.,Used-Units)
+ | | |------------------->|
+ | | | (16)CCA |
+ | | (17)CCA |<-------------------|
+ | |<-------------------| |
+ | |(18)STR | |
+ | |------------------->| |
+ | | (19)STA | |
+ | |<-------------------| |
+
+ Figure A.1: Flow I
+
+
+
+
+
+Hakala, et al. Standards Track [Page 94]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ A credit-control flow for Network Access Services prepaid is shown in
+ Figure A.1. The Diameter [NASREQ] is implemented in the Network
+ Access Server (NAS). The focus of this flow is in the credit
+ authorization.
+
+ The user logs on to the network (1). The Diameter NAS sends a
+ Diameter AA-Request (AAR) to the home Diameter AAA server. The
+ credit-control client populates the AAR with the Credit-Control AVP
+ set to CREDIT_AUTHORIZATION, and service-specific AVPs are included,
+ as usual [NASREQ]. The home Diameter AAA server performs service-
+ specific Authentication and Authorization, as usual. The home
+ Diameter AAA server determines that the user is a prepaid user and
+ notices from the Credit-Control AVP that the NAS has credit-control
+ capabilities. It sends a Diameter Credit-Control-Request with CC-
+ Request-Type set to INITIAL_REQUEST to the Diameter credit-control
+ server to perform credit authorization (3) and to establish a
+ credit-control session. (The home Diameter AAA server may forward
+ service-specific AVPs received from the NAS as input for the rating
+ process.) The Diameter credit-control server checks the end user's
+ account balance, rates the service, and reserves credit from the end
+ user's account. The reserved quota is returned to the home Diameter
+ AAA server in the Diameter Credit-Control-Answer (4). The home
+ Diameter AAA server sends the reserved quota to the NAS in the
+ Diameter AA-Answer (AAA). Upon successful AAA, the NAS starts the
+ credit-control session and starts monitoring the granted units (5).
+ The NAS grants access to the end user (6). At the expiry of the
+ allocated quota, the NAS sends a Diameter Credit-Control-Request with
+ CC-Request-Type set to UPDATE_REQUEST to the Home Diameter AAA server
+ (7). This message contains the units used thus far. The home
+ Diameter AAA server forwards the CCR to the Diameter credit-control
+ server (8). The Diameter credit-control server debits the used units
+ from the end user's account and allocates a new quota that is
+ returned to the home Diameter AAA server in the Diameter Credit-
+ Control-Answer (9). The message is forwarded to the NAS (10).
+ During the ongoing credit-control session, the authorization lifetime
+ expires, and the authorization/authentication client in the NAS
+ performs service specific re-authorization to the home Diameter AAA
+ server, as usual. The credit-control client populates the AAR with
+ the Credit-Control AVP set to RE_AUTHORIZATION, indicating that the
+ credit-control server shall not be contacted, as the credit
+ authorization is controlled by the burning rate of the granted units
+ (11). The home Diameter AAA server performs service-specific re-
+ authorization as usual and returns the AA-Answer to the NAS (12).
+ The end user logs off from the network (13). To debit the used units
+ from the end user's account and to stop the credit-control session,
+ the NAS sends a Diameter Credit-Control-Request with CC-Request-Type
+ set to TERMINATION_REQUEST to the home Diameter AAA server (14). The
+ home Diameter AAA server forwards the CCR to the credit-control
+
+
+
+Hakala, et al. Standards Track [Page 95]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ server (15). The Diameter credit-control server acknowledges the
+ session termination by sending a Diameter Credit-Control-Answer to
+ the home Diameter AAA server (16). The home Diameter AAA server
+ forwards the answer to the NAS (17). STR/STA takes place between the
+ NAS and home Diameter AAA server, as usual (18-19).
+
+A.2. Flow II
+
+ SIP Proxy/Registrar AAA
+ A (CC Client) Server B CC Server
+ |(i) REGISTER | | | |
+ |------------->|(ii) | | |
+ | |------------->| | |
+ | |authentication & | |
+ | |authorization | | |
+ | |<-------------| | |
+ |(iii)200 OK | | |
+ |<-------------| | |
+ : : : :
+ |(1) INVITE | :
+ |------------->|
+ | |(2) CCR (Initial, SIP specific AVP) |
+ | |------------------------------------------->|
+ | |(3) CCA (Granted-Units) |
+ | |<-------------------------------------------|
+ | |(4) INVITE | |
+ | |---------------------------->| |
+ : : : :
+ | |(5) CCR (update, Used-Units) |
+ | |------------------------------------------->|
+ | |(6) CCA (Granted-Units) |
+ | |<-------------------------------------------|
+ : : : :
+ |(7) BYE | | |
+ |------------->| | |
+ | |(8) BYE | |
+ | |---------------------------->| |
+ | |(9) CCR (termination, Used-Units) |
+ | |------------------------------------------->|
+ | |(10) CCA () |
+ | |<-------------------------------------------|
+ | | | |
+
+ Figure A.2: Flow II
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 96]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ This is an example of Diameter credit-control for SIP sessions.
+ Although the flow focuses on illustrating the usage of credit-control
+ messages, the SIP signaling is inaccurate, and the diagram is not by
+ any means an attempt to define a service provider's SIP network.
+ However, for the sake of this example, some assumptions are made
+ below.
+
+ Typically, prepaid services based, for example, on time usage for SIP
+ session require an entity in the service provider network to
+ intercept all the requests within the SIP dialog in order to detect
+ events, such as session establishment and session release, that are
+ essential to perform credit-control operations with the credit-
+ control server. Therefore, in this example, it is assumed that the
+ SIP Proxy adds a Record-Route header in the initial SIP INVITE to
+ make sure that all the future requests in the created dialog traverse
+ through it (for the definitions of 'Record-Route' and 'dialog' please
+ refer to [SIP]). Finally, the degree of credit-control measuring of
+ the media by the proxy depends on the business model design used in
+ setting up the end system and proxies in the SIP network.
+
+ The end user (SIP User Agent A) sends REGISTER with credentials (i).
+ The SIP Proxy sends a request to the home AAA server to perform
+ Multimedia authentication and authorization by using, for instance,
+ Diameter Multimedia application (ii). The home AAA server checks
+ that the credentials are correct and checks the user profile.
+ Eventually, 200 OK response (iii) is sent to the UA. Note that the
+ Authentication and Authorization is valid for the registration
+ validity period duration (i.e., until re-registration is performed).
+ Several SIP sessions may be established without re-authorization.
+
+ UA A sends an INVITE (1). The SIP Proxy sends a Diameter Credit-
+ Control-Request (INITIAL_REQUEST) to the Diameter credit-control
+ server (2). The Credit-Control-Request contains information obtained
+ from the SIP signaling describing the requested service (e.g.,
+ calling party, called party, Session Description Protocol
+ attributes). The Diameter credit-control server checks the end
+ user's account balance, rates the service, and reserves credit from
+ the end user's account. The reserved quota is returned to the SIP
+ Proxy in the Diameter Credit-Control-Answer (3). The SIP Proxy
+ forwards the SIP INVITE to UA B (4). B's phone rings, and B answers.
+ The media flows between them, and the SIP Proxy starts measuring the
+ quota. At the expiry of the allocated quota, the SIP Proxy sends a
+ Diameter Credit-Control-Request (UPDATE_REQUEST) to the Diameter
+ credit-control server (5). This message contains the units used thus
+ far. The Diameter credit-control server debits the used units from
+ the end user's account and allocates new credit that is returned to
+ the SIP Proxy in the Diameter Credit-Control-Answer (6). The end
+ user terminates the service by sending a BYE (7). The SIP Proxy
+
+
+
+Hakala, et al. Standards Track [Page 97]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ forwards the BYE message to UA B (8) and sends a Diameter Credit-
+ Control-Request (TERMINATION_REQUEST) to the credit-control server
+ (9). The Diameter credit-control server acknowledges the session
+ termination by sending a Diameter Credit-Control-Answer to the SIP
+ Proxy (10).
+
+A.3. Flow III
+
+ MMS Server
+ A (CC Client) B CC Server
+ |(1) Send MMS | | |
+ |--------------->| | |
+ | |(2) CCR (event, DIRECT_DEBITING,|
+ | | MMS specific AVP) |
+ | |-------------------------------->|
+ | |(3) CCA (Granted-Units) |
+ | |<--------------------------------|
+ |(4) Send MMS Ack| | |
+ |<---------------| | |
+ | |(5) Notify MMS | |
+ | |--------------->| |
+ : : : :
+ | |(6) Retrieve MMS| |
+ | |<---------------| |
+ | |(7) Retrieve MMS| |
+ | | Ack | |
+ | |--------------->| |
+ | | | |
+
+ Figure A.3: Flow III
+
+ A credit-control flow for Multimedia Messaging Services is shown in
+ Figure A.3. The sender is charged as soon as the messaging server
+ successfully stores the message.
+
+ The end user A sends a Multimedia Message (MMS) to the MMS server
+ (1). The MMS server stores the message and sends a Diameter Credit-
+ Control-Request (EVENT_REQUEST with Requested-Action DIRECT_DEBITING)
+ to the Diameter credit-control server (2). The Credit-Control-
+ Request contains information about the MMS message (e.g., size,
+ recipient address, image coding type). The Diameter credit-control
+ server checks the end user's account balance, rates the service, and
+ debits the service from the end user's account. The granted quota is
+ returned to the MMS server in the Diameter Credit-Control-Answer (3).
+ The MMS server acknowledges the successful reception of the MMS
+ message (4). The MMS Server notifies the recipient about the new MMS
+ (5), and end user B retrieves the message from the MMS message store
+ (6),(7).
+
+
+
+Hakala, et al. Standards Track [Page 98]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+A.4. Flow IV
+
+ MMS Server
+ Content Server (CC Client) B CC Server
+ |(1) Send MMS | | |
+ |--------------->| | |
+ | |(2) CCR (event, CHECK_BALANCE, |
+ | | MMS specific AVP) |
+ | |-------------------------------->|
+ | |(3) CCA (ENOUGH_CREDIT) |
+ | |<--------------------------------|
+ |(4) Send MMS Ack| | |
+ |<---------------| | |
+ | |(5) Notify MMS | |
+ | |--------------->| |
+ : : : :
+ | |(6) Retrieve MMS| |
+ | |<---------------| |
+ | |(7) CCR (event, DIRECT_DEBITING,|
+ | | MMS specific AVP) |
+ | |-------------------------------->|
+ | |(8) CCA (Granted-Units) |
+ | |<--------------------------------|
+ | |(9) Retrieve MMS| |
+ | | Ack | |
+ | |--------------->| |
+ | | | |
+
+ Figure A.4: Flow IV
+
+ This is an example of Diameter credit-control for direct debiting
+ using the Multimedia Messaging Service environment. Although the
+ flow focuses on illustrating the usage of credit-control messages,
+ the MMS signaling is inaccurate, and the diagram is not by any means
+ an attempt to define any service provider's MMS configuration or
+ billing model.
+
+ A credit-control flow for Multimedia Messaging Service is shown in
+ Figure A.4. The recipient is charged at the message delivery.
+
+ A content server sends a Multimedia Message (MMS) to the MMS server
+ (1) that stores the message. The message recipient will be charged
+ for the MMS message in this case. As there can be a substantially
+ long time between the receipt of the message at the MMS server and
+ the actual retrieval of the message, the MMS server does not
+ establish any credit-control session to the Diameter credit-control
+ server but performs first only a balance check (without any credit
+ reservation) by sending a Diameter Credit-Control-Request
+
+
+
+Hakala, et al. Standards Track [Page 99]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ (EVENT_REQUEST with Requested-Action CHECK_BALANCE) to verify that
+ end user B can cover the cost for the MMS (2). The Diameter credit-
+ control server checks the end user's account balance and returns the
+ answer to the MMS server in the Diameter Credit-Control-Answer (3).
+ The MMS server acknowledges the successful reception of the MMS
+ message (4). The MMS server notifies the recipient of the new MMS
+ (5), and after some time end user B retrieves the message from the
+ MMS message store (6). The MMS server sends a Diameter Credit-
+ Control-Request (EVENT_REQUEST with Requested-Action:
+ DIRECT_DEBITING) to the Diameter credit-control server (7). The
+ Credit-Control-Request contains information about the MMS message
+ (e.g., size, recipient address, coding type). The Diameter credit-
+ control server checks the end user's account balance, rates the
+ service, and debits the service from the end user's account. The
+ granted quota is returned to the MMS server in the Diameter Credit-
+ Control-Request (8). The MMS is transferred to end user B (9).
+
+ Note that the transfer of the MMS message can take an extended time
+ and can fail, in which case a recovery action is needed. The MMS
+ server should return the already debited units to the user's account
+ by using the REFUND action described in section 6.4.
+
+A.5. Flow V
+
+ SIP Controller
+ A (CC Client) B CC Server
+ |(1)INVITE B(SDP)| | |
+ |--------------->| | |
+ | |(2) CCR (event, PRICE_ENQUIRY, |
+ | | SIP specific AVPs) |
+ | |-------------------------------->|
+ | |(3) CCA (Cost-Information) |
+ | |<--------------------------------|
+ | (4)MESSAGE(URL)| | |
+ |<---------------| | |
+ |(5)HTTP GET | | |
+ |--------------->| | |
+ |(6)HTTP POST | | |
+ |--------------->|(7)INVITE(SDP) | |
+ | |--------------->| |
+ | | (8)200 OK | |
+ | (9)200 OK |<---------------| |
+ |<---------------| | |
+
+ Figure A.5: Flow V
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 100]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ This is an example of Diameter credit-control for SIP sessions.
+ Although the flow focuses on illustrating the usage of credit-control
+ messages, the SIP signaling is inaccurate, and the diagram is not by
+ any means an attempt to define a service provider's SIP network.
+
+ Figure A.5 is an example of Advice of Charge (AoC) service for SIP
+ call. User A can be either a postpaid or prepaid subscriber using
+ the AoC service. It is assumed that the SIP controller also has HTTP
+ capabilities and delivers an interactive AoC web page with, for
+ instance, the cost information, the details of the call derived from
+ the SDP, and a button to accept/not accept the charges. (There may
+ be many other ways to deliver AoC information; however, this flow
+ focuses on the use of the credit-control messages.) The user has
+ been authenticated and authorized prior to initiating the call and
+ subscribed to AoC service.
+
+ UA A sends an INVITE with SDP to B (1). The SIP controller
+ determines that the user is subscribed to AoC service and sends a
+ Diameter Credit-Control-Request (EVENT_REQUEST with Requested-Action:
+ PRICE_ENQUIRY) to the Diameter credit-control server (2). The
+ Credit-Control-Request contains SIP specific AVPs derived from the
+ SIP signaling, describing the requested service (e.g., calling party,
+ called party, Session Description Protocol attributes). The Diameter
+ credit-control server determines the cost of the service and returns
+ the Credit-Control-Answer including the Cost-Information AVP (3).
+ The SIP controller manufactures the AoC web page with information
+ received in SIP signaling and with the cost information received from
+ the credit-control server. Then it sends a SIP MESSAGE that contains
+ a URL pointing to the AoC information web page (4). At the receipt
+ of the SIP MESSAGE, A's UA automatically invokes the web browser that
+ retrieves the AoC information (5). The user clicks on a proper
+ button and accepts the charges (6). The SIP controller continues the
+ session and sends the INVITE to the B party, which accepts the call
+ (7,8,9).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 101]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+A.6. Flow VI
+
+ Gaming Server
+ End User (CC Client) CC Server
+ | (1)Service Delivery | |
+ |<---------------------->| |
+ : : :
+ : : :
+ | |(2)CCR(event,REFUND,Requested-
+ | |Service-Unit,Service-Parameter-Info)
+ | |----------------------->|
+ | | (3)CCA(Cost-Information)
+ | |<-----------------------|
+ | (4)Notification | |
+ |<-----------------------| |
+
+ Figure A.6: Flow VI
+
+ Figure A.6 illustrates a credit-control flow for the REFUND case. It
+ is assumed that there is a trusted relationship and secure connection
+ between the Gaming server and the Diameter credit-control server.
+ The end user may be a prepaid subscriber or a postpaid subscriber.
+
+ While the end user is playing the game (1), she enters a new level
+ that entitles her to a bonus. The Gaming server sends a Diameter
+ Credit-Control-Request (EVENT_REQUEST with Requested-Action:
+ REFUND_ACCOUNT) to the Diameter credit-control server (2). The
+ Credit-Control-Request Request contains the Requested-Service-Unit
+ AVP with the CC-Service-Specific-Units containing the number of
+ points the user just won. The Service-Parameter-Info AVP is also
+ included in the request and specifies the service event to be rated
+ (e.g., Tetris Bonus). From information received, the Diameter
+ credit-control server determines the amount to be credited, refunds
+ the user's account, and returns the Credit-Control-Answer, including
+ the Cost-Information AVP (3). The Cost-Information indicates the
+ credited amount. At the first opportunity, the Gaming server
+ notifies the end user of the credited amount (4).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 102]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+A.7. Flow VII
+
+ SIP Controller Top-Up
+ A (CC Client) Server B CC Server
+ | | | | |
+ | | (1) CCR(Update,Used-Unit) | |
+ | |------------------------------------------>|
+ | | (2) CCA(Final-Unit, Redirect)|
+ | |<------------------------------------------|
+ : : : : :
+ : : : : :
+ | | (3) CCR(Update, Used-Units)| |
+ | |------------------------------------------>|
+ | | (3a)INVITE("hold") | |
+ | |--------------------------->| |
+ | | | (4) CCA(Validity-Time)|
+ | |<------------------------------------------|
+ | (5)INVITE | (6)INVITE | | |
+ |<--------------|------------->| | |
+ | (7)RTP | | |
+ |..............................| | |
+ | | (8)BYE | | |
+ | |<-------------| | |
+ | | (9)CCR(Update) | |
+ | |------------------------------------------>|
+ | | (10)CCA(Granted-Unit) |
+ | |<------------------------------------------|
+ | (12)INVITE | (11)INVITE | |
+ |<--------------|--------------------------->| |
+
+ Figure A.7: Flow VII
+
+ Figure A.7 is an example of the graceful service termination for a
+ SIP call. It is assumed that the call is set up so that the
+ controller is in the call as a B2BUA (Back to Back User Agent)
+ performing third-party call control (3PCC). Note that the SIP
+ signaling is inaccurate, as the focus of this flow is in the graceful
+ service termination and credit-control authorization. The best
+ practice for 3PCC is defined in [RFC3725].
+
+ The call is ongoing between users A and B; user A has a prepaid
+ subscription. At the expiry of the allocated quota, the SIP
+ controller sends a Diameter Credit-Control-Request (UPDATE_REQUEST)
+ to the Diameter credit-control server (1). This message contains the
+ units used thus far. The Diameter credit-control server debits the
+ used units from the end user's account and allocates the final quota
+ returned to the SIP controller in the Diameter Credit-Control-Answer
+ (2). This message contains the Final-Unit-Indication AVP with the
+
+
+
+Hakala, et al. Standards Track [Page 103]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Final-Unit-Action set to REDIRECT, the Redirect-Address-Type set to
+ SIP URI, and the Redirect-Server-Address set to the Top-up server
+ name (e.g., sip:[email protected]). At the expiry of the
+ final allocated quota, the SIP controller sends a Diameter Credit-
+ Control-Request (UPDATE_REQUEST) to the Diameter credit-control
+ server (3) and places the called party on "hold" by sending an INVITE
+ with the appropriate connection address in the SDP (3a). The
+ Credit-Control-Request message contains the units used thus far. The
+ Diameter credit-control server debits the used units from the end
+ user's account but does not make any credit reservation. The
+ Credit-Control-Answer message, which contains the Validity-Time to
+ supervise the graceful service termination, is returned to the SIP
+ controller (4). The SIP controller establishes a SIP session between
+ the prepaid user and the Top-up server (5, 6). The Top-up server
+ plays an announcement and prompts the user to enter a credit card
+ number and the amount of money to be used to replenish the account
+ (7). The Top-up server validates the credit card number and
+ replenishes the user's account (using some means outside the scope of
+ this specification) and releases the SIP session (8). The SIP
+ controller can now assume that communication between the prepaid user
+ and the Top-up server took place. It sends a spontaneous Credit-
+ Control-Request (UPDATE_REQUEST) to the Diameter credit-control
+ server to check whether the account has been replenished (9). The
+ Diameter credit-control server reserves credit from the end user's
+ account and returns the reserved quota to the SIP controller in the
+ Credit-Control-Answer (10). At this point, the SIP controller re-
+ connects the caller and the called party (11,12).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 104]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+A.8. Flow VIII
+
+ NAS Top-up CC
+ End-User (CC Client) AAA Server Server Server
+ |(1)User Logon |(2)AA Request (CC AVPs) | |
+ |------------------>|------------------->| | |
+ | | |(3)CCR(initial, CC AVPs)
+ | | |------------------->|
+ | | |(4)CCA(Final-Unit, |
+ | | | Validity-Time)|
+ | | |<-------------------|
+ | |(5)AA Answer(Final-Unit,Validity-Time) |
+ |(6)Limited Access |<-------------------| | |
+ | granted | | | |
+ |<----------------->| | | |
+ | | | | |
+ | (7)TCP/HTTP | (8)TCP/HTTP | |
+ |<----------------->|<----------------------------->| |
+ | (9) Replenish account | |
+ |<------------------------------------------------->| |
+ | | | (10)RAR |
+ | |<-------------------|<-------------------|
+ | | (11) RAA | |
+ | |------------------->|------------------->|
+ | |(12)CCR(update) | |
+ | |------------------->|(13)CCR(Update) |
+ | | |------------------->|
+ | | |(14)CCA(Granted-Units)
+ | |(15)CCA(Granted-Units)<------------------|
+ | |<-------------------| |
+
+ Figure A.8: Flow VIII
+
+ Figure A.8 is an example of the graceful service termination
+ initiated when the first interrogation takes place because the user's
+ account is empty. In this example, the credit-control server
+ supports the server-initiated credit re-authorization. The Diameter
+ [NASREQ] is implemented in the Network Access Server (NAS).
+
+ The user logs on to the network (1). The Diameter NAS sends a
+ Diameter AA-Request to the home Diameter AAA server. The credit-
+ control client populates the AAR with the Credit-Control AVP set to
+ CREDIT_AUTHORIZATION, and service specific AVPs are included, as
+ usual [NASREQ]. The home Diameter AAA server performs service
+ specific Authentication and Authorization, as usual. The home
+ Diameter AAA server determines that the user has a prepaid
+ subscription and notices from the Credit-Control AVP that the NAS has
+ credit-control capabilities. It sends a Diameter Credit-Control-
+
+
+
+Hakala, et al. Standards Track [Page 105]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Request with CC-Request-Type set to INITIAL_REQUEST to the Diameter
+ credit-control server to perform credit authorization (3) and to
+ establish a credit-control session. (The home Diameter AAA server
+ may forward service specific AVPs received from the NAS as input for
+ the rating process.) The Diameter credit-control server checks the
+ end user's account balance, determines that the account cannot cover
+ the cost of the service, and initiates the graceful service
+ termination. The Credit-Control-Answer is returned to the home
+ Diameter AAA server (4). This message contains the Final-Unit-
+ Indication AVP and the Validity-Time AVP set to a reasonable amount
+ of time to give the user a chance to replenish his/her account (e.g.,
+ 10 minutes). The Final-Unit-Indication AVP includes the Final-Unit-
+ Action set to REDIRECT, the Redirect-Address-Type set to URL, and the
+ Redirect-Server-Address set to the HTTP Top-up server name. The home
+ Diameter AAA server sends the received credit-control AVPs to the NAS
+ in the Diameter AA-Answer (5). Upon successful AAA, the NAS starts
+ the credit-control session and immediately starts the graceful
+ service termination, as instructed by the server. The NAS grants
+ limited access to the user (6). The HTTP client software running in
+ the user's device opens the transport connection redirected by the
+ NAS to the Top-up server (7,8). The user is displayed an appropriate
+ web page on which to enter the credit card number, and the amount of
+ money to be used to replenish the account, and with a notification
+ message that she is granted unlimited access if the replenishment
+ operation will be successfully executed within the next, for example,
+ 10 minutes. The Top-up server validates the credit card number and
+ replenishes the user's account (using some means outside the scope of
+ this specification)(9). After successful account top-up, the
+ credit-control server sends a Re-Auth-Request message to the NAS
+ (10). The NAS acknowledges the request by returning the Re-Auth-
+ Answer message (11) and initiates the credit re-authorization by
+ sending a Credit-Control-request (UPDATE_REQUEST) to the Diameter
+ credit-control server (12,13).
+
+ The Diameter credit-control server reserves credit from the end
+ user's account and returns the reserved quota to the NAS via the home
+ Diameter AAA server in the Credit-Control-Answer (14,15). The NAS
+ removes the restriction placed by the graceful service termination
+ and starts monitoring the granted units.
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 106]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+A.9. Flow IX
+
+ The Diameter credit-control application defines the Multiple-
+ Services-Credit-Control AVP that can be used to support independent
+ credit-control of multiple services in a single credit-control (sub-)
+ session for service elements that have such capabilities. It is
+ possible to request and allocate resources as a credit pool that is
+ shared between services or rating groups.
+
+ The flow example hereafter illustrates a usage scenario where the
+ credit-control client and server support independent credit-control
+ of multiple services, as defined in section 5.1.2. It is assumed
+ that Service-Identifiers, Rating-Groups, and their associated
+ parameters (e.g., IP 5-tuple) are locally configured in the service
+ element or provisioned by an entity other than the credit-control
+ server.
+
+ End User Service Element CC Server
+ (CC client)
+ |(1)User logon | |
+ |------------------>|(2)CCR(initial, Service-Id access, |
+ | | Access specific AVPs, |
+ | | Multiple-Service-Indicator) |
+ | |---------------------------------------->|
+ | |(3)CCA(Multiple-Services-CC ( |
+ | | Granted-Units(Total-Octets), |
+ | | Service-Id access, |
+ | | Validity-time, |
+ | | G-S-U-Pool-Reference(Pool-Id 1, |
+ | | Multiplier 10))) |
+ | |<----------------------------------------|
+ : : :
+ |(4)Service-Request (Service 1) |
+ |------------------>|(5)CCR(update, Multiple-Services-CC( |
+ | | Requested-Units(), Service-Id 1, |
+ | | Rating-Group 1)) |
+ | |---------------------------------------->|
+ | |(6)CCA(Multiple-Services-CC ( |
+ | | Granted-Units(Time), |
+ | | Rating-Group 1, |
+ | | G-S-U-Pool-Reference(Pool-Id 1, |
+ | | Multiplier 1))) |
+ | |<----------------------------------------|
+ : : :
+ |(7)Service-Request (Service 2) |
+ |------------------>| |
+
+
+
+
+
+Hakala, et al. Standards Track [Page 107]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ : : :
+ : : :
+ |(8)Service-Request (Service 3&4) |
+ |------------------>|(9)CCR(update, Multiple-Services-CC ( |
+ | | Requested-Units(), Service-Id 3, |
+ | | Rating-Group 2), |
+ | | Multiple-Services-CC ( |
+ | | Requested-Units(), Service-Id 4, |
+ | | Rating-Group 3)) |
+ | |---------------------------------------->|
+ | |(10)CCA(Multiple-Services-CC ( |
+ | | Granted-Units(Total-Octets), |
+ | | Service-Id 3, Rating-Group 2, |
+ | | Validity-time, |
+ | | G-S-U-Pool-Reference(Pool-Id 2, |
+ | | Multiplier 2)), |
+ | | Multiple-Services-CC ( |
+ | | Granted-Units(Total-Octets), |
+ | | Service-Id 4, Rating-Group 3 |
+ | | Validity-Time, |
+ | | Final-Unit-Ind.(Terminate), |
+ | | G-S-U-Pool-Reference(Pool-Id 2, |
+ | | Multiplier 5))) |
+ | |<----------------------------------------|
+ : : :
+ : : :
+ | +--------------+ | |
+ | |Validity time | |(11)CCR(update, |
+ | |expires for | | Multiple-Services-CC ( |
+ | |Service-Id | | Requested-Unit(), |
+ | | access | | Used-Units(In-Octets,Out-Octets),|
+ | +--------------+ | Service-Id access)) |
+ | |---------------------------------------->|
+ | |(12)CCA(Multiple-Services-CC ( |
+ | | Granted-Units(Total-Octets), |
+ | | Service-Id access, |
+ | | Validity-Time, |
+ | | G-S-U-Pool-Reference(Pool-Id 1, |
+ | | Multiplier 10))) |
+ | |<----------------------------------------|
+ : : :
+ : : :
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 108]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ | +--------------+ | |
+ | |Total Quota | |(13)CCR(update, |
+ | |elapses for | | Multiple-Services-CC ( |
+ | |pool 2: | | Requested-Unit(), |
+ | |service 4 not | | Used-Units(In-Octets,Out-Octets),|
+ | |allowed, | | Service-Id 3, Rating-group 2), |
+ | |service 3 cont| | Multiple-Services-CC ( |
+ | +--------------+ | Used-Units(In-Octets,Out-Octets),|
+ | | Service-Id 4, Rating-Group 3)) |
+ | |---------------------------------------->|
+ | |(14)CCA(Multiple-Services-CC ( |
+ | | Result-Code 4011, |
+ | | Service-Id 3)) |
+ | |<----------------------------------------|
+ : : :
+ : : :
+ |(15) User logoff | |
+ |------------------>|(16)CCR(term, |
+ | | Multiple-Services-CC ( |
+ | | Used-Units(In-Octets,Out-Octets),|
+ | | Service-Id access), |
+ | | Multiple-Services-CC ( |
+ | | Used-Units(Time), |
+ | | Service-Id 1, Rating-Group 1), |
+ | | Multiple-Services-CC ( |
+ | | Used-Units(Time), |
+ | | Service-Id 2, Rating-Group 1)) |
+ | |---------------------------------------->|
+ | |(17)CCA(term) |
+ | |<----------------------------------------|
+
+ Figure A.9: Flow example independent credit-control of multiple
+ services in a credit-control (sub-)Session
+
+ The user logs on to the network (1). The service element sends a
+ Diameter Credit-Control-Request with CC-Request-Type set to
+ INITIAL_REQUEST to the Diameter credit-control server to perform
+ credit authorization for the bearer service (e.g., Internet access
+ service) and to establish a credit-control session (2). In this
+ message, the credit-control client indicates support for independent
+ credit-control of multiple services within the session by including
+ the Multiple-Service-Indicator AVP. The Diameter credit-control
+ server checks the end user's account balance, with rating information
+ received from the client (i.e., Service-Id and access specific AVPs),
+ rates the request, and reserves credit from the end user's account.
+ Suppose that the server reserves $5 and determines that the cost is
+ $1/MB. It then returns to the service element a Credit-Control-
+ Answer message that includes the Multiple-Services-Credit-Control AVP
+
+
+
+Hakala, et al. Standards Track [Page 109]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ with a quota of 5MB associated to the Service-Id (access), to a
+ multiplier value of 10, and to the Pool-Id 1 (3).
+
+ The user uses Service 1 (4). The service element sends a Diameter
+ Credit-Control-Request with CC-Request-Type set to UPDATE_REQUEST to
+ the credit-control server to perform credit authorization for service
+ 1 (5). This message includes the Multiple-Services-Credit-Control
+ AVP to request service units for Service 1 that belong to Rating-
+ Group 1. The Diameter credit-control server determines that Service
+ 1 draws credit resources from the same account as the access service
+ (i.e., pool 1). It rates the request according to Service-
+ Id/Rating-Group and updates the existing reservation by requesting
+ more credit. Suppose that the server reserves $5 more (now the
+ reservation is $10) and determines that the cost is $0.1/minute. The
+ server authorizes the whole Rating-Group. It then returns to the
+ service element a Credit-Control-Answer message that includes the
+ Multiple-Services-Credit-Control AVP with a quota of 50min.
+ associated to the Rating-Group 1, to a multiplier value of 1, and to
+ the Pool-Id 1 (6). The client adjusts the total amount of resources
+ for pool 1 according the received quota, which gives S for Pool 1 =
+ 100.
+
+ The user uses Service 2, which belongs to the authorized Rating-
+ Group, 1 (7). Resources are then consumed from the pool 1.
+
+ The user now requests Services 3 and 4 as well, which are not
+ authorized (8). The service element sends a Diameter Credit-
+ Control-Request with CC-Request-Type set to UPDATE_REQUEST to the
+ credit-control server in order to perform credit authorization for
+ Services 3 and 4 (9). This message includes two instances of the
+ Multiple-Services-Credit-Control AVP to request service units for
+ Service 3 that belong to Rating-Group 2 and for Service 4 that belong
+ to Rating-Group 3. The Diameter credit-control server determines
+ that Services 3 and 4 draw credit resources from another account
+ (i.e., pool 2). It checks the end user's account balance and,
+ according to Service-Ids/Rating-Groups information, rates the
+ request. Then it reserves credit from pool 2.
+
+ For example, the server reserves $5 and determines that Service 3
+ costs $0.2/MB and Service 4 costs $0.5/MB. The server authorizes
+ only Services 3 and 4. It returns to the service element a Credit-
+ Control-Answer message that includes two instances of the Multiple-
+ Services-Credit-Control AVP (10). One instance grants a quota of
+ 12.5MB associated to the Service-Id 3 to a multiplier value of 2 and
+ to the Pool-Id 2. The other instance grants a quota of 5 MB
+ associated to the Service-Id 4 to a multiplier value of 5 and to the
+ Pool-Id 2.
+
+
+
+
+Hakala, et al. Standards Track [Page 110]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ The server also determines that pool 2 is exhausted and Service 4 is
+ not allowed to continue after these units will be consumed.
+ Therefore the Final-Unit-Indication AVP with action TERMINATE is
+ associated to the Service-Id 4. The client calculates the total
+ amount of resources that can be used for pool 2 according the
+ received quotas and multipliers, which gives S for Pool 2 = 50.
+
+ The Validity-Time for the access service expires. The service
+ element sends a Credit-Control-Request message to the server in order
+ to perform credit re-authorization for Service-Id (access) (11).
+ This message carries one instance of the Multiple-Services-Credit-
+ Control AVP that includes the units used by this service. Suppose
+ that the total amount of used units is 4MB. The client adjusts the
+ total amount of resources for pool 1 accordingly, which gives S for
+ Pool 1 = 60.
+
+ The server deducts $4 from the user's account and updates the
+ reservation by requesting more credit. Suppose that the server
+ reserves $5 more (now the reservation is $11) and already knows the
+ cost of the Service-Id (access), which is $1/MB. It then returns to
+ the service element a Credit-Control-Answer message that includes the
+ Multiple-Services-Credit-Control AVP with a quota of 5 MB associated
+ to the Service-Id (access), to a multiplier value of 10, and to the
+ Pool-Id 1 (12). The client adjusts the total amount of resources for
+ pool 1 according the received quota, which gives S for Pool 1 = 110.
+
+ Services 3 and 4 consume the total amount of pool 2 credit resources
+ (i.e., C1*2 + C2*5 >= S). The service element immediately starts the
+ TERMINATE action concerning Service 4 and sends a Credit-Control-
+ Request message with CC-Request-Type set to UPDATE_REQUEST to the
+ credit-control server in order to perform credit re-authorization for
+ Service 3 (13). This message contains two instances of the
+ Multiple-Services-Credit-Control AVP to report the units used by
+ Services 3 and 4. The server deducts the last $5 from the user's
+ account (pool 2) and returns the answer with Result-Code 4011 in the
+ Multiple-Services-Credit-Control AVP to indicate that Service 3 can
+ continue without credit-control (14).
+
+ The end user logs off from the network (15). To debit the used units
+ from the end user's account and to stop the credit-control session,
+ the service element sends a Diameter Credit-Control-Request with CC-
+ Request-Type set to TERMINATION_REQUEST to the credit-control server
+ (16). This message contains the units consumed by each of the used
+ services in multiple instances of the Multiple-Services-Credit-
+ Control AVP. The used units are associated with the relevant
+ Service-Identifier and Rating-Group. The Diameter credit-control
+
+
+
+
+
+Hakala, et al. Standards Track [Page 111]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ server debits the used units to the user's account (Pool 1) and
+ acknowledges the session termination by sending a Diameter Credit-
+ Control-Answer to the service element (17).
+
+Authors' Addresses
+
+ Harri Hakala
+ Oy L M Ericsson Ab
+ Joukahaisenkatu 1
+ 20520 Turku
+ Finland
+
+ Phone: +358 2 265 3722
+
+
+ Leena Mattila
+ Oy L M Ericsson Ab
+ Joukahaisenkatu 1
+ 20520 Turku
+ Finland
+
+ Phone: +358 2 265 3731
+
+
+ Juha-Pekka Koskinen
+ Nokia Networks
+ Hatanpaanvaltatie 30
+ 33100 Tampere
+ Finland
+
+ Phone: +358 7180 74027
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 112]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+ Marco Stura
+ Nokia Networks
+ Hiomotie 32
+ 00380 Helsinki
+ Finland
+
+ Phone: +358 7180 64308
+
+
+ John Loughney
+ Nokia Research Center
+ Itamerenkatu 11-13
+ 00180 Helsinki
+ Finland
+
+ Phone: +358 50 483 642
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 113]
+
+RFC 4006 Diameter Credit-Control Application August 2005
+
+
+Full Copyright Statement
+
+ Copyright (C) The Internet Society (2005).
+
+ This document is subject to the rights, licenses and restrictions
+ contained in BCP 78, and except as set forth therein, the authors
+ retain all their rights.
+
+ This document and the information contained herein are provided on an
+ "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS
+ OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET
+ ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED,
+ INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
+ INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED
+ WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+Intellectual Property
+
+ The IETF takes no position regarding the validity or scope of any
+ Intellectual Property Rights or other rights that might be claimed to
+ pertain to the implementation or use of the technology described in
+ this document or the extent to which any license under such rights
+ might or might not be available; nor does it represent that it has
+ made any independent effort to identify any such rights. Information
+ on the procedures with respect to rights in RFC documents can be
+ found in BCP 78 and BCP 79.
+
+ Copies of IPR disclosures made to the IETF Secretariat and any
+ assurances of licenses to be made available, or the result of an
+ attempt made to obtain a general license or permission for the use of
+ such proprietary rights by implementers or users of this
+ specification can be obtained from the IETF on-line IPR repository at
+ http://www.ietf.org/ipr.
+
+ The IETF invites any interested party to bring to its attention any
+ copyrights, patents or patent applications, or other proprietary
+ rights that may cover technology that may be required to implement
+ this standard. Please address the information to the IETF at ietf-
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+
+
+
+
+
+
+Hakala, et al. Standards Track [Page 114]
+
diff --git a/lib/diameter/doc/standard/rfc4072.txt b/lib/diameter/doc/standard/rfc4072.txt
new file mode 100644
index 0000000000..dd0b3a18ac
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc4072.txt
@@ -0,0 +1,1851 @@
+
+
+
+
+
+
+Network Working Group P. Eronen, Ed.
+Request for Comments: 4072 Nokia
+Category: Standards Track T. Hiller
+ Lucent Technologies
+ G. Zorn
+ Cisco Systems
+ August 2005
+
+
+ Diameter Extensible Authentication Protocol (EAP) Application
+
+Status of This Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The Internet Society (2005).
+
+Abstract
+
+ The Extensible Authentication Protocol (EAP) provides a standard
+ mechanism for support of various authentication methods. This
+ document defines the Command-Codes and AVPs necessary to carry EAP
+ packets between a Network Access Server (NAS) and a back-end
+ authentication server.
+
+Table of Contents
+
+ 1. Introduction ...................................................2
+ 1.1. Conventions Used in This Document ........................3
+ 2. Extensible Authentication Protocol Support in Diameter .........3
+ 2.1. Advertising Application Support ..........................3
+ 2.2. Protocol Overview ........................................4
+ 2.3. Sessions and NASREQ Interaction ..........................6
+ 2.3.1. Scenario 1: Direct Connection .....................7
+ 2.3.2. Scenario 2: Direct Connection with Redirects ......8
+ 2.3.3. Scenario 3: Direct EAP, Authorization via Agents ..9
+ 2.3.4. Scenario 4: Proxy Agents .........................10
+ 2.4. Invalid Packets .........................................10
+ 2.5. Retransmission ..........................................11
+ 2.6. Fragmentation ...........................................12
+ 2.7. Accounting ..............................................12
+ 2.8. Usage Guidelines ........................................13
+
+
+
+Eronen, et al. Standards Track [Page 1]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ 2.8.1. User-Name AVP ....................................13
+ 2.8.2. Conflicting AVPs .................................13
+ 2.8.3. Displayable Messages .............................14
+ 2.8.4. Role Reversal ....................................14
+ 2.8.5. Identifier Space .................................14
+ 3. Command-Codes .................................................14
+ 3.1. Diameter-EAP-Request (DER) Command ......................15
+ 3.2. Diameter-EAP-Answer (DEA) Command .......................16
+ 4. Attribute-Value Pairs .........................................18
+ 4.1. New AVPs ................................................18
+ 4.1.1. EAP-Payload AVP ..................................18
+ 4.1.2. EAP-Reissued-Payload AVP .........................18
+ 4.1.3. EAP-Master-Session-Key AVP .......................19
+ 4.1.4. EAP-Key-Name AVP .................................19
+ 4.1.5. Accounting-EAP-Auth-Method AVP ...................19
+ 5. AVP Occurrence Tables .........................................19
+ 5.1. EAP Command AVP Table ...................................20
+ 5.2. Accounting AVP Table ....................................21
+ 6. RADIUS/Diameter Interactions ..................................22
+ 6.1. RADIUS Request Forwarded as Diameter Request ............22
+ 6.2. Diameter Request Forwarded as RADIUS Request ............23
+ 6.3. Accounting Requests .....................................24
+ 7. IANA Considerations ...........................................24
+ 8. Security Considerations .......................................24
+ 8.1. Overview ................................................24
+ 8.2. AVP Editing .............................................26
+ 8.3. Negotiation Attacks .....................................27
+ 8.4. Session Key Distribution ................................28
+ 8.5. Privacy Issues ..........................................28
+ 8.6. Note about EAP and Impersonation ........................29
+ 9. Acknowledgements ..............................................29
+ 10. References ....................................................30
+ 10.1. Normative References ....................................30
+ 10.2. Informative References ..................................30
+
+1. Introduction
+
+ The Extensible Authentication Protocol (EAP), defined in [EAP], is an
+ authentication framework which supports multiple authentication
+ mechanisms. EAP may be used on dedicated links, switched circuits,
+ and wired as well as wireless links.
+
+ To date, EAP has been implemented with hosts and routers that connect
+ via switched circuits or dial-up lines using PPP [RFC1661], IEEE 802
+ wired switches [IEEE-802.1X], and IEEE 802.11 wireless access points
+ [IEEE-802.11i]. EAP has also been adopted for IPsec remote access in
+ IKEv2 [IKEv2].
+
+
+
+
+Eronen, et al. Standards Track [Page 2]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ This document specifies the Diameter EAP application that carries EAP
+ packets between a Network Access Server (NAS) working as an EAP
+ Authenticator and a back-end authentication server. The Diameter EAP
+ application is based on the Diameter Network Access Server
+ Application [NASREQ] and is intended for environments similar to
+ NASREQ.
+
+ In the Diameter EAP application, authentication occurs between the
+ EAP client and its home Diameter server. This end-to-end
+ authentication reduces the possibility for fraudulent authentication,
+ such as replay and man-in-the-middle attacks. End-to-end
+ authentication also provides a possibility for mutual authentication,
+ which is not possible with PAP and CHAP in a roaming PPP environment.
+
+ The Diameter EAP application relies heavily on [NASREQ], and in
+ earlier versions was part of the Diameter NASREQ application. It can
+ also be used in conjunction with NASREQ, selecting the application
+ based on the user authentication mechanism (EAP or PAP/CHAP). The
+ Diameter EAP application defines new Command-Codes and Attribute-
+ Value Pairs (AVPs), and can work together with RADIUS EAP support
+ [RFC3579].
+
+1.1. Conventions Used in This Document
+
+ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+ "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+ document are to be interpreted as described in [RFC2119].
+
+2. Extensible Authentication Protocol Support in Diameter
+
+2.1. Advertising Application Support
+
+ Diameter nodes conforming to this specification MUST advertise
+ support by including the Diameter EAP Application ID value of 5 in
+ the Auth-Application-Id AVP of the Capabilities-Exchange-Request and
+ Capabilities-Exchange-Answer command [BASE].
+
+ If the NAS receives a response with the Result-Code set to
+ DIAMETER_APPLICATION_UNSUPPORTED [BASE], it indicates that the
+ Diameter server in the home realm does not support EAP. If possible,
+ the access device MAY attempt to negotiate another authentication
+ protocol, such as PAP or CHAP. An access device SHOULD be cautious
+ when determining whether a less secure authentication protocol will
+ be used, since this could result from a downgrade attack (see
+ Section 8.3).
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 3]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+2.2. Protocol Overview
+
+ The EAP conversation between the authenticating peer and the access
+ device begins with the initiation of EAP within a link layer, such as
+ PPP [RFC1661] or IEEE 802.11i [IEEE-802.11i]. Once EAP has been
+ initiated, the access device will typically send a Diameter-EAP-
+ Request message with an empty EAP-Payload AVP to the Diameter server,
+ signifying an EAP-Start.
+
+ If the Diameter home server is willing to do EAP authentication, it
+ responds with a Diameter-EAP-Answer message containing an EAP-Payload
+ AVP that includes an encapsulated EAP packet. The Result-Code AVP in
+ the message will be set to DIAMETER_MULTI_ROUND_AUTH, signifying that
+ a subsequent request is expected. The EAP payload is forwarded by
+ the access device to the EAP client. This is illustrated in the
+ diagram below.
+
+ User NAS Server
+ | | |
+ | (initiate EAP) | |
+ |<------------------------------>| |
+ | | Diameter-EAP-Request |
+ | | EAP-Payload(EAP Start) |
+ | |------------------------------->|
+ | | |
+ | | Diameter-EAP-Answer |
+ | Result-Code=DIAMETER_MULTI_ROUND_AUTH |
+ | | EAP-Payload(EAP Request #1) |
+ | |<-------------------------------|
+ | EAP Request #1 | |
+ |<-------------------------------| |
+ : : :
+ : ...continues... :
+
+ The initial Diameter-EAP-Answer in a multi-round exchange normally
+ includes an EAP-Request/Identity, requesting the EAP client to
+ identify itself. Upon receipt of the EAP client's EAP-Response, the
+ access device will then issue a second Diameter-EAP-Request message,
+ with the client's EAP payload encapsulated within the EAP-Payload
+ AVP.
+
+ A preferred approach is for the access device to issue the
+ EAP-Request/Identity message to the EAP client, and forward the
+ EAP-Response/Identity packet, encapsulated within the EAP-Payload
+ AVP, as a Diameter-EAP-Request to the Diameter server (see the
+ diagram below). This alternative reduces the number of Diameter
+ message round trips. When the EAP-Request/Identity message is issued
+ by the access device, it SHOULD interpret the EAP-Response/Identity
+
+
+
+Eronen, et al. Standards Track [Page 4]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ packet returned by the authenticating peer, and copy its value to a
+ User-Name AVP in Diameter-EAP-Request. This is useful in roaming
+ environments, since the Destination-Realm is needed for routing
+ purposes. Note that this alternative cannot be universally employed,
+ as there are circumstances in which a user's identity is not needed
+ (such as when authorization occurs based on a calling or called phone
+ number).
+
+ User NAS Server
+ | | |
+ | (initiate EAP) | |
+ |<------------------------------>| |
+ | | |
+ | EAP Request(Identity) | |
+ |<-------------------------------| |
+ | | |
+ | EAP Response(Identity) | |
+ |------------------------------->| |
+ | | Diameter-EAP-Request |
+ | | EAP-Payload(EAP Response) |
+ | |------------------------------->|
+ : : :
+ : ...continues... :
+
+ The conversation continues until the Diameter server sends a
+ Diameter-EAP-Answer with a Result-Code AVP indicating success or
+ failure, and an optional EAP-Payload. The Result-Code AVP is used by
+ the access device to determine whether service is to be provided to
+ the EAP client. The access device MUST NOT rely on the contents of
+ the optional EAP-Payload to determine whether service is to be
+ provided.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 5]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ : ...continued... :
+ : : :
+ | EAP Response #N | |
+ |------------------------------->| |
+ | | Diameter-EAP-Request |
+ | | EAP-Payload(EAP Response #N) |
+ | |------------------------------->|
+ | | |
+ | | Diameter-EAP-Answer |
+ | | Result-Code=DIAMETER_SUCCESS |
+ | | EAP-Payload(EAP Success) |
+ | | [EAP-Master-Session-Key] |
+ | | (authorization AVPs) |
+ | |<-------------------------------|
+ | | |
+ | EAP Success | |
+ |<-------------------------------| |
+
+ If authorization was requested, a Diameter-EAP-Answer with
+ Result-Code set to DIAMETER_SUCCESS SHOULD also include the
+ appropriate authorization AVPs required for the service requested
+ (see Section 5 and [NASREQ]). In some cases, the home server may not
+ be able to provide all necessary authorization AVPs; in this case, a
+ separate authorization step MAY be used as described in
+ Section 2.3.3. Diameter-EAP-Answer messages whose Result-Code AVP is
+ set to DIAMETER_MULTI_ROUND_AUTH MAY include authorization AVPs.
+
+ A Diameter-EAP-Answer with successful Result-Code MAY also include an
+ EAP-Master-Session-Key AVP that contains keying material for
+ protecting the communication between the user and the NAS. Exactly
+ how this keying material is used depends on the link layer in
+ question, and is beyond the scope of this document.
+
+ A home Diameter server MAY request EAP re-authentication by issuing
+ the Re-Auth-Request [BASE] message to the Diameter client.
+
+ Should an EAP authentication session be interrupted due to a home
+ server failure, the session MAY be directed to an alternate server,
+ but the authentication session will have to be restarted from the
+ beginning.
+
+2.3. Sessions and NASREQ Interaction
+
+ The previous section introduced the basic protocol between the NAS
+ and the home server. Since the Diameter-EAP-Answer message may
+ include a Master Session Key (MSK) for protecting the communication
+ between the user and the NAS, one must ensure that this key does not
+ fall into wrong hands.
+
+
+
+Eronen, et al. Standards Track [Page 6]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ Basic Diameter security mechanisms (IPsec and TLS) protect Diameter
+ messages hop-by-hop. Since there are currently no end-to-end
+ (NAS-to-home server) security mechanisms defined for Diameter, this
+ section describes possible scenarios on how the messages could be
+ transport protected using these hop-by-hop mechanisms.
+
+ This list of scenarios is not intended to be exhaustive, and it is
+ possible to combine them. For instance, the first proxy agent after
+ the NAS could use redirects as in Scenario 2 to bypass any additional
+ proxy agents.
+
+2.3.1. Scenario 1: Direct Connection
+
+ The simplest case is when the NAS contacts the home server directly.
+ All authorization AVPs and EAP keying material are delivered by the
+ home server.
+
+ NAS home server
+ | |
+ | Diameter-EAP-Request |
+ | Auth-Request-Type=AUTHORIZE_AUTHENTICATE |
+ | EAP-Payload(EAP Start) |
+ |---------------------------------------------------------------->|
+ | |
+ | Diameter-EAP-Answer |
+ | Result-Code=DIAMETER_MULTI_ROUND_AUTH |
+ | EAP-Payload(EAP Request) |
+ |<----------------------------------------------------------------|
+ | |
+ : ...more EAP Request/Response pairs... :
+ | |
+ | Diameter-EAP-Request |
+ | EAP-Payload(EAP Response) |
+ |---------------------------------------------------------------->|
+ | |
+ | Diameter-EAP-Answer |
+ | Result-Code=DIAMETER_SUCCESS |
+ | EAP-Payload(EAP Success) |
+ | EAP-Master-Session-Key |
+ | (authorization AVPs) |
+ |<----------------------------------------------------------------|
+
+ This scenario is the most likely to be used in small networks, or in
+ cases where Diameter agents are not needed to provide routing or
+ additional authorization AVPs.
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 7]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+2.3.2. Scenario 2: Direct Connection with Redirects
+
+ In this scenario the NAS uses a redirect agent to locate the home
+ server. The rest of the session proceeds as before.
+
+ NAS Local redirect agent Home server
+ | | |
+ | Diameter-EAP-Request | |
+ | Auth-Request-Type=AUTHORIZE_AUTHENTICATE |
+ | EAP-Payload(EAP Start) | |
+ |------------------------------->| |
+ | | |
+ | Diameter-EAP-Answer |
+ | Redirect-Host=homeserver.example.com |
+ | Redirect-Host-Usage=REALM_AND_APPLICATION |
+ |<-------------------------------| |
+ | : |
+ | Diameter-EAP-Request : |
+ | Auth-Request-Type=AUTHORIZE_AUTHENTICATE |
+ | EAP-Payload(EAP Start) : |
+ |---------------------------------------------------------------->|
+ | : |
+ : ...rest of the session continues as in first case... :
+ : : :
+
+ The advantage of this scenario is that knowledge of realms and home
+ servers is centralized to a redirect agent, and it is not necessary
+ to modify the NAS configuration when, for example, a new roaming
+ agreement is made.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 8]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+2.3.3. Scenario 3: Direct EAP, Authorization via Agents
+
+ In this scenario the EAP authentication is done directly with the
+ home server (with Auth-Request-Type set to AUTHENTICATE_ONLY), and
+ authorization AVPs are retrieved from local proxy agents. This
+ scenario is intended for environments in which the home server cannot
+ provide all the necessary authorization AVPs to the NAS.
+
+ NAS Local proxy agent Home server
+ | : |
+ | Diameter-EAP-Request : |
+ | Auth-Request-Type=AUTHENTICATE_ONLY |
+ | EAP-Payload(EAP Start) : |
+ |---------------------------------------------------------------->|
+ | : |
+ | : Diameter-EAP-Answer |
+ | Result-Code=DIAMETER_MULTI_ROUND_AUTH |
+ | : EAP-Payload(EAP Request) |
+ |<----------------------------------------------------------------|
+ | : |
+ : ...more EAP Request/Response pairs... :
+ | : |
+ | Diameter-EAP-Request : |
+ | EAP-Payload(EAP Response) : |
+ |---------------------------------------------------------------->|
+ | : |
+ | : Diameter-EAP-Answer |
+ | : Result-Code=DIAMETER_SUCCESS |
+ | : EAP-Payload(EAP Success) |
+ | : EAP-Master-Session-Key |
+ | : (authorization AVPs) |
+ |<----------------------------------------------------------------|
+ | | |
+ | AA-Request | |
+ | Auth-Request-Type=AUTHORIZE_ONLY |
+ | (some AVPs from first session) | |
+ |------------------------------->| |
+ | | |
+ | AA-Answer | |
+ | Result-Code=DIAMETER_SUCCESS | |
+ | (authorization AVPs) | |
+ |<-------------------------------| |
+
+ The NASREQ application is used here for authorization because the
+ realm-specific routing table supports routing based on application,
+ not on Diameter commands.
+
+
+
+
+
+Eronen, et al. Standards Track [Page 9]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+2.3.4. Scenario 4: Proxy Agents
+
+ This scenario is the same as Scenario 1, but the NAS contacts the
+ home server through proxies. Note that the proxies can see the EAP
+ session keys, thus it is not suitable for environments where proxies
+ cannot be trusted.
+
+ NAS Local proxy/relay agent Home server
+ | | |
+ | Diameter-EAP-Request | |
+ | Auth-Request-Type=AUTHORIZE_AUTHENTICATE |
+ | EAP-Payload(EAP Start) | |
+ |------------------------------->|------------------------------->|
+ | | |
+ | | Diameter-EAP-Answer |
+ | Result-Code=DIAMETER_MULTI_ROUND_AUTH |
+ | | EAP-Payload(EAP Request) |
+ |<-------------------------------|<-------------------------------|
+ | : |
+ : ...more EAP Request/Response pairs... :
+ | : |
+ | Diameter-EAP-Request | |
+ | EAP-Payload(EAP Response) | |
+ |------------------------------->|------------------------------->|
+ | | |
+ | | Diameter-EAP-Answer |
+ | | Result-Code=DIAMETER_SUCCESS |
+ | | EAP-Payload(EAP Success) |
+ | | EAP-Master-Session-Key |
+ | | (authorization AVPs) |
+ |<-------------------------------|<-------------------------------|
+
+2.4. Invalid Packets
+
+ While acting as a pass-through, the NAS MUST validate the EAP header
+ fields (Code, Identifier, Length) prior to forwarding an EAP packet
+ to or from the Diameter server. On receiving an EAP packet from the
+ peer, the NAS checks the Code (Code 2=Response) and Length fields,
+ and matches the Identifier value against the current Identifier,
+ supplied by the Diameter server in the most recently validated EAP
+ Request. On receiving an EAP packet from the Diameter server
+ (encapsulated within a Diameter-EAP-Answer), the NAS checks the Code
+ (Code 1=Request) and Length fields, then updates the current
+ Identifier value. Pending EAP Responses that do not match the
+ current Identifier value are silently discarded by the NAS.
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 10]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ Since EAP method fields (Type, Type-Data) are typically not validated
+ by a NAS operating as a pass-through, despite these checks it is
+ possible for a NAS to forward an invalid EAP packet to or from the
+ Diameter server.
+
+ A Diameter server receiving an EAP-Payload AVP that it does not
+ understand SHOULD determine whether the error is fatal or non-fatal
+ based on the EAP Type. A Diameter server determining that a fatal
+ error has occurred MUST send a Diameter-EAP-Answer with a failure
+ Result-Code and an EAP-Payload AVP encapsulating an EAP Failure
+ packet. A Diameter server determining that a non-fatal error has
+ occurred MUST send a Diameter-EAP-Answer with
+ DIAMETER_MULTI_ROUND_AUTH Result-Code, but no EAP-Payload AVP. To
+ simplify RADIUS translation, this message MUST also include an
+ EAP-Reissued-Payload AVP encapsulating the previous EAP Request sent
+ by the server.
+
+ When receiving a Diameter-EAP-Answer without an EAP-Payload AVP (and
+ DIAMETER_MULTI_ROUND_AUTH Result-Code), the NAS SHOULD discard the
+ EAP-Response packet most recently transmitted to the Diameter server
+ and check whether additional EAP Response packets that match the
+ current Identifier value have been received. If so, a new EAP
+ Response packet, if available, MUST be sent to the Diameter server
+ within an Diameter-EAP-Request. If no EAP Response packet is
+ available, then the previous EAP Request is resent to the peer, and
+ the retransmission timer is reset.
+
+ In order to provide protection against Denial of Service (DoS)
+ attacks, it is advisable for the NAS to allocate a finite buffer for
+ EAP packets received from the peer, and to discard packets according
+ to an appropriate policy once that buffer has been exceeded. Also,
+ the Diameter server is advised to permit only a modest number of
+ invalid EAP packets within a single session, prior to terminating the
+ session with DIAMETER_AUTHENTICATION_REJECTED Result-Code. By
+ default, a value of 5 invalid EAP packets is recommended.
+
+2.5. Retransmission
+
+ As noted in [EAP], if an EAP packet is lost in transit between the
+ authenticating peer and the NAS (or vice versa), the NAS will
+ retransmit.
+
+ It may be necessary to adjust retransmission strategies and
+ authentication time-outs in certain cases. For example, when a token
+ card is used, additional time may be required to allow the user to
+ find the card and enter the token. Since the NAS will typically not
+ have knowledge of the required parameters, these need to be provided
+ by the Diameter server.
+
+
+
+Eronen, et al. Standards Track [Page 11]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ If a Multi-Round-Time-Out AVP [BASE] is present in a Diameter-EAP-
+ Answer message that also contains an EAP-Payload AVP, that value is
+ used to set the EAP retransmission timer for that EAP Request and
+ that Request alone.
+
+2.6. Fragmentation
+
+ Using the EAP-Payload AVP, it is possible for the Diameter server to
+ encapsulate an EAP packet that is larger than the MTU on the link
+ between the NAS and the peer. Since it is not possible for the
+ Diameter server to use MTU discovery to ascertain the link MTU, a
+ Framed-MTU AVP may be included in a Diameter-EAP-Request message in
+ order to provide the Diameter server with this information.
+
+ A Diameter server having received a Framed-MTU AVP in a
+ Diameter-EAP-Request message MUST NOT send any subsequent packet in
+ this EAP conversation containing EAP-Payload AVP whose length exceeds
+ that specified by the Framed-MTU value, taking the link type
+ (specified by the NAS-Port-Type AVP) into account. For example, as
+ noted in [RFC3580] Section 3.10, for a NAS-Port-Type value of IEEE
+ 802.11, the RADIUS server may send an EAP packet as large as
+ Framed-MTU minus four (4) octets, taking into account the additional
+ overhead for the IEEE 802.1X Version (1 octet), Type (1 octet) and
+ Body Length (2 octets) fields.
+
+2.7. Accounting
+
+ When a user is authenticated using EAP, the NAS MAY include an
+ Accounting-Auth-Method AVP [NASREQ] with value 5 (EAP) in
+ Accounting-Request messages. This document specifies one additional
+ AVP for accounting messages. One or more Accounting-EAP-Auth-Method
+ AVPs (see Section 4.1.5) MAY be included in Accounting-Request
+ messages to indicate the EAP method(s) used to authenticate the user.
+
+ If the NAS has authenticated the user with a locally implemented EAP
+ method, it knows the method used and SHOULD include it in an
+ Accounting-EAP-Auth-Method AVP.
+
+ If the authentication was done using Diameter-EAP-Request/Answer
+ messages, the Diameter server SHOULD include one or more
+ Accounting-EAP-Auth-Method AVPs in Diameter-EAP-Answer packets with a
+ successful result code. In this case, the NAS SHOULD include these
+ AVPs in Accounting-Request messages.
+
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 12]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+2.8. Usage Guidelines
+
+2.8.1. User-Name AVP
+
+ Unless the access device interprets the EAP-Response/Identity packet
+ returned by the authenticating peer, it will not have access to the
+ user's identity. Furthermore, some EAP methods support identity
+ protection where the user's real identity is not included in
+ EAP-Response/Identity. Therefore, the Diameter Server SHOULD return
+ the user's identity by inserting a User-Name AVP to
+ Diameter-EAP-Answer messages that have a Result-Code of
+ DIAMETER_SUCCESS. A separate billing identifier or pseudonym MAY be
+ used for privacy reasons (see Section 8.5). If the user's identity
+ is not available to the NAS, the Session-Id AVP MAY be used for
+ accounting and billing; however operationally this could be very
+ difficult to manage.
+
+2.8.2. Conflicting AVPs
+
+ A Diameter-EAP-Answer message containing an EAP-Payload of type
+ EAP-Success or EAP-Failure MUST NOT have the Result-Code AVP set to
+ DIAMETER_MULTI_ROUND_AUTH.
+
+ Some lower layers assume that the authorization decision is made by
+ the EAP server, and thus the peer considers EAP Success as an
+ indication that access was granted. In this case, the Result-Code
+ SHOULD match the contained EAP packet: a successful Result-Code for
+ EAP-Success, and a failure Result-Code for EAP-Failure. If the
+ encapsulated EAP packet does not match the result implied by the
+ Result-Code AVP, the combination is likely to cause confusion,
+ because the NAS and peer will conclude the outcome of the
+ authentication differently. For example, if the NAS receives a
+ failure Result-Code with an encapsulated EAP Success, it will not
+ grant access to the peer. However, on receiving the EAP Success, the
+ peer will be led to believe that access was granted.
+
+ This situation can be difficult to avoid when Diameter proxy agents
+ make authorization decisions (that is, proxies can change the
+ Result-Code AVP sent by the home server). Because it is the
+ responsibility of the Diameter server to avoid conflicts, the NAS
+ MUST NOT "manufacture" EAP result packets in order to correct the
+ contradictory messages that it receives. This behavior, originally
+ mandated within [IEEE-802.1X], is now deprecated.
+
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 13]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+2.8.3. Displayable Messages
+
+ The Reply-Message AVP [NASREQ] MUST NOT be included in any Diameter
+ message containing an EAP-Payload AVP.
+
+2.8.4. Role Reversal
+
+ Some environments in which EAP is used, such as PPP, support
+ peer-to-peer operation. Both parties act as authenticators and
+ authenticatees at the same time, in two simultaneous and independent
+ EAP conversations.
+
+ This specification is intended for communication between EAP
+ (passthrough) authenticator and backend authentication server. A
+ Diameter client MUST NOT send a Diameter-EAP-Request encapsulating an
+ EAP Request packet, and a Diameter server receiving such a packet
+ MUST respond with a failure Result-Code.
+
+2.8.5. Identifier Space
+
+ In EAP, each session has its own unique Identifier space. Diameter
+ server implementations MUST be able to distinguish between EAP
+ packets with the same Identifier existing within distinct EAP
+ sessions and originating on the same NAS. This is done by using the
+ Session-Id AVP.
+
+ If a Diameter NAS is in the middle of a multi-round authentication
+ exchange, and it detects that the EAP session between the client and
+ the NAS has been terminated, it MUST select a new Diameter Session-Id
+ for any subsequent EAP sessions. This is necessary in order to
+ distinguish a restarted EAP authentication process from the
+ continuation of an ongoing process (by the same user on the same NAS
+ and port).
+
+ In RADIUS, the same functionality can be achieved through the
+ inclusion or omission of the State attribute. Translation rules in
+ [NASREQ] ensure that an Access-Request without the State attribute
+ maps to a new Diameter Session-Id AVP value. Furthermore, a
+ translation agent will always include a State attribute in
+ Access-Challenge messages, making sure that the State attribute is
+ available for a RADIUS NAS.
+
+3. Command-Codes
+
+ This section defines new Command-Code values that MUST be supported
+ by all Diameter implementations conforming to this specification.
+ The following commands are defined in this section:
+
+
+
+
+Eronen, et al. Standards Track [Page 14]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ Command-Name Abbrev. Code Reference
+ --------------------------------------------------------
+ Diameter-EAP-Request DER 268 3.1
+ Diameter-EAP-Answer DEA 268 3.2
+
+ When the NASREQ AA-Request (AAR) or AA-Answer (AAA) commands are used
+ for AUTHORIZE_ONLY messages in conjunction with EAP (see
+ Section 2.3.3), an Application Identifier value of 1 (NASREQ) is
+ used, and the commands follow the rules and ABNF defined in [NASREQ].
+
+ When the Re-Auth-Request (RAR), Re-Auth-Answer (RAA),
+ Session-Termination-Request (STR), Session-Termination-Answer (STA),
+ Abort-Session-Request (ASR), Abort-Session-Answer (ASA),
+ Accounting-Request (ACR), and Accounting-Answer (ACA) commands are
+ used together with the Diameter EAP application, they follow the
+ rules in [NASREQ] and [BASE]. The accounting commands use
+ Application Identifier value of 3 (Diameter Base Accounting); the
+ others use 0 (Diameter Common Messages).
+
+3.1. Diameter-EAP-Request (DER) Command
+
+ The Diameter-EAP-Request (DER) command, indicated by the Command-Code
+ field set to 268 and the 'R' bit set in the Command Flags field, is
+ sent by a Diameter client to a Diameter server, and conveys an
+ EAP-Response from the EAP client. The Diameter-EAP-Request MUST
+ contain one EAP-Payload AVP containing the actual EAP payload. An
+ EAP-Payload AVP with no data MAY be sent to the Diameter server to
+ initiate an EAP authentication session.
+
+ The DER message MAY be the result of a multi-round authentication
+ exchange that occurs when the DEA is received with the Result-Code
+ AVP set to DIAMETER_MULTI_ROUND_AUTH [BASE]. A subsequent DER
+ message MUST include any State AVPs [NASREQ] that were present in the
+ DEA. For re-authentication, it is recommended that the Identity
+ request be skipped in order to reduce the number of authentication
+ round trips. This is only possible when the user's identity is
+ already known by the home Diameter server.
+
+ Message format
+
+ <Diameter-EAP-Request> ::= < Diameter Header: 268, REQ, PXY >
+ < Session-Id >
+ { Auth-Application-Id }
+ { Origin-Host }
+ { Origin-Realm }
+ { Destination-Realm }
+ { Auth-Request-Type }
+ [ Destination-Host ]
+
+
+
+Eronen, et al. Standards Track [Page 15]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ [ NAS-Identifier ]
+ [ NAS-IP-Address ]
+ [ NAS-IPv6-Address ]
+ [ NAS-Port ]
+ [ NAS-Port-Id ]
+ [ NAS-Port-Type ]
+ [ Origin-State-Id ]
+ [ Port-Limit ]
+ [ User-Name ]
+ { EAP-Payload }
+ [ 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 ]
+
+3.2. Diameter-EAP-Answer (DEA) Command
+
+ The Diameter-EAP-Answer (DEA) message, indicated by the Command-Code
+ field set to 268 and the 'R' bit cleared in the Command Flags field,
+ is sent by the Diameter server to the client for one of the following
+ reasons:
+
+ 1. The message is part of a multi-round authentication exchange, and
+ the server is expecting a subsequent Diameter-EAP-Request. This
+ is indicated by setting the Result-Code to
+ DIAMETER_MULTI_ROUND_AUTH, and MAY include zero or more State
+ AVPs.
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 16]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ 2. The EAP client has been successfully authenticated and
+ authorized, in which case the message MUST include the
+ Result-Code AVP indicating success, and SHOULD include an
+ EAP-Payload of type EAP-Success. This event MUST cause the
+ access device to provide service to the EAP client.
+
+ 3. The EAP client has not been successfully authenticated and/or
+ authorized, and the Result-Code AVP is set to indicate failure.
+ This message SHOULD include an EAP-Payload, but this AVP is not
+ used to determine whether service is to be provided.
+
+ If the message from the Diameter client included a request for
+ authorization, a successful response MUST include the authorization
+ AVPs that are relevant to the service being provided.
+
+ Message format
+
+ <Diameter-EAP-Answer> ::= < 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 ]
+
+
+
+Eronen, et al. Standards Track [Page 17]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ [ 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 ]
+
+4. Attribute-Value Pairs
+
+ This section both defines new AVPs, unique to the EAP Diameter
+ application and describes the usage of AVPs defined elsewhere (if
+ that usage in the EAP application is noteworthy).
+
+4.1. New AVPs
+
+4.1.1. EAP-Payload AVP
+
+ The EAP-Payload AVP (AVP Code 462) is of type OctetString and is used
+ to encapsulate the actual EAP packet that is being exchanged between
+ the EAP client and the home Diameter server.
+
+4.1.2. EAP-Reissued-Payload AVP
+
+ The EAP-Reissued-Payload AVP (AVP Code 463) is of type OctetString.
+ The use of this AVP is described in Section 2.4.
+
+
+
+
+
+Eronen, et al. Standards Track [Page 18]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+4.1.3. EAP-Master-Session-Key AVP
+
+ The EAP-Master-Session-Key AVP (AVP Code 464) is of type OctetString.
+ It contains keying material for protecting the communications between
+ the user and the NAS. Exactly how this keying material is used
+ depends on the link layer in question, and is beyond the scope of
+ this document.
+
+4.1.4. EAP-Key-Name AVP
+
+ The EAP-Key-Name AVP (Radius Attribute Type 102) is of type
+ OctetString. It contains an opaque key identifier (name) generated
+ by the EAP method. Exactly how this name is used depends on the link
+ layer in question, and is beyond the scope of this document (see
+ [EAPKey] for more discussion).
+
+ Note that not all link layers use this name, and currently most EAP
+ methods do not generate it. Since the NAS operates in pass-through
+ mode, it cannot know the Key-Name before receiving it from the AAA
+ server. As a result, a Key-Name AVP sent in a Diameter-EAP-Request
+ MUST NOT contain any data. A home Diameter server receiving a
+ Diameter-EAP-Request with a Key-Name AVP with non-empty data MUST
+ silently discard the AVP. In addition, the home Diameter server
+ SHOULD include this AVP in Diameter-EAP-Response only if an empty
+ EAP-Key-Name AVP was present in Diameter-EAP-Request.
+
+4.1.5. Accounting-EAP-Auth-Method AVP
+
+ The Accounting-EAP-Auth-Method AVP (AVP Code 465) is of type
+ Unsigned64. In case of expanded types [EAP, Section 5.7], this AVP
+ contains the value ((Vendor-Id * 2^32) + Vendor-Type).
+
+ The use of this AVP is described in Section 2.7.
+
+5. AVP Occurrence Tables
+
+ The following tables use these 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
+ 0-1 Zero or one instance of the AVP MAY be present in the message
+ 1 One instance of the AVP MUST be present in the message
+
+ Note that AVPs that can only be present within a Grouped AVP are not
+ represented in these tables.
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 19]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+5.1. EAP Command AVP Table
+
+ The following table lists the AVPs that may be present in the DER and
+ DEA Commands, as defined in this document; the AVPs listed are
+ defined both here and in [NASREQ].
+
+ +---------------+
+ | Command-Code |
+ |-------+-------+
+ Attribute Name | DER | DEA |
+ ------------------------------------|-------+-------|
+ Accounting-EAP-Auth-Method | 0 | 0+ |
+ Acct-Interim-Interval [BASE] | 0 | 0-1 |
+ Auth-Application-Id [BASE] | 1 | 1 |
+ Auth-Grace-Period [BASE] | 0-1 | 0-1 |
+ Auth-Request-Type [BASE] | 1 | 1 |
+ Auth-Session-State [BASE] | 0-1 | 0-1 |
+ Authorization-Lifetime [BASE] | 0-1 | 0-1 |
+ Callback-Id [NASREQ] | 0 | 0-1 |
+ Callback-Number [NASREQ] | 0-1 | 0-1 |
+ Called-Station-Id [NASREQ] | 0-1 | 0 |
+ Calling-Station-Id [NASREQ] | 0-1 | 0 |
+ Class [BASE] | 0 | 0+ |
+ Configuration-Token [NASREQ] | 0 | 0+ |
+ Connect-Info [NASREQ] | 0-1 | 0 |
+ Destination-Host [BASE] | 0-1 | 0 |
+ Destination-Realm [BASE] | 1 | 0 |
+ EAP-Master-Session-Key | 0 | 0-1 |
+ EAP-Key-Name | 0-1 | 0-1 |
+ EAP-Payload | 1 | 0-1 |
+ EAP-Reissued-Payload | 0 | 0-1 |
+ Error-Message [BASE] | 0 | 0-1 |
+ Error-Reporting-Host [BASE] | 0 | 0-1 |
+ Failed-AVP [BASE] | 0 | 0+ |
+ Filter-Id [NASREQ] | 0 | 0+ |
+ Framed-Appletalk-Link [NASREQ] | 0 | 0-1 |
+ Framed-Appletalk-Network [NASREQ] | 0 | 0+ |
+ Framed-Appletalk-Zone [NASREQ] | 0 | 0-1 |
+ Framed-Compression [NASREQ] | 0+ | 0+ |
+ Framed-Interface-Id [NASREQ] | 0-1 | 0-1 |
+ Framed-IP-Address [NASREQ] | 0-1 | 0-1 |
+ Framed-IP-Netmask [NASREQ] | 0-1 | 0-1 |
+ Framed-IPv6-Prefix [NASREQ] | 0+ | 0+ |
+ Framed-IPv6-Pool [NASREQ] | 0 | 0-1 |
+ Framed-IPv6-Route [NASREQ] | 0 | 0+ |
+ Framed-IPX-Network [NASREQ] | 0 | 0-1 |
+ Framed-MTU [NASREQ] | 0-1 | 0-1 |
+ Framed-Pool [NASREQ] | 0 | 0-1 |
+
+
+
+Eronen, et al. Standards Track [Page 20]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ Framed-Protocol [NASREQ] | 0-1 | 0-1 |
+ Framed-Route [NASREQ] | 0 | 0+ |
+ Framed-Routing [NASREQ] | 0 | 0-1 |
+ Idle-Timeout [NASREQ] | 0 | 0-1 |
+ Multi-Round-Time-Out [BASE] | 0 | 0-1 |
+ NAS-Filter-Rule [NASREQ] | 0 | 0+ |
+ NAS-Identifier [NASREQ] | 0-1 | 0 |
+ NAS-IP-Address [NASREQ] | 0-1 | 0 |
+ NAS-IPv6-Address [NASREQ] | 0-1 | 0 |
+ NAS-Port [NASREQ] | 0-1 | 0 |
+ NAS-Port-Id [NASREQ] | 0-1 | 0 |
+ NAS-Port-Type [NASREQ] | 0-1 | 0 |
+ Originating-Line-Info [NASREQ] | 0-1 | 0 |
+ Origin-Host [BASE] | 1 | 1 |
+ Origin-Realm [BASE] | 1 | 1 |
+ Origin-State-Id [BASE] | 0-1 | 0-1 |
+ Port-Limit [NASREQ] | 0-1 | 0-1 |
+ Proxy-Info [BASE] | 0+ | 0+ |
+ QoS-Filter-Rule [NASREQ] | 0 | 0+ |
+ Re-Auth-Request-Type [BASE] | 0 | 0-1 |
+ Redirect-Host [BASE] | 0 | 0+ |
+ Redirect-Host-Usage [BASE] | 0 | 0-1 |
+ Redirect-Max-Cache-Time [BASE] | 0 | 0-1 |
+ Reply-Message [NASREQ] | 0 | 0+ |
+ Result-Code [BASE] | 0 | 1 |
+ Route-Record [BASE] | 0+ | 0+ |
+ Service-Type [NASREQ] | 0-1 | 0-1 |
+ Session-Id [BASE] | 1 | 1 |
+ Session-Timeout [BASE] | 0 | 0-1 |
+ State [NASREQ] | 0-1 | 0-1 |
+ Tunneling [NASREQ] | 0+ | 0+ |
+ User-Name [BASE] | 0-1 | 0-1 |
+
+5.2. Accounting AVP Table
+
+ The table in this section is used to represent which AVPs defined in
+ this document are to be present in the Accounting messages, as
+ defined in [BASE].
+
+ +-----------+
+ | Command |
+ | Code |
+ |-----+-----+
+ Attribute Name | ACR | ACA |
+ ---------------------------------------|-----+-----+
+ Accounting-EAP-Auth-Method | 0+ | 0 |
+
+
+
+
+
+Eronen, et al. Standards Track [Page 21]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+6. RADIUS/Diameter Interactions
+
+ Section 9 of [NASREQ] describes basic guidelines for translation
+ agents that translate between RADIUS and Diameter protocols. These
+ guidelines SHOULD be followed for Diameter EAP application as well,
+ with some additional guidelines given in this section. Note that
+ this document does not restrict implementations from creating
+ additional methods, as long as the translation function does not
+ violate the RADIUS or the Diameter protocols.
+
+6.1. RADIUS Request Forwarded as Diameter Request
+
+ RADIUS Access-Request to Diameter-EAP-Request:
+
+ o RADIUS EAP-Message attribute(s) are translated to a Diameter
+ EAP-Payload AVP. If multiple RADIUS EAP-Message attributes are
+ present, they are concatenated and translated to a single Diameter
+ EAP-Payload AVP.
+
+ o An empty RADIUS EAP-Message attribute (with length 2) signifies
+ EAP-Start, and it is translated to an empty EAP-Payload AVP.
+
+ Diameter-EAP-Answer to RADIUS Access-Accept/Reject/Challenge:
+
+ o Diameter EAP-Payload AVP is translated to RADIUS EAP-Message
+ attribute(s). If necessary, the value is split into multiple
+ RADIUS EAP-Message attributes.
+
+ o Diameter EAP-Reissued-Payload AVP is translated to a message that
+ contains RADIUS EAP-Message attribute(s), and a RADIUS Error-Cause
+ attribute [RFC3576] with value 202 (decimal), "Invalid EAP Packet
+ (Ignored)" [RFC3579].
+
+ o As described in [NASREQ], if the Result-Code AVP set to
+ DIAMETER_MULTI_ROUND_AUTH and the Multi-Round-Time-Out AVP is
+ present, it is translated to the RADIUS Session-Timeout attribute.
+
+ o Diameter EAP-Master-Session-Key AVP can be translated to the
+ vendor-specific RADIUS MS-MPPE-Recv-Key and MS-MPPE-Send-Key
+ attributes [RFC2548]. The first up to 32 octets of the key is
+ stored into MS-MPPE-Recv-Key, and the next up to 32 octets (if
+ present) are stored into MS-MPPE-Send-Key. The encryption of this
+ attribute is described in [RFC2548].
+
+ o Diameter Accounting-EAP-Auth-Method AVPs, if present, are
+ discarded.
+
+
+
+
+
+Eronen, et al. Standards Track [Page 22]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+6.2. Diameter Request Forwarded as RADIUS Request
+
+ Diameter-EAP-Request to RADIUS Access-Request:
+
+ o The Diameter EAP-Payload AVP is translated to RADIUS EAP-Message
+ attribute(s).
+
+ o An empty Diameter EAP-Payload AVP signifies EAP-Start, and is
+ translated to an empty RADIUS EAP-Message attribute.
+
+ o The type (or expanded type) field from the EAP-Payload AVP can be
+ saved either in a local state table, or encoded in a RADIUS
+ Proxy-State attribute. This information is needed to construct an
+ Accounting-EAP-Auth-Method AVP for the answer message (see below).
+
+ RADIUS Access-Accept/Reject/Challenge to Diameter-EAP-Answer:
+
+ o If the RADIUS Access-Challenge message does not contain an
+ Error-Cause attribute [RFC3576] with value 202 (decimal), "Invalid
+ EAP Packet (Ignored)" [RFC3579], any RADIUS EAP-Message attributes
+ are translated to a Diameter EAP-Payload AVP, concatenating them
+ if multiple attributes are present.
+
+ o If the Error-Cause attribute with value 202 is present, any RADIUS
+ EAP-Message attributes are translated to a Diameter
+ EAP-Reissued-Payload AVP, concatenating them if multiple
+ attributes are present.
+
+ o As described in [NASREQ], if the Session-Timeout attribute is
+ present in a RADIUS Access-Challenge message, it is translated to
+ the Diameter Multi-Round-Time-Out AVP.
+
+ o If the vendor-specific RADIUS MS-MPPE-Recv-Key and/or
+ MS-MPPE-Send-Key attributes [RFC2548] are present, they can be
+ translated to a Diameter EAP-Master-Session-Key AVP. The
+ attributes have to be decrypted before conversion, and the Salt,
+ Key-Length and Padding sub-fields are discarded. The Key
+ sub-fields are concatenated (MS-MPPE-Recv-Key first,
+ MS-MPPE-Send-Key next), and the concatenated value is stored into
+ a Diameter EAP-Master-Session-Key AVP.
+
+ o If the Diameter-EAP-Answer will have a successful result code, the
+ saved state (see above) can be used to construct an
+ Accounting-EAP-Auth-Method AVP.
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 23]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+6.3. Accounting Requests
+
+ In Accounting-Requests, the vendor-specific RADIUS MS-Acct-EAP-Type
+ attribute [RFC2548] can be translated to a Diameter
+ Accounting-EAP-Auth-Method AVP, and vice versa.
+
+ When translating from Diameter to RADIUS, note that the
+ MS-Acct-EAP-Type attribute does not support expanded EAP types. Type
+ values greater than 255 should be translated to type 254.
+
+7. IANA Considerations
+
+ This document does not create any new namespaces to be maintained by
+ IANA, but it requires new values in namespaces that have been defined
+ in the Diameter Base protocol and RADIUS specifications.
+
+ o This document defines one new Diameter command (in Section 3)
+ whose Command Code is allocated from the Command Code namespace
+ defined in [BASE]. The Command Code for DER / DEA is 268.
+
+ o This document defines four new AVPs whose AVP Codes are allocated
+ from the AVP Code namespace defined in [BASE] as follows:
+
+ 462 for EAP-Payload (defined in Section 4.1.1),
+ 463 for EAP-Reissued-Payload (defined in Section 4.1.2),
+ 464 for EAP-Master-Session-Key (defined in Section 4.1.3), and
+ 465 for Accounting-EAP-Auth-Method (defined in Section 4.1.5).
+
+ o This document defines one new AVP (attribute) whose AVP Code
+ (Attribute Type) is to be allocated from the Attribute Type
+ namespace defined in [RFC2865] and [RFC3575]. The Radius
+ Attribute Type for EAP-Key-Name (defined in Section 4.1.4) is 102.
+
+ o This document defines one new Diameter application (in
+ Section 2.1) whose Application ID is to be allocated from the
+ Application Identifier namespace defined in [BASE]. The
+ Application ID for Diameter EAP is 5.
+
+8. Security Considerations
+
+8.1. Overview
+
+ Diameter peer-to-peer connections can be protected with IPsec or TLS.
+ These mechanisms are believed to provide sufficient protection under
+ the normal Internet threat model, that is, assuming the authorized
+ nodes engaging in the protocol have not been compromised, but the
+ attacker has complete control over the communication channels between
+ them. This includes eavesdropping, message modification, insertion,
+
+
+
+Eronen, et al. Standards Track [Page 24]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ man-in-the-middle and replay attacks. The details and related
+ security considerations are discussed in [BASE].
+
+ In addition to authentication provided by IPsec or TLS, authorization
+ is also required. Here, authorization means determining if a
+ Diameter message received from an authenticated Diameter peer should
+ be accepted (and not authorization of users requesting network access
+ from a NAS). In other words, when a Diameter server receives a
+ Diameter-EAP-Request, it has to decide if the client is authorized to
+ act as a NAS for the specific user, service type, and so on.
+ Correspondingly, when a NAS contacts a server to send a
+ Diameter-EAP-Request, it has to determine whether the server is
+ authorized to act as home server for the realm in question.
+
+ Authorization can involve local Access Control Lists (ACLs),
+ information contained in certificates, or some other means. See
+ [BASE] for more discussion and related security considerations. Note
+ that authorization issues are particularly relevant when Diameter
+ redirects are used. While redirection reduces the number of nodes
+ which have access to the contents of Diameter messages, a compromised
+ Diameter agent may not supply the right home server's address. If
+ the Diameter client is unable to tell whether this particular server
+ is authorized to act as the home server for this particular user, the
+ security of the communications rests on the redirect agent.
+
+ The hop-by-hop security mechanisms (IPsec and TLS) combined with
+ proper authorization provide good protection against "outside"
+ attackers, except for denial-of-service attacks. The remaining part
+ of this section deals with attacks by nodes that have been properly
+ authorized (to function as a NAS, Diameter agent, or Diameter
+ server), but abuse their authorization or have been compromised. In
+ general, it is not possible to completely protect against attacks by
+ compromised nodes, but this section offers advice on limiting the
+ extent of the damage.
+
+ Attacks involving eavesdropping or modification of EAP messages are
+ beyond the scope of these document. See [EAP] for discussion of
+ these security considerations (including method negotiation,
+ dictionary attacks, and privacy issues). While these attacks can be
+ carried out by an attacker between the client and the NAS,
+ compromised NASes and Diameter agents are naturally also in a good
+ position to modify and eavesdrop on the EAP messages.
+
+ Similarly, attacks involving the link layer protocol used between the
+ client and the NAS, such as PPP or IEEE 802.11, are beyond the scope
+ of this document.
+
+
+
+
+
+Eronen, et al. Standards Track [Page 25]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+8.2. AVP Editing
+
+ Diameter agents can modify, insert, and delete AVPs. Diameter agents
+ are usually meant to modify AVPs, and the protocol cannot distinguish
+ well-intentioned and malicious modifications (see [RFC2607] for more
+ discussion). Similarly, a compromised NAS or server can naturally
+ include a different set of AVPs than expected.
+
+ Therefore, the question is what an attacker who compromises an
+ authorized NAS, agent, or server can do using Diameter EAP messages.
+ Some of the consequences are rather obvious. For instance, a
+ Diameter agent can give access to unauthorized users by changing the
+ Result-Code to DIAMETER_SUCCESS. Other consequences are less obvious
+ and are discussed below and authentication method negotiation attacks
+ are discussed in the next section.
+
+ By including suitable AVPs in an AA-Answer/Diameter-EAP-Answer
+ messages, an attacker may be able (depending on implementation and
+ configuration details) to:
+
+ o Give unauthorized users access, or deny access to authorized users
+ (Result-Code).
+
+ o Give an attacker a login session to a host otherwise protected by
+ firewalls, or redirect an authorized user's login session to a
+ host controlled by the attacker (Login-Host).
+
+ o Route an authorized user's traffic through a host controlled by
+ the attacker (various tunneling AVPs).
+
+ o Redirect an authorized user's DNS requests to a malicious DNS
+ server (various vendor-specific AVPs).
+
+ o Modify routing tables at the NAS and thus redirect packets
+ destined for someone else (Framed-Route, Framed-Routing).
+
+ o Remove packet filters and other restrictions for user (Filter,
+ Callback, various vendor-specific AVPs).
+
+ o Cause the NAS to call some number, possibly an expensive toll
+ number controlled by the attacker (callback AVPs).
+
+ o Execute Command Line Interface (CLI) commands on the NAS (various
+ vendor-specific attributes).
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 26]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ By modifying an AA-Request/Diameter-EAP-Request, an attacker may be
+ able to:
+
+ o Change NAS-Identifier/NAS-Port/Origin-Host (or another attribute)
+ so that a valid user appears to be accessing the network from a
+ different NAS than in reality.
+
+ o Modify Calling-Station-ID (either to hide the true value, gain
+ access, or frame someone else).
+
+ o Modify password change messages (some vendor-specific attributes).
+
+ o Modify usage information in accounting messages.
+
+ o Modify contents of Class and State AVPs.
+
+ Some of these attacks can be prevented if the NAS or server is
+ configured to not accept some particular AVPs, or accepts them only
+ from some nodes.
+
+8.3. Negotiation Attacks
+
+ This section deals with attacks where the NAS, any Diameter agents,
+ or Diameter server attempt to cause the authenticating user to choose
+ some authentication method other than EAP, such as PAP or CHAP
+ (negotiation attacks within EAP are discussed in [EAP], Section 7.8).
+
+ The vulnerability can be mitigated via implementation of a per-
+ connection policy by the authenticating peer, and a per-user policy
+ by the Diameter server. For the authenticating peer, the
+ authentication policy should be set on a per-connection basis.
+
+ With a per-connection policy, an authenticating peer will only
+ attempt to negotiate EAP for a session in which EAP support is
+ expected. As a result, it is presumed that an authenticating peer
+ selecting EAP requires that level of security. If it cannot be
+ provided, there is likely a misconfiguration, or the authenticating
+ peer may be contacting the wrong server. In this case, the
+ authenticating peer simply disconnects.
+
+ Similarly, with a per-user policy, the home server will not accept
+ authentication methods other than EAP for users for which EAP support
+ is expected.
+
+ For a NAS, it may not be possible to determine whether a peer is
+ required to authenticate with EAP until the peer's identity is known.
+ For example, for shared-uses NASes one reseller may implement EAP
+ while another does not. Alternatively, some peer might be
+
+
+
+Eronen, et al. Standards Track [Page 27]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ authenticated locally by the NAS while other peers are authenticated
+ via Diameter. In such cases, if any peers of the NAS MUST do EAP,
+ then the NAS MUST attempt to negotiate EAP for every session. This
+ avoids forcing a peer to support more than one authentication type,
+ which could weaken security.
+
+8.4. Session Key Distribution
+
+ Since there are currently no end-to-end (NAS-to-home server) security
+ mechanisms specified for Diameter, any agents that process
+ Diameter-EAP-Answer messages can see the contents of the
+ EAP-Master-Session-Key AVP. For this reason, this specification
+ strongly recommends avoiding Diameter agents when they cannot be
+ trusted to keep the keys secret.
+
+ In environments where agents are present, several factors should be
+ considered when deciding whether the agents that are authorized (and
+ considered "trustworthy enough") to grant access to users and specify
+ various authorization and tunneling AVPs are also "trustworthy
+ enough" to handle the session keys. These factors include (but are
+ not limited to) the type of access provided (e.g., public Internet or
+ corporate internet), security level of the agents, and the
+ possibilities for attacking user's traffic after it has been
+ decrypted by the NAS.
+
+ Note that the keys communicated in Diameter messages are usually
+ short-term session keys (or short-term master keys that are used to
+ derive session keys). To actually cause any damage, those session
+ keys must end up with some malicious party that must be able to
+ eavesdrop, modify, or insert traffic between the user and the NAS
+ during the lifetime of those keys (for example, in 802.11i the
+ attacker must also eavesdrop the "four-way handshake").
+
+8.5. Privacy Issues
+
+ Diameter messages can contain AVPs that can be used to identify the
+ user (e.g., User-Name) and approximate location of the user (e.g.,
+ Origin-Host for WLAN access points, Calling-Station-Id for fixed
+ phone lines). Thus, any Diameter nodes that process the messages may
+ be able to determine the geographic location of users.
+
+ Note that in many cases, the user identity is also sent in clear
+ inside EAP-Payload AVPs, and it may be possible to eavesdrop this
+ between the user and the NAS.
+
+ This can be mitigated somewhat by using EAP methods that provide
+ identity protection (see [EAP], Section 7.3), and using Session-Id or
+ pseudonyms for accounting.
+
+
+
+Eronen, et al. Standards Track [Page 28]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+8.6. Note about EAP and Impersonation
+
+ If the EAP method used does not provide mutual authentication,
+ obviously anyone can impersonate the network to the user. Even when
+ EAP mutual authentication is used, it occurs between the user and the
+ Diameter home server. See [EAPKey] for an extensive discussion about
+ the details and their implications.
+
+ One issue is worth pointing out here. As described in [EAPKey], the
+ current EAP architecture does not allow the home server to restrict
+ what service parameters or identities (such as SSID or BSSID in
+ 802.11 wireless LANs) are advertised by the NAS to the client. That
+ is, a compromised NAS can change its BSSID or SSID, and thus appear
+ to offer a different service than intended. Even if these parameters
+ are included in Diameter-EAP-Answer messages, the NAS can tell
+ different values to the client.
+
+ Therefore, the NAS's possession of the session keys proves that the
+ user is talking to an authorized NAS, but a compromised NAS can lie
+ about its exact identity. See [EAPKey] for discussion on how
+ individual EAP methods can provide authentication of NAS service
+ parameters and identities.
+
+ Note that the usefulness of this authentication may be rather limited
+ in many environments. For instance, in wireless LANs the user does
+ not usually securely know the identity (such as BSSID) of the "right"
+ access point; it is simply picked from a beacon message that has the
+ correct SSID and good signal strength (something that is easy to
+ spoof). Thus, simply authenticating the identity may not allow the
+ user to distinguish the "right" access point from all others.
+
+9. Acknowledgements
+
+ This Diameter application relies heavily on earlier work on Diameter
+ NASREQ application [NASREQ] and RADIUS EAP support [RFC3579]. Much
+ of the material in this specification has been copied from these
+ documents.
+
+ The authors would also like to acknowledge the following people for
+ their contributions to this document: Bernard Aboba, Jari Arkko,
+ Julien Bournelle, Pat Calhoun, Henry Haverinen, John Loughney,
+ Yoshihiro Ohba, and Joseph Salowey.
+
+
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 29]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+10. References
+
+10.1. Normative References
+
+ [BASE] Calhoun, P., Loughney, J., Guttman, E., Zorn, G., and
+ J. Arkko, "Diameter Base Protocol", RFC 3588,
+ September 2003.
+
+ [EAP] Aboba, B., Blunk, L., Vollbrecht, J., Carlson, J., and
+ H. Levkowetz, "Extensible Authentication Protocol
+ (EAP)", RFC 3748, June 2004.
+
+ [NASREQ] Calhoun, P., Zorn, G., Spence, D., and D. Mitton,
+ "Diameter Network Access Server Application", RFC
+ 4005, August 2005.
+
+ [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+10.2. Informative References
+
+ [EAPKey] Aboba, B., Simon, D., Arkko, J., Eronen, P., and H.
+ Levkowetz, "Extensible Authentication Protocol (EAP)
+ Key Management Framework", Work in Progress, July
+ 2004.
+
+ [IEEE-802.1X] Institute of Electrical and Electronics Engineers,
+ "Local and Metropolitan Area Networks: Port-Based
+ Network Access Control", IEEE Standard 802.1X,
+ September 2001.
+
+ [IEEE-802.11i] Institute of Electrical and Electronics Engineers,
+ "IEEE Standard for Information technology -
+ Telecommunications and information exchange between
+ systems - Local and metropolitan area networks -
+ Specific requirements - Part 11: Wireless Medium
+ Access Control (MAC) and Physical Layer (PHY)
+ Specifications: Amendment 6: Medium Access Control
+ (MAC) Security Enhancements", IEEE Standard
+ 802.11i-2004, July 2004.
+
+ [IKEv2] Kaufman, C., Ed., "Internet Key Exchange (IKEv2)
+ Protocol", Work in Progress, June 2004.
+
+ [RFC1661] Simpson, W., "The Point-to-Point Protocol (PPP)",
+ STD 51, RFC 1661, July 1994.
+
+
+
+
+
+Eronen, et al. Standards Track [Page 30]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+ [RFC2548] Zorn, G., "Microsoft Vendor-specific RADIUS
+ Attributes", RFC 2548, March 1999.
+
+ [RFC2607] Aboba, B. and J. Vollbrecht, "Proxy Chaining and
+ Policy Implementation in Roaming", RFC 2607,
+ June 1999.
+
+ [RFC2865] Rigney, C., Willens, S., Rubens, A., and W. Simpson,
+ "Remote Authentication Dial In User Service (RADIUS)",
+ RFC 2865, June 2000.
+
+ [RFC3575] Aboba, B., "IANA Considerations for RADIUS (Remote
+ Authentication Dial In User Service)", RFC 3575,
+ July 2003.
+
+ [RFC3576] Chiba, M., Dommety, G., Eklund, M., Mitton, D., and B.
+ Aboba, "Dynamic Authorization Extensions to Remote
+ Authentication Dial In User Service (RADIUS)",
+ RFC 3576, July 2003.
+
+ [RFC3579] Aboba, B. and P. Calhoun, "RADIUS (Remote
+ Authentication Dial In User Service) Support For
+ Extensible Authentication Protocol (EAP)", RFC 3579,
+ September 2003.
+
+ [RFC3580] Congdon, P., Aboba, B., Smith, A., Zorn, G., and J.
+ Roese, "IEEE 802.1X Remote Authentication Dial In User
+ Service (RADIUS) Usage Guidelines", RFC 3580,
+ September 2003.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 31]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+Authors' Addresses
+
+ Pasi Eronen (editor)
+ Nokia Research Center
+ P.O. Box 407
+ FIN-00045 Nokia Group
+ Finland
+
+
+
+ Tom Hiller
+ Lucent Technologies
+ 1960 Lucent Lane
+ Naperville, IL 60566
+ USA
+
+ Phone: +1 630 979 7673
+
+
+ Glen Zorn
+ Cisco Systems
+ 500 108th Avenue N.E., Suite 500
+ Bellevue, WA 98004
+ USA
+
+ Phone: +1 425 344 8113
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 32]
+
+RFC 4072 Diameter EAP Application August 2005
+
+
+Full Copyright Statement
+
+ Copyright (C) The Internet Society (2005).
+
+ This document is subject to the rights, licenses and restrictions
+ contained in BCP 78, and except as set forth therein, the authors
+ retain all their rights.
+
+ This document and the information contained herein are provided on an
+ "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS
+ OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET
+ ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED,
+ INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
+ INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED
+ WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+Intellectual Property
+
+ The IETF takes no position regarding the validity or scope of any
+ Intellectual Property Rights or other rights that might be claimed to
+ pertain to the implementation or use of the technology described in
+ this document or the extent to which any license under such rights
+ might or might not be available; nor does it represent that it has
+ made any independent effort to identify any such rights. Information
+ on the procedures with respect to rights in RFC documents can be
+ found in BCP 78 and BCP 79.
+
+ Copies of IPR disclosures made to the IETF Secretariat and any
+ assurances of licenses to be made available, or the result of an
+ attempt made to obtain a general license or permission for the use of
+ such proprietary rights by implementers or users of this
+ specification can be obtained from the IETF on-line IPR repository at
+ http://www.ietf.org/ipr.
+
+ The IETF invites any interested party to bring to its attention any
+ copyrights, patents or patent applications, or other proprietary
+ rights that may cover technology that may be required to implement
+ this standard. Please address the information to the IETF at ietf-
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+
+
+
+
+
+
+Eronen, et al. Standards Track [Page 33]
+
diff --git a/lib/diameter/doc/standard/rfc4740.txt b/lib/diameter/doc/standard/rfc4740.txt
new file mode 100644
index 0000000000..2154334b66
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc4740.txt
@@ -0,0 +1,4035 @@
+
+
+
+
+
+
+Network Working Group M. Garcia-Martin, Ed.
+Request for Comments: 4740 Nokia
+Category: Standards Track M. Belinchon
+ M. Pallares-Lopez
+ C. Canales-Valenzuela
+ Ericsson
+ K. Tammi
+ Nokia
+ November 2006
+
+
+ Diameter Session Initiation Protocol (SIP) Application
+
+Status of This Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The IETF Trust (2006).
+
+Abstract
+
+ This document specifies the Diameter Session Initiation Protocol
+ (SIP) application. This is a Diameter application that allows a
+ Diameter client to request authentication and authorization
+ information. This application is designed to be used in conjunction
+ with SIP and provides a Diameter client co-located with a SIP server,
+ with the ability to request the authentication of users and
+ authorization of SIP resources usage from a Diameter server.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 1]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+Table of Contents
+
+ 1. Introduction ....................................................4
+ 2. Terminology .....................................................5
+ 3. Definitions .....................................................5
+ 4. Acronyms ........................................................6
+ 5. Applicability Statement .........................................6
+ 6. Overview of Operation ...........................................7
+ 6.1. General Architecture .......................................7
+ 6.2. Diameter Server Authenticates the User .....................9
+ 6.3. Delegating Final Authentication Check to the SIP Server ...12
+ 6.4. SIP Server Requests Authentication and Authorization ......15
+ 6.5. Locating the Recipient of the SIP Request .................16
+ 6.6. Update of the User Profile ................................17
+ 6.7. SIP Soft State Termination ................................18
+ 6.8. Diameter Server Discovery .................................19
+ 7. Advertising Application Support ................................21
+ 8. Diameter SIP Application Command Codes .........................22
+ 8.1. User-Authorization-Request (UAR) Command ..................22
+ 8.2. User-Authorization-Answer (UAA) Command ...................23
+ 8.3. Server-Assignment-Request (SAR) Command ...................27
+ 8.4. Server-Assignment-Answer (SAA) Command ....................29
+ 8.5. Location-Info-Request (LIR) Command .......................33
+ 8.6. Location-Info-Answer (LIA) Command ........................33
+ 8.7. Multimedia-Auth-Request (MAR) Command .....................35
+ 8.8. Multimedia-Auth-Answer (MAA) Command ......................36
+ 8.9. Registration-Termination-Request (RTR) Command ............39
+ 8.10. Registration-Termination-Answer (RTA) Command ............39
+ 8.11. Push-Profile-Request (PPR) Command .......................41
+ 8.12. Push-Profile-Answer (PPA) Command ........................42
+ 9. Diameter SIP Application AVPs ..................................44
+ 9.1. SIP-Accounting-Information AVP ............................46
+ 9.1.1. SIP-Accounting-Server-URI AVP ......................47
+ 9.1.2. SIP-Credit-Control-Server-URI AVP ..................47
+ 9.2. SIP-Server-URI AVP ........................................47
+ 9.3. SIP-Server-Capabilities AVP ...............................47
+ 9.3.1. SIP-Mandatory-Capability AVP .......................48
+ 9.3.2. SIP-Optional-Capability AVP ........................48
+ 9.4. SIP-Server-Assignment-Type AVP ............................48
+ 9.5. SIP-Auth-Data-Item AVP ....................................50
+ 9.5.1. SIP-Authentication-Scheme AVP ......................50
+ 9.5.2. SIP-Item-Number AVP ................................51
+ 9.5.3. SIP-Authenticate AVP ...............................51
+ 9.5.4. SIP-Authorization AVP ..............................52
+ 9.5.5. SIP-Authentication-Info AVP ........................52
+ 9.5.6. Digest AVPs ........................................53
+ 9.6. SIP-Number-Auth-Items AVP .................................55
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 2]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ 9.7. SIP-Deregistration-Reason AVP .............................55
+ 9.7.1. SIP-Reason-Code AVP ................................55
+ 9.7.2. SIP-Reason-Info AVP ................................56
+ 9.8. SIP-AOR AVP ...............................................56
+ 9.9. SIP-Visited-Network-Id AVP ................................56
+ 9.10. SIP-User-Authorization-Type AVP ..........................56
+ 9.11. SIP-Supported-User-Data-Type AVP .........................57
+ 9.12. SIP-User-Data AVP ........................................57
+ 9.12.1. SIP-User-Data-Type AVP ............................58
+ 9.12.2. SIP-User-Data-Contents AVP ........................58
+ 9.13. SIP-User-Data-Already-Available AVP ......................58
+ 9.14. SIP-Method AVP ...........................................59
+ 10. New Values for Existing AVPs ..................................59
+ 10.1. Extension to the Result-Code AVP Values ..................59
+ 10.1.1. Success Result-Code AVP Values ....................59
+ 10.1.2. Transient Failures Result-Code AVP Values .........60
+ 10.1.3. Permanent Failures Result-Code AVP Values .........60
+ 11. Authentication Details ........................................61
+ 12. Migration from RADIUS .........................................63
+ 12.1. Gateway from RADIUS Client to Diameter Server ............63
+ 12.2. Gateway from Diameter Client to RADIUS Server ............63
+ 12.3. Known Limitations ........................................64
+ 13. IANA Considerations ...........................................64
+ 13.1. Application Identifier ...................................64
+ 13.2. Command Codes ............................................65
+ 13.3. AVP Codes ................................................65
+ 13.4. Additional Values for the Result-Code AVP Value ..........65
+ 13.5. Creation of the SIP-Server-Assignment-Type
+ Section in the AAA .......................................66
+ 13.6. Creation of the SIP-Authentication-Scheme Section
+ in the AAA ...............................................66
+ 13.7. Creation of the SIP-Reason-Code Section in the
+ AAA Registry .............................................66
+ 13.8. Creation of the SIP-User-Authorization-Type
+ Section in the AAA .......................................66
+ 13.9. Creation of the SIP-User-Data-Already-Available
+ Section in the ...........................................66
+ 14. Security Considerations .......................................67
+ 14.1. Final Authentication Check in the Diameter
+ Client/SIP Server ........................................67
+ 15. Contributors ..................................................68
+ 16. Acknowledgements ..............................................68
+ 17. References ....................................................68
+ 17.1. Normative References .....................................68
+ 17.2. Informative References ...................................69
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 3]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+1. Introduction
+
+ This document specifies the Diameter Session Initiation Protocol
+ (SIP) application. This is a Diameter application that allows a
+ Diameter client to request authentication and authorization
+ information to a Diameter server for SIP-based IP multimedia services
+ (see [RFC3261] about SIP). Furthermore, this Diameter SIP
+ application provides the Diameter client with functions that go
+ beyond the typical authorization and authentication, such as the
+ ability to download or receive updated user profiles, or rudimentary
+ routing functions that can assist a SIP server in finding another SIP
+ server allocated to the user.
+
+ We assume that the SIP server (such as SIP proxy server, registrar,
+ redirect server, or alike) and the Diameter client are co-located in
+ the same node, so that the SIP server is able to receive and process
+ SIP requests and responses. In turn, the SIP server relies on the
+ Authentication, Authorization, and Accounting (AAA) infrastructure
+ for authenticating the SIP request and authorizing the usage of
+ particular SIP services.
+
+ This document provides Diameter procedures to implement certain
+ required functionality when SIP is the protocol chosen to initiate
+ and tear down multimedia sessions or when SIP is used for other
+ non-session-related applications. However, this document does not
+ mandate any particular mapping of SIP procedures to Diameter SIP
+ application procedures, nor does it mandate any particular sequence
+ of events between SIP and Diameter. This document provides useful
+ examples to show the interaction between SIP and the Diameter SIP
+ application in order to achieve the desired functionality.
+
+ This application does not require and is not related to other
+ authentication services provided by the Diameter Mobile IPv4
+ [RFC4004] or the Diameter Network Access Server [RFC4005]
+ applications.
+
+ This Diameter SIP application is loosely related to the Diameter
+ credit-control application [RFC4006]. Although both applications are
+ independent, the Diameter SIP application is able to supply the
+ addresses of credit-control servers that will be implementing the
+ Diameter credit-control application [RFC4006].
+
+ Section 5 discusses assumptions and configurations assumed by this
+ document.
+
+ Section 6 provides the reader with informative descriptions of the
+ Diameter SIP application commands and responses and with some
+ guidance about their linkage with SIP procedures.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 4]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Advertisement of this application is specified in Section 7.
+
+ Section 8 provides a normative description of all the new Diameter
+ commands defined by this specification.
+
+ This application extends the Result-Code Attribute-Value-Pair (AVP)
+ with some new values. Further information is described in
+ Section 10.
+
+ This application defines some new AVPs. All these AVPs are described
+ in Section 9.
+
+ Some extra information about authentication is provided in
+ Section 11.
+
+2. Terminology
+
+ In this document, the key words "MUST", "MUST NOT", "REQUIRED",
+ "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT
+ RECOMMENDED", "MAY", and "OPTIONAL" are to be interpreted as
+ described in BCP 14, RFC 2119 [RFC2119] and indicate requirement
+ levels for compliant implementations.
+
+3. Definitions
+
+ For the purpose of this document, the following terms and definitions
+ apply:
+
+ Node: an addressable device attached to a computer network that
+ implements SIP functionality, Diameter functionality, or a
+ combination of both.
+
+ For the purpose of this document, the following terms and definitions
+ given in RFC 3261 [RFC3261] Section 6, apply:
+
+ o Address-of-Record (AOR)
+ o Outbound proxy
+ o Proxy
+ o Registrar
+ o Server (SIP server)
+ o User Agent (UA)
+ o User Agent Client (UAC)
+ o User Agent Server (UAS)
+
+ For the purpose of this document, the following terms and definitions
+ given in RFC 3588 [RFC3588] Section 1.3, apply:
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 5]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ o Authorization
+ o Authentication
+ o Attribute-Value Pair (AVP)
+ o Diameter Client
+ o Diameter Server
+ o Home Realm
+ o Redirect Agent
+ o User
+
+4. Acronyms
+
+ AKA: Authentication and Key Agreement
+ LIR: Location-Info-Request
+ LIA: Location-Info-Answer
+ MAR: Multimedia-Auth-Request
+ MAA: Multimedia-Auth-Answer
+ PPR: Push-Profile-Request
+ PPA: Push-Profile-Answer
+ RTR: Registration-Termination-Request
+ RTA: Registration-Termination-Answer
+ SAR: Server-Assignment-Request
+ SAA: Server-Assignment-Answer
+ SL: Subscriber Locator
+ UAR: User-Authorization-Request
+ UAA: User-Authorization-Answer
+
+5. Applicability Statement
+
+ This document assumes a general architecture where a Home Realm is
+ composed of one or more nodes implementing Diameter or SIP functions.
+ Users are issuing SIP requests to access SIP resources. For each
+ particular user, the Home Realm needs to authenticate and authorize
+ the usage of those resources and/or the route to the appropriate
+ node. We assume that the database containing the user-related data
+ is located outside the SIP node that requires authorization. Data
+ belonging to different users may be stored in different nodes in the
+ Home Realm, but we assume that all the data related to a particular
+ user is stored in a single node.
+
+ Note: Central to the architecture is the fact that the user data
+ is stored in a single point in the network. This restriction does
+ not mandate a particular implementation, e.g., it is possible to
+ implement clusters of databases operating in mirror mode to
+ provide redundancy. The property required by this specification
+ is that the user data the Diameter server has access to is stored
+ safely in what is seen, from the external point of view, as a
+ single user database.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 6]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ This document allows several configurations of the Home Realm. In
+ one configuration, a SIP server (proxy, registrar, etc.) is allocated
+ to a user for the purpose of triggering and executing services. The
+ allocation of the SIP server may be done dynamically, e.g., at the
+ time the user registers in the network. This configuration requires
+ a SIP server, typically located at the edge of the network, that is
+ able to allocate another SIP server for the user and that also
+ supports routing of SIP requests and responses towards that allocated
+ SIP server. Both SIP server nodes implement a Diameter client.
+
+ In another configuration, the address of a SIP outbound proxy is
+ configured (by means outside the scope of this specification) into
+ the SIP User Agent. The outbound Diameter client in the SIP outbound
+ proxy node authenticates the user, requests authorization for SIP
+ requests, and performs accounting activities.
+
+6. Overview of Operation
+
+ This section provides an informative description of how the Diameter
+ SIP application can be used together with SIP. This section is not
+ intended to mandate any specific usage of the Diameter SIP
+ application nor does it mandate a specific mapping between SIP and
+ Diameter messages. We provide a collection of examples that show how
+ the required AAA functionality can be achieved in conjunction with
+ SIP.
+
+6.1. General Architecture
+
+ The Diameter SIP application can be used in a SIP environment where
+ an interface to a AAA infrastructure is required to authenticate and
+ authorize the usage of SIP resources. This application provides
+ support for SIP User Agents and proxies that implement and use HTTP
+ Digest authentication [RFC2617], which is the authentication
+ mechanism mandated by SIP [RFC3261]. The application is extensible
+ and, if need arises, it can be extended to provide support for other
+ authentication mechanisms or extensions to HTTP Digest authentication
+ when they occur.
+
+ This application provides limited support for accounting services as
+ follows: the Diameter server is able to provide the addresses of
+ accounting severs to the Diameter client. Figure 1, below, shows a
+ general overview of the integration of the SIP architecture with the
+ AAA architecture.
+
+ According to Figure 1, there are one or more SIP User Agents (UAs)
+ that initiate or terminate SIP traffic through one or more SIP
+ servers. Both SIP servers implement a Diameter client that supports
+ the Diameter application described in this specification.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 7]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ +--------+
+ UAR/UAA +--->|Diameter|<----+ PPR/PPA
+ LIR/LIA | | server | | MAR/MAA
+ | +--------+ | SAR/SAA
+ | | RTR/RTA
+ | |
+ v v
+ +------+ SIP +--------+ SIP +--------+ SIP +------+
+ | SIP |<--------->| SIP |<-------->| SIP |<--------->| SIP |
+ | UA | |server 1| |server 2| | UA |
+ +------+ +--------+ +--------+ +------+
+ ^ ^
+ UAR/UAA | |
+ LIR/LIA | | MAR/MAA
+ | +--------+ | SAR/SAA
+ +--->|Diameter|<----+
+ | SL |
+ +--------+
+
+ Figure 1: Architecture of the Diameter application for SIP
+
+ In Figure 1, it can be seen that SIP server 1 sends different
+ Diameter commands and receives different responses than those sent
+ and received by SIP server 2. This is because SIP server 1 in
+ Figure 1 is located at the edge of a network, and its main task is to
+ locate SIP server 2. SIP server 2 is requesting and receiving
+ authentication and authorization data from the Diameter server and is
+ not located at the edge of the network.
+
+ This Diameter application assumes that all the data pertaining to a
+ given user is stored in a single Diameter server. For redundancy
+ purposes, several Diameter servers can be configured in a redundancy
+ fashion, in which case all of them keep the data synchronized and
+ operate externally as a single Diameter server.
+
+ With respect to SIP server 1 in Figure 1, the Diameter SIP
+ application provides support for the existence of a farm of these
+ servers, typically configured through one or more DNS records that
+ point to several hosts (this is a typical configuration in common SIP
+ deployments). There is no requirement for these types of servers to
+ keep state related to the Diameter SIP application.
+
+ The Diameter SIP application provides support for a feature that
+ allows an administrative domain to provide a collection of SIP
+ servers 2 (as per Figure 1). Once the user registers for the first
+ time, one of these SIP servers is selected and all the SIP requests
+ related to the user are processed by the same SIP server.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 8]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ The Diameter Subscriber Locator (SL) serves the purpose of locating
+ the Diameter server that contains the user-related data. Its
+ functionality is based on the Diameter redirect mechanism and is
+ further described in Section 6.8.
+
+ It should be noted that this document does not mandate any particular
+ SIP/AAA architecture. However, the Diameter SIP application provides
+ the functionality needed to accommodate all the different
+ architectures where SIP and Diameter are used.
+
+ The following subsections provide an informative overview of the
+ Diameter SIP application, its commands, and a possible interaction
+ with SIP signaling.
+
+6.2. Diameter Server Authenticates the User
+
+ This is the generic mechanism to authenticate users. In this
+ approach, we show an example of an administrative network where the
+ Diameter server is authenticating SIP user requests. This could be
+ the case of a medium-size network where the Diameter server is
+ keeping user records and authenticating SIP requests to perform a
+ certain transaction. We have chosen to show a SIP REGISTER request
+ in the example, but the SIP server could request authentication of
+ any other SIP request.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 9]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ +--------+ +--------+ +--------+
+ | SIP | |Diameter| | SIP |
+ |server 1| | server | |server 2|
+ +--------+ +--------+ +--------+
+ | | |
+ 1. SIP REGISTER | | |
+ -------------------->| 2. UAR | |
+ |------------------>| |
+ | 3. UAA | |
+ |<------------------| |
+ | 4. SIP REGISTER |
+ |-------------------------------------->|
+ | | 5. MAR |
+ | |<------------------|
+ | | 6. MAA |
+ | |------------------>|
+ | 7. SIP 401 (Unauthorized) |
+ 8. SIP 401 (Unauth.) |<--------------------------------------|
+ <--------------------| | |
+ 9. SIP REGISTER | | |
+ -------------------->| 10. UAR | |
+ |------------------>| |
+ | 11. UAA | |
+ |<------------------| |
+ | 12. SIP REGISTER |
+ |-------------------------------------->|
+ | | 13. MAR |
+ | |<------------------|
+ | | 14. MAA |
+ | |------------------>|
+ | 15. SIP 200 (OK) |
+ 16. SIP 200 (OK) |<--------------------------------------|
+ <--------------------| | |
+ | | 17. SAR |
+ | |<------------------|
+ | | 18. SAA |
+ | |------------------>|
+ | | |
+
+ Figure 2: Authentication performed in the Diameter server
+
+ According to Figure 2, a SIP User Agent Client (UAC) sends a SIP
+ REGISTER request (step 1) to SIP server 1, which receives the SIP
+ request. In Figure 2, we assume that this SIP server is located at
+ the edge of the administrative home domain. The Diameter client in
+ SIP server 1 contacts its Diameter server by sending a Diameter
+ User-Authorization-Request (UAR) message (step 2) to determine if
+ this user is allowed to receive service, and if so, request the
+
+
+
+Garcia-Martin, et al. Standards Track [Page 10]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ address of a local SIP server capable of handling this user. The
+ Diameter server answers with a Diameter User-Authorization-Answer
+ (UAA) message (step 3), which indicates a list of capabilities that
+ SIP server 1 may use to select an appropriate SIP server (SIP server
+ 2) and/or a SIP or SIPS URI pointing to SIP server 2.
+
+ SIP server 1 forwards the SIP REGISTER request (step 4) to an
+ appropriate SIP server (SIP server 2). Then the Diameter client in
+ SIP server 2 requests user authentication from the Diameter server by
+ sending a Diameter Multimedia-Auth-Request (MAR) message (step 5).
+ This request also serves to make the Diameter server aware of the SIP
+ or SIPS URI of SIP server 2, so as to return subsequent requests for
+ the same user to the same SIP server 2. The Diameter server responds
+ with a Diameter Multimedia-Auth-Answer (MAA) message (step 6) with
+ Result-Code AVP set to the value DIAMETER_MULTI_ROUND_AUTH. The
+ Diameter server also generates a nonce and includes a challenge in
+ the MAA message. SIP server 2 uses that challenge to map into the
+ WWW-Authenticate header in the SIP 401 (Unauthorized) response (step
+ 7), which is sent back to SIP server 1 and then to the SIP UAC (step
+ 8).
+
+ SIP server 1 receives a next SIP REGISTER request containing the user
+ credentials (step 9). Note that SIP server 1 does not need to keep a
+ state, and even more, there is no guarantee that the SIP request
+ arrives at the same SIP server 1; there could be a farm of SIP
+ servers 1 operating in redundant configuration. The Diameter client
+ in SIP server 1 contacts the Diameter server by sending a Diameter
+ UAR message (step 10) to determine the SIP server allocated to the
+ user. The Diameter server sends the SIP or SIPS URI of SIP server 2
+ in a Diameter UAA message (step 11).
+
+ Then SIP server 1 forwards the SIP REGISTER request to SIP server 2
+ (step 12). SIP server 2 extracts the credentials from the SIP
+ REGISTER request. The Diameter client in SIP server 2 sends those
+ credentials in a Diameter MAR message (step 13) to the Diameter
+ server. At this point, the Diameter server is able to authenticate
+ the user, and upon success, returns a Diameter MAA message (step 14)
+ with the AVP Result-Code set to the value DIAMETER_SUCCESS.
+
+ Then SIP server 2 generates a SIP 200 (OK) response (step 15), which
+ is forwarded to SIP server 1 and eventually to the SIP UAC (step 16).
+
+ If the Diameter client in SIP server 2 is interested in downloading
+ the user profile information or is required to store the address of
+ the SIP server in the Diameter server, then the Diameter client sends
+ a Diameter SAR message (step 17) to the Diameter server. The
+ Diameter server replies with a Diameter SAA message (step 18) that
+ contains the requested user profile information and the
+
+
+
+Garcia-Martin, et al. Standards Track [Page 11]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ acknowledgement of the SIP server address storage. These actions are
+ needed when the SIP server has to retrieve a user profile used to
+ provide services to the served user, or when the SIP server keeps a
+ state for the user, so the Diameter server needs to store the SIP
+ server's address.
+
+6.3. Delegating Final Authentication Check to the SIP Server
+
+ An operator with a large base of installed SIP servers may wish to
+ minimize the number of round-trips between the Diameter client and
+ the Diameter server. We provide support for a mechanism where the
+ Diameter server delegates the final authentication check to the SIP
+ server, thereby saving a round-trip. Section 14.1 discusses the
+ security considerations of this scenario.
+
+ It must noted that this scenario is not applicable when the Diameter
+ server is configured to use a session MD5 (MD5-sess) algorithm,
+ because the Diameter server requires the client nonce to compute the
+ H(A1) before sending it to the Diameter client. However, the client
+ nonce might not be available at that time.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 12]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ +--------+ +--------+ +--------+
+ | SIP | |Diameter| | SIP |
+ |server 1| | server | |server 2|
+ +--------+ +--------+ +--------+
+ | | |
+ 1. SIP REGISTER | | |
+ -------------------->| 2. UAR | |
+ |------------------>| |
+ | 3. UAA | |
+ |<------------------| |
+ | 4. SIP REGISTER |
+ |-------------------------------------->|
+ | | 5. MAR |
+ | |<------------------|
+ | | 6. MAA |
+ | |------------------>|
+ | 7. SIP 401 (Unauthorized) |
+ 8. SIP 401 (Unauth.) |<--------------------------------------|
+ <--------------------| | |
+ 9. SIP REGISTER | | |
+ -------------------->| 10. UAR | |
+ |------------------>| |
+ | 11. UAA | |
+ |<------------------| |
+ | 12. SIP REGISTER |
+ |-------------------------------------->|
+ | | 13. SAR |
+ | |<------------------|
+ | | 14. SAA |
+ | |------------------>|
+ | 15. SIP 200 (OK) |
+ 16. SIP 200 (OK) |<--------------------------------------|
+ <--------------------| | |
+ | | |
+
+ Figure 3: Delegation of authentication to the SIP server
+
+ Figure 3 shows an example where a SIP server is dynamically allocated
+ to serve a SIP User Agent with the support of the Diameter server.
+ This may be the case of certain architectures, such as that of the
+ 3rd Generation Partnership Project (3GPP) IP Multimedia Core Network
+ Subsystem.
+
+ A first SIP server receives a SIP REGISTER request (step 1) whose
+ target is the home network domain. In Figure 3, we assume that this
+ SIP server is located at the edge of the administrative home domain.
+ The Diameter client in this SIP server requests authorization from
+ the Diameter server to proceed with the registration, by sending a
+
+
+
+Garcia-Martin, et al. Standards Track [Page 13]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Diameter User-Authorization-Request (UAR) message (step 2). The
+ message includes, among other Attribute-Value-Pairs (AVPs), the SIP
+ Address-Of-Record (AOR) that is included in the SIP REGISTER request.
+ The Diameter server verifies the SIP AOR and, if it is a valid
+ defined user in the home network, authorizes the registration to
+ proceed. The Diameter server responds with a Diameter
+ User-Authorization-Answer (UAA) message (step 3), which informs the
+ Diameter client/SIP server about the result of the user
+ authorization. In case of a successful authorization, the Diameter
+ UAA message indicates the address of a local SIP server (SIP server 2
+ in Figure 3) and/or a list of capabilities that SIP server 1 may use
+ to select an appropriate SIP server 2.
+
+ When the authorization is successful, SIP server 1 forwards the SIP
+ REGISTER request (step 4) to the appropriate SIP server (SIP server
+ 2). The Diameter client in SIP server 2 requests authentication
+ parameters by sending a Diameter Multimedia-Auth-Request (MAR)
+ message (step 5) to the Diameter server. This request also makes the
+ Diameter server aware of the SIP or SIPS URI of SIP server 2, so as
+ to return subsequent requests of the same user to the same SIP server
+ 2. The Diameter server responds with a Diameter
+ Multimedia-Auth-Answer (MAA) message (step 6), which includes a nonce
+ and all the rest of the parameters necessary for the designated
+ authentication algorithm associated with the user. Among others, the
+ MAA message includes a Digest-HA1 AVP that contains H(A1) (as defined
+ in RFC 2617 [RFC2617]), and that allows the Diameter client to
+ calculate the expected response. Then the Diameter client can
+ compare this expected response with the response to the challenge
+ sent from the SIP UA. The absence of the Digest-HA1 AVP in MAA
+ indicates that authentication and authorization take place in the
+ Diameter server, as per the scenario described in Section 6.2.
+
+ SIP server 2 creates a SIP 401 (Unauthorized) SIP response (step 7)
+ based on the challenge included in the MAA message, including the
+ authentication material needed by the SIP User Agent Client (UAC) to
+ include the appropriate credentials. SIP server 1 forwards the SIP
+ response to the SIP UAC (step 8).
+
+ The SIP server 1 receives the next SIP REGISTER request containing
+ the user credentials (step 9). Because SIP server 1 does not need to
+ keep a state (and there is no guarantee that the SIP request arrives
+ to the same SIP server 1), the Diameter client in SIP server 1
+ contacts the Diameter server again by sending a Diameter UAR message
+ (step 10) to determine the SIP server allocated to the user. The
+ Diameter server sends the SIP or SIPS URI of SIP server 2 in a
+ Diameter UAA message (step 11).
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 14]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ SIP server 1 forwards the SIP REGISTER request to SIP server 2 (step
+ 12). SIP server 2 validates the credentials by comparing the
+ response supplied by the SIP UA with the expected response calculated
+ by the SIP server 2 (based on the H(A1) received from the Diameter
+ server).
+
+ If the credentials are valid, SIP server 2 sends a Diameter
+ Server-Assignment-Request (SAR) message (step 13) requesting the
+ Diameter server to confirm the completion of the authentication
+ procedure and to confirm the SIP or SIPS URI of the SIP server that
+ is currently serving the user. The Diameter SAR message also serves
+ the purpose of requesting that the Diameter server send the user
+ profile to the SIP server. The Diameter server responds with a
+ Diameter Server-Assignment-Answer (SAA) message (step 14). If the
+ Result-Code AVP value does not inform SIP Server 2 of an error, the
+ SAA message can include zero or more SIP-User-Data AVPs containing
+ the information that SIP server 2 needs in order to provide a service
+ to the user.
+
+ SIP server 2 generates a SIP 200 (OK) response (step 15), which is
+ forwarded to SIP server 1 and eventually to the SIP UAC (step 16).
+
+6.4. SIP Server Requests Authentication and Authorization
+
+ Figure 4 depicts a typical scenario where a stateless SIP proxy
+ requests authentication information and authorization to a Diameter
+ server, for the purpose of providing SIP routing services to a SIP
+ User Agent. The SIP proxy server may be configured as an outbound
+ SIP proxy, so that all the requests initiated by the SIP UA traverse
+ the SIP proxy.
+
+ According to Figure 4, a SIP User Agent sends a SIP request to its
+ outbound SIP proxy server. In this case, the message is a SIP INVITE
+ request (see step 1), but it could be any other SIP request. We
+ assume that this SIP request does not contain any credentials at this
+ time. The outbound SIP proxy server needs to authenticate and
+ authorize the proxy services offered to the user. The Diameter
+ client in the SIP server sends a Multimedia-Auth-Request (MAR)
+ message (step 2). The Diameter server generates a nonce and sends a
+ Multimedia-Auth-Answer (MAA) message (step 3) that includes the nonce
+ and the rest of the data necessary for the SIP server to challenge
+ the user, typically with HTTP Digest Authentication indicated in the
+ MAA message. This data enables the SIP server to create a SIP 407
+ (Proxy Authentication Required) response (step 4) that contains a
+ challenge. The SIP UA creates a new INVITE request (step 5) that
+ contains the credentials. The Diameter client in the SIP server
+ sends the credentials to the Diameter server in a new Diameter MAR
+ message (step 6). The Diameter server validates the credentials and
+
+
+
+Garcia-Martin, et al. Standards Track [Page 15]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ authorize the SIP transaction in a Diameter MAA message (step 7).
+ The SIP server forwards the SIP INVITE request to its destination
+ (step 8) as per regular SIP procedures. Eventually, the session
+ setup is confirmed with a SIP 200 (OK) response (step 9) that is
+ forwarded to the SIP UA (step 10). The session setup is complete.
+
+ +--------+ +--------+
+ |Diameter| | SIP |
+ | server | | server |
+ +--------+ +--------+
+ | |
+ | |
+ 1. SIP INVITE |
+ ----------------------------------->|
+ | 2. MAR |
+ |<------------------|
+ | 3. MAA |
+ |------------------>|
+ | |
+ 4. SIP 407 (Proxy |
+ Authentication Required) |
+ <-----------------------------------|
+ | |
+ 5. SIP INVITE |
+ ----------------------------------->|
+ | 6. MAR |
+ |<------------------|
+ | 7. MAA |
+ |------------------>| 8. SIP INVITE
+ | |---------------->
+ | | 9. SIP 200 (OK)
+ 10. SIP 200 (OK) |<----------------
+ <-----------------------------------|
+ | |
+
+ Figure 4: SIP server requests authorization
+
+6.5. Locating the Recipient of the SIP Request
+
+ Figure 5 shows the scenario where SIP server 1 may be configured as a
+ SIP edge proxy server, processing SIP traffic at the edge of a
+ network. SIP server 1 receives a SIP INVITE request (step 1). SIP
+ server 1 needs to find the address of SIP server 2, which is serving
+ the recipient of the SIP request. The Diameter client in SIP server
+ 1 sends a Diameter Location-Info-Request (LIR) message (step 2) to
+ the Diameter server. The Diameter server responds with a Diameter
+ Location-Info-Answer (LIA) message (step 3) that contains the SIP or
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 16]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ SIPS URI of SIP server 2. SIP server 1 then forwards the SIP INVITE
+ to SIP server 2 (step 4). SIP server 2 eventually forwards the SIP
+ INVITE to the appropriate UAS (step 5).
+
+ +--------+ +--------+ +--------+
+ | SIP | |Diameter| | SIP |
+ |server 1| | server | |server 2|
+ +--------+ +--------+ +--------+
+ | | |
+ 1. SIP INVITE | | |
+ -------------->| 2. LIR | |
+ |---------------->| |
+ | 3. LIA | |
+ |<----------------| |
+ | 4. SIP INVITE |
+ |--------------------------------->|
+ | | | 5. SIP INVITE
+ | | |-------------->
+ | | |
+ | | |
+
+ Figure 5: Locating the SIP server of the recipient
+
+ Although the example shows the connection between a SIP INVITE
+ request and the Diameter LIR message, any SIP request other than
+ REGISTER (such as SUBSCRIBE, OPTIONS, etc.) would trigger the same
+ Diameter message. (A SIP REGISTER request will trigger a Diameter
+ UAR message, as indicated in Figure 2 and Figure 3.)
+
+ The scenario described in this section is also applicable in case an
+ outbound SIP server is not interested in authenticating the user, but
+ is required to locate a further SIP server to route the outbound SIP
+ requests. In this case, the outbound SIP server is mapped to SIP
+ server 1 as shown in Figure 5.
+
+6.6. Update of the User Profile
+
+ The Diameter SIP application provides a mechanism for a Diameter
+ server to asynchronously download a user profile to a SIP server
+ whenever there is an update of such user profile. It must be noted
+ that the Diameter server also attaches the user profile to the
+ Diameter Server-Assignment-Answer (SAA) message. This is valid for
+ most of the daily situations; however, the administrator may decide
+ to update or modify the user profile for a particular user, due to,
+ e.g., new services made available to the user. This may involve
+ mechanisms outside the scope of this specification, such as human
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 17]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ intervention, in the Diameter server. In this situation, the
+ Diameter server is able to push the new user profile into the SIP
+ server allocated to the user.
+
+ The scenario is illustrated in Figure 6. When the user profile
+ changes, the Diameter server sends a Diameter Push-Profile-Request
+ (PPR) message (step 1) to the Diameter client in the SIP server
+ allocated to that user (SIP server 2 in the examples). The Diameter
+ PPR message contains one or more SIP-User-Data AVPs, a User-Name AVP
+ and zero or more SIP-AOR AVPs. The Diameter client in SIP server 2
+ acknowledges the Diameter PPR message by sending a Diameter
+ Push-Profile-Answer (PPA) message (step 2) to the Diameter server.
+
+ +--------+ +--------+
+ |Diameter| | SIP |
+ | server | |server 2|
+ +--------+ +--------+
+ | |
+ | 1. PPR |
+ |------------------>|
+ | |
+ | 2. PPA |
+ |<------------------|
+ | |
+
+ Figure 6: Diameter server pushes an update of the user profile
+
+6.7. SIP Soft State Termination
+
+ SIP can create soft states in SIP nodes based on events such as SIP
+ registrations or SIP event subscriptions. These states are
+ periodically refreshed, and cease to exist if they are not refreshed.
+ Additionally, an administrative action can be taken to terminate a
+ SIP soft state, or the SIP UA can explicitly terminate a SIP soft
+ state.
+
+ The Diameter base protocol offers a mechanism to create and delete
+ states in Diameter nodes. These states are called Diameter user
+ sessions. The Diameter server decides whether to use a Diameter user
+ session as a mechanism to map to a SIP soft state. If the Diameter
+ server decides to use Diameter user sessions, the termination of a
+ Diameter user session implies the termination of the corresponding
+ SIP soft state (e.g., registration, event subscription), and vice
+ versa. If the Diameter server does not use Diameter user sessions,
+ this Diameter SIP application offers specific commands to manage the
+ SIP soft states. Implementations compliant with this specification
+ MUST support both mechanisms of session management.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 18]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ We provide support for both Diameter client- and Diameter
+ server-initiated session termination. Depending on whether Diameter
+ sessions are used, termination of a SIP soft state can be achieved by
+ one of the following methods:
+
+ o When the Diameter client (SIP proxy) wants to terminate the SIP
+ soft state and Diameter user sessions are not maintained (i.e.,
+ the Auth-Session-State AVP has been previously set to
+ NO_STATE_MAINTAINED), the Diameter client MUST send a
+ Server-Assignment-Request (SAR) message with the
+ SIP-Server-Assignment-Type AVP (Section 9.4) set to any of the
+ deregistration values: TIMEOUT_DEREGISTRATION,
+ USER_DEREGISTRATION, TIMEOUT_DEREGISTRATION_STORE_SERVER_NAME,
+ USER_DEREGISTRATION_STORE_SERVER_NAME,
+ ADMINISTRATIVE_DEREGISTRATION, DEREGISTRATION_TOO_MUCH_DATA.
+
+ o When the Diameter client (SIP proxy) wants to terminate the SIP
+ soft state and Diameter user sessions are maintained (i.e., the
+ Auth-Session-State AVP has been previously set to
+ STATE_MAINTAINED), the Diameter client MUST send a Session-
+ Termination-Request (STR) message as per regular procedures
+ according to RFC 3588 [RFC3588].
+
+ o When the Diameter server wants to terminate the SIP soft state and
+ Diameter user sessions are not maintained (i.e., the
+ Auth-Session-State AVP has been previously set to
+ NO_STATE_MAINTAINED), the Diameter server MUST send a
+ Registration-Termination-Request (RTR) message (see Section 8.9).
+
+ o When the Diameter server wants to terminate the SIP soft state and
+ Diameter user sessions are maintained (i.e., the
+ Auth-Session-State AVP has been previously set to
+ STATE_MAINTAINED), the Diameter server MUST send an
+ Abort-Session-Request (ASR) message as per regular procedures
+ according to RFC 3588 [RFC3588].
+
+6.8. Diameter Server Discovery
+
+ The basic architecture assumption of this document is that all the
+ data related to a user is stored in a unique Diameter server.
+ Contrary to general opinion, this does not create a single point of
+ failure. It is assumed that Diameter servers are configured in a
+ redundant fashion in an attempt to mitigate the
+ single-point-of-failure problem.
+
+ In large networks, where the number of users may be significantly
+ high, there might be a need to scale the number of Diameter servers.
+ All the data associated with a user is still stored in one Diameter
+
+
+
+Garcia-Martin, et al. Standards Track [Page 19]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ server (typically, operating in a redundant configuration), but the
+ data associated with different users may reside in different Diameter
+ servers.
+
+ Although this configuration scales well, it introduces a new problem,
+ namely: given the user's SIP AOR as an input, how to determine which
+ of various Diameter servers is storing the data for that particular
+ SIP AOR. We solve this problem with inspiration from the Diameter
+ redirection mechanism specified in RFC 3588 [RFC3588]. We include in
+ the architecture a new Diameter node that, for the purpose of this
+ document, is known as Diameter Subscriber Locator (SL). The Diameter
+ SL contains a database or routing tables that map SIP AORs to
+ Diameter server URIs. A particular Diameter server URI points to the
+ actual Diameter server that stores all the data related to a
+ particular SIP AOR, and in consequence, to the user who owns the SIP
+ AOR. The Diameter SL acts in a similar way to a Diameter Redirect
+ Agent, dispatching Diameter requests (e.g., providing the redirection
+ URI in the answer). The Diameter SL can redirect all the request
+ pertaining to a user by setting the Redirect-Host-Usage AVP with a
+ value ALL_USER, as specified in RFC 3588 [RFC3588].
+
+ The Diameter SL can be replicated in different nodes along the
+ network, for the purpose of building scalability and redundancy. The
+ database or routing tables have to be consistent across all these
+ different Diameter SLs, so that equal Diameter requests will produce
+ equal Diameter answers, no matter which Diameter SL processes the
+ request.
+
+ +--------+ +--------+ +--------+ +--------+
+ | SIP | |Diameter| |Diameter| | SIP |
+ |server 1| |SL red. | |server 1| |server 2|
+ +--------+ +--------+ +--------+ +--------+
+ | | | |
+ 1. SIP INVITE| | | |
+ ------------>| 2. LIR | | |
+ |---------->| | |
+ | 3. LIA | | |
+ |<----------| | |
+ | 4. LIR | |
+ |---------------------->| |
+ | 5. LIA | |
+ |<----------------------| |
+ | 6. SIP INVITE | |
+ |----------------------------------->| 7. SIP INVITE
+ | | | | ------------->
+ | | | |
+
+ Figure 7: Locating a Diameter server. SL redirecting requests
+
+
+
+Garcia-Martin, et al. Standards Track [Page 20]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Figure 7 shows an example of operation of a Diameter SL acting in
+ redirect mode. SIP server 1 receives an INVITE request (step 1)
+ addressed (in the SIP Request-URI) to a user for which the Diameter
+ client in SIP server 1 does not possess routing information. In
+ other words, the Diameter client in SIP server 1 does not know the
+ URI of the Diameter server 1. The Diameter client sends a Diameter
+ LIR message (step 2) to any of the Diameter SLs configured in the
+ network. The address of those SLs is assumed to be pre-provisioned
+ in the Diameter client. The Diameter SL, based on the contents of
+ the SIP-AOR AVP and its own routing tables, determines the Diameter
+ server that stores the information allocated to such user. Then it
+ builds a Diameter LIA message (step 3) that includes a Result-Code
+ AVP set to DIAMETER_REDIRECT_INDICATION and one Redirect-Host AVP,
+ whose value is set to the URI of the Diameter server that stores the
+ information related to such user. Then the Diameter client in SIP
+ server 1 builds a new LIR message (step 4) addressed to the Diameter
+ server received in the Redirect-Host AVP. The rest of the procedure
+ is completed as described in previous sections.
+
+7. Advertising Application Support
+
+ Diameter implementations conforming to this specification MUST
+ advertise its support by including an Auth-Application-Id AVP in the
+ Capabilities-Exchange-Request (CER) and Capabilities-Exchange-Answer
+ (CEA) commands, according to the Diameter base protocol, RFC 3588
+ [RFC3588]. This Auth-Application-Id AVP MUST be set to the value of
+ this Diameter SIP application (Section 13.1 indicates the actual
+ value allocated by IANA).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 21]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+8. Diameter SIP Application Command Codes
+
+ All the Diameter implementations conforming to this specification
+ MUST implement and support the list of Diameter commands listed in
+ Table 1.
+
+ +-------------------------------------+-------+------+--------------+
+ | Command Name | Abbr. | Code | Reference |
+ +-------------------------------------+-------+------+--------------+
+ | User-Authorization-Request | UAR | 283 | Section 8.1 |
+ | User-Authorization-Answer | UAA | 283 | Section 8.2 |
+ | Server-Assignment-Request | SAR | 284 | Section 8.3 |
+ | Server-Assignment-Answer | SAA | 284 | Section 8.4 |
+ | Location-Info-Request | LIR | 285 | Section 8.5 |
+ | Location-Info-Answer | LIA | 285 | Section 8.6 |
+ | Multimedia-Auth-Request | MAR | 286 | Section 8.7 |
+ | Multimedia-Auth-Answer | MAA | 286 | Section 8.8 |
+ | Registration-Termination-Request | RTR | 287 | Section 8.9 |
+ | Registration-Termination-Answer | RTA | 287 | Section 8.10 |
+ | Push-Profile-Request | PPR | 288 | Section 8.11 |
+ | Push-Profile-Answer | PPA | 288 | Section 8.12 |
+ +-------------------------------------+-------+------+--------------+
+
+ Table 1: Defined command codes
+
+ Sections defining commands contain the Message Format for that
+ particular command. The Message Formats included in this document
+ are defined as per Section 3.2 of RFC 3588 [RFC3588].
+
+8.1. User-Authorization-Request (UAR) Command
+
+ The User-Authorization-Request (UAR) is indicated by the Command-Code
+ set to 283 and the Command Flags' 'R' bit set. The Diameter client
+ in a SIP server sends this command to the Diameter server to request
+ authorization for the SIP User Agent to route a SIP REGISTER request.
+ Because the SIP REGISTER request implicitly carries a permission to
+ bind an AOR to a contact address, the Diameter client uses the
+ Diameter UAR as a first authorization request towards the Diameter
+ server to authorize the registration. For instance, the Diameter
+ server can verify that the AOR is a legitimate user of the realm.
+
+ The Diameter client in the SIP server requests authorization for one
+ of the possible values defined in the SIP-User-Authorization-Type AVP
+ (Section 9.10).
+
+ The user name used for authentication of the user is conveyed in a
+ User-Name AVP (defined in the Diameter base protocol, RFC 3588
+ [RFC3588]). The location of the authentication user name in the SIP
+
+
+
+Garcia-Martin, et al. Standards Track [Page 22]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ REGISTER request varies depending on the authentication mechanism.
+ When the authentication mechanism is HTTP Digest as defined in RFC
+ 2617 [RFC2617], the authentication user name is found in the
+ "username" directive of the SIP Authorization header field value.
+ This Diameter SIP application only provides support for HTTP Digest
+ authentication in SIP; other authentication mechanisms are not
+ currently supported.
+
+ The SIP or SIPS URI to be registered is conveyed in the SIP-AOR AVP
+ (Section 9.8). Typically this SIP or SIPS URI is found in the To
+ header field value of the SIP REGISTER request that triggered the
+ Diameter UAR message.
+
+ The SIP-Visited-Network-Id AVP indicates the network that is
+ providing SIP services (e.g., SIP proxy functionality or any other
+ kind of services) to the SIP User Agent.
+
+ The Message Format of the UAR command is as follows:
+
+ <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) Command
+
+ The User-Authorization-Answer (UAA) is indicated by the Command-Code
+ set to 283 and the Command Flags' 'R' bit cleared. The Diameter
+ server sends this command in response to a previously received
+ Diameter User-Authorization-Request (UAR) command. The Diameter
+ server indicates the result of the requested registration
+ authorization. Additionally, the Diameter server may indicate a
+ collection of SIP capabilities that assists the Diameter client to
+ select a SIP proxy to the AOR under registration.
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 23]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ In addition to the values already defined in RFC 3588 [RFC3588], the
+ Result-Code AVP may contain one of the values defined in
+ Section 10.1.
+
+ Whenever the Diameter server fails to process the Diameter UAR
+ message, it MUST stop processing and return the relevant error in the
+ Diameter UAA message. When there is success in the process, the
+ Diameter server MUST set the code to DIAMETER_SUCCESS in the Diameter
+ UAA message.
+
+ If the Diameter server requires a User-Name AVP value to process the
+ Diameter UAR request, but the Diameter UAR message did not contain a
+ User-Name AVP value, the Diameter server MUST set the Result-Code AVP
+ value to DIAMETER_USER_NAME_REQUIRED (see Section 10.1.2) and return
+ it in a Diameter UAA message. Upon reception of this Diameter UAA
+ message with the Result-Code AVP value set to
+ DIAMETER_USER_NAME_REQUIRED, the SIP server typically requests
+ authentication by sending a SIP 401 (Unauthorized) or SIP 407 (Proxy
+ Authentication Required) response back to the originator.
+
+ When the authorization procedure succeeds, the Diameter server
+ constructs a User-Authorization-Answer (UAA) message that MUST
+ include (1) the address of the SIP server already assigned to the
+ user name, (2) the capabilities needed by the SIP server (Diameter
+ client) to select another SIP server for the user, or (3) a
+ combination of the previous two options.
+
+ If the Diameter server is already aware of a SIP server allocated to
+ the user, the Diameter UAA message contains the address of that SIP
+ server.
+
+ The Diameter UAA message contains the capabilities required by a SIP
+ server to trigger and execute services. It is required that these
+ capabilities are present in the Diameter UAA message due to the
+ possibility that the Diameter client (in the SIP server) allocates a
+ different SIP server to trigger and execute services for that
+ particular user.
+
+ If a User-Name AVP is present in the Diameter UAR message, then the
+ Diameter server MUST verify the existence of the user in the realm,
+ i.e., the User-Name AVP value is a valid user within that realm. If
+ the Diameter server does not recognize the user name received in the
+ User-Name AVP, the Diameter server MUST build a Diameter User-
+ Authorization-Answer (UAA) message and MUST set the Result-Code AVP
+ to DIAMETER_ERROR_USER_UNKNOWN.
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 24]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ If a User-Name AVP is present in the Diameter UAR message, then the
+ Diameter server MUST authorize that User-Name AVP value is able to
+ register the SIP or SIPS URI included in the SIP-AOR AVP. If this
+ authorization fails, the Diameter server must set the Result-Code AVP
+ to DIAMETER_ERROR_IDENTITIES_DONT_MATCH and send it in a Diameter
+ User-Authorization-Answer (UAA) message.
+
+ Note: Correlation between User-Name and SIP-AOR AVP values is
+ required in order to avoid registration of a SIP-AOR allocated to
+ another user.
+
+ If there is a SIP-Visited-Network-Id AVP in the Diameter UAR message,
+ and the SIP-User-Authorization-Type AVP value received in the
+ Diameter UAR message is set to REGISTRATION or REGISTRATION&
+ CAPABILITIES, then the Diameter server SHOULD verify whether the user
+ is allowed to roam into the network specified in the
+ SIP-Visited-Network-Id AVP in the Diameter UAR message. If the user
+ is not allowed to roam into that network, the Diameter AAA server
+ MUST set the Result-Code AVP value in the Diameter UAA message to
+ DIAMETER_ERROR_ROAMING_NOT_ALLOWED.
+
+ If the SIP-User-Authorization-Type AVP value received in the Diameter
+ UAR message is set to REGISTRATION or REGISTRATION&CAPABILITIES, then
+ the Diameter server SHOULD verify whether the SIP-AOR AVP value is
+ authorized to register in the Home Realm. Where the SIP AOR is not
+ authorized to register in the Home Realm, the Diameter server MUST
+ set the Result-Code AVP to DIAMETER_AUTHORIZATION_REJECTED and send
+ it in a Diameter UAA message.
+
+ When the SIP-User-Authorization-Type AVP is not present in the
+ Diameter UAR message, or when it is present and its value is set to
+ REGISTRATION, then:
+
+ o If the Diameter server is not aware of any previous registration
+ of the user name (including registrations of other SIP AORs
+ allocated to the same user name), then the Diameter server does
+ not know of any SIP server allocated to the user. In this case,
+ the Diameter server MUST set the Result-Code AVP value to
+ DIAMETER_FIRST_REGISTRATION in the Diameter UAA message, and the
+ Diameter server SHOULD include the required SIP server
+ capabilities in the SIP-Server-Capabilities AVP value in the
+ Diameter UAA message. The SIP-Server-Capabilities AVP assists the
+ Diameter client (SIP server) to select an appropriate SIP server
+ for the user, according to the required capabilities.
+
+ o In some cases, the Diameter server is aware of a previously
+ assigned SIP server for the same or different SIP AORs allocated
+ to the same user name. In these cases, re-assignment of a new SIP
+
+
+
+Garcia-Martin, et al. Standards Track [Page 25]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ server may or may not be needed, depending on the capabilities of
+ the SIP server. The Diameter server MUST always include the
+ allocated SIP server URI in the SIP-Server-URI AVP of the UAA
+ message. If the Diameter server does not return the SIP
+ capabilities, the Diameter server MUST set the Result-Code AVP in
+ the Diameter UAA message to DIAMETER_SUBSEQUENT_REGISTRATION.
+ Otherwise (i.e., if the Diameter server includes a
+ SIP-Server-Capabilities AVP), then the Diameter server MUST set
+ the Result-Code AVP in the Diameter UAA message to
+ DIAMETER_SERVER_SELECTION. Then the Diameter client determines,
+ based on the received information, whether it needs to select a
+ new SIP server.
+
+ When the SIP-User-Authorization-Type AVP value received in the
+ Diameter UAR message is set to REGISTRATION&CAPABILITIES, then
+ Diameter Server MUST return the list of capabilities in the
+ SIP-Server-Capabilities AVP value of the Diameter UAA message, it
+ MUST set the Result-Code to DIAMETER_SUCCESS, and it MUST NOT return
+ a SIP-Server-URI AVP. The SIP-Server-Capabilities AVP enables the
+ SIP server (Diameter client) to select another appropriate SIP server
+ for invoking and executing services for the user, depending on the
+ required capabilities. The Diameter server MAY leave the list of
+ capabilities empty to indicate that any SIP server can be selected.
+
+ When the SIP-User-Authorization-Type AVP value received in the
+ Diameter UAR message is set to DEREGISTRATION, then:
+
+ o If the Diameter server is aware of a SIP server assigned to the
+ SIP AOR under deregistration, the Diameter server MUST set the
+ Result-Code AVP to DIAMETER_SUCCESS and MUST set the
+ SIP-Server-URI AVP value to the known SIP server, and return them
+ in the Diameter UAA message.
+
+ o If the Diameter server is not aware of a SIP server assigned to
+ the SIP AOR under deregistration, then the Diameter server MUST
+ set the Result-Code AVP in the Diameter UAA message to
+ DIAMETER_ERROR_IDENTITY_NOT_REGISTERED.
+
+ The Message Format of the UAA command is as follows:
+
+ <UAA> ::= < Diameter Header: 283, PXY >
+ < Session-Id >
+ { Auth-Application-Id }
+ { Auth-Session-State }
+ { Result-Code }
+ { Origin-Host }
+ { Origin-Realm }
+ [ SIP-Server-URI ]
+
+
+
+Garcia-Martin, et al. Standards Track [Page 26]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ [ 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) Command
+
+ The Server-Assignment-Request (SAR) command is indicated by the
+ Command-Code set to 284 and the Command Flags' 'R' bit set. The
+ Diameter client in a SIP server sends this command to the Diameter
+ server to indicate the completion of the authentication process and
+ to request that the Diameter server store the URI of the SIP server
+ that is currently serving the user. The main functions of the
+ Diameter SAR command are to inform the Diameter server of the URI of
+ the SIP server allocated to the user, and to store or clear it from
+ the Diameter server. Additionally, the Diameter client can request
+ to download the user profile or part of it.
+
+ During the registration procedure, a SIP server becomes assigned to
+ the user. The Diameter client in the assigned SIP server MUST
+ include its own URI in the SIP-Server-URI AVP of the
+ Server-Assignment-Request (SAR) Diameter message and send it to the
+ Diameter server. The Diameter server then becomes aware of the
+ allocation of the SIP server to the user name and the server's URI.
+
+ The Diameter client in the SIP server MAY send a Diameter SAR message
+ because of other reasons. These reasons are identified in the
+ SIP-Server-Assignment-Type AVP (Section 9.4) value. For instance, a
+ Diameter client in a SIP server may contact the Diameter server to
+ request deregistration of a user, to inform the Diameter server of an
+ authentication failure, or just to download the user profile. For a
+ complete description of all the SIP-Server-Assignment-Type AVP
+ values, see Section 9.4.
+
+ Typically the reception of a SIP REGISTER request in a SIP server
+ will trigger the Diameter client in the SIP server to send the
+ Diameter SAR message. However, if a SIP server is receiving other
+ SIP request, such as INVITE, and the SIP server does not have the
+ user profile, the Diameter client in the SIP server may send the
+ Diameter SAR message to the Diameter server in order to download the
+ user profile and make the Diameter server aware of the SIP server
+ assigned to the user.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 27]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ The user profile is an important piece of information that dictates
+ the behavior of the SIP server when triggering or providing services
+ for the user. Typically the user profile is divided into:
+
+ o Services to be rendered to the user when the user is registered
+ and initiates a SIP request.
+
+ o Services to be rendered to the user when the user is registered
+ and a SIP request destined to that user arrives to the SIP proxy.
+
+ o Services to be rendered to the user when the user is not
+ registered and a SIP request destined to that user arrives to the
+ SIP proxy.
+
+ The SIP-Server-Assignment-Type AVP indicates the reason why the
+ Diameter client (SIP server) contacted the Diameter server. If the
+ Diameter client sets the SIP-Server-Assignment-Type AVP value to
+ REGISTRATION, RE_REGISTRATION, UNREGISTERED_USER, NO_ASSIGNMENT,
+ AUTHENTICATION_FAILURE or AUTHENTICATION_TIMEOUT, the Diameter client
+ MUST include exactly one SIP-AOR AVP in the Diameter SAR message.
+
+ The SAR message MAY contain zero or more SIP-Supported-User-Data-Type
+ AVPs. Each of them contains a type of user data understood by the
+ SIP server. This allows the Diameter client to provide an indication
+ to the Diameter server of the different format of user data
+ understood by the SIP server. The Diameter server uses this
+ information to select one or more SIP-User-Data AVPs that will be
+ included in the SAA message.
+
+ The Message Format of the SAR command is as follows:
+
+ <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 ]
+
+
+
+Garcia-Martin, et al. Standards Track [Page 28]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+8.4. Server-Assignment-Answer (SAA) Command
+
+ The Server-Assignment-Answer (SAA) is indicated by the Command-Code
+ set to 284 and the Command Flags' 'R' bit cleared. The Diameter
+ server sends this command in response to a previously received
+ Diameter Server-Assignment-Request (SAR) command. The response may
+ include the user profile or part of it, if requested.
+
+ In addition to the values already defined in RFC 3588 [RFC3588], the
+ Result-Code AVP may contain one of the values defined in
+ Section 10.1.
+
+ The Result-Code AVP value in the Diameter SAA message may indicate a
+ success or an error in the execution of the Diameter SAR command. If
+ Result-Code AVP value in the Diameter SAA message does not contain an
+ error code, the SAA message MAY include one or more SIP-User-Data
+ AVPs that typically contain the profile of the user, indicating
+ services that the SIP server can provide to that user.
+
+ The Diameter server MAY include one or more
+ SIP-Supported-User-Data-Type AVPs, each one identifying a type of
+ user data format supported in the Diameter server. If there is not a
+ common supported user data type between the Diameter client and the
+ Diameter server, the Diameter server SHOULD declare its list of
+ supported user data types by including one or more
+ SIP-Supported-User-Data-Type AVPs in a Diameter SAA message. This
+ indication is merely for debugging reasons, since there is not a
+ fallback mechanism that allows the Diameter client to retrieve the
+ profile in a supported format.
+
+ If the Diameter server requires a User-Name AVP value to process the
+ Diameter SAR request, but the Diameter SAR message did not contain a
+ User-Name AVP value, the Diameter server MUST set the Result-Code AVP
+ value to DIAMETER_USER_NAME_REQUIRED (see Section 10.1.2) and return
+ it in a Diameter SAA message. Upon reception of this Diameter SAA
+ message with the Result-Code AVP value set to
+ DIAMETER_USER_NAME_REQUIRED, the SIP server typically requests
+ authentication by generating a SIP 401 (Unauthorized) or SIP 407
+ (Proxy Authentication Required) response back to the originator.
+
+ If the User-Name AVP is included in the Diameter SAR message, upon
+ reception of the Diameter SAR message, the Diameter server MUST
+ verify the existence of the user in the realm, i.e., the User-Name
+ AVP value is a valid user within that realm. If the Diameter server
+ does not recognize the user name received in the User-Name AVP, the
+ Diameter server MUST build a Diameter Server-Assignment-Answer (SAA)
+ message and MUST set the Result-Code AVP to
+ DIAMETER_ERROR_USER_UNKNOWN.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 29]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Then the Diameter server MUST authorize that User-Name AVP value is a
+ valid authentication name for the SIP or SIPS URI included in the
+ SIP-AOR AVP of the Diameter SAR message. If this authorization
+ fails, the Diameter server must set the Result-Code AVP to
+ DIAMETER_ERROR_IDENTITIES_DONT_MATCH and send it in a Diameter
+ Server-Assignment-Answer (SAA) message.
+
+ After successful execution of the Diameter SAR command, the Diameter
+ server MUST clear the "authentication pending" flag and SHOULD move
+ the temporarily stored SIP server URI to permanent storage.
+
+ The actions of the Diameter server upon reception of the Diameter SAR
+ message depend on the value of the SIP-Server-Assignment-Type:
+
+ o If the SIP-Server-Assignment-Type AVP value in the Diameter SAR
+ message is set to REGISTRATION or RE_REGISTRATION, the Diameter
+ server SHOULD verify that there is only one SIP-AOR AVP.
+ Otherwise, the Diameter server MUST answer with a Diameter SAA
+ message with the Result-Code AVP value set to
+ DIAMETER_AVP_OCCURS_TOO_MANY_TIMES and MUST NOT include any
+ SIP-User-Data AVP. If there is only one SIP-AOR AVP and if the
+ SIP-User-Data-Already-Available AVP value is set to
+ USER_DATA_NOT_AVAILABLE, then the Diameter server SHOULD include
+ one or more user profile data with the SIP or SIPS URI (SIP-AOR
+ AVP) and all other SIP identities associated with that AVP in the
+ SIP-User-Data AVP value of the Diameter SAA message. On selecting
+ the type of user data, the Diameter server SHOULD take into
+ account the supported formats at the SIP server
+ (SIP-Supported-User-Data-Type AVP in the SAR message) and the
+ local policy. Additionally, the Diameter server MUST set the
+ Result-Code AVP value to DIAMETER_SUCCESS in the Diameter SAA
+ message. The Diameter server considers the SIP AOR authenticated
+ and registered.
+
+ o If the SIP-Server-Assignment-Type AVP value in the Diameter SAR
+ message is set to UNREGISTERED_USER, then the Diameter server MUST
+ store the SIP server address included in the SIP-Server-URI AVP
+ value. The Diameter server will return the SIP server address in
+ Diameter Location-Info-Answer (LIA) messages. If the
+ SIP-User-Data-Already-Available AVP value is set to
+ USER_DATA_NOT_AVAILABLE, then the Diameter server SHOULD include
+ one or more user profile data associated with the SIP or SIPS URI
+ (SIP-AOR AVP) and associated identities in the SIP-User-Data AVP
+ value of the Diameter SAA message. On selecting the type of user
+ data, the Diameter server SHOULD take into account the supported
+ formats at the SIP server (SIP-Supported-User-Data-Type AVP in the
+ SAR message) and the local policy. The Diameter server MUST set
+ the Result-Code AVP value to DIAMETER_SUCCESS. The Diameter
+
+
+
+Garcia-Martin, et al. Standards Track [Page 30]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ server considers the SIP AOR UNREGISTERED, but with a SIP server
+ allocated to trigger and provide services for unregistered users.
+ Note that in case of UNREGISTERED_USER (SIP-Server-Assignment-Type
+ AVP), the Diameter server MUST verify that there is only one
+ SIP-AOR AVP. Otherwise, the Diameter server MUST answer the
+ Diameter SAR message with a Diameter SAA message, and it MUST set
+ the Result-Code AVP value to DIAMETER_AVP_OCCURS_TOO_MANY_TIMES
+ and MUST NOT include any SIP-User-Data AVP.
+ If the User-Name AVP was not present in the Diameter SAR message
+ and the SIP-AOR is not known for the Diameter server, the Diameter
+ server MUST NOT include a User-Name AVP in the Diameter SAA
+ message and MUST set the Result-Code AVP value to
+ DIAMETER_ERROR_USER_UNKNOWN.
+
+ o If the SIP-Server-Assignment-Type AVP value in the Diameter SAR
+ message is set to TIMEOUT_DEREGISTRATION, USER_DEREGISTRATION,
+ DEREGISTRATION_TOO_MUCH_DATA, or ADMINISTRATIVE_DEREGISTRATION,
+ the Diameter server MUST clear the SIP server address associated
+ with all SIP AORs indicated in each of the SIP-AOR AVP values
+ included in the Diameter SAR message. The Diameter server
+ considers all of these SIP AORs as not registered. The Diameter
+ server MUST set the Result-Code AVP value to DIAMETER_SUCCESS in
+ the Diameter SAA message.
+
+ o If the SIP-Server-Assignment-Type AVP value in the Diameter SAR
+ message is set to TIMEOUT_DEREGISTRATION_STORE_SERVER_NAME or
+ USER_DEREGISTRATION_STORE_SERVER_NAME, the Diameter server MAY
+ keep the SIP server address associated with the SIP AORs included
+ in the SIP-AOR AVP values of the Diameter SAR message, even though
+ the SIP AORs become unregistered. This feature allows a SIP
+ server to request that the Diameter server remain an assigned SIP
+ server for those SIP AORs (SIP-AOR AVP values) allocated to the
+ same user name, and avoid SIP server assignment. The Diameter
+ server MUST consider all these SIP AORs as not registered. If the
+ Diameter server honors the request of the Diameter client (SIP
+ server) to remain as an allocated SIP server, then the Diameter
+ server MUST keep the SIP server assigned to those SIP AORs
+ allocated to the username and MUST set the Result-Code AVP value
+ to DIAMETER_SUCCESS in the Diameter SAA message. Otherwise, when
+ the Diameter server does not honor the request of the Diameter
+ client (SIP server) to remain as an allocated SIP server, the
+ Diameter server MUST clear the SIP server name assigned to those
+ SIP AORs and it MUST set the Result-Code AVP value to
+ DIAMETER_SUCCESS_SERVER_NAME_NOT_STORED in the Diameter SAA
+ message.
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 31]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ o If the SIP-Server-Assignment-Type AVP value in the Diameter SAR
+ message is set to NO_ASSIGNMENT, the Diameter server SHOULD first
+ verify that the SIP-Server-URI AVP value in the Diameter SAR
+ message is the same URI as the one assigned to the SIP-AOR AVP
+ value. If they differ, then the Diameter server MUST set the
+ Result-Code AVP value to DIAMETER_UNABLE_TO_COMPLY in the Diameter
+ SAA message. Otherwise, if the SIP-User-Data-Already-Available
+ AVP value is set to USER_DATA_NOT_AVAILABLE, then the Diameter
+ server SHOULD include the user profile data with the SIP or SIPS
+ URI (SIP-AOR AVP) and all other SIP identities associated with
+ that AVP in the SIP-User-Data AVP value of the Diameter SAA
+ message. On selecting the type of user data, the Diameter server
+ SHOULD take into account the supported formats at the SIP server
+ (SIP-Supported-User-Data-Type AVP in the SAR message) and the
+ local policy.
+
+ o If the SIP-Server-Assignment-Type AVP value in the Diameter SAR
+ message is set to AUTHENTICATION_FAILURE or
+ AUTHENTICATION_TIMEOUT, the Diameter server MUST verify that there
+ is exactly one SIP-AOR AVP in the Diameter SAR message. If the
+ number of occurrences of the SIP-AOR AVP is not exactly one, the
+ Diameter server MUST set the Result-Code AVP value to
+ DIAMETER_AVP_OCCURS_TOO_MANY_TIMES in the Diameter SAA message,
+ and SHOULD not take further actions. If there is exactly one
+ SIP-AOR AVP in the Diameter SAR message, the Diameter server MUST
+ clear the address of the SIP server assigned to the SIP AOR
+ allocated to the user name, and the Diameter server MUST set the
+ Result-Code AVP value to DIAMETER_SUCCESS in the Diameter SAA
+ message. The Diameter server MUST consider the SIP AOR as not
+ registered.
+
+ The Message Format of the SAA command is as follows:
+
+ <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 ]
+
+
+
+Garcia-Martin, et al. Standards Track [Page 32]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ [ Redirect-Max-Cache-Time ]
+ * [ Proxy-Info ]
+ * [ Route-Record ]
+ * [ AVP ]
+
+8.5. Location-Info-Request (LIR) Command
+
+ The Location-Info-Request (LIR) is indicated by the Command-Code set
+ to 285 and the Command Flags' 'R' bit set. The Diameter client in a
+ SIP server sends this command to the Diameter server to request
+ routing information, e.g., the URI of the SIP server assigned to the
+ SIP-AOR AVP value allocated to the users.
+
+ The Message Format of the LIR command is as follows:
+
+ <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) Command
+
+ The Location-Info-Answer (LIA) is indicated by the Command-Code set
+ to 285 and the Command Flags' 'R' bit cleared. The Diameter server
+ sends this command in response to a previously received Diameter
+ Location-Info-Request (LIR) command.
+
+ In addition to the values already defined in RFC 3588 [RFC3588], the
+ Result-Code AVP may contain one of the values defined in
+ Section 10.1. When the Diameter server finds an error in processing
+ the Diameter LIR message, the Diameter server MUST stop the process
+ of the message and answer with a Diameter LIA message that includes
+ the appropriate error code in the Result-Code AVP value. When there
+ is no error, the Diameter server MUST set the Result-Code AVP value
+ to DIAMETER_SUCCESS in the Diameter LIA message.
+
+ One of the errors that the Diameter server may find is that the
+ SIP-AOR AVP value is not a valid user in the realm. In such cases,
+ the Diameter server MUST set the Result-Code AVP value to
+ DIAMETER_ERROR_USER_UNKNOWN and return it in a Diameter LIA message.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 33]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ If the Diameter server cannot process the Diameter LIR command, e.g.,
+ due to a database error, the Diameter server MUST set the Result-Code
+ AVP value to DIAMETER_UNABLE_TO_COMPLY and return it in a Diameter
+ LIA message. The Diameter server MUST NOT include any SIP-Server-URI
+ or SIP-Server-Capabilities AVP in the Diameter LIA message.
+
+ The Diameter server may or may not be aware of a SIP server assigned
+ to the SIP-AOR AVP value included in the Diameter LIR message. If
+ the Diameter server is aware of a SIP server allocated to that
+ particular user, the Diameter server MUST include the URI of such SIP
+ server in the SIP-Server-URI AVP and return it in a Diameter LIA
+ message. This is typically the situation when the user is either
+ registered, or unregistered but a SIP server is still assigned to the
+ user.
+
+ When the Diameter server is not aware of a SIP server allocated to
+ the user (typically the case when the user unregistered), the
+ Result-Code AVP value in the Diameter LIA message depends on whether
+ the Diameter server is aware that the user has services defined for
+ unregistered users:
+
+ o Those users who have services defined for unregistered users may
+ require the allocation of a SIP server to trigger and perhaps
+ execute those services. Therefore, when the Diameter server is
+ not aware of an assigned SIP server, but the user has services
+ defined for unregistered users, the Diameter server MUST set the
+ Result-Code AVP value to DIAMETER_UNREGISTERED_SERVICE and return
+ it in a Diameter LIA message. The Diameter server MAY also
+ include a SIP-Server-Capabilities AVP to facilitate the SIP server
+ (Diameter client) with the selection of an appropriate SIP server
+ with the required capabilities. Absence of the SIP-Server-
+ Capabilities AVP indicates to the SIP server (Diameter client)
+ that any SIP server is suitable to be allocated for the user.
+
+ o Those users who do not have service defined for unregistered users
+ do not require further processing. The Diameter server MUST set
+ the Result-Code AVP value to
+ DIAMETER_ERROR_IDENTITY_NOT_REGISTERED and return it to the
+ Diameter client in a Diameter LIA message. The SIP server
+ (Diameter client) may return the appropriate SIP response (e.g.,
+ 480 (Temporarily unavailable)) to the original SIP request.
+
+ The Message Format of the LIA command is as follows:
+
+ <LIA> ::= < Diameter Header: 285, PXY >
+ < Session-Id >
+ { Auth-Application-Id }
+ { Result-Code }
+
+
+
+Garcia-Martin, et al. Standards Track [Page 34]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ { 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) Command
+
+ The Multimedia-Auth-Request (MAR) command is indicated by the
+ Command-Code set to 286 and the Command Flags' 'R' bit set. The
+ Diameter client in a SIP server sends this command to the Diameter
+ server to request that the Diameter server authenticate and authorize
+ a user attempt to use some SIP service (in this context, SIP service
+ can be something as simple as a SIP subscription or using the proxy
+ services for a SIP request).
+
+ The MAR command may also register the SIP server's own URI to the
+ Diameter server, so that future LIR/LIA messages can return this URI.
+ If the SIP server is acting as a SIP registrar (see examples in
+ Sections 6.2 and 6.3), its Diameter client MUST include a SIP-
+ Server-URI AVP in the MAR command. In any other cases (see example
+ in Section 6.4), its Diameter client MUST NOT include a SIP-Server-
+ URI AVP in the MAR command.
+
+ The SIP-Method AVP MUST include the SIP method name of the SIP
+ request that triggered this Diameter MAR message. The Diameter
+ server can use this AVP to authorize some SIP requests depending on
+ the method.
+
+ The Diameter MAR message MUST include a SIP-AOR AVP. The SIP-AOR AVP
+ indicates the target of the SIP request. The value of the AVP is
+ extracted from different places in SIP request, depending on the
+ semantics of the SIP request. For SIP REGISTER messages the SIP-AOR
+ AVP value indicates the intended public user identity under
+ registration, and it is the SIP or SIPS URI populated in the To
+ header field value (addr-spec as per RFC 3261 [RFC3261]) of the SIP
+ REGISTER request. For other types of SIP requests, such as INVITE,
+ SUBSCRIBE, MESSAGE, etc., the SIP-AOR AVP value indicates the
+ intended destination of the request. This is typically populated in
+ the Request-URI of the SIP request. Extracting the SIP-AOR AVP value
+
+
+
+Garcia-Martin, et al. Standards Track [Page 35]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ from the proper SIP header field is the Diameter client's
+ responsibility. Extensions to SIP (new SIP methods or new semantics)
+ may require the SIP-AOR to be extracted from other parts of the
+ request.
+
+ If the SIP request includes some sort of authentication information,
+ the Diameter client MUST include the user name, extracted from the
+ authentication information of the SIP request, in the User-Name AVP
+ value.
+
+ The Message Format of the MAR command is as follows:
+
+ <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) Command
+
+ The Multimedia-Auth-Answer (MAA) is indicated by the Command-Code set
+ to 286 and the Command Flags' 'R' bit cleared. The Diameter server
+ sends this command in response to a previously received Diameter
+ Multimedia-Auth-Request (MAR) command.
+
+ In addition to the values already defined in RFC 3588 [RFC3588], the
+ Result-Code AVP may contain one of the values defined in
+ Section 10.1.
+
+ If the Diameter server requires a User-Name AVP value to process the
+ Diameter MAR request, but the Diameter MAR message did not contain a
+ User-Name AVP value, the Diameter server MUST set the Result-Code AVP
+ value to DIAMETER_USER_NAME_REQUIRED (see Section 10.1.2) and return
+ it in a Diameter MAA message. The Diameter server MAY include a
+ SIP-Number-Auth-Items AVP and one or more SIP-Auth-Data-Item AVPs
+ with authentication information (e.g., a challenge). Upon reception
+
+
+
+Garcia-Martin, et al. Standards Track [Page 36]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ of this Diameter MAA message with the Result-Code AVP value set to
+ DIAMETER_USER_NAME_REQUIRED, the SIP server typically requests
+ authentication by generating a SIP 401 (Unauthorized) or SIP 407
+ (Proxy Authentication Required) response back to the originator.
+
+ If the User-Name AVP is present in the Diameter MAR message, the
+ Diameter server MUST verify the existence of the user in the realm,
+ i.e., the User-Name AVP value is a valid user within that realm. If
+ the Diameter server does not recognize the user name received in the
+ User-Name AVP, the Diameter server MUST build a Diameter
+ Multimedia-Auth-Answer (MAA) message and MUST set the Result-Code AVP
+ to DIAMETER_ERROR_USER_UNKNOWN.
+
+ If the SIP-Methods AVP value of the Diameter MAR message is set to
+ REGISTER and a User-Name AVP is present, then the Diameter server
+ MUST authorize that User-Name AVP value is able to use the URI
+ included in the SIP-AOR AVP. If this authorization fails, the
+ Diameter server must set the Result-Code AVP to
+ DIAMETER_ERROR_IDENTITIES_DONT_MATCH and send it in a Diameter
+ Multimedia-Auth-Answer (MAA) message.
+
+ Note: Correlation between User-Name and SIP-AOR AVP values is only
+ required for SIP REGISTER request, to prevent a user from
+ registering a SIP-AOR allocated to another user. In other types
+ of SIP requests (e.g., INVITE), the SIP-AOR indicates the intended
+ destination of the request, rather than the originator of it.
+
+ The Diameter server MUST verify whether the authentication scheme
+ (SIP-Authentication-Scheme AVP value) indicated in the grouped
+ SIP-Auth-Data-Item AVP is supported or not. If that authentication
+ scheme is not supported, then the Diameter server MUST set the
+ Result-Code AVP to DIAMETER_ERROR_AUTH_SCHEME_NOT_SUPPORTED and send
+ it in a Diameter Multimedia-Auth-Answer (MAA) message.
+
+ If the SIP-Number-Auth-Items AVP is present in the Diameter MAR
+ message, it indicates the number of authentication data items that
+ the Diameter client is requesting. It is RECOMMENDED that the
+ Diameter server, when building the Diameter MAA message, includes a
+ number of SIP-Auth-Data-Item AVPs that are a subset of the
+ authentication data items requested by the Diameter client in the
+ SIP-Number-Auth-Items AVP value of the Diameter MAR message.
+
+ If the SIP-Server-URI AVP is present in the Diameter MAR message,
+ then the Diameter server MUST compare the stored SIP server (assigned
+ to the user) with the SIP-Server-URI AVP value (received in the
+ Diameter MAR message). If they don't match, the Diameter server MUST
+ temporarily save the newly received SIP server assigned to the user,
+ and MUST set an "authentication pending" flag for the user. If they
+
+
+
+Garcia-Martin, et al. Standards Track [Page 37]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ match, the Diameter server shall clear the "authentication pending"
+ flag for the user.
+
+ In any other situation, if there is a success in processing the
+ Diameter MAR command and the Diameter server stored the
+ SIP-Server-URI, the Diameter server MUST set the Result-Code AVP
+ value to DIAMETER_SUCCESS and return it in a Diameter MAA message.
+
+ If there is a success in processing the Diameter MAR command, but the
+ Diameter server does not store the SIP-Server-URI because the AVP was
+ not present in the Diameter MAR command, then the Diameter server
+ MUST set the Result-Code AVP value to either:
+
+ 1. DIAMETER_SUCCESS_AUTH_SENT_SERVER_NOT_STORED, if the Diameter
+ server is sending authentication credentials to create a
+ challenge.
+
+ 2. DIAMETER_SUCCESS_SERVER_NAME_NOT_STORED, if the Diameter server
+ successfully authenticated the user and authorized the SIP server
+ to proceed with the SIP request.
+
+ Otherwise, the Diameter server MUST set the Result-Code AVP value to
+ DIAMETER_UNABLE_TO_COMPLY, and it MUST NOT include any
+ SIP-Auth-Data-Item AVP.
+
+ The Message Format of the MAA command is as follows:
+
+ <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 ]
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 38]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+8.9. Registration-Termination-Request (RTR) Command
+
+ The Registration-Termination-Request (RTR) command is indicated by
+ the Command-Code set to 287 and the Command Flags' 'R' bit set. The
+ Diameter server sends this command to the Diameter client in a SIP
+ server to indicate to the SIP server that one or more SIP AORs have
+ to be deregistered. The command allows an operator to
+ administratively cancel the registration of a user from a centralized
+ Diameter server.
+
+ The Diameter server has the capability to initiate the deregistration
+ of a user and inform the SIP server by means of the Diameter RTR
+ command. The Diameter server can decide whether only one SIP AOR is
+ going to be deregistered, a list of SIP AORs, or all the SIP AORs
+ allocated to the user.
+
+ The absence of a SIP-AOR AVP in the Diameter RTR message indicates
+ that all the SIP AORs allocated to the user identified by the
+ User-Name AVP are being deregistered.
+
+ The Diameter server MUST include a SIP-Deregistration-Reason AVP
+ value to indicate the reason for the deregistration.
+
+ The Message Format of the RTR command is as follows:
+
+ <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) Command
+
+ The Registration-Termination-Answer (RTA) is indicated by the
+ Command-Code set to 287 and the Command Flags' 'R' bit cleared. The
+ Diameter client sends this command in response to a previously
+ received Diameter Registration-Termination-Request (RTR) command.
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 39]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ In addition to the values already defined in RFC 3588 [RFC3588], the
+ Result-Code AVP may contain one of the values defined in
+ Section 10.1.
+
+ If the SIP server (Diameter client) requires a User-Name AVP value to
+ process the Diameter RTR request, but the Diameter RTR message did
+ not contain a User-Name AVP value, the Diameter client MUST set the
+ Result-Code AVP value to DIAMETER_USER_NAME_REQUIRED (see Section
+ 10.1.2) and return it in a Diameter RTA message.
+
+ The SIP server (Diameter client) applies the administrative
+ deregistration to each of the URIs included in each of the SIP-AOR
+ AVP values, or, if there is no SIP-AOR AVP present in the Diameter
+ RTR request, to all the URIs allocated to the User-Name AVP value.
+
+ The value of the SIP-Deregistration-Reason AVP in the Diameter RTR
+ command has an effect on the actions performed at the SIP server
+ (Diameter client):
+
+ o If the value is set to PERMANENT_TERMINATION, then the user has
+ terminated his/her registration to the realm. If informing the
+ interested parties (e.g., subscribers to the "reg" event
+ [RFC3680]) about the administrative deregistration is supported
+ through SIP procedures, the SIP server (Diameter client) will do
+ so. The Diameter Client in the SIP Server SHOULD NOT request a
+ new user registration. The SIP server clears the registration
+ state of the deregistered AORs.
+
+ o If the value is set to NEW_SIP_SERVER_ASSIGNED, the Diameter
+ server informs the SIP server (Diameter client) that a new SIP
+ server has been allocated to the user, due to some reason. The
+ SIP server, if supported through SIP procedures, will inform the
+ interested parties (e.g., subscribers to the "reg" event
+ [RFC3680]) about the administrative deregistration at this SIP
+ server. The Diameter client in the SIP server SHOULD NOT request
+ a new user registration. The SIP server clears the registration
+ state of the deregistered SIP AORs.
+
+ o If the value is set to SIP_SERVER_CHANGE, the Diameter server
+ informs the SIP server (Diameter client) that a new SIP server has
+ to be allocated to the user, e.g., due to user's capabilities
+ requiring a new SIP server, or not enough resources in the current
+ SIP server. If informing the interested parties about the
+ administrative deregistration is supported through SIP procedures
+ (e.g., subscriptions to the "reg" event [RFC3680]), the SIP server
+ will do so. The Diameter client in the SIP Server SHOULD NOT
+ request a new user registration. The SIP server clears the
+ registration state of the deregistered SIP AORs.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 40]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ o If the value is set to REMOVE_SIP_SERVER, the Diameter server
+ informs the SIP server (Diameter client) that the SIP server will
+ no longer be bound in the Diameter server with that user. The SIP
+ server can delete all data related to the user.
+
+ The Message Format of the RTA command is as follows:
+
+ <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) Command
+
+ The Push-Profile-Request (PPR) command is indicated by the
+ Command-Code set to 288 and the Command Flags' 'R' bit set. The
+ Diameter server sends this command to the Diameter client in a SIP
+ server to update either the user profile of an already registered
+ user in that SIP server or the SIP accounting information. This
+ allows an operator to modify the data of a user profile or the
+ accounting information and push it to the SIP server where the user
+ is registered.
+
+ Each user has a user profile associated with him/her and other
+ accounting information. The profile or the accounting information
+ may change with time, e.g., due to addition of new services to the
+ user. When the user profile or the accounting information changes,
+ the Diameter server sends a Diameter Push-Profile-Request (PPR)
+ command to the Diameter client in a SIP server, in order to start
+ applying those new services.
+
+ A PPR command MAY contain a SIP-Accounting-Information AVP that
+ updates the addresses of the accounting servers. Changes in the
+ addresses of the accounting servers take effect immediately. The
+ Diameter client SHOULD close any existing accounting session with the
+ existing server and start providing accounting information to the
+ newly acquired accounting server.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 41]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ A PPR command MAY contain zero or more SIP-User-Data AVP values
+ containing the new user profile. On selecting the type of user data,
+ the Diameter server SHOULD take into account the supported formats at
+ the SIP server (SIP-Supported-User-Data-Type AVP sent in a previous
+ SAR message) and the local policy.
+
+ The User-Name AVP indicates the user to whom the profile is
+ applicable.
+
+ The Message Format of the PPR command is as follows:
+
+ <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) Command
+
+ The Push-Profile-Answer (PPA) is indicated by the Command-Code set to
+ 288 and the Command Flags' 'R' bit cleared. The Diameter client
+ sends this command in response to a previously received Diameter
+ Push-Profile-Request (PPR) command.
+
+ In addition to the values already defined in RFC 3588 [RFC3588], the
+ Result-Code AVP may contain one of the values defined in
+ Section 10.1.
+
+ If there is no error when processing the received Diameter PPR
+ message, the SIP server (Diameter client) MUST download the received
+ user profile from the SIP-User-Data AVP values in the Diameter PPR
+ message and store it associated with the user specified in the
+ User-Name AVP value.
+
+ If the SIP server does not recognize or does not support some of the
+ data transferred in the SIP-User-Data AVP values, the Diameter client
+ in the SIP server MUST return a Diameter PPA message that includes a
+
+
+
+Garcia-Martin, et al. Standards Track [Page 42]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Result-Code AVP set to the value
+ DIAMETER_ERROR_NOT_SUPPORTED_USER_DATA.
+
+ If the SIP server (Diameter client) receives a Diameter PPR message
+ with a User-Name AVP that is unknown, the Diameter client MUST set
+ the Result-Code AVP value to DIAMETER_ERROR_USER_UNKNOWN and MUST
+ return it to the Diameter server in a Diameter PPA message.
+
+ If the SIP server (Diameter client) receives in the
+ SIP-User-Data-Content AVP value (of the grouped SIP-User-Data AVP)
+ more data than it can accept, it MUST set the Result-Code AVP value
+ to DIAMETER_ERROR_TOO_MUCH_DATA and MUST return it to the Diameter
+ server in a Diameter PPA message. The SIP server MUST NOT override
+ the existing user profile with the one received in the PPR message.
+
+ If the Diameter server receives the Result-Code AVP value set to
+ DIAMETER_ERROR_TOO_MUCH_DATA in a Diameter PPA message, it SHOULD
+ force a new re-registration of the user by sending to the Diameter
+ client a Diameter Registration-Termination-Request (RTR) with the
+ SIP-Deregistration-Reason AVP value set to SIP_SERVER_CHANGE. This
+ will force a re-registration of the user and will trigger a selection
+ of a new SIP server.
+
+ If the Diameter client is not able to honor the command, for any
+ other reason, it MUST set the Result-Code AVP value to
+ DIAMETER_UNABLE_TO_COMPLY and it MUST return it in a Diameter PPA
+ message.
+
+ The Message Format of the PPA command is as follows:
+
+ <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 ]
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 43]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+9. Diameter SIP Application AVPs
+
+ This section defines new AVPs used in this Diameter SIP application.
+ Applications compliant with this specification MUST implement these
+ AVPs.
+
+ Table 2 lists the new AVPs defined in this Diameter SIP application.
+ The following abbreviations are used in the Data-Type column:
+
+ o DURI: DiameterURI
+ o E: Enumerated
+ o G: Grouped
+ o OS: OctetString
+ o UTF8S: UTF8String
+ o U32: Unsigned32
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 44]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ +-----------------------------------+------+----------------+-------+
+ | Attribute Name | AVP | Reference | Data- |
+ | | Code | | Type |
+ +-----------------------------------+------+----------------+-------+
+ | SIP-Accounting-Information | 368 | Section 9.1 | G |
+ | SIP-Accounting-Server-URI | 369 | Section 9.1.1 | DURI |
+ | SIP-Credit-Control-Server-URI | 370 | Section 9.1.2 | DURI |
+ | SIP-Server-URI | 371 | Section 9.2 | UTF8S |
+ | SIP-Server-Capabilities | 372 | Section 9.3 | G |
+ | SIP-Mandatory-Capability | 373 | Section 9.3.1 | U32 |
+ | SIP-Optional-Capability | 374 | Section 9.3.2 | U32 |
+ | SIP-Server-Assignment-Type | 375 | Section 9.4 | E |
+ | SIP-Auth-Data-Item | 376 | Section 9.5 | G |
+ | SIP-Authentication-Scheme | 377 | Section 9.5.1 | E |
+ | SIP-Item-Number | 378 | Section 9.5.2 | U32 |
+ | SIP-Authenticate | 379 | Section 9.5.3 | G |
+ | SIP-Authorization | 380 | Section 9.5.4 | G |
+ | SIP-Authentication-Info | 381 | Section 9.5.5 | G |
+ | SIP-Number-Auth-Items | 382 | Section 9.6 | U32 |
+ | SIP-Deregistration-Reason | 383 | Section 9.7 | G |
+ | SIP-Reason-Code | 384 | Section 9.7.1 | E |
+ | SIP-Reason-Info | 385 | Section 9.7.2 | UTF8S |
+ | SIP-Visited-Network-Id | 386 | Section 9.9 | UTF8S |
+ | SIP-User-Authorization-Type | 387 | Section 9.10 | E |
+ | SIP-Supported-User-Data-Type | 388 | Section 9.11 | UTF8S |
+ | SIP-User-Data | 389 | Section 9.12 | G |
+ | SIP-User-Data-Type | 390 | Section 9.12.1 | UTF8S |
+ | SIP-User-Data-Contents | 391 | Section 9.12.2 | OS |
+ | SIP-User-Data-Already-Available | 392 | Section 9.13 | E |
+ | SIP-Method | 393 | Section 9.14 | UTF8S |
+ +-----------------------------------+------+----------------+-------+
+
+ Table 2: Defined AVPs
+
+ Table 3 expands the table of AVPs included in Section 4.5 of RFC 3588
+ [RFC3588]. The table indicates the Diameter AVPs defined in this
+ Diameter SIP Application, their possible flag values, and whether the
+ AVP may be encrypted. The acronyms 'M', 'P', and 'V' refer to AVP
+ flags whose semantics are described in RFC 3588 [RFC3588]. The value
+ of the 'Encr' column is also described in RFC 3588 [RFC3588].
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 45]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ +----------------------------------+------+-----+-----+------+------+
+ | Attribute Name | MUST | MAY | SHD | MUST | Encr |
+ | | | | NOT | NOT | |
+ +----------------------------------+------+-----+-----+------+------+
+ | SIP-Accounting-Information | M | P | | V | N |
+ | SIP-Accounting-Server-URI | M | P | | V | N |
+ | SIP-Credit-Control-Server-URI | M | P | | V | N |
+ | SIP-Server-URI | M | P | | V | N |
+ | SIP-Server-Capabilities | M | P | | V | N |
+ | SIP-Mandatory-Capability | M | P | | V | N |
+ | SIP-Optional-Capability | M | P | | V | N |
+ | SIP-Server-Assignment-Type | M | P | | V | N |
+ | SIP-Auth-Data-Item | M | P | | V | N |
+ | SIP-Authentication-Scheme | M | P | | V | N |
+ | SIP-Item-Number | M | P | | V | N |
+ | SIP-Authenticate | M | P | | V | N |
+ | SIP-Authorization | M | P | | V | N |
+ | SIP-Authentication-Info | M | P | | V | N |
+ | SIP-Number-Auth-Items | M | P | | V | N |
+ | SIP-Deregistration-Reason | M | P | | V | N |
+ | SIP-Reason-Code | M | P | | V | N |
+ | SIP-Reason-Info | M | P | | V | N |
+ | SIP-Visited-Network-Id | M | P | | V | N |
+ | SIP-User-Authorization-Type | M | P | | V | N |
+ | SIP-Supported-User-Data-Type | M | P | | V | N |
+ | SIP-User-Data | M | P | | V | N |
+ | SIP-User-Data-Type | M | P | | V | N |
+ | SIP-User-Data-Contents | M | P | | V | N |
+ | SIP-User-Data-Already-Available | M | P | | V | N |
+ | SIP-Method | M | P | | V | N |
+ +----------------------------------+------+-----+-----+------+------+
+
+ Table 3: Summary of the new AVPs flags
+
+9.1. SIP-Accounting-Information AVP
+
+ The SIP-Accounting-Information (AVP Code 368) is of type Grouped, and
+ contains the Diameter addresses of those nodes that are able to
+ collect accounting information.
+
+ The SIP-Accounting-Information AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [RFC3588]):
+
+ SIP-Accounting-Information ::= < AVP Header: 368 >
+ * [ SIP-Accounting-Server-URI ]
+ * [ SIP-Credit-Control-Server-URI ]
+ * [ AVP]
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 46]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+9.1.1. SIP-Accounting-Server-URI AVP
+
+ The SIP-Accounting-Server-URI AVP (AVP Code 369) is of type
+ DiameterURI. This AVP contains the address of a Diameter server that
+ is able to receive SIP-session-related accounting information.
+
+9.1.2. SIP-Credit-Control-Server-URI AVP
+
+ The SIP-Credit-Control-Server-URI AVP (AVP Code 370) is of type
+ DiameterURI. This AVP contains the address of a Diameter server that
+ is able to authorize real-time credit control usage. The Diameter
+ Credit-Control Application [RFC4006] may be used for this purpose.
+
+9.2. SIP-Server-URI AVP
+
+ The SIP-Server-URI AVP (AVP Code 371) is of type UTF8String. This
+ AVP contains a SIP or SIPS URI (as defined in RFC 3261 [RFC3261])
+ that identifies a SIP server.
+
+9.3. SIP-Server-Capabilities AVP
+
+ The SIP-Server-Capabilities AVP (AVP Code 372) is of type Grouped.
+ The Diameter indicates in this AVP the requirements for a particular
+ SIP capability, so that the Diameter client (SIP server) is able to
+ select another appropriate SIP server to serve the user.
+
+ The SIP-Server-Capabilities AVP allows a Diameter client (SIP server)
+ to select another SIP server for triggering or executing services to
+ the user. A user may have enabled some services that require the
+ implementation of certain capabilities in the SIP server that
+ triggers or executes those services. For example, the SIP server
+ that triggers or executes services to this user may need to implement
+ SIP servlets [JSR-000116], Call Processing Language (CPL) [RFC3880],
+ or any other kind of capability. Or perhaps that user belongs to a
+ premium users group that has a certain stringent quality-of-service
+ agreement that requires a fast SIP server. The capabilities required
+ or recommended to a given user are conveyed in the
+ SIP-Server-Capabilities AVP. When it receives them, the Diameter
+ client (SIP server) that does the SIP server selection needs to have
+ the means to find out available SIP servers that meet the required or
+ optional capabilities. Such means are outside the scope of this
+ specification.
+
+ Note that the SIP-Server-Capabilities AVP assists the Diameter client
+ (SIP server) to produce a subset of all the available SIP servers to
+ be allocated to the user in the Home Realm; this is the subset that
+ conforms the requirements of capabilities on a per-user basis.
+ Typically this subset will be formed of more than a single SIP
+
+
+
+Garcia-Martin, et al. Standards Track [Page 47]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ server, so once the subset of those SIP servers is identified, it is
+ possible that several instances of these SIP servers exist, in which
+ case the Diameter client (SIP server) should choose one particular
+ SIP server to execute and trigger services to this user. It is
+ expected that at this point the SIP server (Diameter client) will
+ follow the procedures of RFC 3263 [RFC3263] to allocate one SIP
+ server to the user.
+
+ The SIP-Server-Capabilities AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [RFC3588]):
+
+ SIP-Server-Capabilities ::= < AVP Header: 372 >
+ * [ SIP-Mandatory-Capability ]
+ * [ SIP-Optional-Capability ]
+ * [ SIP-Server-URI ]
+ * [ AVP ]
+
+9.3.1. SIP-Mandatory-Capability AVP
+
+ The SIP-Mandatory-Capability AVP (AVP Code 373) is of type
+ Unsigned32. The value represents a certain capability (or set of
+ capabilities) that have to be fulfilled by the SIP server allocated
+ to the user.
+
+ The semantics of the different values are not standardized, as it is
+ a matter of the administrative network to allocate its own semantics
+ within its own network. Each value has to represent a single
+ capability within the administrative network.
+
+9.3.2. SIP-Optional-Capability AVP
+
+ The SIP-Optional-Capability AVP (AVP Code 374) is of type Unsigned32.
+ The value represents a certain capability (or set of capabilities)
+ that, optionally, may be fulfilled by the SIP server allocated to the
+ user.
+
+ The semantics of the different values are not standardized, as it is
+ a matter of the administrative network to allocate its own semantics
+ within its own network. Each value has to represent a single
+ capability within the administrative network.
+
+9.4. SIP-Server-Assignment-Type AVP
+
+ The SIP-Server-Assignment-Type AVP (AVP Code 375) is of type
+ Enumerated and indicates the type of server update being performed in
+ a Diameter Server-Assignment-Request (SAR) operation. The following
+ values are defined:
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 48]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ o NO_ASSIGNMENT (0)
+ The Diameter client uses this value to request the user profile of
+ a SIP AOR, without affecting the registration state of that
+ identity.
+
+ o REGISTRATION (1)
+ First SIP registration of a SIP AOR.
+
+ o RE_REGISTRATION (2)
+ Subsequent SIP registration of a SIP AOR.
+
+ o UNREGISTERED_USER (3)
+ The SIP server has received a SIP request (e.g., SIP INVITE)
+ addressed for a SIP AOR that is not registered.
+
+ o TIMEOUT_DEREGISTRATION (4)
+ The SIP registration timer of an identity has expired.
+
+ o USER_DEREGISTRATION (5)
+ The SIP server has received a request to deregister a SIP AOR.
+
+ o TIMEOUT_DEREGISTRATION_STORE_SERVER_NAME (6)
+ The SIP registration timer of an identity has expired. The SIP
+ server keeps the user data stored and requests the Diameter server
+ to store the SIP server address.
+
+ o USER_DEREGISTRATION_STORE_SERVER_NAME (7)
+ The SIP server has received a user-initiated deregistration
+ request. The SIP server keeps the user data stored and requests
+ the Diameter server to store the SIP server address.
+
+ o ADMINISTRATIVE_DEREGISTRATION (8)
+ The SIP server, due to administrative reasons, has deregistered a
+ SIP AOR.
+
+ o AUTHENTICATION_FAILURE (9)
+ The authentication of a user has failed.
+
+ o AUTHENTICATION_TIMEOUT (10)
+ The authentication timer has expired.
+
+ o DEREGISTRATION_TOO_MUCH_DATA (11)
+ The SIP server has requested user profile information from the
+ Diameter server and has received a volume of data higher than it
+ can accept.
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 49]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+9.5. SIP-Auth-Data-Item AVP
+
+ The SIP-Auth-Data-Item (AVP Code 376) is of type Grouped and contains
+ the authentication and/or authorization information pertaining to a
+ user.
+
+ When the Diameter server uses the grouped SIP-Auth-Data-Item AVP to
+ include a SIP-Authenticate AVP, the Diameter server MUST send a
+ maximum of one authentication data item (e.g., in case the SIP
+ request contained several credentials). Section 11 contains a
+ detailed discussion and normative text of the case when a SIP request
+ contains several credentials.
+
+ The SIP-Auth-Data-Item AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [RFC3588]):
+
+ SIP-Auth-Data-Item ::= < AVP Header: 376 >
+ { SIP-Authentication-Scheme }
+ [ SIP-Item-Number ]
+ [ SIP-Authenticate ]
+ [ SIP-Authorization ]
+ [ SIP-Authentication-Info ]
+ * [ AVP ]
+
+9.5.1. SIP-Authentication-Scheme AVP
+
+ The SIP-Authentication-Scheme AVP (AVP Code 377) is of type
+ Enumerated and indicates the authentication scheme used in the
+ authentication of SIP services. RFC 2617 identifies this value as an
+ "auth-scheme" (see Section 1.2 of RFC 2617 [RFC2617]). The only
+ currently defined value is:
+
+ o DIGEST (0) to indicate HTTP Digest authentication as specified in
+ RFC 2617 [RFC2617] Section 3.2.1. Derivative work is also
+ considered Digest authentication scheme, as long as the
+ "auth-scheme" is identified as Digest in the SIP headers carrying
+ the HTTP authentication. This includes, e.g., the HTTP Digest
+ authentication using AKA [RFC3310].
+
+ Each HTTP Digest directive (parameter) is transported in a
+ corresponding AVP, whose name follows the pattern Digest-*. The
+ Digest-* AVPs are RADIUS attributes imported from the RADIUS
+ Extension for Digest Authentication [RFC4590] namespace, allowing a
+ smooth transition between RADIUS and Diameter applications supporting
+ SIP. The Diameter SIP application goes a step further by grouping
+ the Digest-* AVPs into the SIP-Authenticate, SIP-Authorization, and
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 50]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ SIP-Authentication-Info grouped AVPs that correspond to the SIP WWW-
+ Authenticate/Proxy-Authentication, Authorization/Proxy-Authorization,
+ and Authentication-Info headers fields, respectively.
+
+ Note: Due to the fact that HTTP Digest authentication [RFC2617] is
+ the only mandatory authentication mechanism in SIP, this memo only
+ provides support for HTTP Digest authentication and derivative
+ work such as HTTP Digest authentication using AKA [RFC3310].
+ Extensions to this memo can register new values and new AVPs to
+ provide support for other authentication schemes or extensions to
+ HTTP Digest authentication.
+
+ Note: Although RFC 2617 [RFC2617] defines the Basic and Digest
+ schemes for authenticating HTTP requests, RFC 3261 [RFC3261] only
+ imports HTTP Digest as a mechanism to provide authentication in
+ SIP.
+
+ Due to syntactic requirements, HTTP Digest authentication has to
+ escape quote characters in contents of HTTP Digest directives. When
+ translating directives into Digest-* AVPs, the Diameter client or
+ server removes the surrounding quotes where present, as required by
+ the syntax of the Digest-* attributes defined in the "RADIUS
+ Extension for Digest Authentication" [RFC4590].
+
+9.5.2. SIP-Item-Number AVP
+
+ The SIP-Item-Number (AVP Code 378) is of type Unsigned32 and is
+ included in a SIP-Auth-Data-Item grouped AVP in circumstances where
+ there are multiple occurrences of SIP-Auth-Data-Item AVPs and the
+ order of processing is relevant. The AVP indicates the order in
+ which the Grouped SIP-Auth-Data-Item should be processed. Lower
+ values of the SIP-Item-Number AVP indicate that the whole
+ SIP-Auth-Data-Item SHOULD be processed before other
+ SIP-Auth-Data-Item AVPs that contain higher values in the
+ SIP-Item-Number AVP.
+
+9.5.3. SIP-Authenticate AVP
+
+ The SIP-Authenticate AVP (AVP Code 379) is of type Grouped and
+ contains a reconstruction of either the SIP WWW-Authenticate or
+ Proxy-Authentication header fields specified in RFC 2617 [RFC2617]
+ for the HTTP Digest authentication scheme. Additionally, the AVP may
+ include a Digest-HA1 AVP that contains H(A1) (as defined in RFC 2617
+ [RFC2617]). H(A1) allows the Diameter client to create an expected
+ response and compare it with the Digest response received from the
+ SIP UA.
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 51]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ The SIP-Authenticate AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [RFC3588]):
+
+ 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 ]
+
+9.5.4. SIP-Authorization AVP
+
+ The SIP-Authorization AVP (AVP Code 380) is of type Grouped and
+ contains a reconstruction of either the SIP Authorization or
+ Proxy-Authorization header fields specified in RFC 2617 [RFC2617] for
+ the HTTP Digest authentication scheme.
+
+ The SIP-Authorization AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [RFC3588]):
+
+ 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 ]
+
+9.5.5. SIP-Authentication-Info AVP
+
+ The SIP-Authentication-Info AVP (AVP Code 381) is of type Grouped and
+ contains a reconstruction of the SIP Authentication-Info header
+ specified in RFC 2617 [RFC2617] for the HTTP Digest authentication
+ scheme.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 52]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ The SIP-Authentication-Info AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [RFC3588]):
+
+ SIP-Authentication-Info ::= < AVP Header: 381 >
+ [ Digest-Nextnonce ]
+ [ Digest-QoP ]
+ [ Digest-Response-Auth ]
+ [ Digest-CNonce ]
+ [ Digest-Nonce-Count ]
+ * [ AVP ]
+
+ Note that, in some cases, the Digest-Response-Auth AVP cannot be
+ calculated at the Diameter server, but has to be calculated at the
+ Diameter client (SIP server). For example, if the value of the
+ quality of protection (qop) parameter in Digest is set to "auth-int",
+ then the response-digest (rspauth parameter value in Digest) is
+ calculated with the hash of the body of the SIP response, which is
+ not available at the Diameter server. In this case, the Diameter
+ client (SIP server) must calculate the response-digest once the body
+ of the SIP response is calculated.
+
+ Therefore, a value of "auth-int" in the Digest-QoP AVP of the
+ SIP-Authentication-Info AVP indicates that the Diameter client (SIP
+ server) MUST compute the Digest "rspauth" parameter value at the
+ Diameter client (SIP server).
+
+9.5.6. Digest AVPs
+
+ The following AVPs are RADIUS attributes defined in the RADIUS
+ Extension for Digest Authentication [RFC4590] and imported by this
+ specification: Digest-AKA-Auts, Digest-Algorithm, Digest-Auth-Param,
+ Digest-CNonce, Digest-Domain, Digest-Entity-Body-Hash, Digest-HA1,
+ Digest-Method, Digest-Nextnonce, Digest-Nonce, Digest-Nonce-Count,
+ Digest-Opaque, Digest-QoP, Digest-Realm, Digest-Response,
+ Digest-Response-Auth, Digest-URI, Digest-Username, and Digest-Stale.
+
+9.5.6.1. Considerations about Digest-HA1 AVP
+
+ The Digest-HA1 AVP contains the value, pre-calculated at the Diameter
+ server, of H(A1) as defined in RFC 2617 [RFC2617]. The Diameter
+ client can use H(A1) to calculate the expected Digest response,
+ according to this challenge. If the SIP UA is in possession of the
+ credentials, the calculated expected response and the response sent
+ from the SIP UA will match. The Diameter server MAY include this AVP
+ to enable and assist the SIP server in authenticating the SIP UA.
+
+ This scenario is not applicable when the Diameter server is
+ configured to use a session MD5 (MD5-sess) algorithm, because the
+
+
+
+Garcia-Martin, et al. Standards Track [Page 53]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Diameter server requires the client nonce to compute the H(A1) before
+ sending it to the Diameter client, and the client nonce might not be
+ available when the computation of H(A1) is done. Therefore, if the
+ final authentication is delegated to the Diameter client, it is
+ RECOMMENDED to configure the Diameter server to use algorithms
+ different than MD5-sess in HTTP Digest.
+
+ It is up to the Diameter server to include a Digest-HA1 AVP. The
+ Diameter server calculates the Digest H(A1) with the username,
+ password, and realm (and nonce and cnonce, if applicable) as inputs,
+ and places the result in the Digest-HA1 AVP value. For more details
+ of the A1 computation, see RFC 2617 [RFC2617] Section 3.2.2.2. The
+ Diameter client can calculate the Digest expected response with H(A1)
+ as input, as described in RFC 2617 [RFC2617] Section 3.2.2.
+
+ Section 11 provides further normative details about the usage of the
+ Digest-HA1 AVP.
+
+9.5.6.2. Considerations about Digest-Entity-Body-Hash AVP
+
+ The Digest-Entity-Body-Hash AVP contains a hash of the entity body
+ contained in the SIP message. This hash is required by HTTP Digest
+ with quality of protection set to "auth-int". Diameter clients MUST
+ use this AVP to transport the hash of the entity body when HTTP
+ Digest is the authentication mechanism and the Diameter server
+ requires verification of the integrity of the entity body (e.g., qop
+ parameter set to "auth-int").
+
+ The clarifications described in Section 22.4 of RFC 3261 [RFC3261]
+ about the hash of empty entity bodies apply to the
+ Digest-Entity-Body-Hash AVP.
+
+9.5.6.3. Considerations about Digest-Auth-Param AVP
+
+ The Digest-Auth-Param AVP is the mechanism whereby the Diameter
+ client and Diameter server can exchange possible extension parameters
+ contained in Digest headers that are either not understood by the
+ Diameter client or for which there are no corresponding stand-alone
+ AVPs. Unlike the previously listed Digest-* AVPs, the
+ Digest-Auth-Param contains not only the value, but also the parameter
+ name, since it is unknown to the Diameter client. The Diameter node
+ MUST insert one Digest parameter/value combination per AVP value. If
+ the Digest header contains several unknown parameters, then the
+ Diameter implementation MUST repeat this AVP and each instance MUST
+ contain one different unknown Digest parameter/value combination.
+ This AVP corresponds to the "auth-param" parameter defined in Section
+ 3.2.1 of RFC 2617 [RFC2617].
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 54]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Example: Assume that the Diameter server wants the SIP server to send
+ a "foo" parameter with the value set to "bar", so that the SIP server
+ sends that combination in a SIP WWW-Authenticate header field. The
+ Diameter server builds a grouped SIP-Authenticate AVP that contains a
+ Digest-Auth-Param whose value is set to foo="bar". Then the SIP
+ server creates the WWW-Authenticate header field with all the digest
+ parameters (received in Digest-* AVPs) and adds the foo="bar"
+ parameter to that header field.
+
+9.6. SIP-Number-Auth-Items AVP
+
+ The SIP-Number-Auth-Items AVP (AVP Code 382) is of type Unsigned32
+ and indicates the number of authentication and/or authorization
+ credentials that the Diameter server included in a Diameter message.
+
+ When the AVP is present in a request, it indicates the number of
+ SIP-Auth-Data-Items the Diameter client is requesting. This can be
+ used, for instance, when the SIP server is requesting several
+ pre-calculated authentication credentials. In the answer message,
+ the SIP-Number-Auth-Items AVP indicates the actual number of items
+ that the Diameter server included.
+
+9.7. SIP-Deregistration-Reason AVP
+
+ The SIP-Deregistration-Reason AVP (AVP Code 383) is of type Grouped
+ and indicates the reason for a deregistration operation.
+
+ The SIP-Deregistration-Reason AVP is defined as follows (per the
+ grouped-avp-def of RFC 3588 [RFC3588]):
+
+ SIP-Deregistration-Reason ::= < AVP Header: 383 >
+ { SIP-Reason-Code }
+ [ SIP-Reason-Info ]
+ * [ AVP ]
+
+9.7.1. SIP-Reason-Code AVP
+
+ The SIP-Reason-Code AVP (AVP Code 384) is of type Enumerated and
+ defines the reason for the network initiated deregistration. The
+ following values are defined:
+
+ o PERMANENT_TERMINATION (0)
+ o NEW_SIP_SERVER_ASSIGNED (1)
+ o SIP_SERVER_CHANGE (2)
+ o REMOVE_SIP_SERVER (3)
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 55]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+9.7.2. SIP-Reason-Info AVP
+
+ The SIP-Reason-Info AVP (AVP Code 385) is of type UTF8String and
+ contains textual information that can be rendered to the user, about
+ the reason for a deregistration.
+
+9.8. SIP-AOR AVP
+
+ The SIP-AOR AVP is a RADIUS attribute imported from the RADIUS
+ Extension for Digest Authentication [RFC4590] namespace, allowing a
+ smooth transition between RADIUS and Diameter applications supporting
+ SIP. The SIP-AOR AVP carries the URI of the intended user related to
+ the SIP request (whose location in SIP may vary depending on the
+ actual SIP request and whether the SIP server is acting on Diameter
+ due to a SIP-originated or terminating requests).
+
+ The Diameter client (SIP server) uses the value found in a SIP
+ Request-URI or a header field value of the SIP request to construct
+ the SIP-AOR AVP. The selection of a Request-URI or a particular
+ header field to create the value of the SIP-AOR AVP depends on the
+ semantics of the SIP message and whether the SIP server is acting for
+ originating or terminating requests. For instance, when the SIP
+ server receives an INVITE request addressed to the served user (e.g.,
+ the SIP server is receiving a terminating SIP request), it maps the
+ SIP Request-URI of the SIP request to this AVP. However, when the
+ SIP server receives an INVITE request originated by the served user,
+ it can map either the P-Asserted-Identity or the From header field
+ values to this AVP. If the SIP server is acting as a SIP registrar,
+ then it maps the To header field of the REGISTER request to the
+ SIP-AOR AVP.
+
+9.9. SIP-Visited-Network-Id AVP
+
+ The SIP-Visited-Network-Id AVP (AVP Code 386) is of type UTF8String.
+ This AVP contains an identifier that helps the home network identify
+ the visited network (e.g., the visited network domain name), in order
+ to authorize roaming to that visited network.
+
+9.10. SIP-User-Authorization-Type AVP
+
+ The SIP-User-Authorization-Type AVP (AVP Code 387) is of type
+ Enumerated and indicates the type of user authorization being
+ performed in a User Authorization operation, i.e., the Diameter
+ User-Authorization-Request (UAR) command. The following values are
+ defined:
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 56]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ o REGISTRATION (0)
+ This value is used for initial registration or re-registration.
+ This is the default value.
+
+ o DEREGISTRATION (1)
+ This value is used for deregistration.
+
+ o REGISTRATION_AND_CAPABILITIES (2)
+ This value is used for initial registration or re-registration
+ when the SIP server explicitly requests the Diameter server to get
+ capability information. This capability information helps the SIP
+ server to allocate another SIP server to serve the user.
+
+9.11. SIP-Supported-User-Data-Type AVP
+
+ The SIP-Supported-User-Data-Type AVP (AVP Code 388) is of type
+ UTF8String and contains a string that identifies the type of
+ supported user data (user profile, see SIP-User-Data AVP
+ (Section 9.12)) supported in the node. The AVP can be repeated, if
+ the SIP server supports several user data types. In case of
+ repetition, the Diameter client should order the different instances
+ of this AVP according to its preferences.
+
+ When the Diameter client inserts this AVP in a SAR message, it allows
+ the Diameter client to provide an indication to the Diameter server
+ of the types of user data supported by the SIP server. The Diameter
+ server, upon inspection of these AVPs, will return a suitable
+ SIP-User-Data AVP (Section 9.12) of the type indicated in the
+ SIP-User-Data-Type AVP (Section 9.12.1).
+
+9.12. SIP-User-Data AVP
+
+ The SIP-User-Data AVP (AVP Code 389) is of type Grouped. This AVP
+ allows the Diameter server to transport user-specific data, such as a
+ user profile, to the SIP server (in the Diameter client). The
+ Diameter server selects a type of user data that is understood by the
+ SIP server in the Diameter client, and has been indicated in a
+ SIP-Supported-User-Data-Type AVP. In case the Diameter client
+ indicated support for several types of user data, the Diameter server
+ SHOULD choose the first type supported by the client.
+
+ The SIP-User-Data grouped AVP contains a SIP-User-Data-Type AVP that
+ indicates the type of user data included in the
+ SIP-User-Data-Contents-AVP.
+
+ The SIP-User-Data AVP is defined as follows (per the grouped-avp-def
+ of RFC 3588 [RFC3588]):
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 57]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ SIP-User-Data ::= < AVP Header: 389 >
+ { SIP-User-Data-Type }
+ { SIP-User-Data-Contents }
+ * [ AVP ]
+
+9.12.1. SIP-User-Data-Type AVP
+
+ The SIP-User-Data AVP (AVP Code 390) is of type UTF8String and
+ contains a string that identifies the type of user data included in
+ the SIP-User-Data AVP (Section 9.12).
+
+ This document does not specify a convention to characterize the type
+ of user data contained in the SIP-User-Data AVP (Section 9.12). It
+ is believed that in most cases this feature will be used in
+ environments controlled by a network administrator who can configure
+ both the client and server to assign the same value type at the
+ client and server. It is also RECOMMENDED that organizations
+ developing their own profile of SIP-User-Data AVP (Section 9.12)
+ allocate a type based on their canonical DNS name. For instance,
+ organization "example.com" can define several types of SIP-User-Data
+ and allocate the types "type1.dsa.example.com",
+ "type2.dsa.example.com", and so on. This convention will avoid a
+ clash in the allocation of types of SIP-User-Data AVP (Section 9.12).
+
+9.12.2. SIP-User-Data-Contents AVP
+
+ The SIP-User-Data-Contents AVP (AVP Code 391) is of type OctetString.
+ The Diameter peers do not need to understand the value of this AVP.
+
+ The AVP contains the user profile data required for a SIP server to
+ give service to the user.
+
+9.13. SIP-User-Data-Already-Available AVP
+
+ The SIP-User-Data-Already-Available AVP (AVP Code 392) is of type
+ Enumerated and gives an indication to the Diameter server about
+ whether the Diameter client (SIP server) already received the portion
+ of the user profile needed in order to serve the user. The following
+ values are defined:
+
+ o USER_DATA_NOT_AVAILABLE (0)
+ The Diameter client (SIP server) does not have the data that it
+ needs to serve the user.
+
+ o USER_DATA_ALREADY_AVAILABLE (1)
+ The Diameter client (SIP server) already has received the data
+ that it needs to serve the user.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 58]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+9.14. SIP-Method AVP
+
+ The SIP-Method-AVP (AVP Code 393) is of type UTF8String and contains
+ the method of the SIP request that triggered the Diameter message.
+ The Diameter server MUST use this AVP solely for authorization of SIP
+ requests, and MUST NOT use it to compute the Digest authentication.
+ To compute the Digest authentication, the Diameter server MUST use
+ the Digest-Method AVP instead.
+
+10. New Values for Existing AVPs
+
+ This section defines new values that the Diameter SIP application
+ extends to already existing AVPs.
+
+10.1. Extension to the Result-Code AVP Values
+
+ The Result-Code AVP is already defined in RFC 3588 [RFC3588]. In
+ addition to the values already defined in RFC 3588 [RFC3588], the
+ Diameter SIP application defines the following new Result-Code AVP
+ values:
+
+10.1.1. Success Result-Code AVP Values
+
+ A Diameter peer uses Result-Code AVP values that fall into the
+ success category to inform the remote peer that a request has been
+ successfully completed.
+
+ o DIAMETER_FIRST_REGISTRATION 2003
+ The user was not previously registered. The Diameter server has
+ now authorized the registration.
+
+ o DIAMETER_SUBSEQUENT_REGISTRATION 2004
+ The user is already registered. The Diameter server has now
+ authorized the re-registration.
+
+ o DIAMETER_UNREGISTERED_SERVICE 2005
+ The user is not currently registered, but the requested service
+ can still be granted to the user.
+
+ o DIAMETER_SUCCESS_SERVER_NAME_NOT_STORED 2006
+ The request operation was successfully processed. The Diameter
+ server does not keep a record of the SIP server address assigned
+ to the user.
+
+ o DIAMETER_SERVER_SELECTION 2007
+ The Diameter server has authorized the registration. The user has
+ already been assigned a SIP server, but it may be necessary to
+ select a new SIP server for the user.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 59]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ o DIAMETER_SUCCESS_AUTH_SENT_SERVER_NOT_STORED 2008
+ The requested operation was successfully executed. The Diameter
+ server is sending a number of authentication credentials in the
+ answer message. The Diameter server does not keep a record of the
+ SIP server.
+
+10.1.2. Transient Failures Result-Code AVP Values
+
+ A Diameter peer uses a Result-Code AVP value that falls in the
+ transient failures category to inform the remote peer that a request
+ could not be satisfied at the time it was received, but it MAY be
+ satisfied by the Diameter peer in the future.
+
+ o DIAMETER_USER_NAME_REQUIRED 4013
+ The Diameter request did not contain a User-Name AVP, which is
+ required to complete the transaction. The Diameter peer MAY
+ include a User-Name AVP and attempt the request again.
+
+10.1.3. Permanent Failures Result-Code AVP Values
+
+ A Diameter peer uses a Result-Code AVP value that falls into the
+ permanent failure category to inform the remote peer that the request
+ failed and should not be attempted again.
+
+ o DIAMETER_ERROR_USER_UNKNOWN 5032
+ The SIP-AOR AVP value does not belong to a known user in this
+ realm.
+
+ o DIAMETER_ERROR_IDENTITIES_DONT_MATCH 5033
+ The value in one of the SIP-AOR AVPs is not allocated to the user
+ specified in the User-Name AVP.
+
+ o DIAMETER_ERROR_IDENTITY_NOT_REGISTERED 5034
+ A query for location information is received for a SIP AOR that
+ has not been registered before. The user to which this identity
+ belongs cannot be given service in this situation.
+
+ o DIAMETER_ERROR_ROAMING_NOT_ALLOWED 5035
+ The user is not allowed to roam to the visited network.
+
+ o DIAMETER_ERROR_IDENTITY_ALREADY_REGISTERED 5036
+ The identity being registered has already been assigned a server
+ and the registration status does not allow that it is overwritten.
+
+ o DIAMETER_ERROR_AUTH_SCHEME_NOT_SUPPORTED 5037
+ The authentication scheme indicated in an authentication request
+ is not supported.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 60]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ o DIAMETER_ERROR_IN_ASSIGNMENT_TYPE 5038
+ The SIP server address sent in the SIP-Server-URI AVP value of the
+ Diameter Server-Assignment-Request (SAR) command is the same SIP
+ server address that is currently assigned to the user name, but
+ the SIP-Server-Assignment-Type AVP is not allowed. For example,
+ the user is registered and the Server-Assignment-Request indicates
+ the assignment for an unregistered user.
+
+ o DIAMETER_ERROR_TOO_MUCH_DATA 5039
+ The Diameter peer in the SIP server receives more data than it can
+ accept. The SIP server cannot overwrite the already stored data.
+
+ o DIAMETER_ERROR_NOT SUPPORTED_USER_DATA 5040
+ The SIP server informs the Diameter server that the received
+ subscription data contained information that was not recognized or
+ supported.
+
+11. Authentication Details
+
+ Authenticating a user can occur through various mechanisms.
+ Currently HTTP Digest authentication is supported. The actual
+ authentication is performed in either the SIP server or the Diameter
+ server.
+
+ If the Diameter server wants to assure that authentication will take
+ place in the Diameter server (as opposed to a delegated
+ authentication taking place in the SIP server), it MUST NOT include a
+ Digest-HA1 AVP (part of the grouped SIP-Authenticate AVP, which in
+ turn is part of the SIP-Auth-Data-Item AVP) in a MAA message. The
+ Diameter server MAY include a pre-calculated Digest-HA1 AVP in the
+ MAA message if it wants to delegate authentication of the user to the
+ SIP server.
+
+ Note that on systems where the SIP User Agent is using HTTP Digest
+ authentication [RFC2617] inside of Transport Layer Security (TLS)
+ [RFC4346], where only the SIP proxy server has a certificate,
+ delegating authentication to the SIP server (by making Digest-HA1
+ available to the SIP server) might reduce the load on the Diameter
+ server.
+
+ When requesting authentication, the Diameter client indicates in the
+ SIP-Number-Auth-Items AVP value of a Diameter MAR message how many
+ authentication credentials are being requested. In the Diameter MAA
+ message, the Diameter server MAY include more than one
+ SIP-Auth-Data-Item AVP, but it is only useful for the Diameter client
+ if the Digest-QoP AVP was set to 'auth-int' (in the MAR message), and
+ if future authentications will have the same realm. When including
+ more than one SIP-Auth-Data-Item AVP, the Diameter server SHOULD
+
+
+
+Garcia-Martin, et al. Standards Track [Page 61]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ indicate how many instances of SIP-Auth-Data-Item AVPs are present
+ with the SIP-Number-Auth-Items AVP. This number may be different
+ from the one requested in the Diameter MAR message. If multiple
+ SIP-Auth-Data-Item AVPs are present, and their ordering is
+ significant, the Diameter server MUST include a SIP-Item-Number AVP
+ in each grouping to indicate the order. The
+ SIP-Authentication-Scheme AVP indicates "Digest" and the
+ SIP-Authenticate AVP contains data (typically a challenge of some
+ kind) that the user can use for her authentication. The grouped
+ SIP-Authorization AVP contains the AVPs that conform to the response
+ expected from the user.
+
+ If the Diameter server performs the authentication of the user, the
+ Diameter MAR message that the Diameter client sends to the Diameter
+ server MUST include all the authentication credentials supplied by
+ the SIP UA (there might be more than one credential, e.g., different
+ realms, authentication of proxies, etc.). Each credential is
+ inserted in a grouped SIP-Authorization AVP (part of the grouped
+ SIP-Auth-Data-Item AVP). The Diameter client MUST insert a
+ SIP-Number-Auth-Items AVP with the value set to the number of
+ credentials enclosed. If necessary, the Digest-Entity-Body-Hash AVP
+ will contain a hash of the body, needed to perform the
+ authentication. If the authentication is successful, the Diameter
+ MAA message will contain a Result-Code AVP indicating success, and if
+ necessary, the Diameter server MAY include one or more
+ SIP-Auth-Data-Item AVPs to provide further authentication credentials
+ to the SIP server. If the authentication is unsuccessful due to
+ missing credentials, the Diameter MAA message will include a
+ SIP-Auth-Data-Item AVP with the SIP-Authentication-Scheme and
+ SIP-Authenticate AVPs containing data (typically a challenge of some
+ kind) that the user can use to authenticate itself.
+
+ There are situations where a SIP request traverses several proxies,
+ and each of the proxies requests to authenticate the SIP UA. In this
+ situation, it is a valid scenario that a SIP request received at a
+ SIP server contains several sets of credentials. The 'realm'
+ directive in HTTP is the key that the Diameter client can use to
+ determine which credential is applicable. Also, none of the realms
+ may be of interest to the Diameter client, in which case the Diameter
+ client MUST consider that no credentials (of interest) were sent. In
+ any case, a Diameter client MUST send zero or exactly one credential
+ to the Diameter server. The Diameter client MUST choose the
+ credential based on the 'realm' directive in the
+ Authorization/Proxy-Authorization header field, and it MUST match the
+ realm of the Diameter client.
+
+ It must be noted that nonces are always generated in the Diameter
+ server.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 62]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+12. Migration from RADIUS
+
+ RADIUS offers support for HTTP Digest authentication in the RADIUS
+ Extension for Digest Authentication [RFC4590]. A number of AVPs (the
+ Digest-* AVPs) of this Diameter SIP application are imported from the
+ RADIUS attributes namespace, thus making the migration from RADIUS to
+ Diameter smooth.
+
+ Note that the RADIUS Extension for Digest Authentication [RFC4590]
+ provides a more limited scope than this Diameter SIP application.
+ Specifically, the RADIUS extension for Digest Authentication merely
+ provides support for HTTP Digest authentication, whereas the Diameter
+ SIP application provides support for user location, profile
+ downloading and update, etc.
+
+ The following sections discuss several configurations in which a
+ gateway translates RADIUS to Diameter and vice versa.
+
+12.1. Gateway from RADIUS Client to Diameter Server
+
+ The gateway maps Access-Request messages to MAR request. If a RADIUS
+ Access-Request message contains at least one Digest-* attribute, the
+ gateway maps all Digest-* attributes to the AVPs of a Diameter
+ SIP-Authorization AVP, constructs a MAR message, and sends it to the
+ Diameter server. If the RADIUS Access-Request message does not
+ contain any Digest-* attribute, then the RADIUS client does not want
+ to apply HTTP Digest authentication, in which case, actions at the
+ gateway are outside the scope of this document.
+
+ The Diameter server responds with a MAA message. If the MAA message
+ contains a Result-Code AVP set to the value DIAMETER_MULTI_ROUND_AUTH
+ and contains challenge parameters in a SIP-Authenticate AVP, then the
+ gateway translates the AVPs of SIP-Authenticate AVP and puts the
+ resulting RADIUS attributes into an Access-Challenge message. It
+ sends the Access-Challenge message to the RADIUS client.
+
+ If the MAA message contains a SIP-Authentication-Info and a
+ Digest-Response AVP, the gateway converts these AVPs to the
+ corresponding RADIUS attributes and constructs a RADIUS message. If
+ the Result-Code AVP is DIAMETER_SUCCESS, an Access-Accept is sent.
+ In all other cases, an Access-Reject is sent.
+
+12.2. Gateway from Diameter Client to RADIUS Server
+
+ The Diameter client sends a Diameter MAR message to the gateway. If
+ the MAR message does not contain SIP-Auth-Data-Item AVPs, the gateway
+ constructs an Access-Request message and maps the SIP-AOR and
+ SIP-Method AVPs to RADIUS attributes. The gateway sends the
+
+
+
+Garcia-Martin, et al. Standards Track [Page 63]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Access-Request message to the RADIUS server, which will respond with
+ an Access-Challenge. The gateway creates a MAA message with a
+ Result-Code AVP set to DIAMETER_MULTI_ROUND_AUTH and maps the
+ Digest-* attributes to Diameter AVPs in a SIP-Authenticate AVP. The
+ gateway sends the resulting MAA to the Diameter client, which will
+ respond with a new MAR.
+
+ The gateway checks the SIP-Auth-Data-Item AVPs of this MAR for an AVP
+ where the Digest-Realm AVP matches the locally configured realm
+ value. It takes the AVPs from this SIP-Auth-Data-Item AVP, converts
+ them into the corresponding RADIUS attributes and constructs a RADIUS
+ Access-Request message. The gateway sends the Access-Request message
+ to the RADIUS server. If the RADIUS server responds with an
+ Access-Accept message, the gateway converts the RADIUS attributes to
+ Diameter AVPs, constructs a MAA message with a Result-Code AVP set to
+ DIAMETER_SUCCESS and sends this message to the Diameter client. If
+ the RADIUS server responds with an Access-Reject message, the gateway
+ converts the RADIUS attributes to Diameter AVPs, constructs a MAA
+ message with a Result-Code AVP set to
+ DIAMETER_ERROR_IDENTITIES_DONT_MATCH, and sends this message to the
+ Diameter client.
+
+12.3. Known Limitations
+
+ As mentioned earlier, there is not a 100% match between the Diameter
+ SIP application and the RADIUS Extension for Digest Authentication
+ [RFC4590]. In particular, the RADIUS Extension for Digest
+ Authentication [RFC4590] does not offer equivalent functionality to
+ the Diameter UAR/UAA, SAR/SAA, LIR/LIA, RTR/RTA, and PPR/PPA messages
+ defined by this specification.
+
+13. IANA Considerations
+
+ This document serves as IANA registration request for a number of
+ items that should be registered in the AAA parameters registry.
+
+13.1. Application Identifier
+
+ This document defines a standards-track Application-ID that falls
+ into the Application Identifier standards-track address space defined
+ by RFC 3588 [RFC3588] Section 11.3. This Application-ID has been
+ registered in the Application IDs sub-registry of the AAA parameters
+ registry with the following data:
+
+ ID values Name Reference
+ ----------- ------------------------ ---------
+ 6 Diameter Session Initiation RFC 4740
+ Protocol (SIP) Application
+
+
+
+Garcia-Martin, et al. Standards Track [Page 64]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+13.2. Command Codes
+
+ This document defines new standard commands whose Command Codes are
+ to be allocated within the standard permanent Command Codes address
+ space defined in RFC 3588 [RFC3588] Section 11.2.1. These command
+ codes should be registered in the Command Codes sub-registry of the
+ AAA parameters registry.
+
+ Table 1 in Section 8 contains the detailed list of Command Code names
+ and values that are part of this Diameter application.
+
+13.3. AVP Codes
+
+ This document defines new standard AVPs, whose AVP Codes are to be
+ allocated within the AVP Codes address space defined in RFC 3588
+ [RFC3588] Section 11.4. These AVP codes have been registered in the
+ AVP Codes sub-registry of the AAA parameters registry.
+
+ Table 2 in Section 9 contains the detailed list of AVP names and AVP
+ codes that are part of this Diameter application.
+
+13.4. Additional Values for the Result-Code AVP Value
+
+ This document defines new standard Result-Code AVP values to be
+ allocated within the Result-Code AVP address space defined in RFC
+ 3588 [RFC3588] Section 14.4.1. These values are listed in the
+ Result-Code AVP values section of the AVP Specific Values
+ sub-registry of the AAA parameters registry.
+
+ Section 10.1.1 lists the new Result-Code AVP values that fall into
+ the success category, according to RFC 3588 [RFC3588] Section 7.1.2.
+
+ Section 10.1.2 lists the new Result-Code AVP values that fall into
+ the transient failures category, according to RFC 3588 [RFC3588]
+ Section 7.1.4.
+
+ Section 10.1.3 lists the new Result-Code AVP values that fall into
+ the permanent failures category, according to RFC 3588 [RFC3588]
+ Section 7.1.5.
+
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 65]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+13.5. Creation of the SIP-Server-Assignment-Type Section in the AAA
+ Registry
+
+ This document defines a new SIP-Server-Assignment-Type AVP (see
+ Section 9.4). This AVP is of type Enumerated. We define an initial
+ set of values that should be registered by IANA. IANA should create
+ a new "SIP-Sever-Assignment-Type AVP values" section under the AVP
+ Specific Values sub-registry of the AAA parameters registry. The
+ initial list of values is listed in Section 9.4.
+
+13.6. Creation of the SIP-Authentication-Scheme Section in the AAA
+ Registry
+
+ This document defines a new SIP-Authentication-Scheme AVP (see
+ Section 9.5.1). This AVP is of type Enumerated. We currently define
+ a single value that should be registered by IANA. IANA should create
+ a new "SIP-Authentication-Scheme AVP values" section under the AVP
+ Specific Values sub-registry of the AAA parameters registry. The
+ initial list of values is included in Section 9.5.1.
+
+13.7. Creation of the SIP-Reason-Code Section in the AAA Registry
+
+ This document defines a new SIP-Reason-Code AVP (see Section 9.7.1).
+ This AVP is of type Enumerated. We define an initial set of values
+ that should be registered by IANA. IANA should create a new
+ "SIP-Reason-Code AVP values" section under the AVP Specific Values
+ sub-registry of the AAA parameters registry. The initial list of
+ values is listed in Section 9.7.1.
+
+13.8. Creation of the SIP-User-Authorization-Type Section in the AAA
+ Registry
+
+ This document defines a new SIP-User-Authorization-Type AVP (see
+ Section 9.10). This AVP is of type Enumerated. We define an initial
+ set of values that should be registered by IANA. IANA should create
+ a new "SIP-User-Authorization-Type AVP values" section under the AVP
+ Specific Values sub-registry of the AAA parameters registry. The
+ initial list of values is listed in Section 9.10.
+
+13.9. Creation of the SIP-User-Data-Already-Available Section in the
+ AAA Registry
+
+ This document defines a new SIP-User-Data-Already-Available AVP (see
+ Section 9.13). This AVP is of type Enumerated. We define an initial
+ set of values which should be registered by IANA. IANA should create
+ a new "SIP-User-Data-Already-Available AVP values" section under the
+ AVP Specific Values sub-registry of the AAA parameters registry. The
+ initial list of values is listed in Section 9.13.
+
+
+
+Garcia-Martin, et al. Standards Track [Page 66]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+14. Security Considerations
+
+ This memo does not describe a stand-alone protocol, but a particular
+ application for the Diameter protocol [RFC3588]. Consequently, all
+ the security considerations applicable to Diameter automatically
+ apply to this memo. In particular, Section 13 of RFC 3588 applies to
+ this memo.
+
+ This Diameter SIP application allows a Diameter client to use the
+ properties of HTTP Digest authentication [RFC2617] by evaluating or
+ sending to the Diameter server the credentials supplied by a user.
+ The discussion of HTTP Digest authentication in Section 4 of RFC 2617
+ [RFC2617] is also applicable to this memo.
+
+ This Diameter SIP application also allows a Diameter client to use
+ the properties of HTTP Digest authentication using AKA [RFC3310] by
+ evaluating or sending to the Diameter server the credentials supplied
+ by a user. Section 5 of RFC 3310 [RFC3310] is also applicable to
+ this memo.
+
+14.1. Final Authentication Check in the Diameter Client/SIP Server
+
+ The Diameter SIP application can be configured to operate in a
+ scenario where the final authentication check is performed in the
+ Diameter client (SIP server). There are a number of security
+ considerations associated to it; all of them are consequences of the
+ requirement to transfer H(A1) from the Diameter server to the
+ Diameter client:
+
+ o Both Diameter client and server must trust each other, such as
+ when both client and server belong to the same administrative
+ domain.
+
+ o To avoid eavesdroppers, the transport protocol between the
+ Diameter client and server MUST be secured. RFC 3588 [RFC3588]
+ specifies TLS [RFC4346] and IPsec as possible transport protection
+ mechanisms for Diameter.
+
+ Due to these security considerations, it is RECOMMENDED to configure
+ the Diameter SIP application to operate in the mode where the final
+ authentication check is performed in the Diameter server.
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 67]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+15. Contributors
+
+ The authors would like to thank the following contributors who made
+ substantial contributions to this work:
+
+ Pete McCann Lucent
+
+ Jaakko Rajaniemi Nokia
+
+ Wolfgang Beck (Deutsche Telekom AG) provided the text in Section 12,
+ "Migration from RADIUS".
+
+16. Acknowledgements
+
+ The authors would like to thank Tony Johansson and Kevin Purser for
+ their invaluable contribution to the start-up of this application and
+ the continuous progress. The authors would like to thank Daniel
+ Warren, Jayshree Bharatia, Kuntal Chowdhury, Jari Arkko, Avi Lior,
+ Wolfgang Beck, Ulrich Wiehe, Cullen Jennings, Anu Leinonen, Glen
+ Zorn, German Blanco, Mikko Aittola, Bert Wijnen, and Sam Hartman for
+ their reviews and valuable comments.
+
+ The Diameter SIP application is based on the Diameter application for
+ the Cx interface of the 3GPP IP Multimedia Subsystem [3GPP.29.229].
+ The authors would like to thank 3GPP Working Group CN4 for this work.
+
+17. References
+
+17.1. Normative References
+
+ [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+ [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence,
+ S., Leach, P., Luotonen, A., and L. Stewart, "HTTP
+ Authentication: Basic and Digest Access
+ Authentication", RFC 2617, June 1999.
+
+ [RFC3261] Rosenberg, J., Schulzrinne, H., Camarillo, G.,
+ Johnston, A., Peterson, J., Sparks, R., Handley, M.,
+ and E. Schooler, "SIP: Session Initiation Protocol",
+ RFC 3261, June 2002.
+
+ [RFC3310] Niemi, A., Arkko, J., and V. Torvinen, "Hypertext
+ Transfer Protocol (HTTP) Digest Authentication Using
+ Authentication and Key Agreement (AKA)", RFC 3310,
+ September 2002.
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 68]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ [RFC3588] Calhoun, P., Loughney, J., Guttman, E., Zorn, G., and
+ J. Arkko, "Diameter Base Protocol", RFC 3588,
+ September 2003.
+
+ [RFC4590] Sterman, B., Sadolevsky, D., Schwartz, D., Williams,
+ D., and W. Beck, "RADIUS Extension for Digest
+ Authentication", RFC 4590, July 2006.
+
+17.2. Informative References
+
+ [RFC4346] Dierks, T. and E. Rescorla, "The Transport Layer
+ Security (TLS) Protocol Version 1.1", RFC 4346, April
+ 2006.
+
+ [RFC3263] Rosenberg, J. and H. Schulzrinne, "Session Initiation
+ Protocol (SIP): Locating SIP Servers", RFC 3263,
+ June 2002.
+
+ [RFC3680] Rosenberg, J., "A Session Initiation Protocol (SIP)
+ Event Package for Registrations", RFC 3680,
+ March 2004.
+
+ [RFC3880] Lennox, J., Wu, X., and H. Schulzrinne, "Call
+ Processing Language (CPL): A Language for User Control
+ of Internet Telephony Services", RFC 3880,
+ October 2004.
+
+ [RFC4004] Calhoun, P., Johansson, T., Perkins, C., Hiller, T.,
+ and P. McCann, "Diameter Mobile IPv4 Application",
+ RFC 4004, August 2005.
+
+ [RFC4005] Calhoun, P., Zorn, G., Spence, D., and D. Mitton,
+ "Diameter Network Access Server Application",
+ RFC 4005, August 2005.
+
+ [RFC4006] Hakala, H., Mattila, L., Koskinen, J-P., Stura, M.,
+ and J. Loughney, "Diameter Credit-Control
+ Application", RFC 4006, August 2005.
+
+ [3GPP.29.229] 3GPP, "Cx and Dx interfaces based on the Diameter
+ protocol; Protocol details", 3GPP TS 29.229 5.12.0,
+ June 2006.
+
+ [JSR-000116] Java Community Process, "SIP Servlet API Specification
+ 1.0 Final Release", JSR 000116, March 2003.
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 69]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+Authors' Addresses
+
+ Miguel A. Garcia-Martin (Editor)
+ Nokia
+ P.O. Box 407
+ NOKIA GROUP, FIN 00045
+ Finland
+
+ Phone: +358 50 480 4586
+
+
+ Maria-Carmen Belinchon
+ Ericsson
+ Via de los Poblados 13
+ Madrid 28033
+ Spain
+
+ Phone: +34 91 339 3535
+
+
+ Miguel A. Pallares-Lopez
+ Ericsson
+ Via de los Poblados 13
+ Madrid 28033
+ Spain
+
+ Phone: +34 91 339 4222
+
+
+ Carolina Canales-Valenzuela
+ Ericsson
+ Via de los Poblados 13
+ Madrid 28033
+ Spain
+
+ Phone: +34 91 339 2680
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 70]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+ Kalle Tammi
+ Nokia
+ P.O.Box 785
+ Tampere 33101
+ Finland
+
+ Phone: +358 40 505 8670
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 71]
+
+RFC 4740 Diameter SIP Application November 2006
+
+
+Full Copyright Statement
+
+ Copyright (C) The IETF Trust (2006).
+
+ This document is subject to the rights, licenses and restrictions
+ contained in BCP 78, and except as set forth therein, the authors
+ retain all their rights.
+
+ This document and the information contained herein are provided on an
+ "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS
+ OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST,
+ AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT
+ THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY
+ IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR
+ PURPOSE.
+
+Intellectual Property
+
+ The IETF takes no position regarding the validity or scope of any
+ Intellectual Property Rights or other rights that might be claimed to
+ pertain to the implementation or use of the technology described in
+ this document or the extent to which any license under such rights
+ might or might not be available; nor does it represent that it has
+ made any independent effort to identify any such rights. Information
+ on the procedures with respect to rights in RFC documents can be
+ found in BCP 78 and BCP 79.
+
+ Copies of IPR disclosures made to the IETF Secretariat and any
+ assurances of licenses to be made available, or the result of an
+ attempt made to obtain a general license or permission for the use of
+ such proprietary rights by implementers or users of this
+ specification can be obtained from the IETF on-line IPR repository at
+ http://www.ietf.org/ipr.
+
+ The IETF invites any interested party to bring to its attention any
+ copyrights, patents or patent applications, or other proprietary
+ rights that may cover technology that may be required to implement
+ this standard. Please address the information to the IETF at
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+
+
+
+
+
+Garcia-Martin, et al. Standards Track [Page 72]
+
diff --git a/lib/diameter/doc/standard/rfc5447.txt b/lib/diameter/doc/standard/rfc5447.txt
new file mode 100644
index 0000000000..ec556ccc9f
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc5447.txt
@@ -0,0 +1,955 @@
+
+
+
+
+
+
+Network Working Group J. Korhonen, Ed.
+Request for Comments: 5447 Nokia Siemens Networks
+Category: Standards Track J. Bournelle
+ Orange Labs
+ H. Tschofenig
+ Nokia Siemens Networks
+ C. Perkins
+ WiChorus
+ K. Chowdhury
+ Starent Networks
+ February 2009
+
+
+ Diameter Mobile IPv6:
+ Support for Network Access Server to Diameter Server Interaction
+
+Status of This Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (c) 2009 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.
+
+Abstract
+
+ A Mobile IPv6 node requires a home agent address, a home address, and
+ a security association with its home agent before it can start
+ utilizing Mobile IPv6. RFC 3775 requires that some or all of these
+ parameters be statically configured. Mobile IPv6 bootstrapping work
+ aims to make this information dynamically available to the mobile
+ node. An important aspect of the Mobile IPv6 bootstrapping solution
+ is to support interworking with existing Authentication,
+ Authorization, and Accounting (AAA) infrastructures. This document
+ describes MIPv6 bootstrapping using the Diameter Network Access
+ Server to home AAA server interface.
+
+
+
+
+Korhonen, et al. Standards Track [Page 1]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+Table of Contents
+
+ 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 3
+ 2. Terminology and Abbreviations . . . . . . . . . . . . . . . . 3
+ 3. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
+ 4. Commands, Attribute-Value Pairs, and Advertising
+ Application Support . . . . . . . . . . . . . . . . . . . . . 6
+ 4.1. Advertising Application Support . . . . . . . . . . . . . 6
+ 4.2. Attribute-Value Pair Definitions . . . . . . . . . . . . . 6
+ 4.2.1. MIP6-Agent-Info AVP . . . . . . . . . . . . . . . . . 6
+ 4.2.2. MIP-Home-Agent-Address AVP . . . . . . . . . . . . . . 7
+ 4.2.3. MIP-Home-Agent-Host AVP . . . . . . . . . . . . . . . 7
+ 4.2.4. MIP6-Home-Link-Prefix AVP . . . . . . . . . . . . . . 8
+ 4.2.5. MIP6-Feature-Vector AVP . . . . . . . . . . . . . . . 8
+ 5. Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
+ 5.1. Home Agent Assignment by the NAS . . . . . . . . . . . . . 10
+ 5.2. Home Agent Assignment by the Diameter Server . . . . . . . 11
+ 5.3. Home Agent Assignment by the NAS or Diameter Server . . . 11
+ 6. Attribute-Value Pair Occurrence Tables . . . . . . . . . . . . 12
+ 7. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 13
+ 7.1. Registration of New AVPs . . . . . . . . . . . . . . . . . 13
+ 7.2. New Registry: Mobility Capability . . . . . . . . . . . . 13
+ 8. Security Considerations . . . . . . . . . . . . . . . . . . . 14
+ 9. Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . 14
+ 10. References . . . . . . . . . . . . . . . . . . . . . . . . . . 15
+ 10.1. Normative References . . . . . . . . . . . . . . . . . . . 15
+ 10.2. Informative References . . . . . . . . . . . . . . . . . . 15
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 2]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+1. Introduction
+
+ The Mobile IPv6 (MIPv6) specification [RFC3775] requires a mobile
+ node (MN) to perform registration with a home agent (HA) with
+ information about its current point of attachment (care-of address).
+ The HA creates and maintains the binding between the MN's home
+ address and the MN's care-of address.
+
+ In order to register with an HA, the MN needs to know some
+ information, such as the home link prefix, the HA address, the home
+ address(es), the home link prefix length, and security-association-
+ related information.
+
+ The aforementioned information may be statically configured.
+ However, static provisioning becomes an administrative burden for an
+ operator. Moreover, it does not address load balancing, failover,
+ opportunistic home link assignment, or assignment of local HAs in
+ close proximity to the MN. Also, the ability to react to sudden
+ environmental or topological changes is minimal. Static provisioning
+ may not be desirable, in light of these limitations.
+
+ Dynamic assignment of MIPv6 home registration information is a
+ desirable feature for ease of deployment and network maintenance.
+ For this purpose, the AAA infrastructure, which is used for access
+ authentication, can be leveraged to assign some or all of the
+ necessary parameters. The Diameter server in the Access Service
+ Provider's (ASP's) or Mobility Service Provider's (MSP's) network may
+ return these parameters to the AAA client. Regarding the
+ bootstrapping procedures, the AAA client might either be the Network
+ Access Server, in case of the integrated scenario, or the HA, in case
+ of the split scenario [RFC5026]. The terms "integrated" and "split"
+ are described in the following terminology section and were
+ introduced in [RFC4640] and [AAA].
+
+2. Terminology and Abbreviations
+
+ 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].
+
+ General mobility terminology can be found in [RFC3753]. The
+ following additional terms are either borrowed from [RFC4640] or
+ [RFC5026] or are introduced in this document:
+
+ Access Service Authorizer (ASA):
+
+ A network operator that authenticates an MN and establishes the
+ MN's authorization to receive Internet service.
+
+
+
+Korhonen, et al. Standards Track [Page 3]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ Access Service Provider (ASP):
+
+ A network operator that provides direct IP packet-forwarding to
+ and from the MN.
+
+ Mobility Service Authorizer (MSA):
+
+ A service provider that authorizes MIPv6 service.
+
+ Mobility Service Provider (MSP):
+
+ A service provider that provides MIPv6 service. In order to
+ obtain such service, the MN must be authenticated and authorized
+ to do so.
+
+ Split Scenario:
+
+ A scenario where the mobility service and the network access
+ service are authorized by different entities.
+
+ Integrated Scenario:
+
+ A scenario where the mobility service and the network access
+ service are authorized by the same entity.
+
+ Network Access Server (NAS):
+
+ A device that provides an access service for a user to a network.
+
+ Home AAA (HAAA):
+
+ An Authentication, Authorization, and Accounting server located in
+ the user's home network, i.e., in the home realm.
+
+ Local AAA (LAAA):
+
+ An Authentication, Authorization, and Accounting proxy located in
+ the local (ASP) network.
+
+ Visited AAA (VAAA):
+
+ An Authentication, Authorization, and Accounting proxy located in
+ a visited network, i.e., in the visited realm. In a roaming case,
+ the local Diameter proxy has the VAAA role (see Figure 1).
+
+
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 4]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+3. Overview
+
+ This document addresses the Authentication, Authorization, and
+ Accounting (AAA) functionality required for the MIPv6 bootstrapping
+ solutions outlined in [RFC4640], and focuses on the Diameter-based
+ AAA functionality for the NAS-to-HAAA (home AAA) server
+ communication.
+
+ In the integrated scenario, MIPv6 bootstrapping is provided as part
+ of the network access authentication procedure. Figure 1 shows the
+ participating entities.
+
+ +---------------------------+ +-----------------+
+ |Access Service Provider | |ASA/MSA/(MSP) |
+ |(Mobility Service Provider)| | |
+ | | | |
+ | +--------+ | | +--------+ |
+ | |Local | Diameter | | |Home | |
+ | |Diameter|<---------------------->|Diameter| |
+ | |Proxy | (*) | | |Server | |
+ | +--------+ | | +--------+ |
+ | ^ ^ | | ^ |
+ | | | | | |(+) |
+ | | | | | | |
+ | Diameter | | v |
+ | | |(+) +-------+ | | +-------+ |
+ | | | |Home | | | |Home | |
+ | | +-------->|Agent | | | |Agent | |
+ | (*)| |in ASP | | | |in MSP | |
+ | v +-------+ | | +-------+ |
+ +-------+ IEEE | +-----------+ +-------+ | +-----------------+
+ |Mobile | 802.1X | |NAS/Relay | |DHCPv6 | |
+ |Node |------------|Diameter |---|Server | |
+ | | PANA, | |Client |(+)| | |
+ +-------+ IKEv2, | +-----------+ +-------+ |
+ DHCP,... +---------------------------+
+ (+)
+
+ Legend:
+ (*): Functionality in scope of this specification.
+ (+): Extensions described in other documents.
+
+ Figure 1: Mobile IPv6 Bootstrapping in the Integrated Scenario
+
+ In a typical MIPv6 access scenario, an MN is attached to an ASP's
+ network. During the network attachment procedure, the MN interacts
+ with the NAS/Diameter client. Subsequently, the NAS/Diameter client
+ interacts with the Diameter server over the NAS-to-HAAA interface.
+
+
+
+Korhonen, et al. Standards Track [Page 5]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ When the Diameter server performs the authentication and
+ authorization for network access, it also determines whether the user
+ is authorized for the MIPv6 service. Based on the MIPv6 service
+ authorization and the user's policy profile, the Diameter server may
+ return several MIPv6 bootstrapping-related parameters to the NAS.
+ The NAS-to-HAAA interface described in this document is not tied to
+ the Dynamic Host Configuration Protocol for IPv6 (DHCPv6) as the only
+ mechanism to convey MIPv6-related configuration parameters from the
+ NAS/Diameter client to the mobile node.
+
+ While this specification addresses the bootstrapping of MIPv6 HA
+ information and possibly the assignment of the home link prefix, it
+ does not address how the Security Association (SA) between the MN and
+ the HA for MIPv6 purposes is created. The creation or the use of the
+ SA between the MN and the HA takes places after the procedures
+ described in this specification, and therefore are out of scope.
+
+4. Commands, Attribute-Value Pairs, and Advertising Application Support
+
+4.1. Advertising Application Support
+
+ This document does not define a new application. On the other hand,
+ it defines a number of attribute-value pairs (AVPs) used in the
+ interface between NAS to HAAA for the integrated scenario of MIPv6
+ bootstrapping. These AVPs can be used with any present and future
+ Diameter applications, where permitted by the command ABNF. The
+ examples using existing applications and their commands in the
+ following sections are for informational purposes only. The examples
+ in this document reuse the Extensible Authentication Protocol (EAP)
+ [RFC4072] application and its respective commands.
+
+4.2. Attribute-Value Pair Definitions
+
+4.2.1. MIP6-Agent-Info AVP
+
+ The MIP6-Agent-Info AVP (AVP code 486) is of type Grouped and
+ contains necessary information to assign an HA to the MN. When the
+ MIP6-Agent-Info AVP is present in a message, it MUST contain either
+ the MIP-Home-Agent-Address AVP, the MIP-Home-Agent-Host AVP, or both
+ AVPs. The grouped AVP has the following modified ABNF (as defined in
+ [RFC3588]):
+
+ MIP6-Agent-Info ::= < AVP-Header: 486 >
+ *2[ MIP-Home-Agent-Address ]
+ [ MIP-Home-Agent-Host ]
+ [ MIP6-Home-Link-Prefix ]
+ * [ AVP ]
+
+
+
+
+Korhonen, et al. Standards Track [Page 6]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ If both the MIP-Home-Agent-Address and MIP-Home-Agent-Host APVs are
+ present in the MIP6-Agent-Info, the MIP-Home-Agent-Address SHOULD
+ have a precedence over the MIP-Home-Agent-Host. The reason for this
+ recommendation is that the MIP-Home-Agent-Address points to a
+ specific home agent, whereas the MIP-Home-Agent-Host may point to a
+ group of HAs located within the same realm. A Diameter client or
+ agent may use the MIP-Home-Agent-Host AVP, for instance, to find out
+ in which realm the HA is located.
+
+ The ABNF allows returning up to two MIPv6 HA addresses. This is a
+ useful feature for deployments where the HA has both IPv6 and IPv4
+ addresses, and particularly addresses Dual Stack Mobile IPv6
+ (DSMIPv6) deployment scenarios [DSMIPv6].
+
+ The MIP6-Agent-Info AVP MAY also be attached by the NAS or by the
+ intermediating Diameter proxies in a request message when sent to the
+ Diameter server as a hint of a locally assigned HA. This AVP MAY
+ also be attached by the intermediating Diameter proxies in a reply
+ message from the Diameter server, if locally assigned HAs are
+ authorized by the Diameter server. There MAY be multiple instances
+ of the MIP6-Agent-Info AVP in Diameter messages, for example, in
+ cases where the NAS receives HA information from an MN's home network
+ and locally allocated HA information from the visited network. See
+ Section 4.2.5 for further discussion on possible scenarios.
+
+4.2.2. MIP-Home-Agent-Address AVP
+
+ The MIP-Home-Agent-Address AVP (AVP Code 334 [RFC4004]) is of type
+ Address and contains the IPv6 or IPv4 address of the MIPv6 HA. The
+ Diameter server MAY decide to assign an HA to the MN that is in close
+ proximity to the point of attachment (e.g., determined by the NAS-
+ Identifier AVP). There may be other reasons for dynamically
+ assigning HAs to the MN, for example, to share the traffic load.
+
+4.2.3. MIP-Home-Agent-Host AVP
+
+ The MIP-Home-Agent-Host AVP (AVP Code 348 [RFC4004]) is of type
+ Grouped and contains the identity of the assigned MIPv6 HA. Both the
+ Destination-Realm and the Destination-Host AVPs of the HA are
+ included in the grouped AVP. The usage of the MIP-Home-Agent-Host
+ AVP is equivalent to the MIP-Home-Agent-Address AVP but offers an
+ additional level of indirection by using the DNS infrastructure. The
+ Destination-Host AVP is used to identify an HA, and the Destination-
+ Realm AVP is used to identify the realm where the HA is located.
+
+ Depending on the actual deployment and DNS configuration, the
+ Destination-Host AVP MAY represent one or more home agents. It is
+ RECOMMENDED that the Destination-Host AVP identifies exactly one HA.
+
+
+
+Korhonen, et al. Standards Track [Page 7]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ It is RECOMMENDED that the MIP-Home-Agent-Host AVP is always included
+ in the MIP6-Agent-Info AVP. In this way, the HA can be associated
+ with the corresponding realm of the Diameter entity that added the
+ MIP6-Agent-Info AVP using the Destination-Realm AVP, which is
+ included in the MIP-Home-Agent-Host AVP.
+
+4.2.4. MIP6-Home-Link-Prefix AVP
+
+ The MIP6-Home-Link-Prefix AVP (AVP Code 125) is of type OctetString
+ and contains the Mobile IPv6 home network prefix information in a
+ network byte order. The home network prefix MUST be encoded as the
+ 8-bit prefix length information (one octet) followed by the 128-bit
+ field (16 octets) for the available home network prefix. The
+ trailing bits of the IPv6 prefix after the prefix length bits MUST be
+ set to zero (e.g., if the prefix length is 60, then the remaining 68
+ bits MUST be set to zero).
+
+ The HAAA MAY act as a central entity managing prefixes for MNs. In
+ this case, the HAAA returns to the NAS the prefix allocated to the
+ MN. The NAS/ASP then delivers the home link prefix to the MN using,
+ e.g., mechanisms described in [INTEGRATED]. The NAS/ASP MAY propose
+ to the HAAA a specific prefix to allocate to the MN by including the
+ MIP6-Home-Link-Prefix AVP in the request message. However, the HAAA
+ MAY override the prefix allocation hint proposed by the NAS/ASP and
+ return a different prefix in the response message.
+
+4.2.5. MIP6-Feature-Vector AVP
+
+ The MIP6-Feature-Vector AVP (AVP Code 124) is of type Unsigned64 and
+ contains a 64-bit flags field of supported capabilities of the NAS/
+ ASP. Sending and receiving the MIP6-Feature-Vector AVP with value 0
+ MUST be supported, although that does not provide much guidance about
+ specific needs of bootstrapping.
+
+ The NAS MAY include this AVP to indicate capabilities of the NAS/ASP
+ to the Diameter server. For example, the NAS may indicate that a
+ local HA can be provided. Similarly, the Diameter server MAY include
+ this AVP to inform the NAS/ASP about which of the NAS/ASP indicated
+ capabilities are supported or authorized by the ASA/MSA(/MSP).
+
+ The following capabilities are defined in this document:
+
+
+
+
+
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 8]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ MIP6_INTEGRATED (0x0000000000000001)
+
+ When this flag is set by the NAS, it means that the Mobile IPv6
+ integrated scenario bootstrapping functionality is supported by
+ the NAS. When this flag is set by the Diameter server, then the
+ Mobile IPv6 integrated scenario bootstrapping is supported by the
+ Diameter server.
+
+ LOCAL_HOME_AGENT_ASSIGNMENT (0x0000000000000002)
+
+ When this flag is set in the request message, a local home agent
+ outside the home realm is requested and may be assigned to the MN.
+ When this flag is set by the Diameter server in the answer
+ message, then the assignment of local HAs is authorized by the
+ Diameter server.
+
+ A local HA may be assigned by the NAS, LAAA, or VAAA depending on
+ the network architecture and the deployment.
+
+ The following examples show how the LOCAL_HOME_AGENT_ASSIGNMENT
+ (referred to as LOCAL-bit in the examples) capability and the MIP-
+ Agent-Info AVP (referred to as HA-Info in the examples) are used to
+ assign HAs -- either a local HA (L-HA) or a home network HA (H-HA).
+ Below are examples of request message combinations as seen by the
+ HAAA:
+
+ LOCAL-bit HA-Info Meaning
+
+ 0 - ASP or [LV]AAA is not able to assign an L-HA.
+ 0 L-HA Same as above. HA-Info must be ignored.
+ 1 - ASP or [LV]AAA can/wishes to assign an L-HA.
+ 1 L-HA Same as above but the ASP or [LV]AAA also
+ provides a hint of the assigned L-HA.
+
+ The same as above but for answer message combinations as seen by the
+ NAS:
+
+ LOCAL-bit HA-Info Meaning
+
+ 0 - No HA assignment allowed for HAAA or [LV]AAA.
+ 0 H-HA L-HA is not allowed. HAAA assigns an H-HA.
+ 1 - L-HA is allowed. No HAAA- or [LV]AAA-assigned HA.
+ 1 L-HA L-HA is allowed. [LV]AAA also assigns an L-HA.
+ 1 H-HA L-HA is allowed. HAAA also assigns an HA.
+ 1 H-HA L-HA is allowed. HAAA assigns an H-HA and
+ + L-HA [LV]AAA also assigns an L-HA.
+
+ An NAS should expect to receive multiple MIP6-Agent-Info AVPs.
+
+
+
+Korhonen, et al. Standards Track [Page 9]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+5. Examples
+
+5.1. Home Agent Assignment by the NAS
+
+ In this scenario, we consider the case where the NAS wishes to
+ allocate a local HA to the MN. The NAS will also inform the Diameter
+ server about the HA address it has assigned to the visiting MN (e.g.,
+ 2001:db8:1:c020::1). The Diameter-EAP-Request message, therefore,
+ has the MIP6-Feature-Vector with the LOCAL_HOME_AGENT_ASSIGNMENT and
+ the MIP6_INTEGRATED set. The MIP6-Agent-Info AVP contains the MIP-
+ Home-Agent-Address AVP with the address of the proposed HA.
+
+ Diameter
+ NAS/VAAA Server
+ | |
+ | Diameter-EAP-Request |
+ | MIP6-Feature-Vector=(LOCAL_HOME_AGENT_ASSIGNMENT |
+ | | MIP6_INTEGRATED) |
+ | MIP6-Agent-Info{ |
+ | MIP-Home-Agent-Address(2001:db8:1:c020::1)} |
+ | } |
+ | Auth-Request-Type=AUTHORIZE_AUTHENTICATE |
+ | EAP-Payload(EAP Start) |
+ |---------------------------------------------------------------->|
+ | |
+ | |
+ : ...more EAP Request/Response pairs... :
+ | |
+ | |
+ | Diameter-EAP-Answer |
+ | MIP6-Feature-Vector=(LOCAL_HOME_AGENT_ASSIGNMENT |
+ | | MIP6_INTEGRATED) |
+ | Result-Code=DIAMETER_SUCCESS |
+ | EAP-Payload(EAP Success) |
+ | EAP-Master-Session-Key |
+ | (authorization AVPs) |
+ | ... |
+ |<----------------------------------------------------------------|
+ | |
+
+ Figure 2: Home Agent Assignment by the NAS
+
+ Depending on the Diameter server's configuration and the user's
+ subscription profile, the Diameter server either accepts or rejects
+ the local HA allocated by the NAS. In our example, the Diameter
+ server accepts the proposal, and the MIP6-Feature-Vector AVP with
+ LOCAL_HOME_AGENT_ASSIGNMENT flag (together with the MIP6_INTEGRATED
+ flag) is set and returned to the NAS.
+
+
+
+Korhonen, et al. Standards Track [Page 10]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+5.2. Home Agent Assignment by the Diameter Server
+
+ In this scenario, we consider the case where the NAS supports the
+ Diameter MIPv6 integrated scenario as defined in this document, but
+ does not offer local HA assignment. Hence, the MIP6-Feature-Vector
+ AVP only has the MIP6_INTEGRATED flag set. The Diameter server
+ allocates an HA to the mobile node and conveys the address in the
+ MIP-Home-Agent-Address AVP that is encapsulated in the MIP6-Agent-
+ Info AVP. Additionally, the MIP6-Feature-Vector AVP has the
+ MIP6_INTEGRATED flag set.
+
+ Diameter
+ NAS Server
+ | |
+ | Diameter-EAP-Request |
+ | MIP6-Feature-Vector=(MIP6_INTEGRATED) |
+ | Auth-Request-Type=AUTHORIZE_AUTHENTICATE |
+ | EAP-Payload(EAP Start) |
+ |---------------------------------------------------------------->|
+ | |
+ | |
+ : ...more EAP Request/Response pairs... :
+ | |
+ | |
+ | Diameter-EAP-Answer |
+ | MIP6-Agent-Info{ |
+ | MIP-Home-Agent-Address(2001:db8:6000:302::1) |
+ | } |
+ | MIP6-Feature-Vector=(MIP6_INTEGRATED) |
+ | Result-Code=DIAMETER_SUCCESS |
+ | EAP-Payload(EAP Success) |
+ | EAP-Master-Session-Key |
+ | (authorization AVPs) |
+ | ... |
+ |<----------------------------------------------------------------|
+ | |
+
+ Figure 3: Home Agent Assignment by the Diameter Server
+
+5.3. Home Agent Assignment by the NAS or Diameter Server
+
+ This section shows another message flow for the MIPv6 integrated
+ scenario bootstrapping where the NAS informs the Diameter server that
+ it is able to locally assign an HA to the MN. The Diameter server is
+ able to provide an HA to the MN but also authorizes the assignment of
+ the local HA. The Diameter server then replies to the NAS with
+ HA-related bootstrapping information.
+
+
+
+
+Korhonen, et al. Standards Track [Page 11]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ Whether the NAS/ASP then offers a locally assigned HA or the
+ Diameter-server-assigned HA to the MN is, in this example, based on
+ the local ASP policy.
+
+ Diameter
+ NAS/VAAA Server
+ | |
+ | Diameter-EAP-Request |
+ | MIP6-Feature-Vector=(LOCAL_HOME_AGENT_ASSIGNMENT |
+ | | MIP6_INTEGRATED) |
+ | MIP6-Agent-Info{ |
+ | MIP-Home-Agent-Address(2001:db8:1:c020::1)} |
+ | } |
+ | Auth-Request-Type=AUTHORIZE_AUTHENTICATE |
+ | EAP-Payload(EAP Start) |
+ |---------------------------------------------------------------->|
+ | |
+ | |
+ : ...more EAP Request/Response pairs... :
+ | |
+ | |
+ | Diameter-EAP-Answer |
+ | MIP6-Agent-Info{ |
+ | MIP-Home-Agent-Address(2001:db8:6000:302::1)} |
+ | MIP6-Feature-Vector=(LOCAL_HOME_AGENT_ASSIGNMENT |
+ | | MIP6_INTEGRATED) |
+ | Result-Code=DIAMETER_SUCCESS |
+ | EAP-Payload(EAP Success) |
+ | EAP-Master-Session-Key |
+ | (authorization AVPs) |
+ | ... |
+ |<----------------------------------------------------------------|
+ | |
+
+ Figure 4: Home Agent Assignment by the NAS or Diameter Server
+
+ If the Diameter server does not allow the MN to use a locally
+ assigned HA, the Diameter server returns to the MN the MIP6-Feature-
+ Vector AVP with the LOCAL_HOME_AGENT_ASSIGNMENT bit unset and the HA
+ address it allocated.
+
+6. Attribute-Value Pair Occurrence Tables
+
+ Figure 5 lists the MIPv6 bootstrapping NAS-to-HAAA interface AVPs
+ along with a specification determining how many of each new AVP may
+ be included in a Diameter command. They may be present in any
+ Diameter application request and answer commands, where permitted by
+ the command ABNF.
+
+
+
+Korhonen, et al. Standards Track [Page 12]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ +-----------+
+ | Command |
+ |-----+-----+
+ Attribute Name | Req | Ans |
+ -------------------------------|-----+-----|
+ MIP6-Agent-Info | 0+ | 0+ |
+ MIP6-Feature-Vector | 0-1 | 0-1 |
+ +-----+-----+
+
+ Figure 5: Generic Request and Answer Commands AVP Table
+
+7. IANA Considerations
+
+7.1. Registration of New AVPs
+
+ This specification defines the following AVPs that have been
+ allocated from a normal Diameter AVP Code space (values >= 256):
+
+ MIP6-Agent-Info is set to 486
+
+ The following new AVPs are to be allocated from RADIUS Attribute Type
+ space [RFC2865] so that they are RADIUS backward-compatible (AVP Code
+ values between 0-255):
+
+ MIP6-Feature-Vector is set to 124
+ MIP6-Home-Link-Prefix is set to 125
+
+7.2. New Registry: Mobility Capability
+
+ IANA has created a new registry for the Mobility Capability as
+ described in Section 4.2.5.
+
+ Token | Value | Description
+ ----------------------------------+---------------------+------------
+ MIP6_INTEGRATED | 0x0000000000000001 | [RFC5447]
+ LOCAL_HOME_AGENT_ASSIGNMENT | 0x0000000000000002 | [RFC5447]
+ Available for Assignment via IANA | 2^x |
+
+ Allocation rule: Only numeric values that are 2^x (power of two,
+ where x >= 2) are allowed, based on the allocation policy described
+ below.
+
+ Following the example policies described in [RFC5226], new values for
+ the Mobility Capability Registry will be assigned based on the
+ "Specification Required" policy. No mechanism to mark entries as
+ "deprecated" is envisioned.
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 13]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+8. Security Considerations
+
+ The security considerations for the Diameter interaction required to
+ accomplish the integrated scenario are described in [INTEGRATED].
+ Additionally, the security considerations for the Diameter base
+ protocol [RFC3588], the Diameter NASREQ application [RFC4005], and
+ the Diameter EAP application (with respect to network access
+ authentication and the transport of keying material) [RFC4072] are
+ applicable to this document. Developers should insure that special
+ attention is paid to configuring the security associations protecting
+ the messages that enable the global positioning and allocation of
+ home agents, for instance, as outlined in Section 5.
+
+ Furthermore, the Diameter messages may be transported between the NAS
+ and the Diameter server via one or more AAA brokers or Diameter
+ agents (such as proxies). In this case, the AAA communication from
+ the NAS to the Diameter server relies on the security properties of
+ the intermediate AAA brokers and Diameter agents.
+
+9. Acknowledgments
+
+ This document is heavily based on the ongoing work for RADIUS MIPv6
+ interaction. Hence, credits go to respective authors for their work
+ with "RADIUS Mobile IPv6 Support" (November 2008). Furthermore, the
+ authors of this document would like to thank the authors of "Diameter
+ Mobile IPv6 Application" (November 2004) -- Franck Le, Basavaraj
+ Patil, Charles E. Perkins, and Stefano Faccin -- for their work in
+ the context of MIPv6 Diameter interworking. Their work influenced
+ this document. Jouni Korhonen would like to thank the Academy of
+ Finland and TEKES MERCoNe Project for providing funding to work on
+ this document while he was with TeliaSonera. Julien Bournelle would
+ like to thank GET/INT since he began to work on this document while
+ he was in their employ. Authors would also like to acknowledge
+ Raymond Hsu for his valuable feedback on local HA assignment and
+ Wolfgang Fritsche for his thorough review. Additionally, we would
+ like to Domagoj Premec for his review comments.
+
+ Finally, we would like to thank Alper Yegin, Robert Marks, and David
+ Frascone for their comments at the second WG Last Call.
+
+
+
+
+
+
+
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 14]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+10. References
+
+10.1. Normative References
+
+ [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+ [RFC2865] Rigney, C., Willens, S., Rubens, A., and W. Simpson,
+ "Remote Authentication Dial In User Service (RADIUS)",
+ RFC 2865, June 2000.
+
+ [RFC3588] Calhoun, P., Loughney, J., Guttman, E., Zorn, G., and
+ J. Arkko, "Diameter Base Protocol", RFC 3588,
+ September 2003.
+
+ [RFC3775] Johnson, D., Perkins, C., and J. Arkko, "Mobility
+ Support in IPv6", RFC 3775, June 2004.
+
+ [RFC4004] Calhoun, P., Johansson, T., Perkins, C., Hiller, T.,
+ and P. McCann, "Diameter Mobile IPv4 Application",
+ RFC 4004, August 2005.
+
+ [RFC4005] Calhoun, P., Zorn, G., Spence, D., and D. Mitton,
+ "Diameter Network Access Server Application", RFC 4005,
+ August 2005.
+
+ [RFC4072] Eronen, P., Hiller, T., and G. Zorn, "Diameter
+ Extensible Authentication Protocol (EAP) Application",
+ RFC 4072, August 2005.
+
+10.2. Informative References
+
+ [AAA] Giaretta, G., Guardini, I., Demaria, E., Bournelle, J.,
+ and R. Lopez, "AAA Goals for Mobile IPv6", Work
+ in Progress, May 2008.
+
+ [DSMIPv6] Solimand, H., "Mobile IPv6 Support for Dual Stack Hosts
+ and Routers (DSMIPv6)", Work in Progress,
+ December 2008.
+
+ [INTEGRATED] Chowdhury, K. and A. Yegin, "MIP6-bootstrapping for the
+ Integrated Scenario", Work in Progress, April 2008.
+
+ [RFC3753] Manner, J. and M. Kojo, "Mobility Related Terminology",
+ RFC 3753, June 2004.
+
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 15]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+ [RFC4640] Patel, A. and G. Giaretta, "Problem Statement for
+ bootstrapping Mobile IPv6 (MIPv6)", RFC 4640,
+ September 2006.
+
+ [RFC5026] Giaretta, G., Kempf, J., and V. Devarapalli, "Mobile
+ IPv6 Bootstrapping in Split Scenario", RFC 5026,
+ October 2007.
+
+ [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing
+ an IANA Considerations Section in RFCs", BCP 26,
+ RFC 5226, May 2008.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 16]
+
+RFC 5447 Diameter MIPv6 NAS-to-HAAA Interaction February 2009
+
+
+Authors' Addresses
+
+ Jouni Korhonen (editor)
+ Nokia Siemens Networks
+ Linnoitustie 6
+ Espoo FIN-02600
+ Finland
+
+
+
+ Julien Bournelle
+ Orange Labs
+ 38-4O rue du general Leclerc
+ Issy-Les-Moulineaux 92794
+ France
+
+
+
+ Hannes Tschofenig
+ Nokia Siemens Networks
+ Linnoitustie 6
+ Espoo 02600
+ Finland
+
+ URI: http://www.tschofenig.priv.at
+
+
+ Charles E. Perkins
+ WiChorus Inc.
+ 3590 North First St., Suite 300
+ San Jose, CA 95134
+ US
+
+
+
+ Kuntal Chowdhury
+ Starent Networks
+ 30 International Place
+ Tewksbury, MA 01876
+ US
+
+
+
+
+
+
+Korhonen, et al. Standards Track [Page 17]
+
diff --git a/lib/diameter/ebin/.gitignore b/lib/diameter/ebin/.gitignore
new file mode 100644
index 0000000000..185bb606e3
--- /dev/null
+++ b/lib/diameter/ebin/.gitignore
@@ -0,0 +1,5 @@
+
+*.app
+*.appup
+*.beam
+
diff --git a/lib/diameter/examples/.gitignore b/lib/diameter/examples/.gitignore
new file mode 100644
index 0000000000..d7995d4e6b
--- /dev/null
+++ b/lib/diameter/examples/.gitignore
@@ -0,0 +1,3 @@
+
+*.beam
+
diff --git a/lib/diameter/examples/GNUmakefile b/lib/diameter/examples/GNUmakefile
new file mode 100644
index 0000000000..4c3f87939b
--- /dev/null
+++ b/lib/diameter/examples/GNUmakefile
@@ -0,0 +1,35 @@
+#
+# %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%
+#
+
+EXAMPLES = client server relay # redirect proxy
+
+CALLBACKS = $(EXAMPLES:%=%_cb)
+MODULES = peer $(EXAMPLES) $(EXAMPLES:%=%_cb)
+
+BEAM = $(MODULES:%=%.beam)
+
+%.beam: %.erl
+ erlc -W $<
+
+all: $(BEAM)
+
+clean:
+ rm -f $(BEAM)
+
+.PHONY: all clean
diff --git a/lib/diameter/examples/client.erl b/lib/diameter/examples/client.erl
new file mode 100644
index 0000000000..36a77dd524
--- /dev/null
+++ b/lib/diameter/examples/client.erl
@@ -0,0 +1,125 @@
+%%
+%% %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%
+%%
+
+%%
+%% An example Diameter client that can sends base protocol RAR
+%% requests to a connected peer.
+%%
+%% The simplest usage is as follows this to connect to a server
+%% listening on the default port on the local host, assuming diameter
+%% is already started (eg. diameter:start()).
+%%
+%% client:start().
+%% client:connect(tcp).
+%% client:call().
+%%
+%% The first call starts the a service with the default name of
+%% ?MODULE, the second defines a connecting transport that results in
+%% a connection to the peer (if it's listening), the third sends it a
+%% RAR and returns the answer.
+%%
+
+-module(client).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+-export([start/1, %% start a service
+ connect/2, %% add a connecting transport
+ call/1, %% send using the record encoding
+ cast/1, %% send using the list encoding and detached
+ stop/1]). %% stop a service
+%% A real application would typically choose an encoding and whether
+%% they want the call to return the answer or not. Sending with
+%% both the record and list encoding here, one detached and one not,
+%% is just for demonstration purposes.
+
+%% Convenience functions using the default service name, ?SVC_NAME.
+-export([start/0,
+ connect/1,
+ stop/0,
+ call/0,
+ cast/0]).
+
+-define(SVC_NAME, ?MODULE).
+-define(APP_ALIAS, ?MODULE).
+-define(CALLBACK_MOD, client_cb).
+
+-define(L, atom_to_list).
+
+%% The service configuration. As in the server example, a client
+%% supporting multiple Diameter applications may or may not want to
+%% configure a common callback module on all applications.
+-define(SERVICE(Name), [{'Origin-Host', ?L(Name) ++ ".example.com"},
+ {'Origin-Realm', "example.com"},
+ {'Vendor-Id', 0},
+ {'Product-Name', "Client"},
+ {'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]},
+ {application, [{alias, ?APP_ALIAS},
+ {dictionary, ?DIAMETER_DICT_COMMON},
+ {module, ?CALLBACK_MOD}]}]).
+
+%% start/1
+
+start(Name)
+ when is_atom(Name) ->
+ peer:start(Name, ?SERVICE(Name)).
+
+start() ->
+ start(?SVC_NAME).
+
+%% connect/2
+
+connect(Name, T) ->
+ peer:connect(Name, T).
+
+connect(T) ->
+ connect(?SVC_NAME, T).
+
+%% call/1
+
+call(Name) ->
+ SId = diameter:session_id(?L(Name)),
+ RAR = #diameter_base_RAR{'Session-Id' = SId,
+ 'Auth-Application-Id' = 0,
+ 'Re-Auth-Request-Type' = 0},
+ diameter:call(Name, ?APP_ALIAS, RAR, []).
+
+call() ->
+ call(?SVC_NAME).
+
+%% cast/1
+
+cast(Name) ->
+ SId = diameter:session_id(?L(Name)),
+ RAR = ['RAR', {'Session-Id', SId},
+ {'Auth-Application-Id', 0},
+ {'Re-Auth-Request-Type', 1}],
+ diameter:call(Name, ?APP_ALIAS, RAR, [detach]).
+
+cast() ->
+ cast(?SVC_NAME).
+
+%% stop/1
+
+stop(Name) ->
+ peer:stop(Name).
+
+stop() ->
+ stop(?SVC_NAME).
diff --git a/lib/diameter/examples/client_cb.erl b/lib/diameter/examples/client_cb.erl
new file mode 100644
index 0000000000..524a8f94a1
--- /dev/null
+++ b/lib/diameter/examples/client_cb.erl
@@ -0,0 +1,103 @@
+%%
+%% %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(client_cb).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+%% diameter callbacks
+-export([peer_up/3,
+ peer_down/3,
+ pick_peer/4,
+ prepare_request/3,
+ prepare_retransmit/3,
+ handle_answer/4,
+ handle_error/4,
+ handle_request/3]).
+
+%% peer_up/3
+
+peer_up(_SvcName, _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(#diameter_packet{msg = ['RAR' = T | Avps]}, _, {_, Caps}) ->
+ #diameter_caps{origin_host = {OH, DH},
+ origin_realm = {OR, DR}}
+ = Caps,
+
+ {send, [T, {'Origin-Host', OH},
+ {'Origin-Realm', OR},
+ {'Destination-Host', DH},
+ {'Destination-Realm', DR}
+ | Avps]};
+
+prepare_request(#diameter_packet{msg = Rec}, _, {_, Caps}) ->
+ #diameter_caps{origin_host = {OH, DH},
+ origin_realm = {OR, DR}}
+ = Caps,
+
+ {send, Rec#diameter_base_RAR{'Origin-Host' = OH,
+ 'Origin-Realm' = OR,
+ 'Destination-Host' = DH,
+ 'Destination-Realm' = DR}}.
+
+%% prepare_retransmit/3
+
+prepare_retransmit(Packet, SvcName, Peer) ->
+ prepare_request(Packet, SvcName, Peer).
+
+%% handle_answer/4
+
+%% Since client.erl has detached the call when using the list
+%% encoding and not otherwise, output to the terminal in the
+%% the former case, return in the latter.
+
+handle_answer(#diameter_packet{msg = Msg}, Request, _SvcName, _Peer)
+ when is_list(Request) ->
+ io:format("answer: ~p~n", [Msg]);
+
+handle_answer(#diameter_packet{msg = Msg}, _Request, _SvcName, _Peer) ->
+ {ok, Msg}.
+
+%% handle_error/4
+
+handle_error(Reason, Request, _SvcName, _Peer)
+ when is_list(Request) ->
+ io:format("error: ~p~n", [Reason]);
+
+handle_error(Reason, _Request, _SvcName, _Peer) ->
+ {error, Reason}.
+
+%% handle_request/3
+
+handle_request(_Packet, _SvcName, _Peer) ->
+ erlang:error({unexpected, ?MODULE, ?LINE}).
diff --git a/lib/diameter/examples/peer.erl b/lib/diameter/examples/peer.erl
new file mode 100644
index 0000000000..89203e15c3
--- /dev/null
+++ b/lib/diameter/examples/peer.erl
@@ -0,0 +1,139 @@
+%%
+%% %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 library module that factors out commonality in the example
+%% Diameter peers.
+%%
+
+-module(peer).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+-export([start/2,
+ listen/2,
+ connect/2,
+ stop/1]).
+
+-type service_name()
+ :: term().
+
+-type protocol()
+ :: tcp | sctp.
+
+-type ip_address()
+ :: default
+ | inet:ip_address().
+
+-type server_config()
+ :: protocol()
+ | {protocol(), ip_address(), non_neg_integer()}.
+
+-type client_config()
+ :: protocol()
+ | {protocol(), ip_address(), non_neg_integer()}
+ | {protocol(), ip_address(), ip_address(), non_neg_integer()}.
+
+-define(DEFAULT_ADDR, {127,0,0,1}).
+-define(DEFAULT_PORT, 3868).
+
+%% ---------------------------------------------------------------------------
+%% Interface functions
+%% ---------------------------------------------------------------------------
+
+%% start/2
+
+-spec start(service_name(), list())
+ -> ok
+ | {error, term()}.
+
+start(Name, Opts)
+ when is_atom(Name), is_list(Opts) ->
+ diameter:start_service(Name, Opts).
+
+%% connect/2
+
+-spec connect(service_name(), client_config())
+ -> {ok, reference()}
+ | {error, term()}.
+
+connect(Name, T) ->
+ diameter:add_transport(Name, {connect, [{reconnect_timer, 5000}
+ | client(T)]}).
+
+%% listen/2
+
+-spec listen(service_name(), server_config())
+ -> {ok, reference()}
+ | {error, term()}.
+
+listen(Name, T) ->
+ diameter:add_transport(Name, {listen, server(T)}).
+
+%% stop/1
+
+-spec stop(service_name())
+ -> ok
+ | {error, term()}.
+
+stop(Name) ->
+ diameter:stop_service(Name).
+
+%% ---------------------------------------------------------------------------
+%% Internal functions
+%% ---------------------------------------------------------------------------
+
+%% server/1
+%%
+%% Return config for a listening transport.
+
+server({T, Addr, Port}) ->
+ [{transport_module, tmod(T)},
+ {transport_config, [{reuseaddr, true},
+ {ip, addr(Addr)},
+ {port, Port}]}];
+
+server(T) ->
+ server({T, ?DEFAULT_ADDR, ?DEFAULT_PORT}).
+
+%% client/1
+%%
+%% Return config for a connecting transport.
+
+client({T, LA, RA, RP}) ->
+ [{transport_module, tmod(T)},
+ {transport_config, [{ip, addr(LA)},
+ {raddr, addr(RA)},
+ {rport, RP},
+ {reuseaddr, true}]}];
+
+client({T, LA, RP}) ->
+ client({T, LA, LA, RP});
+
+client(T) ->
+ client({T, ?DEFAULT_ADDR, ?DEFAULT_ADDR, ?DEFAULT_PORT}).
+
+tmod(tcp) -> diameter_tcp;
+tmod(sctp) -> diameter_sctp.
+
+addr(default) ->
+ ?DEFAULT_ADDR;
+addr(A) ->
+ A.
diff --git a/lib/diameter/examples/redirect.erl b/lib/diameter/examples/redirect.erl
new file mode 100644
index 0000000000..b54701243f
--- /dev/null
+++ b/lib/diameter/examples/redirect.erl
@@ -0,0 +1,70 @@
+%%
+%% %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(redirect).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+-export([start/1,
+ listen/2,
+ stop/1]).
+
+-export([start/0,
+ listen/1,
+ stop/0]).
+
+-define(APP_ALIAS, ?MODULE).
+-define(SVC_NAME, ?MODULE).
+-define(CALLBACK_MOD, redirect_mod).
+
+%% The service configuration.
+-define(SERVICE(Name), [{'Origin-Host', atom_to_list(Name) ++ ".example.com"},
+ {'Origin-Realm', "example.com"},
+ {'Vendor-Id', 193},
+ {'Product-Name', "RedirectAgent"},
+ {'Auth-Application-Id', [?DIAMETER_APP_ID_RELAY]},
+ {application, [{alias, ?APP_ALIAS},
+ {dictionary, ?DIAMETER_DICT_RELAY},
+ {module, ?CALLBACK_MOD}]}]).
+
+%% start/1
+
+start(Name)
+ when is_atom(Name) ->
+ peer:start(Name, ?SERVICE(Name)).
+
+start() ->
+ start(?SVC_NAME).
+
+%% listen/2
+
+listen(Name, T) ->
+ peer:listen(Name, T).
+
+listen(T) ->
+ listen(?SVC_NAME, T).
+
+%% stop/1
+
+stop(Name) ->
+ peer:stop(Name).
+
+stop() ->
+ stop(?SVC_NAME).
diff --git a/lib/diameter/examples/redirect_cb.erl b/lib/diameter/examples/redirect_cb.erl
new file mode 100644
index 0000000000..ea7ad38749
--- /dev/null
+++ b/lib/diameter/examples/redirect_cb.erl
@@ -0,0 +1,63 @@
+%%
+%% %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(redirect_cb).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+%% diameter callbacks
+-export([peer_up/3,
+ peer_down/3,
+ pick_peer/4,
+ prepare_request/3,
+ prepare_retransmit/3,
+ handle_answer/4,
+ handle_error/4,
+ handle_request/3]).
+
+-define(UNEXPECTED, erlang:error({unexpected, ?MODULE, ?LINE})).
+
+peer_up(_SvcName, {PeerRef, _}, State) ->
+ io:format("up: ~p~n", [PeerRef]),
+ State.
+
+peer_down(_SvcName, {PeerRef, _}, State) ->
+ io:format("down: ~p~n", [PeerRef]),
+ State.
+
+pick_peer(_, _, _SvcName, _State) ->
+ ?UNEXPECTED.
+
+prepare_request(_, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+prepare_retransmit(_Packet, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+handle_answer(_Packet, _Request, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+handle_error(_Reason, _Request, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+handle_request(#diameter_packet{msg = _, errors = []}, _SvcName, {_, Caps}) ->
+ #diameter_caps{}
+ = Caps,
+ discard. %% TODO
diff --git a/lib/diameter/examples/relay.erl b/lib/diameter/examples/relay.erl
new file mode 100644
index 0000000000..deecb1cfc0
--- /dev/null
+++ b/lib/diameter/examples/relay.erl
@@ -0,0 +1,92 @@
+%%
+%% %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%
+%%
+
+%%
+%% An example Diameter relay agent.
+%%
+%% Usage to connect to a server listening on the default port over TCP
+%% and to listen on the default port over SCTP is as follows, assuming
+%% diameter is already started (eg. diameter:start()).
+%%
+%% Eg. relay:start().
+%% relay:connect(tcp).
+%% relay:listen(sctp).
+%%
+
+-module(relay).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+-export([start/1,
+ listen/2,
+ connect/2,
+ stop/1]).
+
+-export([start/0,
+ listen/1,
+ connect/1,
+ stop/0]).
+
+-define(APP_ALIAS, ?MODULE).
+-define(SVC_NAME, ?MODULE).
+-define(CALLBACK_MOD, relay_cb).
+
+%% The service configuration.
+-define(SERVICE(Name), [{'Origin-Host', atom_to_list(Name) ++ ".example.com"},
+ {'Origin-Realm', "example.com"},
+ {'Vendor-Id', 193},
+ {'Product-Name', "RelayAgent"},
+ {'Auth-Application-Id', [?DIAMETER_APP_ID_RELAY]},
+ {application, [{alias, ?MODULE},
+ {dictionary, ?DIAMETER_DICT_RELAY},
+ {module, ?CALLBACK_MOD}]}]).
+
+%% start/1
+
+start(Name)
+ when is_atom(Name) ->
+ peer:start(Name, ?SERVICE(Name)).
+
+start() ->
+ start(?SVC_NAME).
+
+%% listen/2
+
+listen(Name, T) ->
+ peer:listen(Name, T).
+
+listen(T) ->
+ listen(?SVC_NAME, T).
+
+%% connect/2
+
+connect(Name, T) ->
+ peer:connect(Name, T).
+
+connect(T) ->
+ connect(?SVC_NAME, T).
+
+%% stop/1
+
+stop(Name) ->
+ peer:stop(Name).
+
+stop() ->
+ stop(?SVC_NAME).
diff --git a/lib/diameter/examples/relay_cb.erl b/lib/diameter/examples/relay_cb.erl
new file mode 100644
index 0000000000..9ed6517d5c
--- /dev/null
+++ b/lib/diameter/examples/relay_cb.erl
@@ -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%
+%%
+
+-module(relay_cb).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+%% diameter callbacks
+-export([peer_up/3,
+ peer_down/3,
+ pick_peer/5,
+ prepare_request/4,
+ prepare_retransmit/4,
+ handle_answer/5,
+ handle_error/5,
+ handle_request/3]).
+
+peer_up(_SvcName, {PeerRef, _}, State) ->
+ io:format("up: ~p~n", [PeerRef]),
+ State.
+
+peer_down(_SvcName, {PeerRef, _}, State) ->
+ io:format("down: ~p~n", [PeerRef]),
+ State.
+
+%% Returning 'relay' from handle_request causes diameter to resend the
+%% incoming request, which leads to pick_peer and prepare_request
+%% callbacks as if sending explicitly. The 'extra' argument is
+%% appended to the argument list for callbacks following from
+%% resending of the request.
+
+handle_request(_Pkt, _SvcName, _Peer) ->
+ {relay, [{timeout, 1000}, {extra, [relayed]}]}.
+
+%% diameter will filter the sender in the Peers list.
+pick_peer([Peer | _], _, _SvcName, _State, relayed) ->
+ {ok, Peer}.
+
+prepare_request(Pkt, _SvcName, _Peer, relayed) ->
+ {send, Pkt}.
+
+prepare_retransmit(Pkt, _SvcName, _Peer, relayed) ->
+ {send, Pkt}.
+
+%% diameter expects handle_answer to return the diameter_packet record
+%% containing the answer when called for a relayed request.
+
+handle_answer(Pkt, _Request, _SvcName, _Peer, relayed) ->
+ Pkt.
+
+handle_error(Reason, _Request, _SvcName, _Peer, relayed) ->
+ {error, Reason}.
diff --git a/lib/diameter/examples/sctp.erl b/lib/diameter/examples/sctp.erl
new file mode 100644
index 0000000000..2e0e9d8b0b
--- /dev/null
+++ b/lib/diameter/examples/sctp.erl
@@ -0,0 +1,113 @@
+
+-module(sctp).
+
+%%
+%% A small example demonstrating the establishment of an SCTP
+%% association with gen_sctp.
+%%
+
+-export([assoc/0,
+ dbg/0]).
+
+-include_lib("kernel/include/inet_sctp.hrl").
+
+-define(ADDR, {127,0,0,1}).
+-define(SERVER_PORT, 3868).
+-define(CONNECT_TIMEOUT, 2000).
+-define(REQUEST, <<0:64>>).
+-define(REPLY, <<1:64>>).
+
+-record(server, {client,
+ socket,
+ assoc}).
+
+-record(client, {socket,
+ assoc}).
+
+%% assoc/0
+%%
+%% Return on a successfully established association, raise an
+%% exception otherwise.
+
+assoc() ->
+ {_, MRef} = spawn_monitor(fun server/0),
+ receive {'DOWN', MRef, process, _, Info} -> Info end.
+
+%% dbg/0
+
+dbg() ->
+ dbg:tracer(),
+ dbg:p(all,c),
+ dbg:tpl(?MODULE, [{'_',[],[{exception_trace}]}]),
+ dbg:tp(gen_sctp, [{'_',[],[{exception_trace}]}]),
+ ok.
+
+%% server/0
+
+server() ->
+ {ok, Sock} = gen_sctp:open([binary,
+ {reuseaddr, true},
+ {active, true},
+ {ip, ?ADDR},
+ {port, ?SERVER_PORT}]),
+ ok = gen_sctp:listen(Sock, true),
+ {_Pid, MRef} = spawn_monitor(fun client/0),
+ s(#server{client = MRef, socket = Sock}),
+ gen_sctp:close(Sock).
+
+%% s/1
+
+s(#server{} = S) ->
+ s(s(receive T -> T end, S));
+s(T) ->
+ T.
+
+%% s/2
+
+s({sctp, Sock, _RA, _RP, {[], #sctp_assoc_change{state = comm_up,
+ assoc_id = Id}}},
+ #server{socket = Sock, assoc = undefined}
+ = S) ->
+ S#server{assoc = Id};
+
+s({sctp, Sock, _RA, _RP, {[#sctp_sndrcvinfo{assoc_id = AId,
+ stream = SId}],
+ ?REQUEST}},
+ #server{socket = Sock, assoc = AId}
+ = S) ->
+ ok = gen_sctp:send(Sock, AId, SId, ?REPLY),
+ S;
+
+s({'DOWN', MRef, process, _, normal} = T, #server{client = MRef}) ->
+ T.
+
+%% client/0
+
+client() ->
+ {ok, Sock} = gen_sctp:open([binary,
+ {reuseaddr, true},
+ {active, true},
+ {ip, ?ADDR},
+ {port, 0}]),
+ ok = gen_sctp:connect_init(Sock, ?ADDR, ?SERVER_PORT, []),
+ c(#client{socket = Sock}),
+ gen_sctp:close(Sock).
+
+
+%% c/1
+
+c(#client{} = S) ->
+ c(c(receive T -> T end, S));
+c(T) ->
+ T.
+
+c({sctp, Sock, _RA, _RP, {[], #sctp_assoc_change{state = comm_up,
+ assoc_id = Id}}},
+ #client{socket = Sock, assoc = undefined}
+ = S) ->
+ ok = gen_sctp:send(Sock, Id, 0, ?REQUEST),
+ S#client{assoc = Id};
+
+c({sctp, Sock, _RA, _RP, {[#sctp_sndrcvinfo{assoc_id = AId}], ?REPLY}},
+ #client{socket = Sock, assoc = AId}) ->
+ ok.
diff --git a/lib/diameter/examples/server.erl b/lib/diameter/examples/server.erl
new file mode 100644
index 0000000000..ebb408e501
--- /dev/null
+++ b/lib/diameter/examples/server.erl
@@ -0,0 +1,88 @@
+%%
+%% %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%
+%%
+
+%%
+%% An example Diameter server that can respond to the base protocol
+%% RAR sent by the client example.
+%%
+%% The simplest example to start a server listening on the loopback
+%% address (which will serve the example usage given in client.erl) is
+%% like this assuming diameter is already started (eg. diameter:start()):
+%%
+%% server:start().
+%% server:listen(tcp).
+%%
+%% The first call starts a service, the second adds a transport listening
+%% on the default port.
+%%
+
+-module(server).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+-export([start/1, %% start a service
+ listen/2, %% add a listening transport
+ stop/1]). %% stop a service
+
+%% Convenience functions using the default service name, ?SVC_NAME.
+-export([start/0,
+ listen/1,
+ stop/0]).
+
+-define(SVC_NAME, ?MODULE).
+-define(APP_ALIAS, ?MODULE).
+-define(CALLBACK_MOD, server_cb).
+
+%% The service configuration. In a server supporting multiple Diameter
+%% applications each application may have its own, although they could all
+%% be configured with a common callback module.
+-define(SERVICE(Name), [{'Origin-Host', atom_to_list(Name) ++ ".example.com"},
+ {'Origin-Realm', "example.com"},
+ {'Vendor-Id', 193},
+ {'Product-Name', "Server"},
+ {'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]},
+ {application, [{alias, ?APP_ALIAS},
+ {dictionary, ?DIAMETER_DICT_COMMON},
+ {module, ?CALLBACK_MOD}]}]).
+
+%% start/1
+
+start(Name)
+ when is_atom(Name) ->
+ peer:start(Name, ?SERVICE(Name)).
+
+start() ->
+ start(?SVC_NAME).
+
+%% listen/2
+
+listen(Name, T) ->
+ peer:listen(Name, T).
+
+listen(T) ->
+ listen(?SVC_NAME, T).
+
+%% stop/1
+
+stop(Name) ->
+ peer:stop(Name).
+
+stop() ->
+ stop(?SVC_NAME).
diff --git a/lib/diameter/examples/server_cb.erl b/lib/diameter/examples/server_cb.erl
new file mode 100644
index 0000000000..b8705aedfc
--- /dev/null
+++ b/lib/diameter/examples/server_cb.erl
@@ -0,0 +1,118 @@
+%%
+%% %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 diameter application callback module configured by server.erl.
+%%
+
+-module(server_cb).
+
+-include_lib("diameter/include/diameter.hrl").
+-include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl").
+
+%% diameter callbacks
+-export([peer_up/3,
+ peer_down/3,
+ pick_peer/4,
+ prepare_request/3,
+ prepare_retransmit/3,
+ handle_answer/4,
+ handle_error/4,
+ handle_request/3]).
+
+-define(UNEXPECTED, erlang:error({unexpected, ?MODULE, ?LINE})).
+
+peer_up(_SvcName, {PeerRef, _}, State) ->
+ io:format("up: ~p~n", [PeerRef]),
+ State.
+
+peer_down(_SvcName, {PeerRef, _}, State) ->
+ io:format("down: ~p~n", [PeerRef]),
+ State.
+
+pick_peer(_, _, _SvcName, _State) ->
+ ?UNEXPECTED.
+
+prepare_request(_, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+prepare_retransmit(_Packet, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+handle_answer(_Packet, _Request, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+handle_error(_Reason, _Request, _SvcName, _Peer) ->
+ ?UNEXPECTED.
+
+%% A request whose decode was successful ...
+handle_request(#diameter_packet{msg = Req, errors = []}, _SvcName, {_, Caps})
+ when is_record(Req, diameter_base_RAR) ->
+ #diameter_caps{origin_host = {OH,_},
+ origin_realm = {OR,_}}
+ = Caps,
+ #diameter_base_RAR{'Session-Id' = Id,
+ 'Re-Auth-Request-Type' = RT}
+ = Req,
+
+ {reply, answer(RT, Id, OH, OR)};
+
+%% ... or one that wasn't. 3xxx errors are answered by diameter itself
+%% but these are non-3xxx errors for which we must contruct a reply.
+%% Returning a packet with the non-[] errors field will cause
+%% diameter to add the appropriate result code and Failed-AVPs avps.
+%% We just have to return the relevant answer record with any required
+%% avps.
+handle_request(#diameter_packet{msg = Req} = Pkt, _SvcName, {_, Caps})
+ when is_record(Req, diameter_base_RAR) ->
+ #diameter_caps{origin_host = {OH,_},
+ origin_realm = {OR,_}}
+ = Caps,
+ #diameter_base_RAR{'Session-Id' = Id}
+ = Req,
+
+ Ans = #diameter_base_RAA{'Origin-Host' = OH,
+ 'Origin-Realm' = OR,
+ 'Session-Id' = Id},
+
+ {reply, Pkt#diameter_packet{msg = Ans}};
+
+%% Should really reply to other base messages that we don't support
+%% but simply discard them instead.
+handle_request(#diameter_packet{}, _SvcName, {_,_}) ->
+ discard.
+
+%% ---------------------------------------------------------------------------
+
+%% Answer using the record or list encoding depending on
+%% Re-Auth-Request-Type. This is just as an example. You would
+%% typically just choose one, and this has nothing to do with the how
+%% client.erl sends.
+
+answer(0, Id, OH, OR) ->
+ #diameter_base_RAA{'Result-Code' = 2001, %% DIAMETER_SUCCESS
+ 'Origin-Host' = OH,
+ 'Origin-Realm' = OR,
+ 'Session-Id' = Id};
+
+answer(_, Id, OH, OR) ->
+ ['RAA', {'Result-Code', 5012}, %% DIAMETER_UNABLE_TO_COMPLY
+ {'Origin-Host', OH},
+ {'Origin-Realm', OR},
+ {'Session-Id', Id}].
diff --git a/lib/diameter/include/diameter.hrl b/lib/diameter/include/diameter.hrl
new file mode 100644
index 0000000000..8bd1ad1e51
--- /dev/null
+++ b/lib/diameter/include/diameter.hrl
@@ -0,0 +1,130 @@
+%%
+%% %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%
+%%
+
+-ifndef(diameter_hrl).
+-define(diameter_hrl, true).
+
+%% RFC 3588, 2.4:
+-define(DIAMETER_APP_ID_COMMON, 0).
+-define(DIAMETER_APP_ID_ACCOUNTING, 3).
+-define(DIAMETER_APP_ID_RELAY, 16#FFFFFFFF).
+
+%% Corresponding dictionaries:
+-define(DIAMETER_DICT_COMMON, diameter_gen_base_rfc3588).
+-define(DIAMETER_DICT_ACCOUNTING, diameter_gen_base_accounting).
+-define(DIAMETER_DICT_RELAY, diameter_gen_relay).
+
+%% Events sent to processes that have subscribed with
+%% diameter:subscribe/1.
+%%
+-record(diameter_event,
+ {service, %% name
+ info}). %% tuple()
+
+%% diameter_packet records are passed through the encode/decode
+%% interface supplied by a dictionary module configured on a Diameter
+%% application. For an incoming message the bin field contains the
+%% received binary and the header, avps, msg and errors fields the
+%% result of decoding.
+
+-record(diameter_packet,
+ {header, %% #diameter_header{}
+ avps, %% deep list() of #diameter_avp{}
+ msg, %% fully decoded message
+ bin, %% binary received/sent over the wire
+ errors = [],%% list() of Result-Code | {Result-Code, #diameter_avp{}}
+ transport_data}).
+
+-record(diameter_header,
+ {version, %% 8-bit unsigned
+ length, %% 24-bit unsigned
+ cmd_code, %% 8-bit unsigned
+ application_id, %% 24-bit unsigned
+ hop_by_hop_id, %% 32-bit unsigned
+ end_to_end_id, %% 32-bit unsigned
+ is_request, %% boolean() R flag
+ is_proxiable, %% boolean() P flag
+ is_error, %% boolean() E flag
+ is_retransmitted}). %% boolean() T flag
+
+-record(diameter_avp,
+ {code, %% 32-bit unsigned
+ vendor_id, %% 32-bit unsigned
+ is_mandatory = false, %% boolean() M flag
+ need_encryption = false, %% boolean() P flag
+ data, %% encoded binary()
+ name, %% atom() AVP name
+ value, %% decoded term() decoded | undefined
+ type, %% atom() type name,
+ index}). %% non_neg_integer() | undefined
+
+%% A diameter_caps record corresponds to capabilities configuration on
+%% diameter:start_service/2. In application callbacks is identifies
+%% the peer connection for which the callback is taking place, and in
+%% this case each field is a 2-tuple specifying the host (ie. local)
+%% and peer (ie. remote) values, host values having been configured
+%% and peer values having been received at capabilities exchange.
+
+-record(diameter_caps,
+ {origin_host, %% 'DiameterIdentity'()
+ origin_realm, %% 'DiameterIdentity'()
+ host_ip_address = [], %% ['Address'()]
+ vendor_id, %% 'Unsigned32'()
+ product_name, %% 'OctetString'()
+ origin_state_id = [], %% ['Unsigned32'()]
+ supported_vendor_id = [], %% ['Unsigned32'()]
+ auth_application_id = [], %% ['Unsigned32'()]
+ inband_security_id = [], %% ['Unsigned32'()]
+ acct_application_id = [], %% ['Unsigned32'()]
+ vendor_specific_application_id = [], %% ['Grouped'()]
+ firmware_revision = [], %% ['Unsigned32()]
+ avp = []}).
+
+%% AVP's of type DiameterURI are encoded as a diameter_uri record.
+%% Note that AVP's of type IPFilterRule and QoSFilterRule are currently
+%% encoded simply as OctetString's.
+
+-record(diameter_uri,
+ {type, %% aaa | aaas
+ fqdn, %% string()
+ port = 3868, %% non_neg_integer(),
+ transport = sctp, %% | tcp,
+ protocol = diameter}). %% | radius | 'tacacs+'
+
+%% 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
+%% should) only be interested diameter_service.host_ip_address.
+
+-record(diameter_service,
+ {pid,
+ capabilities, %% #diameter_caps{}
+ applications = []}). %% [#diameter_app{}]
+
+-record(diameter_app,
+ {alias, %% option 'alias'
+ dictionary, %% option 'dictionary', module()
+ module, %% [Mod | Args] callback module() and extra args
+ 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?
+
+-endif. %% -ifdef(diameter_hrl).
diff --git a/lib/diameter/include/diameter_gen.hrl b/lib/diameter/include/diameter_gen.hrl
new file mode 100644
index 0000000000..4c91954a21
--- /dev/null
+++ b/lib/diameter/include/diameter_gen.hrl
@@ -0,0 +1,431 @@
+%%
+%% %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 file contains code that's included by encode/decode modules
+%% generated by diameter_codegen.erl. This code does most of the work, the
+%% generated code being kept simple.
+%%
+
+-define(THROW(T), throw({?MODULE, T})).
+
+%%% ---------------------------------------------------------------------------
+%%% # encode_avps/3
+%%%
+%%% Returns: binary()
+%%% ---------------------------------------------------------------------------
+
+encode_avps(Name, Vals)
+ when is_list(Vals) ->
+ encode_avps(Name, '#set-'(Vals, newrec(Name)));
+
+encode_avps(Name, Rec) ->
+ try
+ list_to_binary(encode(Name, Rec))
+ catch
+ throw: {?MODULE, Reason} ->
+ diameter_dbg:log({encode, error},
+ ?MODULE,
+ ?LINE,
+ {Reason, Name, Rec}),
+ erlang:error(list_to_tuple(Reason ++ [Name, Rec, ?MODULE]));
+ error: Reason ->
+ Stack = erlang:get_stacktrace(),
+ diameter_dbg:log({encode, failure},
+ ?MODULE,
+ ?LINE,
+ {Reason, Name, Rec, Stack}),
+ erlang:error({encode_failure, Reason, Name, Rec, ?MODULE, Stack})
+ end.
+
+%% encode/2
+
+encode(Name, Rec) ->
+ lists:flatmap(fun(A) -> encode(Name, A, '#get-'(A, Rec)) end,
+ '#info-'(element(1, Rec), fields)).
+
+%% encode/3
+
+encode(Name, AvpName, Values) ->
+ e(Name, AvpName, avp_arity(Name, AvpName), Values).
+
+%% e/4
+
+e(_, AvpName, 1, undefined) ->
+ ?THROW([mandatory_avp_missing, AvpName]);
+
+e(Name, AvpName, 1, Value) ->
+ e(Name, AvpName, [Value]);
+
+e(_, _, {0,_}, []) ->
+ [];
+
+e(_, AvpName, _, T)
+ when not is_list(T) ->
+ ?THROW([repeated_avp_as_non_list, AvpName, T]);
+
+e(_, AvpName, {Min, _}, L)
+ when length(L) < Min ->
+ ?THROW([repeated_avp_insufficient_arity, AvpName, Min, L]);
+
+e(_, AvpName, {_, Max}, L)
+ when Max < length(L) ->
+ ?THROW([repeated_avp_excessive_arity, AvpName, Max, L]);
+
+e(Name, AvpName, _, Values) ->
+ e(Name, AvpName, Values).
+
+%% e/3
+
+e(Name, 'AVP', Values) ->
+ [pack_AVP(Name, A) || A <- Values];
+
+e(_, AvpName, Values) ->
+ e(AvpName, Values).
+
+%% e/2
+
+e(AvpName, Values) ->
+ H = avp_header(AvpName),
+ [diameter_codec:pack_avp(H, avp(encode, V, AvpName)) || V <- Values].
+
+%% pack_AVP/2
+
+%% No value: assume AVP data is already encoded. The normal case will
+%% be when this is passed back from #diameter_packet.errors as a
+%% consequence of a failed decode. Any AVP can be encoded this way
+%% however, which side-steps any arity checks for known AVP's and
+%% could potentially encode something unfortunate.
+pack_AVP(_, #diameter_avp{value = undefined} = A) ->
+ diameter_codec:pack_avp(A);
+
+%% Missing name for value encode.
+pack_AVP(_, #diameter_avp{name = N, value = V})
+ when N == undefined;
+ N == 'AVP' ->
+ ?THROW([value_with_nameless_avp, N, V]);
+
+%% Or not. Ensure that 'AVP' is the appropriate field. Note that if we
+%% don't know this AVP at all then the encode will fail.
+pack_AVP(Name, #diameter_avp{name = AvpName,
+ value = Data}) ->
+ 0 == avp_arity(Name, AvpName)
+ orelse ?THROW([known_avp_as_AVP, Name, AvpName, Data]),
+ e(AvpName, [Data]).
+
+%%% ---------------------------------------------------------------------------
+%%% # decode_avps/2
+%%%
+%%% Returns: {Rec, Avps, Failed}
+%%%
+%%% Rec = decoded message record
+%%% Avps = list of Avp
+%%% Failed = list of {ResultCode, #diameter_avp{}}
+%%%
+%%% Avp = #diameter_avp{} if type is not Grouped
+%%% | list of Avp where first element has type Grouped
+%%% and following elements are its component
+%%% AVP's.
+%%% ---------------------------------------------------------------------------
+
+decode_avps(Name, Recs) ->
+ d_rc(Name, lists:foldl(fun(T,A) -> decode(Name, T, A) end,
+ {[], {newrec(Name), []}},
+ Recs)).
+
+newrec(Name) ->
+ '#new-'(name2rec(Name)).
+
+%% No errors so far: keep looking.
+d_rc(Name, {Avps, {Rec, [] = Failed}}) ->
+ try
+ true = have_required_avps(Rec, Name),
+ {Rec, Avps, Failed}
+ catch
+ throw: {?MODULE, {AvpName, Reason}} ->
+ diameter_dbg:log({decode, error},
+ ?MODULE,
+ ?LINE,
+ {AvpName, Reason, Rec}),
+ {Rec, Avps, [{5005, empty_avp(AvpName)}]}
+ end;
+%% 3588:
+%%
+%% DIAMETER_MISSING_AVP 5005
+%% The request did not contain an AVP that is required by the Command
+%% Code definition. If this value is sent in the Result-Code AVP, a
+%% Failed-AVP AVP SHOULD be included in the message. The Failed-AVP
+%% AVP MUST contain an example of the missing AVP complete with the
+%% Vendor-Id if applicable. The value field of the missing AVP
+%% should be of correct minimum length and contain zeroes.
+
+%% Or not. Only need to report the first error so look no further.
+d_rc(_, {Avps, {Rec, Failed}}) ->
+ {Rec, Avps, lists:reverse(Failed)}.
+
+%% empty_avp/1
+
+empty_avp(Name) ->
+ {Code, Flags, VId} = avp_header(Name),
+ {Name, Type} = avp_name(Code, VId),
+ #diameter_avp{name = Name,
+ code = Code,
+ vendor_id = VId,
+ is_mandatory = 0 /= (Flags band 2#01000000),
+ need_encryption = 0 /= (Flags band 2#00100000),
+ data = empty_value(Name),
+ type = Type}.
+
+%% have_required_avps/2
+
+have_required_avps(Rec, Name) ->
+ lists:foreach(fun(F) -> hra(Name, F, Rec) end,
+ '#info-'(element(1, Rec), fields)),
+ true.
+
+hra(Name, AvpName, Rec) ->
+ Arity = avp_arity(Name, AvpName),
+ hra(Arity, '#get-'(AvpName, Rec))
+ orelse ?THROW({AvpName, {insufficient_arity, Arity}}).
+
+%% Maximum arities have already been checked in building the record.
+
+hra({Min, _}, L) ->
+ Min =< length(L);
+hra(N, V) ->
+ N /= 1 orelse V /= undefined.
+
+%% 3588, ch 7:
+%%
+%% 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
+%% specific errors that can be described by this AVP are described in
+%% the following section.
+
+%% decode/3
+
+decode(Name, #diameter_avp{code = Code, vendor_id = Vid} = Avp, Acc) ->
+ decode(Name, avp_name(Code, Vid), Avp, Acc).
+
+%% decode/4
+
+%% Don't know this AVP: see if it can be packed in an 'AVP' field
+%% undecoded, unless it's mandatory. Need to give Failed-AVP special
+%% treatment since it'll contain any unrecognized mandatory AVP's.
+decode(Name, 'AVP', #diameter_avp{is_mandatory = M} = Avp, {Avps, Acc}) ->
+ {[Avp | Avps], if M, Name /= 'Failed-AVP' ->
+ unknown(Avp, Acc);
+ true ->
+ pack_AVP(Name, Avp, Acc)
+ end};
+%% Note that the type field is 'undefined' in this case.
+
+%% Or try to decode.
+decode(Name, {AvpName, Type}, Avp, Acc) ->
+ d(Name, Avp#diameter_avp{name = AvpName, type = Type}, Acc).
+
+%% d/3
+
+d(Name, Avp, {Avps, Acc}) ->
+ #diameter_avp{name = AvpName,
+ data = Data}
+ = Avp,
+
+ try avp(decode, Data, AvpName) of
+ V ->
+ {H, A} = ungroup(V, Avp),
+ {[H | Avps], pack_avp(Name, A, Acc)}
+ catch
+ error: Reason ->
+ %% Failures here won't be visible since they're a "normal"
+ %% occurrence if the peer sends a faulty AVP that we need to
+ %% respond sensibly to. Log the occurence for traceability,
+ %% but the peer will also receive info in the resulting
+ %% answer-message.
+ diameter_dbg:log({decode, failure},
+ ?MODULE,
+ ?LINE,
+ {Reason, Avp, erlang:get_stacktrace()}),
+ {Rec, Failed} = Acc,
+ {[Avp|Avps], {Rec, [{rc(Reason), Avp} | Failed]}}
+ end.
+
+%% rc/1
+
+%% diameter_types will raise an error of this form to communicate
+%% DIAMETER_INVALID_AVP_LENGTH (5014). A module specified to a
+%% @custom_types tag in a spec file can also raise an error of this
+%% form.
+rc({'DIAMETER', RC, _}) ->
+ RC;
+
+%% 3588:
+%%
+%% 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.
+rc(_) ->
+ 5004.
+
+%% ungroup/2
+%%
+%% Returns: {Avp, Dec}
+%%
+%% Avp = #diameter_avp{} if type is not Grouped
+%% | list of Avp where first element has type Grouped
+%% and following elements are its component
+%% AVP's.
+%% = as for decode_avps/2
+%%
+%% Dec = #diameter_avp{}, either Avp or its head in the list case.
+
+%% The decoded value in the Grouped case is as returned by grouped_avp/3:
+%% a record and a list of component AVP's.
+ungroup(V, #diameter_avp{type = 'Grouped'} = Avp) ->
+ {Rec, As} = V,
+ A = Avp#diameter_avp{value = Rec},
+ {[A|As], A};
+
+%% Otherwise it's just a plain value.
+ungroup(V, #diameter_avp{} = Avp) ->
+ A = Avp#diameter_avp{value = V},
+ {A, A}.
+
+%% pack_avp/3
+
+pack_avp(Name, #diameter_avp{name = AvpName} = Avp, Acc) ->
+ pack_avp(Name, avp_arity(Name, AvpName), Avp, Acc).
+
+%% pack_avp/4
+
+pack_avp(Name, 0, Avp, Acc) ->
+ pack_AVP(Name, Avp, Acc);
+
+pack_avp(_, Arity, Avp, Acc) ->
+ pack(Arity, Avp#diameter_avp.name, Avp, Acc).
+
+%% pack_AVP/3
+
+pack_AVP(Name, Avp, Acc) ->
+ case avp_arity(Name, 'AVP') of
+ 0 ->
+ unknown(Avp, Acc);
+ Arity ->
+ pack(Arity, 'AVP', Avp, Acc)
+ end.
+
+%% 3588:
+%%
+%% 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_AVP_NOT_ALLOWED 5008
+%% A message was received with an AVP that MUST NOT be present. The
+%% Failed-AVP AVP MUST be included and contain a copy of the
+%% offending AVP.
+%%
+unknown(#diameter_avp{is_mandatory = B} = Avp, {Rec, Failed}) ->
+ {Rec, [{if B -> 5001; true -> 5008 end, Avp} | Failed]}.
+
+%% pack/4
+
+pack(Arity, FieldName, Avp, {Rec, _} = Acc) ->
+ pack('#get-'(FieldName, Rec), Arity, FieldName, Avp, Acc).
+
+%% pack/5
+
+pack(undefined, 1, FieldName, Avp, Acc) ->
+ p(FieldName, fun(V) -> V end, Avp, Acc);
+
+%% 3588:
+%%
+%% 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
+%% the offending AVP that exceeded the maximum number of occurrences
+%%
+pack(_, 1, _, Avp, {Rec, Failed}) ->
+ {Rec, [{5009, Avp} | Failed]};
+pack(L, {_, Max}, _, Avp, {Rec, Failed})
+ when length(L) == Max ->
+ {Rec, [{5009, Avp} | Failed]};
+
+pack(L, _, FieldName, Avp, Acc) ->
+ p(FieldName, fun(V) -> [V|L] end, Avp, Acc).
+
+%% p/4
+
+p(F, Fun, Avp, {Rec, Failed}) ->
+ {'#set-'({F, Fun(value(F, Avp))}, Rec), Failed}.
+
+value('AVP', Avp) ->
+ Avp;
+value(_, Avp) ->
+ Avp#diameter_avp.value.
+
+%%% ---------------------------------------------------------------------------
+%%% # grouped_avp/3
+%%% ---------------------------------------------------------------------------
+
+grouped_avp(decode, Name, Data) ->
+ {Rec, Avps, []} = decode_avps(Name, diameter_codec:collect_avps(Data)),
+ {Rec, Avps};
+%% Note that a failed match here will result in 5004. Note that this is
+%% the only AVP type that doesn't just return the decoded value, also
+%% returning the list of component #diameter_avp{}'s.
+
+grouped_avp(encode, Name, Data) ->
+ encode_avps(Name, Data).
+
+%%% ---------------------------------------------------------------------------
+%%% # empty_group/1
+%%% ---------------------------------------------------------------------------
+
+empty_group(Name) ->
+ list_to_binary(empty_body(Name)).
+
+empty_body(Name) ->
+ [z(F, avp_arity(Name, F)) || F <- '#info-'(name2rec(Name), fields)].
+
+z(Name, 1) ->
+ z(Name);
+z(_, {0,_}) ->
+ [];
+z(Name, {Min, _}) ->
+ lists:duplicate(Min, z(Name)).
+
+z('AVP') ->
+ <<0:64/integer>>; %% minimal header
+z(Name) ->
+ Bin = diameter_codec:pack_avp(avp_header(Name), empty_value(Name)),
+ << <<0>> || <<_>> <= Bin >>.
+
+%%% ---------------------------------------------------------------------------
+%%% # empty/1
+%%% ---------------------------------------------------------------------------
+
+empty(AvpName) ->
+ avp(encode, zero, AvpName).
diff --git a/lib/diameter/info b/lib/diameter/info
new file mode 100644
index 0000000000..67ef726781
--- /dev/null
+++ b/lib/diameter/info
@@ -0,0 +1,3 @@
+group: comm
+short: Diameter
+
diff --git a/lib/diameter/make/release_targets.mk b/lib/diameter/make/release_targets.mk
new file mode 100644
index 0000000000..479a9aded1
--- /dev/null
+++ b/lib/diameter/make/release_targets.mk
@@ -0,0 +1,92 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2010. 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
new file mode 100644
index 0000000000..9fd1c3b0d0
--- /dev/null
+++ b/lib/diameter/make/rules.mk.in
@@ -0,0 +1,195 @@
+#-*-makefile-*- ; force emacs to enter makefile-mode
+# ----------------------------------------------------
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2009-2010. 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 compatability
+$(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 compatability
+$(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
new file mode 100644
index 0000000000..49198bbefd
--- /dev/null
+++ b/lib/diameter/make/subdir.mk
@@ -0,0 +1,53 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 1997-2009. 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
new file mode 100644
index 0000000000..4ae470b9e2
--- /dev/null
+++ b/lib/diameter/make/target.mk
@@ -0,0 +1,33 @@
+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/Makefile b/lib/diameter/src/Makefile
new file mode 100644
index 0000000000..6935eb053e
--- /dev/null
+++ b/lib/diameter/src/Makefile
@@ -0,0 +1,43 @@
+#
+# %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
+
+# ----------------------------------------------------
+# Common Macros
+# ----------------------------------------------------
+
+include subdirs.mk
+
+SPECIAL_TARGETS =
+
+# ----------------------------------------------------
+# Default Subdir Targets
+# ----------------------------------------------------
+ifneq ($(ERL_TOP),)
+include $(ERL_TOP)/make/otp_subdir.mk
+else
+include $(DIAMETER_TOP)/make/subdir.mk
+endif
+#include ../make/subdir.mk
diff --git a/lib/diameter/src/app/.gitignore b/lib/diameter/src/app/.gitignore
new file mode 100644
index 0000000000..1310a0da6b
--- /dev/null
+++ b/lib/diameter/src/app/.gitignore
@@ -0,0 +1,5 @@
+
+/diameter_gen_*.erl
+/diameter_gen_*.hrl
+/depend.mk
+
diff --git a/lib/diameter/src/app/Makefile b/lib/diameter/src/app/Makefile
new file mode 100644
index 0000000000..8985ca4911
--- /dev/null
+++ b/lib/diameter/src/app/Makefile
@@ -0,0 +1,199 @@
+#
+# %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_ERL_FILES = \
+ $(SPEC_FILES:%.dia=%.erl)
+
+SPEC_HRL_FILES = \
+ $(SPEC_FILES:%.dia=%.hrl)
+
+APP_MODULES = \
+ $(MODULES) \
+ $(SPEC_FILES:%.dia=%)
+
+TARGET_FILES = \
+ $(APP_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 ../{compiler,transport} but good enough for now.
+$(APP_TARGET): $(APP_SRC) \
+ ../../vsn.mk \
+ modules.mk \
+ ../compiler/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 ../compiler $(APP_TARGET) APP_TARGET=$(APP_TARGET)
+ $(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
+# ----------------------------------------------------
+
+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) modules.mk 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/depend.sed b/lib/diameter/src/app/depend.sed
new file mode 100644
index 0000000000..9df0133960
--- /dev/null
+++ b/lib/diameter/src/app/depend.sed
@@ -0,0 +1,31 @@
+#
+# %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. The output is massaged
+# further in Makefile.
+#
+
+/^-include/!d
+/"diameter/!d
+
+s@^-include_lib("[^/]*@$(DIAMETER_TOP)@
+s@^-include("@@
+s@".*@@
+s@^@$(EBIN)/.$(EMULATOR): @
diff --git a/lib/diameter/src/app/diameter.app.src b/lib/diameter/src/app/diameter.app.src
new file mode 100644
index 0000000000..119997953e
--- /dev/null
+++ b/lib/diameter/src/app/diameter.app.src
@@ -0,0 +1,28 @@
+%%
+%% %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%
+%%
+
+{application, diameter,
+ [{description, "Diameter protocol"},
+ {vsn, "%VSN%"},
+ {modules, [%APP_MODULES%,%COMPILER_MODULES%,%TRANSPORT_MODULES%]},
+ {registered, []},
+ {applications, [stdlib, kernel]},
+ {env, []},
+ {mod, {diameter_app, []}}
+ ]}.
diff --git a/lib/diameter/src/app/diameter.appup.src b/lib/diameter/src/app/diameter.appup.src
new file mode 100644
index 0000000000..2b96153575
--- /dev/null
+++ b/lib/diameter/src/app/diameter.appup.src
@@ -0,0 +1,27 @@
+%% 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%",
+ [
+ ],
+ [
+ ]
+}.
+
diff --git a/lib/diameter/src/app/diameter.erl b/lib/diameter/src/app/diameter.erl
new file mode 100644
index 0000000000..5f2ab82475
--- /dev/null
+++ b/lib/diameter/src/app/diameter.erl
@@ -0,0 +1,212 @@
+%%
+%% %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/1,
+ 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]).
+
+%% Backwards compatibility.
+-export([add_connector/2,
+ add_listener/2,
+ remove_connector/2,
+ remove_listener/2]).
+
+-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/[12]
+%%% --------------------------------------------------------------------------
+
+-spec service_info(service_name(), atom() | [atom()])
+ -> any().
+
+service_info(SvcName, Option) ->
+ diameter_service:info(SvcName, Option).
+
+service_info(SvcName) ->
+ service_info(SvcName, all).
+
+%%% --------------------------------------------------------------------------
+%%% 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).
+
+add_listener(SvcName, Opts) ->
+ add_transport(SvcName, {listen, Opts}).
+
+add_connector(SvcName, Opts) ->
+ add_transport(SvcName, {connect, Opts}).
+
+%%% --------------------------------------------------------------------------
+%%% remove_transport/2
+%%% --------------------------------------------------------------------------
+
+-spec remove_transport(service_name(), transport_pred())
+ -> ok | {error, term()}.
+
+remove_transport(SvcName, Pred) ->
+ diameter_config:remove_transport(SvcName, Pred).
+
+remove_listener(SvcName, Pred) ->
+ remove_transport(SvcName, {listen, Pred}).
+
+remove_connector(SvcName, Pred) ->
+ remove_transport(SvcName, {connect, 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
new file mode 100644
index 0000000000..c161064303
--- /dev/null
+++ b/lib/diameter/src/app/diameter.mk.in
@@ -0,0 +1,47 @@
+#-*-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_app.erl b/lib/diameter/src/app/diameter_app.erl
new file mode 100644
index 0000000000..600f7ff04d
--- /dev/null
+++ b/lib/diameter/src/app/diameter_app.erl
@@ -0,0 +1,36 @@
+%%
+%% %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_app).
+
+-behaviour(application).
+
+%% application callbacks
+-export([start/2,
+ stop/1]).
+
+%% start/2
+
+start(_Type, _Args) ->
+ diameter_sup:start_link().
+
+%% stop/1
+
+stop(_) ->
+ ok.
diff --git a/lib/diameter/src/app/diameter_callback.erl b/lib/diameter/src/app/diameter_callback.erl
new file mode 100644
index 0000000000..fcf9a8fc1e
--- /dev/null
+++ b/lib/diameter/src/app/diameter_callback.erl
@@ -0,0 +1,91 @@
+%%
+%% %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) ->
+ Pkt.
+
+%%% ----------------------------------------------------------
+%%% # prepare_retransmit/3
+%%% ----------------------------------------------------------
+
+prepare_retransmit(Pkt, _SvcName, _Peer) ->
+ Pkt.
+
+%%% ----------------------------------------------------------
+%%% # handle_request/3
+%%% ----------------------------------------------------------
+
+handle_request(_Pkt, _SvcName, _Peer) ->
+ discard.
+
+%%% ----------------------------------------------------------
+%%% # handle_answer/4
+%%% ----------------------------------------------------------
+
+handle_answer(#diameter_packet{msg = Ans}, _Req, _SvcName, _Peer) ->
+ {ok, Ans}.
+
+%%% ---------------------------------------------------------------------------
+%%% # handle_error/4
+%%% ---------------------------------------------------------------------------
+
+handle_error(Reason, _Req, _SvcName, _Peer) ->
+ {error, Reason}.
diff --git a/lib/diameter/src/app/diameter_capx.erl b/lib/diameter/src/app/diameter_capx.erl
new file mode 100644
index 0000000000..aa5318e79d
--- /dev/null
+++ b/lib/diameter/src/app/diameter_capx.erl
@@ -0,0 +1,388 @@
+%%
+%% %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 builds CER and CEA records for use during capabilities
+%% exchange. All of a CER/CEA is built from AVP values configured on
+%% the service in question but values for Supported-Vendor-Id,
+%% Vendor-Specific-Application-Id, Auth-Application-Id and
+%% Acct-Application-id are also obtained using an older method that
+%% remains only for backwards compatibility. With this method, each
+%% dictionary module was required to export a cer/0 that returned a
+%% diameter_base_CER record (or corresponding list, although the list
+%% is also a later addition). Each returned CER contributes its member
+%% values for the aforementioned four AVPs to the resulting CER, with
+%% remaining AVP's either unspecified or identical to those configured
+%% on the service. Auth-Application-Id and Acct-Application-id were
+%% originally treated a little differently, each callback being
+%% required to return either no value of the same value as the other
+%% callbacks, but this coupled the callback modules unnecessarily. (A
+%% union is backwards compatible to boot.)
+%%
+%% Values obtained from the service and callbacks are all included
+%% when building a CER. Older code with only callback can continue to
+%% use them, newer code should probably stick to service configuration
+%% (since this is more explicit) or mix at their own peril.
+%%
+%% The cer/0 callback is now undocumented (despite never being fully
+%% documented to begin with) and should be considered deprecated even
+%% by those poor souls still using it.
+%%
+
+-module(diameter_capx).
+
+-export([build_CER/1,
+ recv_CER/2,
+ recv_CEA/2,
+ make_caps/2]).
+
+-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(NO_INBAND_SECURITY, 0).
+
+%% ===========================================================================
+
+-type tried(T) :: {ok, T} | {error, {term(), list()}}.
+
+-spec build_CER(#diameter_caps{})
+ -> tried(#diameter_base_CER{}).
+
+build_CER(Caps) ->
+ try_it([fun bCER/1, Caps]).
+
+-spec recv_CER(#diameter_base_CER{}, #diameter_service{})
+ -> tried({['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{}}).
+
+recv_CEA(CEA, Svc) ->
+ try_it([fun rCEA/2, CEA, Svc]).
+
+make_caps(Caps, Opts) ->
+ try_it([fun mk_caps/2, Caps, Opts]).
+
+%% ===========================================================================
+%% ===========================================================================
+
+try_it([Fun | Args]) ->
+ try apply(Fun, Args) of
+ T -> {ok, T}
+ catch
+ throw: ?FAILURE(Reason) -> {error, {Reason, Args}}
+ end.
+
+%% mk_caps/2
+
+mk_caps(Caps0, Opts) ->
+ {Caps, _} = lists:foldl(fun set_cap/2,
+ {Caps0, #diameter_caps{_ = false}},
+ Opts),
+ Caps.
+
+-define(SC(K,F),
+ set_cap({K, Val}, {Caps, #diameter_caps{F = false} = C}) ->
+ {Caps#diameter_caps{F = cap(K, Val)}, C#diameter_caps{F = true}}).
+
+?SC('Origin-Host', origin_host);
+?SC('Origin-Realm', origin_realm);
+?SC('Host-IP-Address', host_ip_address);
+?SC('Vendor-Id', vendor_id);
+?SC('Product-Name', product_name);
+?SC('Origin-State-Id', origin_state_id);
+?SC('Supported-Vendor-Id', supported_vendor_id);
+?SC('Auth-Application-Id', auth_application_id);
+?SC('Inband-Security-Id', inband_security_id);
+?SC('Acct-Application-Id', acct_application_id);
+?SC('Vendor-Specific-Application-Id', vendor_specific_application_id);
+?SC('Firmware-Revision', firmware_revision);
+
+set_cap({Key, _}, _) ->
+ ?THROW({duplicate, Key}).
+
+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) ->
+ [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) ->
+ Vs;
+
+cap(K, V) ->
+ ?THROW({invalid, K, V}).
+
+ipaddr(A) ->
+ try
+ diameter_lib:ipaddr(A)
+ catch
+ error: {invalid_address, _} = T ->
+ ?THROW(T)
+ end.
+
+%% bCER/1
+%%
+%% 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}.
+
+%% rCER/2
+%%
+%% Build a CEA record to send to a remote peer in response to an
+%% incoming CER. RFC 3588 gives no guidance on what should be sent
+%% here: should we advertise applications that the peer hasn't sent in
+%% its CER (aside from the relay application) or not? If we send
+%% applications that the peer hasn't advertised then the peer may have
+%% to be aware of the possibility. If we don't then we just look like
+%% a server that supports a subset (possibly) of what the client
+%% advertised, so this feels like the path of least incompatibility.
+%% However, the current draft standard (draft-ietf-dime-rfc3588bis-26,
+%% expires 24 July 2011) says this in section 5.3, Capabilities
+%% Exchange:
+%%
+%% 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
+%% 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
+%% the receiver regarding all of its application capabilities.
+%%
+%% Both RFC and the draft also say this:
+%%
+%% 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.
+%%
+%% 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.
+
+rCER(CER, #diameter_service{capabilities = LCaps} = Svc) ->
+ #diameter_base_CER{'Inband-Security-Id' = RIS}
+ = CER,
+ #diameter_base_CEA{}
+ = CEA
+ = cea_from_cer(bCER(LCaps)),
+
+ RCaps = capx_to_caps(CER),
+ SApps = common_applications(LCaps, RCaps, 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(true, _, _, 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.
+
+%% cea_from_cer/1
+
+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))
+ catch
+ 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}),
+
+ RCaps = capx_to_caps(CEA),
+ SApps = common_applications(LCaps, RCaps, Svc),
+
+ [] == SApps andalso ?THROW({no_common_apps, LCaps, RCaps}),
+
+ {SApps, RCaps};
+
+rCEA(CEA, _Svc) ->
+ ?THROW({invalid, CEA}).
+
+%% capx_to_caps/1
+
+capx_to_caps(#diameter_base_CEA{'Origin-Host' = OH,
+ 'Origin-Realm' = OR,
+ 'Host-IP-Address' = IP,
+ 'Vendor-Id' = VId,
+ 'Product-Name' = PN,
+ 'Origin-State-Id' = OSI,
+ 'Supported-Vendor-Id' = SV,
+ 'Auth-Application-Id' = Auth,
+ 'Inband-Security-Id' = IS,
+ 'Acct-Application-Id' = Acct,
+ 'Vendor-Specific-Application-Id' = VSA,
+ 'Firmware-Revision' = FR,
+ 'AVP' = X}) ->
+ #diameter_caps{origin_host = OH,
+ origin_realm = OR,
+ vendor_id = VId,
+ product_name = PN,
+ origin_state_id = OSI,
+ host_ip_address = IP,
+ supported_vendor_id = SV,
+ auth_application_id = Auth,
+ inband_security_id = IS,
+ acct_application_id = Acct,
+ vendor_specific_application_id = VSA,
+ firmware_revision = FR,
+ avp = X};
+
+capx_to_caps(#diameter_base_CER{} = CER) ->
+ capx_to_caps(cea_from_cer(CER)).
+
+%% ---------------------------------------------------------------------------
+%% ---------------------------------------------------------------------------
+
+%% common_applications/3
+%%
+%% Identify the (local) applications to be supported on the connection
+%% in question.
+
+common_applications(LCaps, RCaps, #diameter_service{applications = Apps}) ->
+ LA = app_union(LCaps),
+ RA = app_union(RCaps),
+
+ lists:foldl(fun(I,A) -> ca(I, Apps, RA, A) end, [], LA).
+
+ca(Id, Apps, RA, Acc) ->
+ Relay = lists:member(?APP_ID_RELAY, RA),
+ #diameter_app{alias = Alias} = find_app(Id, Apps),
+ tcons(Relay %% peer is a relay
+ orelse ?APP_ID_RELAY == Id %% we're a relay
+ orelse lists:member(Id, RA), %% app is supported by the peer
+ Id,
+ Alias,
+ Acc).
+%% 5.3 of the RFC states that a peer advertising itself as a relay must
+%% be interpreted as having common applications.
+
+%% Extract the list of all application identifiers from Auth-Application-Id,
+%% Acct-Application-Id and Vendor-Specific-Application-Id.
+app_union(#diameter_caps{auth_application_id = U,
+ acct_application_id = C,
+ vendor_specific_application_id = V}) ->
+ set_list(U ++ C ++ lists:flatmap(fun vsa_apps/1, V)).
+
+vsa_apps(#'diameter_base_Vendor-Specific-Application-Id'
+ {'Auth-Application-Id' = U,
+ 'Acct-Application-Id' = C}) ->
+ U ++ C;
+vsa_apps(L) ->
+ Rec = ?BASE:'#new-'('diameter_base_Vendor-Specific-Application-Id', L),
+ vsa_apps(Rec).
+
+%% It's a configuration error for a locally advertised application not
+%% to be represented in Apps. Don't just match on lists:keyfind/3 in
+%% order to generate a more helpful error.
+find_app(Id, Apps) ->
+ case lists:keyfind(Id, #diameter_app.id, Apps) of
+ #diameter_app{} = A ->
+ A;
+ false ->
+ ?THROW({app_not_configured, Id})
+ end.
+
+set_list(L) ->
+ sets:to_list(sets:from_list(L)).
+
+tcons(true, K, V, Acc) ->
+ [{K,V} | Acc];
+tcons(false, _, _, Acc) ->
+ Acc.
diff --git a/lib/diameter/src/app/diameter_codec.erl b/lib/diameter/src/app/diameter_codec.erl
new file mode 100644
index 0000000000..f6cbde5446
--- /dev/null
+++ b/lib/diameter/src/app/diameter_codec.erl
@@ -0,0 +1,569 @@
+%%
+%% %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_codec).
+
+-export([encode/2,
+ decode/2,
+ decode/3,
+ collect_avps/1,
+ decode_header/1,
+ sequence_numbers/1,
+ hop_by_hop_id/2,
+ msg_name/1,
+ msg_id/1]).
+
+%% Towards generated encoders (from diameter_gen.hrl).
+-export([pack_avp/1,
+ pack_avp/2]).
+
+-include_lib("diameter/include/diameter.hrl").
+-include("diameter_internal.hrl").
+
+-define(MASK(N,I), ((I) band (1 bsl (N)))).
+
+%% 0 1 2 3
+%% 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | Version | Message Length |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | command flags | Command-Code |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | Application-ID |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | Hop-by-Hop Identifier |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | End-to-End Identifier |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | AVPs ...
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-
+
+%%% ---------------------------------------------------------------------------
+%%% # encode/[2-4]
+%%% ---------------------------------------------------------------------------
+
+encode(Mod, #diameter_packet{} = Pkt) ->
+ try
+ e(Mod, Pkt)
+ catch
+ error: Reason ->
+ %% Be verbose rather than letting the emulator truncate the
+ %% error report.
+ X = {Reason, ?STACK},
+ diameter_lib:error_report(X, {?MODULE, encode, [Mod, Pkt]}),
+ exit(X)
+ end;
+
+encode(Mod, Msg) ->
+ Seq = diameter_session:sequence(),
+ Hdr = #diameter_header{version = ?DIAMETER_VERSION,
+ end_to_end_id = Seq,
+ hop_by_hop_id = Seq},
+ encode(Mod, #diameter_packet{header = Hdr,
+ msg = Msg}).
+
+e(_, #diameter_packet{msg = [#diameter_header{} = Hdr | As]} = Pkt) ->
+ Avps = encode_avps(As),
+ Length = size(Avps) + 20,
+
+ #diameter_header{version = Vsn,
+ cmd_code = Code,
+ application_id = Aid,
+ hop_by_hop_id = Hid,
+ end_to_end_id = Eid}
+ = Hdr,
+
+ Flags = make_flags(0, Hdr),
+
+ Pkt#diameter_packet{bin = <<Vsn:8, Length:24,
+ Flags:8, Code:24,
+ Aid:32,
+ Hid:32,
+ Eid:32,
+ Avps/binary>>};
+
+e(Mod0, #diameter_packet{header = Hdr, msg = Msg} = Pkt) ->
+ #diameter_header{version = Vsn,
+ hop_by_hop_id = Hid,
+ end_to_end_id = Eid}
+ = Hdr,
+
+ {Mod, MsgName} = rec2msg(Mod0, Msg),
+ {Code, Flags0, Aid} = msg_header(Mod, MsgName, Hdr),
+ Flags = make_flags(Flags0, Hdr),
+
+ Avps = encode_avps(Mod, MsgName, values(Msg)),
+ Length = size(Avps) + 20,
+
+ Pkt#diameter_packet{header = Hdr#diameter_header
+ {length = Length,
+ cmd_code = Code,
+ application_id = Aid,
+ is_request = 0 /= ?MASK(7, Flags),
+ is_proxiable = 0 /= ?MASK(6, Flags),
+ is_error = 0 /= ?MASK(5, Flags),
+ is_retransmitted = 0 /= ?MASK(4, Flags)},
+ bin = <<Vsn:8, Length:24,
+ Flags:8, Code:24,
+ Aid:32,
+ Hid:32,
+ Eid:32,
+ Avps/binary>>}.
+
+%% make_flags/2
+
+make_flags(Flags0, #diameter_header{is_request = R,
+ is_proxiable = P,
+ is_error = E,
+ is_retransmitted = T}) ->
+ {Flags, 3} = lists:foldl(fun(B,{F,N}) -> {mf(B,F,N), N-1} end,
+ {Flags0, 7},
+ [R,P,E,T]),
+ Flags.
+
+mf(undefined, F, _) ->
+ F;
+mf(B, F, N) -> %% reset the affected bit
+ (F bxor (F band (1 bsl N))) bor (bit(B) bsl N).
+
+bit(true) -> 1;
+bit(false) -> 0.
+
+%% values/1
+
+values([H|T])
+ when is_atom(H) ->
+ T;
+values(Avps) ->
+ Avps.
+
+%% encode_avps/3
+
+%% Specifying values as a #diameter_avp list bypasses arity and other
+%% checks: the values are expected to be already encoded and the AVP's
+%% presented are simply sent. This is needed for relay agents, since
+%% these have to be able to resend whatever comes.
+
+%% Message as a list of #diameter_avp{} ...
+encode_avps(_, _, [#diameter_avp{} | _] = Avps) ->
+ encode_avps(reorder(Avps, [], Avps));
+
+%% ... or as a tuple list or record.
+encode_avps(Mod, MsgName, Values) ->
+ Mod:encode_avps(MsgName, Values).
+
+%% reorder/1
+
+reorder([#diameter_avp{index = 0} | _] = Avps, Acc, _) ->
+ Avps ++ Acc;
+
+reorder([#diameter_avp{index = N} = A | Avps], Acc, _)
+ when is_integer(N) ->
+ lists:reverse(Avps, [A | Acc]);
+
+reorder([H | T], Acc, Avps) ->
+ reorder(T, [H | Acc], Avps);
+
+reorder([], Acc, _) ->
+ Acc.
+
+%% encode_avps/1
+
+encode_avps(Avps) ->
+ list_to_binary(lists:map(fun pack_avp/1, 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 bor choose(P, 2#01000000, 0);
+p(Flags, _) ->
+ Flags.
+
+%% The header below is that of the incoming request being answered,
+%% not of the answer (which hasn't been encoded yet).
+
+h(Mod, 'answer-message' = MsgName, Header) ->
+ ?BASE = Mod,
+ #diameter_header{is_request = true,
+ cmd_code = Code}
+ = Header,
+ {_, Flags, ApplId} = ?BASE:msg_header(MsgName),
+ {Code, Flags, ApplId};
+
+h(Mod, MsgName, #diameter_header{is_request = true,
+ cmd_code = Code}) ->
+ {Code, _, _} = Mod:msg_header(MsgName); %% ensure Code
+
+h(Mod, MsgName, _) ->
+ Mod:msg_header(MsgName).
+
+%% rec2msg/2
+
+rec2msg(_, ['answer-message' = M | _]) ->
+ {?BASE, M};
+
+rec2msg(Mod, [MsgName|_])
+ when is_atom(MsgName) ->
+ {Mod, MsgName};
+
+rec2msg(Mod, Rec) ->
+ R = element(1, Rec),
+ A = 'answer-message',
+ case ?BASE:msg2rec(A) of
+ R ->
+ {?BASE, A};
+ _ ->
+ {Mod, Mod:rec2msg(R)}
+ end.
+
+%%% ---------------------------------------------------------------------------
+%%% # decode/2
+%%% ---------------------------------------------------------------------------
+
+%% Unsuccessfully decoded AVPs will be placed in #diameter_packet.errors.
+
+decode(Mod, Pkt) ->
+ decode(Mod:id(), Mod, Pkt).
+
+%% If we're a relay application then just extract the avp's without
+%% any decoding of their data since we don't know the application in
+%% question.
+decode(?APP_ID_RELAY, _, #diameter_packet{} = Pkt) ->
+ case collect_avps(Pkt) of
+ {Bs, As} ->
+ Pkt#diameter_packet{avps = As,
+ errors = [Bs]};
+ As ->
+ Pkt#diameter_packet{avps = As}
+ end;
+
+%% Otherwise decode using the dictionary.
+decode(_, Mod, #diameter_packet{header = Hdr} = Pkt)
+ when is_atom(Mod) ->
+ #diameter_header{cmd_code = CmdCode,
+ is_request = IsRequest,
+ is_error = IsError}
+ = Hdr,
+
+ {M, MsgName} = if IsError andalso not IsRequest ->
+ {?BASE, 'answer-message'};
+ true ->
+ {Mod, Mod:msg_name(CmdCode, IsRequest)}
+ end,
+
+ decode_avps(MsgName, M, Pkt, collect_avps(Pkt));
+
+decode(Id, Mod, Bin)
+ when is_bitstring(Bin) ->
+ decode(Id, Mod, #diameter_packet{header = decode_header(Bin), bin = Bin}).
+
+decode_avps(MsgName, Mod, Pkt, {Bs, Avps}) -> %% invalid avp bits ...
+ ?LOG(invalid, Pkt#diameter_packet.bin),
+ #diameter_packet{errors = Failed}
+ = P
+ = decode_avps(MsgName, Mod, Pkt, Avps),
+ P#diameter_packet{errors = [Bs | Failed]};
+
+decode_avps('', Mod, Pkt, Avps) -> %% unknown message ...
+ ?LOG(unknown, {Mod, Pkt#diameter_packet.header}),
+ Pkt#diameter_packet{errors = lists:reverse(Avps)};
+%% msg = undefined identifies this case.
+
+decode_avps(MsgName, Mod, Pkt, Avps) -> %% ... or not
+ {Rec, As, Failed} = Mod:decode_avps(MsgName, Avps),
+ ?LOGC([] /= Failed, failed, {Mod, Failed}),
+ Pkt#diameter_packet{msg = Rec,
+ errors = Failed,
+ avps = As}.
+
+%%% ---------------------------------------------------------------------------
+%%% # decode_header/1
+%%% ---------------------------------------------------------------------------
+
+decode_header(<<Version:8,
+ MsgLength:24,
+ CmdFlags:1/binary,
+ CmdCode:24,
+ ApplicationId:32,
+ HopByHopId:32,
+ EndToEndId:32,
+ _/bitstring>>) ->
+ <<R:1, P:1, E:1, T:1, _:4>>
+ = CmdFlags,
+ %% 3588 (ch 3) says that reserved bits MUST be set to 0 and ignored
+ %% by the receiver.
+
+ %% The RFC is quite unclear about the order of the bits in this
+ %% case. It writes
+ %%
+ %% 0 1 2 3 4 5 6 7
+ %% +-+-+-+-+-+-+-+-+
+ %% |R P E T r r r r|
+ %% +-+-+-+-+-+-+-+-+
+ %%
+ %% in defining these but the scale refers to the (big endian)
+ %% transmission order, first to last, not the bit order. That is,
+ %% R is the high order bit. It's odd that a standard reserves
+ %% low-order bit rather than high-order ones.
+
+ #diameter_header{version = Version,
+ length = MsgLength,
+ cmd_code = CmdCode,
+ application_id = ApplicationId,
+ hop_by_hop_id = HopByHopId,
+ end_to_end_id = EndToEndId,
+ is_request = 1 == R,
+ is_proxiable = 1 == P,
+ is_error = 1 == E,
+ is_retransmitted = 1 == T};
+
+decode_header(_) ->
+ false.
+
+%%% ---------------------------------------------------------------------------
+%%% # sequence_numbers/1
+%%% ---------------------------------------------------------------------------
+
+%% The End-To-End identifier must be unique for at least 4 minutes. We
+%% maintain a 24-bit wraparound counter, and add an 8-bit persistent
+%% wraparound counter. The 8-bit counter is incremented each time the
+%% system is restarted.
+
+sequence_numbers(#diameter_packet{bin = Bin})
+ when is_binary(Bin) ->
+ sequence_numbers(Bin);
+
+sequence_numbers(#diameter_packet{header = #diameter_header{} = H}) ->
+ sequence_numbers(H);
+
+sequence_numbers(#diameter_header{hop_by_hop_id = H,
+ end_to_end_id = E}) ->
+ {H,E};
+
+sequence_numbers(<<_:12/binary, H:32, E:32, _/binary>>) ->
+ {H,E}.
+
+%%% ---------------------------------------------------------------------------
+%%% # hop_by_hop_id/2
+%%% ---------------------------------------------------------------------------
+
+hop_by_hop_id(Id, <<H:12/binary, _:32, T/binary>>) ->
+ <<H/binary, Id:32, T/binary>>.
+
+%%% ---------------------------------------------------------------------------
+%%% # msg_name/1
+%%% ---------------------------------------------------------------------------
+
+msg_name(#diameter_header{application_id = ?APP_ID_COMMON,
+ cmd_code = C,
+ is_request = R}) ->
+ ?BASE:msg_name(C,R);
+
+msg_name(Hdr) ->
+ msg_id(Hdr).
+
+%% Note that messages in different applications could have the same
+%% name.
+
+%%% ---------------------------------------------------------------------------
+%%% # msg_id/1
+%%% ---------------------------------------------------------------------------
+
+msg_id(#diameter_packet{msg = [#diameter_header{} = Hdr | _]}) ->
+ msg_id(Hdr);
+
+msg_id(#diameter_packet{header = #diameter_header{} = Hdr}) ->
+ msg_id(Hdr);
+
+msg_id(#diameter_header{application_id = A,
+ cmd_code = C,
+ is_request = R}) ->
+ {A, C, if R -> 1; true -> 0 end};
+
+msg_id(<<_:32, Rbit:1, _:7, CmdCode:24, ApplId:32, _/bitstring>>) ->
+ {ApplId, CmdCode, Rbit}.
+
+%%% ---------------------------------------------------------------------------
+%%% # collect_avps/1
+%%% ---------------------------------------------------------------------------
+
+%% Note that the returned list of AVP's is reversed relative to their
+%% order in the binary. Note also that grouped avp's aren't unraveled,
+%% only those at the top level.
+
+collect_avps(#diameter_packet{bin = Bin}) ->
+ <<_:20/binary, Avps/bitstring>> = Bin,
+ collect_avps(Avps);
+
+collect_avps(Bin) ->
+ collect_avps(Bin, 0, []).
+
+collect_avps(<<>>, _, Acc) ->
+ Acc;
+collect_avps(Bin, N, Acc) ->
+ try split_avp(Bin) of
+ {Rest, AVP} ->
+ collect_avps(Rest, N+1, [AVP#diameter_avp{index = N} | Acc])
+ catch
+ ?FAILURE(_) ->
+ {Bin, Acc}
+ end.
+
+%% 0 1 2 3
+%% 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | AVP Code |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% |V M P r r r r r| AVP Length |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | Vendor-ID (opt) |
+%% +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+%% | Data ...
+%% +-+-+-+-+-+-+-+-+
+
+%% split_avp/1
+
+split_avp(Bin) ->
+ 8 =< size(Bin) orelse ?THROW(truncated_header),
+
+ <<Code:32, Flags:1/binary, Length:24, Rest/bitstring>>
+ = Bin,
+
+ DataSize = Length - 8, % size(Code+Flags+Length) = 8 octets
+ PadSize = (4 - (DataSize rem 4)) rem 4,
+
+ DataSize + PadSize =< size(Rest)
+ orelse ?THROW(truncated_data),
+
+ <<Data:DataSize/binary, _:PadSize/binary, R/bitstring>>
+ = Rest,
+ <<Vbit:1, Mbit:1, Pbit:1, _Reserved:5>>
+ = Flags,
+
+ 0 == Vbit orelse 4 =< size(Data)
+ orelse ?THROW(truncated_vendor_id),
+
+ {Vid, D} = vid(Vbit, Data),
+ {R, #diameter_avp{code = Code,
+ vendor_id = Vid,
+ is_mandatory = 1 == Mbit,
+ need_encryption = 1 == Pbit,
+ data = D}}.
+
+%% The RFC is a little misleading when stating that OctetString is
+%% padded to a 32-bit boundary while other types align naturally. All
+%% other types are already multiples of 32 bits so there's no need to
+%% distinguish between types here. Any invalid lengths will result in
+%% decode error in diameter_types.
+
+vid(1, <<Vid:32, Data/bitstring>>) ->
+ {Vid, Data};
+vid(0, Data) ->
+ {undefined, Data}.
+
+%%% ---------------------------------------------------------------------------
+%%% # pack_avp/1
+%%% ---------------------------------------------------------------------------
+
+%% The normal case here is data as an #diameter_avp{} list or an
+%% iolist, which are the cases that generated codec modules use. The
+%% other case is as a convenience in the relay case in which the
+%% dictionary doesn't know about specific AVP's.
+
+%% Grouped AVP whose components need packing ...
+pack_avp(#diameter_avp{data = [#diameter_avp{} | _] = Avps} = A) ->
+ pack_avp(A#diameter_avp{data = encode_avps(Avps)});
+
+%% ... data as a type/value tuple, possibly with header data, ...
+pack_avp(#diameter_avp{data = {Type, Value}} = A)
+ when is_atom(Type) ->
+ pack_avp(A#diameter_avp{data = diameter_types:Type(encode, Value)});
+pack_avp(#diameter_avp{data = {{_,_,_} = T, {Type, Value}}}) ->
+ pack_avp(T, iolist_to_binary(diameter_types:Type(encode, Value)));
+pack_avp(#diameter_avp{data = {{_,_,_} = T, Bin}})
+ when is_binary(Bin) ->
+ pack_avp(T, Bin);
+pack_avp(#diameter_avp{data = {Dict, Name, Value}} = A) ->
+ {Code, _Flags, Vid} = Hdr = Dict:avp_header(Name),
+ {Name, Type} = Dict:avp_name(Code, Vid),
+ pack_avp(A#diameter_avp{data = {Hdr, {Type, Value}}});
+
+%% ... or as an iolist.
+pack_avp(#diameter_avp{code = Code,
+ vendor_id = V,
+ is_mandatory = M,
+ need_encryption = P,
+ data = Data}) ->
+ Flags = lists:foldl(fun flag_avp/2, 0, [{V /= undefined, 2#10000000},
+ {M, 2#01000000},
+ {P, 2#00100000}]),
+ pack_avp({Code, Flags, V}, iolist_to_binary(Data)).
+
+flag_avp({true, B}, F) ->
+ F bor B;
+flag_avp({false, _}, F) ->
+ F.
+
+%%% ---------------------------------------------------------------------------
+%%% # pack_avp/2
+%%% ---------------------------------------------------------------------------
+
+pack_avp({Code, Flags, VendorId}, Bin)
+ when is_binary(Bin) ->
+ Sz = size(Bin),
+ pack_avp(Code, Flags, VendorId, Sz, pad(Sz rem 4, Bin)).
+
+pad(0, Bin) ->
+ Bin;
+pad(N, Bin) ->
+ P = 8*(4-N),
+ <<Bin/binary, 0:P>>.
+%% Note that padding is not included in the length field as mandated by
+%% the RFC.
+
+%% pack_avp/5
+%%
+%% Prepend the vendor id as required.
+
+pack_avp(Code, Flags, Vid, Sz, Bin)
+ when 0 == Flags band 2#10000000 ->
+ undefined = Vid, %% sanity check
+ pack_avp(Code, Flags, Sz, Bin);
+
+pack_avp(Code, Flags, Vid, Sz, Bin) ->
+ pack_avp(Code, Flags, Sz+4, <<Vid:32, Bin/binary>>).
+
+%% pack_avp/4
+
+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/app/diameter_config.erl
new file mode 100644
index 0000000000..42c70890b3
--- /dev/null
+++ b/lib/diameter/src/app/diameter_config.erl
@@ -0,0 +1,681 @@
+%%
+%% %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 writes service/transport configuration to the table
+%% diameter_config, so that the config will survive service process
+%% death, and then turns it into calls towards diameter_service. It
+%% also restarts services upon their death.
+%%
+%% The table diameter_config is only written here while
+%% diameter_service reads. This is all somewhat after the fact. Once
+%% upon a time the config was only stored in the service process,
+%% causing much grief if these processes died (which they did with
+%% some regularity) and one was forced to reconfigure. This module was
+%% then inserted into the service start in order to keep a more
+%% permanent record of the config. That said, service processes are
+%% now much more robust than they once were and crashing is a thing of
+%% the past.
+%%
+
+-module(diameter_config).
+-compile({no_auto_import, [monitor/2]}).
+
+-behaviour(gen_server).
+
+-export([start_service/2,
+ stop_service/1,
+ add_transport/2,
+ remove_transport/2,
+ have_transport/2,
+ lookup/1]).
+
+%% child server start
+-export([start_link/0]).
+
+%% gen_server callbacks
+-export([init/1,
+ terminate/2,
+ handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+ code_change/3]).
+
+%% diameter_sync requests.
+-export([sync/1]).
+
+%% debug
+-export([state/0,
+ uptime/0]).
+
+-include_lib("diameter/include/diameter.hrl").
+-include("diameter_internal.hrl").
+
+%% Server state.
+-record(state, {id = now()}).
+
+%% Registered name of the server.
+-define(SERVER, ?MODULE).
+
+%% Table config is written to.
+-define(TABLE, ?MODULE).
+
+%% Workaround for dialyzer's lack of understanding of match specs.
+-type match(T)
+ :: T | '_' | '$1' | '$2' | '$3' | '$4'.
+
+%% Configuration records in ?TABLE.
+
+-record(service,
+ {name,
+ rec :: match(#diameter_service{}),
+ options :: match(list())}).
+
+-record(transport,
+ {service, %% name
+ ref = make_ref() :: match(reference()),
+ type :: match(connect | listen),
+ options :: match(list())}).
+
+%% Monitor entry in ?TABLE.
+-record(monitor, {mref = make_ref() :: reference(),
+ service}). %% name
+
+%% Time to lay low before restarting a dead service.
+-define(RESTART_SLEEP, 2000).
+
+%% A minimal diameter_caps for checking for valid capabilities values.
+-define(EXAMPLE_CAPS,
+ #diameter_caps{origin_host = "TheHost",
+ origin_realm = "TheRealm",
+ host_ip_address = [{127,0,0,1}],
+ vendor_id = 42,
+ product_name = "TheProduct"}).
+
+-define(VALUES(Rec), tl(tuple_to_list(Rec))).
+
+%%% The return values below assume the server diameter_config is started.
+%%% The functions will exit if it isn't.
+
+%% --------------------------------------------------------------------------
+%% # start_service(SvcName, Opts)
+%%
+%% Output: ok | {error, Reason}
+%% --------------------------------------------------------------------------
+
+start_service(SvcName, Opts)
+ when is_list(Opts) ->
+ start_rc(sync(SvcName, {start_service, SvcName, Opts})).
+
+start_rc({ok = T, _Pid}) ->
+ T;
+start_rc({error, _} = No) ->
+ No;
+start_rc(timeout) ->
+ {error, application_not_started}.
+
+%% --------------------------------------------------------------------------
+%% # stop_service(SvcName)
+%%
+%% Output: ok
+%% --------------------------------------------------------------------------
+
+stop_service(SvcName) ->
+ sync(SvcName, {stop_service, SvcName}).
+
+%% --------------------------------------------------------------------------
+%% # add_transport(SvcName, {Type, Opts})
+%%
+%% Input: Type = connect | listen
+%%
+%% Output: {ok, Ref} | {error, Reason}
+%% --------------------------------------------------------------------------
+
+add_transport(SvcName, {T, Opts})
+ when is_list(Opts), (T == connect orelse T == listen) ->
+ sync(SvcName, {add, SvcName, T, Opts}).
+
+%% --------------------------------------------------------------------------
+%% # remove_transport(SvcName, Pred)
+%%
+%% Input: Pred = arity 3 fun on transport ref, connect|listen and Opts,
+%% returning true if the transport is to be removed, false if
+%% not
+%% | arity 2 fun on Ref and Opts only
+%% | arity 1 fun on Opts only
+%% | Opts matching all transports that have all of the specified
+%% options
+%% | Ref matching only the transport with this reference.
+%% | {M,F,A} applied to Ref, connect|listen and Opts
+%% | boolean()
+%%
+%% Output: ok | {error, Reason}
+%% --------------------------------------------------------------------------
+
+remove_transport(SvcName, Pred) ->
+ try
+ sync(SvcName, {remove, SvcName, pred(Pred)})
+ catch
+ ?FAILURE(Reason) ->
+ {error, Reason}
+ end.
+
+pred(Pred)
+ when is_function(Pred, 3) ->
+ Pred;
+pred(Pred)
+ when is_function(Pred, 2) ->
+ fun(R,_,O) -> Pred(R,O) end;
+pred(Pred)
+ when is_function(Pred, 1) ->
+ fun(_,_,O) -> Pred(O) end;
+pred(Opts)
+ when is_list(Opts) ->
+ fun(_,_,O) -> [] == Opts -- O end;
+pred(Ref)
+ when is_reference(Ref) ->
+ fun(R,_,_) -> R == Ref end;
+pred({M,F,A})
+ when is_atom(M), is_atom(F), is_list(A) ->
+ fun(R,T,O) -> apply(M,F,[R,T,O|A]) end;
+pred({Type, Pred}) -> %% backwards compatibility
+ P = pred(Pred),
+ fun(R,T,O) -> T == Type andalso P(R,T,O) end;
+pred(B)
+ when is_boolean(B) ->
+ fun(_,_,_) -> B end;
+pred(_) ->
+ ?THROW(pred).
+
+%% --------------------------------------------------------------------------
+%% # have_transport/2
+%%
+%% Output: true | false
+%% --------------------------------------------------------------------------
+
+have_transport(SvcName, Ref) ->
+ member([{#transport{service = '$1',
+ ref = '$2',
+ _ = '_'},
+ [{'andalso', {'=:=', '$1', {const, SvcName}},
+ {'=:=', '$2', {const, Ref}}}],
+ [true]}]).
+
+%% --------------------------------------------------------------------------
+%% # lookup/1
+%% --------------------------------------------------------------------------
+
+lookup(SvcName) ->
+ select([{#service{name = '$1', rec = '$2', options = '$3'},
+ [{'=:=', '$1', {const, SvcName}}],
+ [{{'$1', '$2', '$3'}}]},
+ {#transport{service = '$1',
+ ref = '$2',
+ type = '$3',
+ options = '$4'},
+ [{'=:=', '$1', {const, SvcName}}],
+ [{{'$2', '$3', '$4'}}]}]).
+
+%% ---------------------------------------------------------
+%% 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/1
+%%% ----------------------------------------------------------
+
+init([]) ->
+ {ok, #state{}}.
+
+%%% ----------------------------------------------------------
+%%% # handle_call/2
+%%% ----------------------------------------------------------
+
+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) ->
+ warning_msg("received unexpected request from ~p:~n~w", [From, Req]),
+ Reply = {error, {bad_request, Req}},
+ {reply, Reply, State}.
+
+%%% ----------------------------------------------------------
+%%% # handle_cast/2
+%%% ----------------------------------------------------------
+
+handle_cast(Msg, State) ->
+ warning_msg("received unexpected message:~n~w", [Msg]),
+ {noreply, State}.
+
+%%% ----------------------------------------------------------
+%%% # handle_info/2
+%%% ----------------------------------------------------------
+
+%% A service process has died. This is most likely a consequence of
+%% stop_service, in which case the restart will find no config for the
+%% service and do nothing. The entry keyed on the monitor ref is only
+%% removed as a result of the 'DOWN' notification however.
+handle_info({'DOWN', MRef, process, _, Reason}, State) ->
+ [#monitor{service = SvcName} = T] = select([{#monitor{mref = MRef,
+ _ = '_'},
+ [],
+ ['$_']}]),
+ queue_restart(Reason, SvcName),
+ delete_object(T),
+ {noreply, State};
+
+handle_info({monitor, SvcName, Pid}, State) ->
+ monitor(Pid, SvcName),
+ {noreply, State};
+
+handle_info({restart, SvcName}, State) ->
+ restart(SvcName),
+ {noreply, State};
+
+handle_info(restart, State) ->
+ restart(),
+ {noreply, State};
+
+handle_info(Info, State) ->
+ warning_msg("received unknown info:~n~w", [Info]),
+ {noreply, State}.
+
+%%--------------------------------------------------------------------
+%% # terminate/2
+%%--------------------------------------------------------------------
+
+terminate(_Reason, _State) ->
+ ok.
+
+%%% ----------------------------------------------------------
+%%% # code_change/3
+%%% ----------------------------------------------------------
+
+code_change(_OldVsn, State, _Extra) ->
+ {ok, State}.
+
+%% ---------------------------------------------------------
+%% INTERNAL FUNCTIONS
+%% ---------------------------------------------------------
+
+insert(T) ->
+ ets:insert(?TABLE, T).
+
+%% ?TABLE is a bag: check only for a service entry.
+have_service(SvcName) ->
+ member([{#service{name = '$1', _ = '_'},
+ [{'=:=', '$1', {const, SvcName}}],
+ [true]}]).
+
+member(MatchSpec) ->
+ '$end_of_table' =/= ets:select(?TABLE, MatchSpec, 1).
+
+delete_object(T) ->
+ ets:delete_object(?TABLE, T).
+
+delete(Key) ->
+ ets:delete(?TABLE, Key).
+
+select(MatchSpec) ->
+ ets:select(?TABLE, MatchSpec).
+
+select_delete(MatchSpec) ->
+ ets:select_delete(?TABLE, MatchSpec).
+
+%% sync/2
+%%
+%% Interface functions used to be implemented as calls to ?SERVER but
+%% now serialize things per service instead since stopping a service
+%% can take time if the server doesn't answer DPR. A caller who wants
+%% to stop multiple services can then improve performance by spawning
+%% processes to stop them concurrently.
+
+sync(SvcName, T) ->
+ diameter_sync:call({?MODULE, SvcName},
+ {?MODULE, sync, [T]},
+ infinity,
+ infinity).
+
+%% sync/1
+
+sync({restart, SvcName}) ->
+ have_service(SvcName) andalso start(SvcName);
+
+sync({start_service, SvcName, Opts}) ->
+ try
+ start(have_service(SvcName), SvcName, Opts)
+ catch
+ ?FAILURE(Reason) -> {error, Reason}
+ end;
+
+sync({stop_service, SvcName}) ->
+ stop(SvcName);
+
+sync({add, SvcName, Type, Opts}) ->
+ try
+ add(SvcName, Type, Opts)
+ catch
+ ?FAILURE(Reason) -> {error, Reason}
+ end;
+
+sync({remove, SvcName, Pred}) ->
+ remove(select([{#transport{service = '$1', _ = '_'},
+ [{'=:=', '$1', {const, SvcName}}],
+ ['$_']}]),
+ SvcName,
+ Pred).
+
+%% start/3
+
+start(true, _, _) ->
+ {error, already_started};
+start(false, SvcName, Opts) ->
+ insert(make_config(SvcName, Opts)),
+ start(SvcName).
+
+%% start/1
+
+start(SvcName) ->
+ RC = diameter_service:start(SvcName),
+ startmon(SvcName, RC),
+ RC.
+
+startmon(SvcName, {ok, Pid}) ->
+ ?SERVER ! {monitor, SvcName, Pid};
+startmon(_, {error, _}) ->
+ ok.
+
+monitor(Pid, SvcName) ->
+ MRef = erlang:monitor(process, Pid),
+ insert(#monitor{mref = MRef, service = SvcName}).
+
+%% queue_restart/2
+
+%% Service has gone down on monitor death. Note that all service-related
+%% config is deleted.
+queue_restart({shutdown, {monitor, _}}, SvcName) ->
+ delete(SvcName);
+
+%% Application shutdown: ignore.
+queue_restart(shutdown, _) ->
+ ok;
+
+%% Or not.
+queue_restart(_, SvcName) ->
+ erlang:send_after(?RESTART_SLEEP, self(), {restart, SvcName}).
+
+%% restart/1
+
+restart(SvcName) ->
+ sync(SvcName, {restart, SvcName}).
+
+%% restart/0
+%%
+%% Start anything configured as required. Bang 'restart' to the server
+%% to kick things into gear manually. (Not that it should be required
+%% but it's been useful for test.)
+
+restart() ->
+ MatchSpec = [{#service{name = '$1', _ = '_'},
+ [],
+ ['$1']}],
+ lists:foreach(fun restart/1, select(MatchSpec)).
+
+%% stop/1
+
+stop(SvcName) ->
+ %% If the call to the service returns error for any reason other
+ %% than the process not being alive then deleting the config from
+ %% under it will surely bring it down.
+ diameter_service:stop(SvcName),
+ %% Delete only the service entry, not everything keyed on the name,
+ select_delete([{#service{name = '$1', _ = '_'},
+ [{'=:=', '$1', {const, SvcName}}],
+ [true]}]),
+ ok.
+%% Note that a transport has to be removed for its statistics to be
+%% deleted.
+
+%% add/3
+
+add(SvcName, Type, Opts) ->
+ %% Ensure usable capabilities. diameter_service:merge_service/2
+ %% depends on this.
+ lists:foreach(fun(Os) ->
+ is_list(Os) orelse ?THROW({capabilities, Os}),
+ ok = encode_CER(Os)
+ end,
+ [Os || {capabilities, Os} <- Opts, is_list(Os)]),
+
+ Ref = make_ref(),
+ T = {Ref, Type, Opts},
+ %% The call to the service returns error if the service isn't
+ %% started yet, which is harmless. The transport will be started
+ %% when the service is in that case.
+ case start_transport(SvcName, T) of
+ ok ->
+ insert(#transport{service = SvcName,
+ ref = Ref,
+ type = Type,
+ options = Opts}),
+ {ok, Ref};
+ {error, _} = No ->
+ No
+ end.
+
+start_transport(SvcName, T) ->
+ case diameter_service:start_transport(SvcName, T) of
+ {ok, _Pid} ->
+ ok;
+ {error, no_service} ->
+ ok;
+ {error, _} = No ->
+ No
+ end.
+
+%% remove/3
+
+remove(L, SvcName, Pred) ->
+ rm(SvcName, lists:filter(fun(#transport{ref = R, type = T, options = O}) ->
+ Pred(R,T,O)
+ end,
+ L)).
+
+rm(_, []) ->
+ ok;
+rm(SvcName, L) ->
+ Refs = lists:map(fun(#transport{ref = R}) -> R end, L),
+ case stop_transport(SvcName, Refs) of
+ ok ->
+ lists:foreach(fun delete_object/1, L);
+ {error, _} = No ->
+ No
+ end.
+
+stop_transport(SvcName, Refs) ->
+ case diameter_service:stop_transport(SvcName, Refs) of
+ ok ->
+ ok;
+ {error, no_service} ->
+ ok;
+ {error, _} = No ->
+ No
+ end.
+
+%% make_config/2
+
+make_config(SvcName, Opts) ->
+ Apps = init_apps(Opts),
+ [] == Apps andalso ?THROW(no_apps),
+
+ %% Use the fact that diameter_caps has the same field names as CER.
+ Fields = diameter_gen_base_rfc3588:'#info-'(diameter_base_CER) -- ['AVP'],
+
+ COpts = [T || {K,_} = T <- Opts, lists:member(K, Fields)],
+ Caps = make_caps(#diameter_caps{}, COpts),
+
+ 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}]),
+ %% share_peers and use_shared_peers are currently undocumented.
+
+ #service{name = SvcName,
+ rec = #diameter_service{applications = Apps,
+ capabilities = Caps},
+ options = Os}.
+
+make_caps(Caps, Opts) ->
+ case diameter_capx:make_caps(Caps, Opts) of
+ {ok, T} ->
+ T;
+ {error, {Reason, _}} ->
+ ?THROW(Reason)
+ end.
+
+%% Validate types by encoding a CER.
+encode_CER(Opts) ->
+ {ok, CER} = diameter_capx:build_CER(make_caps(?EXAMPLE_CAPS, Opts)),
+
+ Hdr = #diameter_header{version = ?DIAMETER_VERSION,
+ end_to_end_id = 0,
+ hop_by_hop_id = 0},
+
+ try
+ diameter_codec:encode(?BASE, #diameter_packet{header = Hdr,
+ msg = CER}),
+ ok
+ catch
+ exit: Reason ->
+ ?THROW(Reason)
+ end.
+
+init_apps(Opts) ->
+ lists:foldl(fun app_acc/2, [], lists:reverse(Opts)).
+
+app_acc({application, Opts}, Acc) ->
+ is_list(Opts) orelse ?THROW({application, Opts}),
+
+ [Dict, Mod] = get_opt([dictionary, module], Opts),
+ Alias = get_opt(alias, Opts, Dict),
+ ModS = get_opt(state, Opts, Alias),
+ M = get_opt(call_mutates_state, Opts, false),
+ A = get_opt(answer_errors, Opts, report),
+ [#diameter_app{alias = Alias,
+ dictionary = Dict,
+ id = cb(Dict, id),
+ module = init_mod(Mod),
+ init_state = ModS,
+ mutable = init_mutable(M),
+ answer_errors = init_answers(A)}
+ | Acc];
+app_acc(_, Acc) ->
+ Acc.
+
+init_mod(M)
+ when is_atom(M) ->
+ [M];
+init_mod([M|_] = L)
+ when is_atom(M) ->
+ L;
+init_mod(M) ->
+ ?THROW({module, M}).
+
+init_mutable(M)
+ when M == true;
+ M == false ->
+ M;
+init_mutable(M) ->
+ ?THROW({call_mutates_state, M}).
+
+init_answers(A)
+ when callback == A;
+ report == A;
+ discard == A ->
+ A;
+init_answers(A) ->
+ ?THROW({answer_errors, A}).
+
+%% Get a single value at the specified key.
+get_opt(Keys, List)
+ when is_list(Keys) ->
+ [get_opt(K, List) || K <- Keys];
+get_opt(Key, List) ->
+ case [V || {K,V} <- List, K == Key] of
+ [V] -> V;
+ _ -> ?THROW({arity, Key})
+ end.
+
+%% Get an optional value at the specified key.
+get_opt(Key, List, Def) ->
+ case [V || {K,V} <- List, K == Key] of
+ [] -> Def;
+ [V] -> V;
+ _ -> ?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
+ catch
+ E: Reason ->
+ ?THROW({callback, E, Reason, ?STACK})
+ end.
+
+%% call/1
+
+call(Request) ->
+ gen_server:call(?SERVER, Request, infinity).
+
+%% warning_msg/2
+
+warning_msg(F, A) ->
+ ?diameter_warning("~p: " ++ F, [?MODULE | A]).
diff --git a/lib/diameter/src/app/diameter_dbg.erl b/lib/diameter/src/app/diameter_dbg.erl
new file mode 100644
index 0000000000..b18f34e13d
--- /dev/null
+++ b/lib/diameter/src/app/diameter_dbg.erl
@@ -0,0 +1,565 @@
+%%
+%% %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_dbg).
+
+-export([table/1,
+ tables/0,
+ fields/1,
+ help/0,
+ modules/0,
+ versions/0,
+ version_info/0,
+ compiled/0,
+ procs/0,
+ latest/0,
+ nl/0,
+ log/4]).
+
+-export([diameter_config/0,
+ diameter_peer/0,
+ diameter_reg/0,
+ diameter_request/0,
+ diameter_sequence/0,
+ diameter_service/0,
+ diameter_stats/0]).
+
+-export([pp/1,
+ subscriptions/0,
+ children/0]).
+
+%% Trace help.
+-export([tracer/0, tracer/1,
+ p/0, p/1,
+ stop/0,
+ tpl/1,
+ tp/1]).
+
+-include_lib("diameter/include/diameter.hrl").
+-include("diameter_internal.hrl").
+
+
+-define(INFO, diameter_info).
+-define(SEP(), ?INFO:sep()).
+
+-define(LOCAL, [diameter_config,
+ diameter_peer,
+ diameter_reg,
+ diameter_request,
+ diameter_sequence,
+ diameter_service,
+ diameter_stats]).
+
+-define(VALUES(Rec), tl(tuple_to_list(Rec))).
+
+%%% ----------------------------------------------------------
+%%% # log/4
+%%%
+%%% Called to have something to trace on for happenings of interest.
+%%% ----------------------------------------------------------
+
+log(_Slogan, _Mod, _Line, _Details) ->
+ ok.
+
+%%% ----------------------------------------------------------
+%%% # help()
+%%% ----------------------------------------------------------
+
+help() ->
+ ?INFO:usage(usage()).
+
+usage() ->
+ not_yet_implemented.
+
+%%% ----------------------------------------------------------
+%%% # table(TableName)
+%%%
+%%% Input: TableName = diameter table containing record entries.
+%%%
+%%% Output: Count | undefined
+%%% ----------------------------------------------------------
+
+table(T)
+ when (T == diameter_peer) orelse (T == diameter_reg) ->
+ ?INFO:format(collect(T), fields(T), fun ?INFO:split/2);
+
+table(diameter_service = T) ->
+ Fs = [name, started] ++ fields(T) ++ [peerT,
+ connT,
+ share_peers,
+ use_shared_peers,
+ shared_peers,
+ local_peers,
+ monitor],
+ ?INFO:format(T,
+ fun(R) ->
+ [I,N,S|Vs] = ?VALUES(R),
+ {Fs, [N,I] ++ ?VALUES(S) ++ Vs}
+ end,
+ fun ?INFO:split/2);
+
+table(Table)
+ when is_atom(Table) ->
+ case fields(Table) of
+ undefined = No ->
+ No;
+ Fields ->
+ ?INFO:format(Table, Fields, fun ?INFO:split/2)
+ end.
+
+%%% ----------------------------------------------------------
+%%% # TableName()
+%%% ----------------------------------------------------------
+
+-define(TABLE(Name), Name() -> table(Name)).
+
+?TABLE(diameter_config).
+?TABLE(diameter_peer).
+?TABLE(diameter_reg).
+?TABLE(diameter_request).
+?TABLE(diameter_sequence).
+?TABLE(diameter_service).
+?TABLE(diameter_stats).
+
+%%% ----------------------------------------------------------
+%%% # tables()
+%%%
+%%% Output: Number of records output.
+%%%
+%%% Description: Pretty-print records in diameter tables from all nodes.
+%%% ----------------------------------------------------------
+
+tables() ->
+ format_all(fun ?INFO:split/3).
+
+format_all(SplitFun) ->
+ ?INFO:format(field(?LOCAL), SplitFun, fun collect/1).
+
+field(Tables) ->
+ lists:map(fun(T) -> {T, fields(T)} end, lists:sort(Tables)).
+
+%%% ----------------------------------------------------------
+%%% # modules()
+%%% ----------------------------------------------------------
+
+modules() ->
+ Path = filename:join([appdir(), atom_to_list(?APPLICATION) ++ ".app"]),
+ {ok, [{application, ?APPLICATION, Attrs}]} = file:consult(Path),
+ {modules, Mods} = lists:keyfind(modules, 1, Attrs),
+ Mods.
+
+appdir() ->
+ [_|_] = code:lib_dir(?APPLICATION, ebin).
+
+%%% ----------------------------------------------------------
+%%% # versions()
+%%% ----------------------------------------------------------
+
+versions() ->
+ ?INFO:versions(modules()).
+
+%%% ----------------------------------------------------------
+%%% # versions()
+%%% ----------------------------------------------------------
+
+version_info() ->
+ ?INFO:version_info(modules()).
+
+%%% ----------------------------------------------------------
+%%% # compiled()
+%%% ----------------------------------------------------------
+
+compiled() ->
+ ?INFO:compiled(modules()).
+
+%%% ----------------------------------------------------------
+%%% procs()
+%%% ----------------------------------------------------------
+
+procs() ->
+ ?INFO:procs(?APPLICATION).
+
+%%% ----------------------------------------------------------
+%%% # latest()
+%%% ----------------------------------------------------------
+
+latest() ->
+ ?INFO:latest(modules()).
+
+%%% ----------------------------------------------------------
+%%% # nl()
+%%% ----------------------------------------------------------
+
+nl() ->
+ lists:foreach(fun(M) -> abcast = c:nl(M) end, modules()).
+
+%%% ----------------------------------------------------------
+%%% # pp(Bin)
+%%%
+%%% Description: Pretty-print a message binary.
+%%% ----------------------------------------------------------
+
+%% Network byte order = big endian.
+
+pp(<<Version:8, MsgLength:24,
+ Rbit:1, Pbit:1, Ebit:1, Tbit:1, Reserved:4, CmdCode:24,
+ ApplId:32,
+ HbHid:32,
+ E2Eid:32,
+ AVPs/binary>>) ->
+ ?SEP(),
+ ppp(["Version",
+ "Message length",
+ "[Actual length]",
+ "R(equest)",
+ "P(roxiable)",
+ "E(rror)",
+ "T(Potential retrans)",
+ "Reserved bits",
+ "Command code",
+ "Application id",
+ "Hop by hop id",
+ "End to end id"],
+ [Version, MsgLength, size(AVPs) + 20,
+ Rbit, Pbit, Ebit, Tbit, Reserved,
+ CmdCode,
+ ApplId,
+ HbHid,
+ E2Eid]),
+ N = avp_loop({AVPs, MsgLength - 20}, 0),
+ ?SEP(),
+ N;
+
+pp(<<_Version:8, MsgLength:24, _/binary>> = Bin) ->
+ {bad_message_length, MsgLength, size(Bin)};
+
+pp(Bin)
+ when is_binary(Bin) ->
+ {truncated_binary, size(Bin)};
+
+pp(_) ->
+ not_binary.
+
+%% avp_loop/2
+
+avp_loop({Bin, Size}, N) ->
+ avp_loop(avp(Bin, Size), N+1);
+avp_loop(ok, N) ->
+ N;
+avp_loop([_E, _Rest] = L, N) ->
+ io:format("! ~s: ~p~n", L),
+ N;
+avp_loop([E, Rest, Fmt | Values], N)
+ when is_binary(Rest) ->
+ io:format("! ~s (" ++ Fmt ++ "): ~p~n", [E|Values] ++ [Rest]),
+ N.
+
+%% avp/2
+
+avp(<<>>, 0) ->
+ ok;
+avp(<<Code:32, Flags:1/binary, Length:24, Rest/binary>>,
+ Size) ->
+ avp(Code, Flags, Length, Rest, Size);
+avp(Bin, _) ->
+ ["truncated AVP header", Bin].
+
+%% avp/5
+
+avp(Code, Flags, Length, Rest, Size) ->
+ <<V:1, M:1, P:1, Res:5>>
+ = Flags,
+ b(),
+ ppp(["AVP Code",
+ "V(endor)",
+ "M(andatory)",
+ "P(Security)",
+ "R(eserved)",
+ "Length"],
+ [Code, V, M, P, Res, Length]),
+ avp(V, Rest, Length - 8, Size - 8).
+
+%% avp/4
+
+avp(1, <<V:32, Data/binary>>, Length, Size) ->
+ ppp({"Vendor-ID", V}),
+ data(Data, Length - 4, Size - 4);
+avp(1, Bin, _, _) ->
+ ["truncated Vendor-ID", Bin];
+avp(0, Data, Length, Size) ->
+ data(Data, Length, Size).
+
+data(Bin, Length, Size)
+ when size(Bin) >= Length ->
+ <<AVP:Length/binary, Rest/binary>> = Bin,
+ ppp({"Data", AVP}),
+ unpad(Rest, Size - Length, Length rem 4);
+
+data(Bin, _, _) ->
+ ["truncated AVP data", Bin].
+
+%% Remove padding bytes up to the next word boundary.
+unpad(Bin, Size, 0) ->
+ {Bin, Size};
+unpad(Bin, Size, N) ->
+ un(Bin, Size, 4 - N).
+
+un(Bin, Size, N)
+ when size(Bin) >= N ->
+ ppp({"Padding bytes", N}),
+ <<Pad:N/binary, Rest/binary>> = Bin,
+ Bits = N*8,
+ case Pad of
+ <<0:Bits>> ->
+ {Rest, Size - N};
+ _ ->
+ ["non-zero padding", Bin, "~p", N]
+ end;
+
+un(Bin, _, _) ->
+ ["truncated padding", Bin].
+
+b() ->
+ io:format("#~n").
+
+ppp(Fields, Values) ->
+ lists:foreach(fun ppp/1, lists:zip(Fields, Values)).
+
+ppp({Field, Value}) ->
+ io:format(": ~-22s : ~p~n", [Field, Value]).
+
+%%% ----------------------------------------------------------
+%%% # subscriptions()
+%%%
+%%% Output: list of {SvcName, Pid}
+%%% ----------------------------------------------------------
+
+subscriptions() ->
+ diameter_service:subscriptions().
+
+%%% ----------------------------------------------------------
+%%% # children()
+%%% ----------------------------------------------------------
+
+children() ->
+ diameter_sup:tree().
+
+%%% ----------------------------------------------------------
+
+%% tracer/[12]
+
+tracer(Port)
+ when is_integer(Port) ->
+ dbg:tracer(port, dbg:trace_port(ip, Port));
+
+tracer(Path)
+ when is_list(Path) ->
+ dbg:tracer(port, dbg:trace_port(file, Path)).
+
+tracer() ->
+ dbg:tracer(process, {fun p/2, ok}).
+
+p(T,_) ->
+ io:format("+ ~p~n", [T]).
+
+%% p/[01]
+
+p() ->
+ p([c,timestamp]).
+
+p(T) ->
+ dbg:p(all,T).
+
+%% stop/0
+
+stop() ->
+ dbg:ctp(),
+ dbg:stop_clear().
+
+%% tpl/1
+%% tp/1
+
+tpl(T) ->
+ dbg(tpl, dbg(T)).
+
+tp(T) ->
+ dbg(tp, dbg(T)).
+
+%% dbg/1
+
+dbg(x) ->
+ [{M, x, []} || M <- [diameter_tcp,
+ diameter_etcp,
+ diameter_sctp,
+ diameter_peer_fsm,
+ diameter_watchdog]];
+
+dbg(log) ->
+ {?MODULE, log, 4};
+
+dbg({log = F, Mods})
+ when is_list(Mods) ->
+ {?MODULE, F, [{['_','$1','_','_'],
+ [?ORCOND([{'==', '$1', M} || M <- Mods])],
+ []}]};
+
+dbg({log = F, Mod}) ->
+ dbg({F, [Mod]});
+
+dbg(send) ->
+ {diameter_peer, send, 2};
+
+dbg(recv) ->
+ {diameter_peer, recv, 2};
+
+dbg(sendrecv) ->
+ [{diameter_peer, send, 2},
+ {diameter_peer, recv, 2}];
+
+dbg(decode) ->
+ [{diameter_codec,decode,2}];
+
+dbg(encode) ->
+ [{diameter_codec,encode,2,[]},
+ {diameter_codec,encode,3,[]},
+ {diameter_codec,encode,4}];
+
+dbg(transition = T) ->
+ [{?MODULE, log, [{[T,M,'_','_'],[],[]}]}
+ || M <- [diameter_watchdog, diameter_peer_fsm]];
+
+dbg(T) ->
+ T.
+
+%% dbg/2
+
+dbg(TF, L)
+ when is_list(L) ->
+ {ok, lists:foldl(fun(T,A) -> {ok, X} = dbg(TF, T), [X|A] end, [], L)};
+
+dbg(F, M)
+ when is_atom(M) ->
+ dbg(F, {M});
+
+dbg(F, T)
+ when is_tuple(T) ->
+ [_|_] = A = tuple_to_list(T),
+ {ok,_} = apply(dbg, F, case is_list(lists:last(A)) of
+ false ->
+ A ++ [[{'_',[],[{exception_trace}]}]];
+ true ->
+ A
+ end).
+
+%% ===========================================================================
+%% ===========================================================================
+
+%% collect/1
+
+collect(diameter_peer) ->
+ lists:flatmap(fun peers/1, diameter:services());
+
+collect(diameter_reg) ->
+ diameter_reg:terms();
+
+collect(Name) ->
+ c(ets:info(Name), Name).
+
+c(undefined, _) ->
+ [];
+c(_, Name) ->
+ ets:tab2list(Name).
+
+%% peers/1
+
+peers(Name) ->
+ peers(Name, diameter:service_info(Name, transport)).
+
+peers(_, undefined) ->
+ [];
+peers(Name, {Cs,As}) ->
+ mk_peer(Name, connector, Cs) ++ mk_peer(Name, acceptor, As).
+
+mk_peer(Name, T, Ts) ->
+ [[Name | mk_peer(T,Vs)] || Vs <- Ts].
+
+mk_peer(Type, Vs) ->
+ [Ref, State, Opts, WPid, TPid, SApps, Caps]
+ = get_values(Vs, [ref, state, options, watchdog, peer, apps, caps]),
+ [Ref, State, [{type, Type} | Opts], s(WPid), s(TPid), SApps, Caps].
+
+get_values(Vs, Ks) ->
+ [proplists:get_value(K, Vs) || K <- Ks].
+
+s(undefined = T) ->
+ T;
+
+%% Collect states from watchdog/transport pids.
+s(Pid) ->
+ MRef = erlang:monitor(process, Pid),
+ Pid ! {state, self()},
+ receive
+ {'DOWN', MRef, process, _, _} ->
+ Pid;
+ {Pid, _} = T ->
+ erlang:demonitor(MRef, [flush]),
+ T
+ end.
+
+%% fields/1
+
+-define(FIELDS(Table), fields(Table) -> record_info(fields, Table)).
+
+fields(diameter_config) ->
+ [];
+
+fields(T)
+ when T == diameter_request;
+ T == diameter_sequence ->
+ fun kv/1;
+
+fields(diameter_stats) ->
+ fun({Ctr, N}) when not is_pid(Ctr) ->
+ {[counter, value], [Ctr, N]};
+ (_) ->
+ []
+ end;
+
+?FIELDS(diameter_service);
+?FIELDS(diameter_event);
+?FIELDS(diameter_uri);
+?FIELDS(diameter_avp);
+?FIELDS(diameter_header);
+?FIELDS(diameter_packet);
+?FIELDS(diameter_app);
+?FIELDS(diameter_caps);
+
+fields(diameter_peer) ->
+ [service, ref, state, options, watchdog, peer, applications, capabilities];
+
+fields(diameter_reg) ->
+ [property, pids];
+
+fields(_) ->
+ undefined.
+
+kv({_,_}) ->
+ [key, value];
+kv(_) ->
+ [].
diff --git a/lib/diameter/src/app/diameter_dict.erl b/lib/diameter/src/app/diameter_dict.erl
new file mode 100644
index 0000000000..3b9ba00a3f
--- /dev/null
+++ b/lib/diameter/src/app/diameter_dict.erl
@@ -0,0 +1,153 @@
+%%
+%% %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 provide OTP's dict interface built on top of ets.
+%%
+%% Note that while the interface is the same as dict the semantics
+%% aren't quite. A Dict here is just a table identifier (although
+%% this fact can't be used if you want dict/ets-based implementations
+%% to be interchangeable) so changes made to the Dict modify the
+%% underlying table. For merge/3, the first argument table is modified.
+%%
+%% The underlying ets table implementing a dict is deleted when the
+%% process from which new() was invoked exits and the dict is only
+%% writable from this process.
+%%
+%% The reason for this is to be able to swap dict/ets-based
+%% implementations: the former is easier to debug, the latter is
+%% faster for larger tables. It's also just a nice interface even
+%% when there's no need for swapability.
+%%
+
+-module(diameter_dict).
+
+-export([append/3,
+ append_list/3,
+ erase/2,
+ fetch/2,
+ fetch_keys/1,
+ filter/2,
+ find/2,
+ fold/3,
+ from_list/1,
+ is_key/2,
+ map/2,
+ merge/3,
+ new/0,
+ store/3,
+ to_list/1,
+ update/3,
+ update/4,
+ update_counter/3]).
+
+%%% ----------------------------------------------------------
+%%% EXPORTED INTERNAL FUNCTIONS
+%%% ----------------------------------------------------------
+
+append(Key, Value, Dict) ->
+ append_list(Key, [Value], Dict).
+
+append_list(Key, ValueList, Dict)
+ when is_list(ValueList) ->
+ update(Key, fun(V) -> V ++ ValueList end, ValueList, Dict).
+
+erase(Key, Dict) ->
+ ets:delete(Dict, Key),
+ Dict.
+
+fetch(Key, Dict) ->
+ {ok, V} = find(Key, Dict),
+ V.
+
+fetch_keys(Dict) ->
+ ets:foldl(fun({K,_}, Acc) -> [K | Acc] end, [], Dict).
+
+filter(Pred, Dict) ->
+ lists:foreach(fun({K,V}) -> filter(Pred(K,V), K, Dict) end, to_list(Dict)),
+ Dict.
+
+find(Key, Dict) ->
+ case ets:lookup(Dict, Key) of
+ [{Key, V}] ->
+ {ok, V};
+ [] ->
+ error
+ end.
+
+fold(Fun, Acc0, Dict) ->
+ ets:foldl(fun({K,V}, Acc) -> Fun(K, V, Acc) end, Acc0, Dict).
+
+from_list(List) ->
+ lists:foldl(fun store/2, new(), List).
+
+is_key(Key, Dict) ->
+ ets:member(Dict, Key).
+
+map(Fun, Dict) ->
+ lists:foreach(fun({K,V}) -> store(K, Fun(K,V), Dict) end, to_list(Dict)),
+ Dict.
+
+merge(Fun, Dict1, Dict2) ->
+ fold(fun(K2,V2,_) ->
+ update(K2, fun(V1) -> Fun(K2, V1, V2) end, V2, Dict1)
+ end,
+ Dict1,
+ Dict2).
+
+new() ->
+ ets:new(?MODULE, [set]).
+
+store(Key, Value, Dict) ->
+ store({Key, Value}, Dict).
+
+to_list(Dict) ->
+ ets:tab2list(Dict).
+
+update(Key, Fun, Dict) ->
+ store(Key, Fun(fetch(Key, Dict)), Dict).
+
+update(Key, Fun, Initial, Dict) ->
+ store(Key, map(Key, Fun, Dict, Initial), Dict).
+
+update_counter(Key, Increment, Dict)
+ when is_integer(Increment) ->
+ update(Key, fun(V) -> V + Increment end, Increment, Dict).
+
+%%% ---------------------------------------------------------
+%%% INTERNAL FUNCTIONS
+%%% ---------------------------------------------------------
+
+store({_,_} = T, Dict) ->
+ ets:insert(Dict, T),
+ Dict.
+
+filter(true, _, _) ->
+ ok;
+filter(false, K, Dict) ->
+ erase(K, Dict).
+
+map(Key, Fun, Dict, Error) ->
+ case find(Key, Dict) of
+ {ok, V} ->
+ Fun(V);
+ error ->
+ Error
+ end.
+
diff --git a/lib/diameter/src/app/diameter_exprecs.erl b/lib/diameter/src/app/diameter_exprecs.erl
new file mode 100644
index 0000000000..5e120d6f44
--- /dev/null
+++ b/lib/diameter/src/app/diameter_exprecs.erl
@@ -0,0 +1,301 @@
+%%
+%% %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%
+%%
+
+%%
+%% Parse transform for generating record access functions
+%%
+%% This parse transform can be used to reduce compile-time
+%% dependencies in large systems.
+%%
+%% In the old days, before records, Erlang programmers often wrote
+%% access functions for tuple data. This was tedious and error-prone.
+%% The record syntax made this easier, but since records were implemented
+%% fully in the pre-processor, a nasty compile-time dependency was
+%% introduced.
+%%
+%% This module automates the generation of access functions for
+%% records. While this method cannot fully replace the utility of
+%% pattern matching, it does allow a fair bit of functionality on
+%% records without the need for compile-time dependencies.
+%%
+%% Whenever record definitions need to be exported from a module,
+%% inserting a compiler attribute,
+%%
+%% export_records([RecName, ...])
+%%
+%% causes this transform to lay out access functions for the exported
+%% records:
+%%
+%% -module(foo)
+%% -compile({parse_transform, diameter_exprecs}).
+%%
+%% -record(r, {a, b, c}).
+%% -export_records([a]).
+%%
+%% -export(['#info-'/1, '#info-'/2,
+%% '#new-'/1, '#new-'/2,
+%% '#get-'/2, '#set-'/2,
+%% '#new-a'/0, '#new-a'/1,
+%% '#get-a'/2, '#set-a'/2,
+%% '#info-a'/1]).
+%%
+%% '#info-'(RecName) ->
+%% '#info-'(RecName, fields).
+%%
+%% '#info-'(r, Info) ->
+%% '#info-r'(Info).
+%%
+%% '#new-'(r) -> #r{}.
+%% '#new-'(r, Vals) -> '#new-r'(Vals)
+%%
+%% '#new-r'() -> #r{}.
+%% '#new-r'(Vals) -> '#set-r'(Vals, #r{}).
+%%
+%% '#get-'(Attrs, #r{} = Rec) ->
+%% '#get-r'(Attrs, Rec).
+%%
+%% '#get-r'(Attrs, Rec) when is_list(Attrs) ->
+%% ['#get-r'(A, Rec) || A <- Attrs];
+%% '#get-r'(a, Rec) -> Rec#r.a;
+%% '#get-r'(b, Rec) -> Rec#r.b;
+%% '#get-r'(c, Rec) -> Rec#r.c.
+%%
+%% '#set-'(Vals, #r{} = Rec) ->
+%% '#set-r'(Vals, Rec).
+%%
+%% '#set-r'(Vals, Rec) when is_list(Vals) ->
+%% lists:foldl(fun '#set-r'/2, Rec, Vals);
+%% '#set-r'({a,V}, Rec) -> Rec#r{a = V};
+%% '#set-r'({b,V}, Rec) -> Rec#r{b = V};
+%% '#set-r'({c,V}, Rec) -> Rec#r{c = V}.
+%%
+%% '#info-r'(fields) -> record_info(fields, r);
+%% '#info-r'(size) -> record_info(size, r);
+%% '#info-r'({index, a}) -> 1;
+%% '#info-r'({index, b}) -> 2;
+%% '#info-r'({index, c}) -> 3;
+%%
+
+-module(diameter_exprecs).
+
+-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}).
+
+%% 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.
+
+is_head(T) ->
+ not lists:member(element(1,T), [function, eof]).
+
+%% a_export/1
+
+a_export(Exports) ->
+ {?attribute, export, [{fname(info), 1},
+ {fname(info), 2},
+ {fname(new), 1},
+ {fname(new), 2},
+ {fname(get), 2},
+ {fname(set), 2}
+ | lists:flatmap(fun export/1, Exports)]}.
+
+export(Rname) ->
+ New = fname(new, Rname),
+ [{New, 0},
+ {New, 1},
+ {fname(get, Rname), 2},
+ {fname(set, Rname), 2},
+ {fname(info, Rname), 1}].
+
+%% f_accessors/2
+
+f_accessors(Es, Rs) ->
+ ['#info-/1'(),
+ '#info-/2'(Es),
+ '#new-/1'(Es),
+ '#new-/2'(Es),
+ '#get-/2'(Es),
+ '#set-/2'(Es)
+ | lists:flatmap(fun(N) -> accessors(N, fields(N, Rs)) end, Es)].
+
+accessors(Rname, Fields) ->
+ ['#new-X/0'(Rname),
+ '#new-X/1'(Rname),
+ '#get-X/2'(Rname, Fields),
+ '#set-X/2'(Rname, Fields),
+ '#info-X/1'(Rname, Fields)].
+
+fields(Rname, Recs) ->
+ {Rname, Fields} = lists:keyfind(Rname, 1, Recs),
+ lists:map(fun({record_field, _, {atom, _, N}}) -> N;
+ ({record_field, _, {atom, _, N}, _}) -> N
+ end,
+ Fields).
+
+fname_prefix(Op) ->
+ "#" ++ atom_to_list(Op) ++ "-".
+
+fname(Op) ->
+ list_to_atom(fname_prefix(Op)).
+
+fname(Op, Rname) ->
+ Prefix = fname_prefix(Op),
+ list_to_atom(Prefix ++ atom_to_list(Rname)).
+
+%% Generated functions.
+
+'#info-/1'() ->
+ Fname = fname(info),
+ {?function, Fname, 1,
+ [{?clause, [?VAR('RecName')],
+ [],
+ [?CALL(Fname, [?VAR('RecName'), ?ATOM(fields)])]}]}.
+
+'#info-/2'(Exports) ->
+ {?function, fname(info), 2,
+ lists:map(fun 'info-'/1, Exports)}.
+
+'info-'(R) ->
+ {?clause, [?ATOM(R), ?VAR('Info')],
+ [],
+ [?CALL(fname(info, R), [?VAR('Info')])]}.
+
+'#new-/1'(Exports) ->
+ {?function, fname(new), 1,
+ lists:map(fun 'new-'/1, Exports)}.
+
+'new-'(R) ->
+ {?clause, [?ATOM(R)],
+ [],
+ [{?record, R, []}]}.
+
+'#new-/2'(Exports) ->
+ {?function, fname(new), 2,
+ lists:map(fun 'new--'/1, Exports)}.
+
+'new--'(R) ->
+ {?clause, [?ATOM(R), ?VAR('Vals')],
+ [],
+ [?CALL(fname(new, R), [?VAR('Vals')])]}.
+
+'#get-/2'(Exports) ->
+ {?function, fname(get), 2,
+ lists:map(fun 'get-'/1, Exports)}.
+
+'get-'(R) ->
+ {?clause, [?VAR('Attrs'),
+ {?match, {?record, R, []}, ?VAR('Rec')}],
+ [],
+ [?CALL(fname(get, R), [?VAR('Attrs'), ?VAR('Rec')])]}.
+
+'#set-/2'(Exports) ->
+ {?function, fname(set), 2,
+ lists:map(fun 'set-'/1, Exports)}.
+
+'set-'(R) ->
+ {?clause, [?VAR('Vals'), {?match, {?record, R, []}, ?VAR('Rec')}],
+ [],
+ [?CALL(fname(set, R), [?VAR('Vals'), ?VAR('Rec')])]}.
+
+'#new-X/0'(Rname) ->
+ {?function, fname(new, Rname), 0,
+ [{?clause, [],
+ [],
+ [{?record, Rname, []}]}]}.
+
+'#new-X/1'(Rname) ->
+ {?function, fname(new, Rname), 1,
+ [{?clause, [?VAR('Vals')],
+ [],
+ [?CALL(fname(set, Rname), [?VAR('Vals'), {?record, Rname, []}])]}]}.
+
+'#set-X/2'(Rname, Fields) ->
+ {?function, fname(set, Rname), 2,
+ [{?clause, [?VAR('Vals'), ?VAR('Rec')],
+ [[?CALL(is_list, [?VAR('Vals')])]],
+ [?APPLY(lists, foldl, [{?'fun', {function, fname(set, Rname), 2}},
+ ?VAR('Rec'),
+ ?VAR('Vals')])]}
+ | lists:map(fun(A) -> 'set-X'(Rname, A) end, Fields)]}.
+
+'set-X'(Rname, Attr) ->
+ {?clause, [{?tuple, [?ATOM(Attr), ?VAR('V')]}, ?VAR('Rec')],
+ [],
+ [{?record, ?VAR('Rec'), Rname,
+ [{?record_field, ?ATOM(Attr), ?VAR('V')}]}]}.
+
+'#get-X/2'(Rname, Fields) ->
+ FName = fname(get, Rname),
+ {?function, FName, 2,
+ [{?clause, [?VAR('Attrs'), ?VAR('Rec')],
+ [[?CALL(is_list, [?VAR('Attrs')])]],
+ [{?lc, ?CALL(FName, [?VAR('A'), ?VAR('Rec')]),
+ [{?generate, ?VAR('A'), ?VAR('Attrs')}]}]}
+ | lists:map(fun(A) -> 'get-X'(Rname, A) end, Fields)]}.
+
+'get-X'(Rname, Attr) ->
+ {?clause, [?ATOM(Attr), ?VAR('Rec')],
+ [],
+ [{?record_field, ?VAR('Rec'), Rname, ?ATOM(Attr)}]}.
+
+'#info-X/1'(Rname, Fields) ->
+ {?function, fname(info, Rname), 1,
+ [{?clause, [?ATOM(fields)],
+ [],
+ [?CALL(record_info, [?ATOM(fields), ?ATOM(Rname)])]},
+ {?clause, [?ATOM(size)],
+ [],
+ [?CALL(record_info, [?ATOM(size), ?ATOM(Rname)])]}
+ | lists:map(fun(A) -> 'info-X'(Rname, A) end, Fields)]}.
+
+'info-X'(Rname, Attr) ->
+ {?clause, [{?tuple, [?ATOM(index), ?ATOM(Attr)]}],
+ [],
+ [{?record_index, Rname, ?ATOM(Attr)}]}.
diff --git a/lib/diameter/src/app/diameter_gen_base_accounting.dia b/lib/diameter/src/app/diameter_gen_base_accounting.dia
new file mode 100644
index 0000000000..64e95dddb5
--- /dev/null
+++ b/lib/diameter/src/app/diameter_gen_base_accounting.dia
@@ -0,0 +1,68 @@
+;;
+;; %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
new file mode 100644
index 0000000000..4a12e21acd
--- /dev/null
+++ b/lib/diameter/src/app/diameter_gen_base_rfc3588.dia
@@ -0,0 +1,413 @@
+;;
+;; %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_gen_relay.dia b/lib/diameter/src/app/diameter_gen_relay.dia
new file mode 100644
index 0000000000..d86446e368
--- /dev/null
+++ b/lib/diameter/src/app/diameter_gen_relay.dia
@@ -0,0 +1,24 @@
+;;
+;; %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 0xFFFFFFFF
+@prefix diameter_relay
+@vendor 0 IETF
+
+@inherits diameter_gen_base_rfc3588
diff --git a/lib/diameter/src/app/diameter_info.erl b/lib/diameter/src/app/diameter_info.erl
new file mode 100644
index 0000000000..39d32d07cd
--- /dev/null
+++ b/lib/diameter/src/app/diameter_info.erl
@@ -0,0 +1,869 @@
+%%
+%% %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_info).
+
+-export([usage/1,
+ format/1,
+ format/2,
+ format/3,
+ format/4,
+ table/2,
+ tables/1,
+ tables/2,
+ split/2,
+ split/3,
+ tab2list/1,
+ modules/1,
+ versions/1,
+ version_info/1,
+ attrs/2,
+ compiled/1,
+ procs/1,
+ latest/1,
+ list/1]).
+
+%% Support for rolling your own.
+-export([sep/0,
+ sep/1,
+ widest/1,
+ p/1,
+ p/3]).
+
+-compile({no_auto_import,[max/2]}).
+
+-export([collect/2]).
+
+-define(LONG_TIMEOUT, 30000).
+-define(VALUES(Rec), tl(tuple_to_list(Rec))).
+
+%%% ----------------------------------------------------------
+%%% # usage(String)
+%%% ----------------------------------------------------------
+
+usage(Usage) ->
+ sep($+),
+ io:format("+ ~p~n", [?MODULE]),
+ io:format("~n~s~n~n", [compact(Usage)]),
+ sep($+).
+
+%%%
+%%% The function format/3, for pretty-printing tables, comes in
+%%% several flavours.
+%%%
+
+%%% ----------------------------------------------------------
+%%% # format(TableName, Fields, SplitFun)
+%%%
+%%% Input: TableName = atom() name of table.
+%%%
+%%% Fields = List of field names for the records maintained
+%%% in the specified table. Can be empty, in which
+%%% case entries are listed unadorned of field names
+%%% and SplitFun is unused.
+%%% | Integer, equivalent to a list with this many '' atoms.
+%%% | Arity 1 fun mapping a table entry to a Fields list
+%%% or a tuple {Fields, Values} of lists of the same
+%%% length.
+%%%
+%%% If Fields is a list then its length must be the same
+%%% as or one less than the size of the tuples contained
+%%% in the table. (The values printed then being those
+%%% in the tuple or record in question.)
+%%%
+%%% SplitFun = Arity 3 fun applied as
+%%%
+%%% SplitFun(TableName, Fields, Values)
+%%%
+%%% in order to obtain a tuple
+%%%
+%%% {Field, RestFields, Value, RestValues}
+%%%
+%%% for which Field/Value will be formatted on
+%%% STDOUT. (This is to allow a value to be
+%%% transformed before being output by returning a
+%%% new value and/or replacing the remainder of
+%%% the list.) The returned lists must have the
+%%% same length and Field here is an atom, '' causing
+%%% a value to be listed unadorned of the field name.
+%%%
+%%% Field can also be list of field names, in
+%%% which case Value must be a record of the
+%%% corresponding type.
+%%%
+%%% | Arity 2 fun applied as SplitFun(Fields, Values).
+%%%
+%%% Output: Count | undefined
+%%%
+%%% Count = Number of entries output.
+%%%
+%%% Description: Pretty-print records in a named table.
+%%% ----------------------------------------------------------
+
+format(Table, Fields, SFun)
+ when is_atom(Table), is_function(SFun, 2) ->
+ ft(ets:info(Table), Table, SFun, Fields);
+
+format(Table, Fields, SFun)
+ when is_atom(Table), is_function(SFun, 3) ->
+ format(Table, Fields, fun(Fs,Vs) -> SFun(Table, Fs, Vs) end);
+
+%%% ----------------------------------------------------------
+%%% # format(Recs, Fields, SplitFun)
+%%%
+%%% Input: Recs = list of records/tuples
+%%% Fields = As for format(Table, Fields, SplitFun), a table
+%%% entry there being a member of Recs.
+%%% SplitFun = Arity 3 fun applied as above but with the TableName
+%%% replaced by the first element of the records in
+%%% question.
+%%% | Arity 2 fun as for format/3.
+%%%
+%%% Output: length(Recs)
+%%%
+%%% Description: Pretty print records/tuples.
+%%% ----------------------------------------------------------
+
+format(Recs, Fields, SFun)
+ when is_list(Recs), is_function(SFun, 3) ->
+ lists:foldl(fun(R,A) -> f(recsplit(SFun, R), 0, Fields, R, A) end,
+ 0,
+ Recs);
+
+format(Recs, Fields, SFun)
+ when is_list(Recs), is_function(SFun, 2) ->
+ lists:foldl(fun(R,A) -> f(SFun, 0, Fields, R, A) end,
+ 0,
+ Recs);
+
+%%% ----------------------------------------------------------
+%%% # format(Tables, SplitFun, CollectFun)
+%%%
+%%% Input: Tables = list of {TableName, Fields}.
+%%% SplitFun = As for format(Table, Fields, SplitFun).
+%%% CollectFun = arity 1 fun mapping a table name to a list
+%%% of elements. A non-list can be returned to indicate
+%%% that the table in question doesn't exist.
+%%%
+%%% Output: Number of entries output.
+%%%
+%%% Description: Pretty-print records in a named tables as collected
+%%% from known nodes. Each table listing is preceeded by
+%%% a banner.
+%%% ----------------------------------------------------------
+
+format(Tables, SFun, CFun)
+ when is_list(Tables), is_function(CFun, 1) ->
+ format_remote(Tables,
+ SFun,
+ rpc:multicall(nodes(known),
+ ?MODULE,
+ collect,
+ [CFun, lists:map(fun({T,_}) -> T end, Tables)],
+ ?LONG_TIMEOUT));
+
+%%% ----------------------------------------------------------
+%%% # format(LocalTables, RemoteTables, SplitFun, CollectFun)
+%%% # format(LocalTables, RemoteTables, SplitFun)
+%%%
+%%% Input: LocalTables = list of {TableName, Fields}.
+%%% | list of {TableName, Recs, Fields}
+%%% RemoteTable = list of {TableName, Fields}.
+%%% SplitFun, CollectFun = As for format(Table, CollectFun, SplitFun).
+%%%
+%%% Output: Number of entries output.
+%%%
+%%% Description: Pretty-print records in a named tables as collected
+%%% from local and remote nodes. Each table listing is
+%%% preceeded by a banner.
+%%% ----------------------------------------------------------
+
+format(Local, Remote, SFun) ->
+ format(Local, Remote, SFun, fun tab2list/1).
+
+format(Local, Remote, SFun, CFun)
+ when is_list(Local), is_list(Remote), is_function(CFun, 1) ->
+ format_local(Local, SFun) + format(Remote, SFun, CFun).
+
+%%% ----------------------------------------------------------
+%%% # format(Tables, SplitFun)
+%%% ----------------------------------------------------------
+
+format(Tables, SFun)
+ when is_list(Tables), (is_function(SFun, 2) or is_function(SFun, 3)) ->
+ format(Tables, SFun, fun tab2list/1);
+
+format(Tables, CFun)
+ when is_list(Tables), is_function(CFun, 1) ->
+ format(Tables, fun split/2, CFun).
+
+%%% ----------------------------------------------------------
+%%% # format(Table|Tables)
+%%% ----------------------------------------------------------
+
+format(Table)
+ when is_atom(Table) ->
+ format(Table, [], fun split/2);
+
+format(Tables)
+ when is_list(Tables) ->
+ format(Tables, fun split/2, fun tab2list/1).
+
+%%% ----------------------------------------------------------
+%%% # split(TableName, Fields, Values)
+%%%
+%%% Description: format/3 SplitFun that does nothing special.
+%%% ----------------------------------------------------------
+
+split([F|FT], [V|VT]) ->
+ {F, FT, V, VT}.
+
+split(_, Fs, Vs) ->
+ split(Fs, Vs).
+
+%%% ----------------------------------------------------------
+%%% # tab2list(TableName)
+%%%
+%%% Description: format/4 CollectFun that extracts records from an
+%%% existing ets table.
+%%% ----------------------------------------------------------
+
+tab2list(Table) ->
+ case ets:info(Table) of
+ undefined = No ->
+ No;
+ _ ->
+ ets:tab2list(Table)
+ end.
+
+list(Table) ->
+ l(tab2list(Table)).
+
+l(undefined = No) ->
+ No;
+l(List)
+ when is_list(List) ->
+ io:format("~p~n", [List]),
+ length(List).
+
+%%% ----------------------------------------------------------
+%%% # table(TableName, Fields)
+%%% ----------------------------------------------------------
+
+table(Table, Fields) ->
+ format(Table, Fields, fun split/2).
+
+%%% ----------------------------------------------------------
+%%% # tables(LocalTables, RemoteTables)
+%%% ----------------------------------------------------------
+
+tables(Local, Remote) ->
+ format(Local, Remote, fun split/2).
+
+%%% ----------------------------------------------------------
+%%% # tables(Tables)
+%%% ----------------------------------------------------------
+
+tables(Tables) ->
+ format(Tables, fun split/2).
+
+%%% ----------------------------------------------------------
+%%% # modules(Prefix|Prefixes)
+%%%
+%%% Input: Prefix = atom()
+%%%
+%%% Description: Return the list of all loaded modules with the
+%%% specified prefix.
+%%% ----------------------------------------------------------
+
+modules(Prefix)
+ when is_atom(Prefix) ->
+ lists:sort(mods(Prefix));
+
+modules(Prefixes)
+ when is_list(Prefixes) ->
+ lists:sort(lists:flatmap(fun modules/1, Prefixes)).
+
+mods(Prefix) ->
+ P = atom_to_list(Prefix),
+ lists:filter(fun(M) ->
+ lists:prefix(P, atom_to_list(M))
+ end,
+ erlang:loaded()).
+
+%%% ----------------------------------------------------------
+%%% # versions(Modules|Prefix)
+%%%
+%%% Output: Number of modules listed.
+%%%
+%%% Description: List the versions of the specified modules.
+%%% ----------------------------------------------------------
+
+versions(Modules) ->
+ {SysInfo, OsInfo, ModInfo} = version_info(Modules),
+ sep(),
+ print_sys_info(SysInfo),
+ sep(),
+ print_os_info(OsInfo),
+ sep(),
+ print_mod_info(ModInfo),
+ sep().
+
+%%% ----------------------------------------------------------
+%%% # attrs(Modules|Prefix, Attr|FormatFun)
+%%%
+%%% Output: Number of modules listed.
+%%%
+%%% Description: List an attribute from module_info.
+%%% ----------------------------------------------------------
+
+attrs(Modules, Attr)
+ when is_atom(Attr) ->
+ attrs(Modules, fun(W,M) -> attr(W, M, Attr, fun attr/1) end);
+
+attrs(Modules, Fun)
+ when is_list(Modules) ->
+ sep(),
+ W = 2 + widest(Modules),
+ N = lists:foldl(fun(M,A) -> Fun(W,M), A+1 end, 0, Modules),
+ sep(),
+ N;
+
+attrs(Prefix, Fun) ->
+ attrs(modules(Prefix), Fun).
+
+%% attr/1
+
+attr(T) when is_atom(T) ->
+ atom_to_list(T);
+attr(N) when is_integer(N) ->
+ integer_to_list(N);
+attr(V) ->
+ case is_list(V) andalso lists:all(fun is_char/1, V) of
+ true -> %% string
+ V;
+ false ->
+ io_lib:format("~p", [V])
+ end.
+
+is_char(C) ->
+ 0 =< C andalso C < 256.
+
+%% attr/4
+
+attr(Width, Mod, Attr, VFun) ->
+ io:format(": ~*s~s~n", [-Width, Mod, attr(Mod, Attr, VFun)]).
+
+attr(Mod, Attr, VFun) ->
+ Key = key(Attr),
+ try
+ VFun(val(Attr, keyfetch(Attr, Mod:module_info(Key))))
+ catch
+ _:_ ->
+ "-"
+ end.
+
+attr(Mod, Attr) ->
+ attr(Mod, Attr, fun attr/1).
+
+key(time) -> compile;
+key(_) -> attributes.
+
+val(time, {_,_,_,_,_,_} = T) ->
+ lists:flatten(io_lib:format("~p-~2..0B-~2..0B ~2..0B:~2..0B:~2..0B",
+ tuple_to_list(T)));
+val(_, [V]) ->
+ V.
+
+%%% ----------------------------------------------------------
+%%% # compiled(Modules|Prefix)
+%%%
+%%% Output: Number of modules listed.
+%%%
+%%% Description: List the compile times of the specified modules.
+%%% ----------------------------------------------------------
+
+compiled(Modules)
+ when is_list(Modules) ->
+ attrs(Modules, fun compiled/2);
+
+compiled(Prefix) ->
+ compiled(modules(Prefix)).
+
+compiled(Width, Mod) ->
+ io:format(": ~*s~19s ~s~n", [-Width,
+ Mod,
+ attr(Mod, time),
+ opt(attr(Mod, date))]).
+
+opt("-") ->
+ "";
+opt(D) ->
+ "(" ++ D ++ ")".
+
+%%% ----------------------------------------------------------
+%%% # procs(Pred|Prefix|Prefixes|Pid|Pids)
+%%%
+%%% Input: Pred = arity 2 fun returning true|false when applied to a
+%%% pid and its process info.
+%%%
+%%% Output: Number of processes listed.
+%%%
+%%% Description: List process info for all local processes that test
+%%% true with the specified predicate. With the prefix
+%%% form, those processes that are either currently
+%%% executing in, started executing in, or have a
+%%% registered name with a specified prefix are listed.
+%%% With the pid forms, only those process that are local
+%%% are listed and those that are dead list only the pid
+%%% itself.
+%%% ----------------------------------------------------------
+
+procs(Pred)
+ when is_function(Pred, 2) ->
+ procs(Pred, erlang:processes());
+
+procs([]) ->
+ 0;
+
+procs(Prefix)
+ when is_atom(Prefix) ->
+ procs(fun(_,I) -> info(fun pre1/2, I, atom_to_list(Prefix)) end);
+
+procs(Prefixes)
+ when is_atom(hd(Prefixes)) ->
+ procs(fun(_,I) -> info(fun pre/2, I, Prefixes) end);
+
+procs(Pid)
+ when is_pid(Pid) ->
+ procs(fun true2/2, [Pid]);
+
+procs(Pids)
+ when is_list(Pids) ->
+ procs(fun true2/2, Pids).
+
+true2(_,_) ->
+ true.
+
+%% procs/2
+
+procs(Pred, Pids) ->
+ Procs = lists:foldl(fun(P,A) ->
+ procs_acc(Pred, P, catch process_info(P), A)
+ end,
+ [],
+ Pids),
+ sep(0 < length(Procs)),
+ lists:foldl(fun(T,N) -> p(T), sep(), N+1 end, 0, Procs).
+
+procs_acc(_, Pid, undefined, Acc) -> %% dead
+ [[{pid, Pid}] | Acc];
+procs_acc(Pred, Pid, Info, Acc)
+ when is_list(Info) ->
+ p_acc(Pred(Pid, Info), Pid, Info, Acc);
+procs_acc(_, _, _, Acc) ->
+ Acc.
+
+p_acc(true, Pid, Info, Acc) ->
+ [[{pid, Pid} | Info] | Acc];
+p_acc(false, _, _, Acc) ->
+ Acc.
+
+%% info/3
+
+info(Pred, Info, T) ->
+ lists:any(fun(I) -> i(Pred, I, T) end, Info).
+
+i(Pred, {K, {M,_,_}}, T)
+ when K == current_function;
+ K == initial_call ->
+ Pred(M,T);
+i(Pred, {registered_name, N}, T) ->
+ Pred(N,T);
+i(_,_,_) ->
+ false.
+
+pre1(A, Pre) ->
+ lists:prefix(Pre, atom_to_list(A)).
+
+pre(A, Prefixes) ->
+ lists:any(fun(P) -> pre1(A, atom_to_list(P)) end, Prefixes).
+
+%%% ----------------------------------------------------------
+%%% # latest(Modules|Prefix)
+%%%
+%%% Output: {Mod, {Y,M,D,HH,MM,SS}, Version}
+%%%
+%%% Description: Return the compile time of the most recently compiled
+%%% module from the specified non-empty list. The modules
+%%% are assumed to exist.
+%%% ----------------------------------------------------------
+
+latest(Prefix)
+ when is_atom(Prefix) ->
+ latest(modules(Prefix));
+
+latest([_|_] = Modules) ->
+ {Mod, T}
+ = hd(lists:sort(fun latest/2, lists:map(fun compile_time/1, Modules))),
+ {Mod, T, app_vsn(Mod)}.
+
+app_vsn(Mod) ->
+ keyfetch(app_vsn, Mod:module_info(attributes)).
+
+compile_time(Mod) ->
+ T = keyfetch(time, Mod:module_info(compile)),
+ {Mod, T}.
+
+latest({_,T1},{_,T2}) ->
+ T1 > T2.
+
+%%% ----------------------------------------------------------
+%%% version_info(Modules|Prefix)
+%%%
+%%% Output: {SysInfo, OSInfo, [ModInfo]}
+%%%
+%%% SysInfo = {Arch, Vers}
+%%% OSInfo = {Vers, {Fam, Name}}
+%%% ModInfo = {Vsn, AppVsn, Time, CompilerVsn}
+%%% ----------------------------------------------------------
+
+version_info(Prefix)
+ when is_atom(Prefix) ->
+ version_info(modules(Prefix));
+
+version_info(Mods)
+ when is_list(Mods) ->
+ {sys_info(), os_info(), [{M, mod_version_info(M)} || M <- Mods]}.
+
+mod_version_info(Mod) ->
+ try
+ Info = Mod:module_info(),
+ [[Vsn], AppVsn] = get_values(attributes, [vsn, app_vsn], Info),
+ [Ver, Time] = get_values(compile, [version, time], Info),
+ [Vsn, AppVsn, Ver, Time]
+ catch
+ _:_ ->
+ []
+ end.
+
+get_values(Attr, Keys, Info) ->
+ As = proplists:get_value(Attr, Info),
+ [proplists:get_value(K, As, "?") || K <- Keys].
+
+sys_info() ->
+ [A,V] = [chomp(erlang:system_info(K)) || K <- [system_architecture,
+ system_version]],
+ {A,V}.
+
+os_info() ->
+ {os:version(), case os:type() of
+ {_Fam, _Name} = T ->
+ T;
+ Fam ->
+ {Fam, ""}
+ end}.
+
+chomp(S) ->
+ string:strip(S, right, $\n).
+
+print_sys_info({Arch, Ver}) ->
+ io:format("System info:~n"
+ " architecture : ~s~n"
+ " version : ~s~n",
+ [Arch, Ver]).
+
+print_os_info({Vsn, {Fam, Name}}) ->
+ io:format("OS info:~n"
+ " family : ~s ~s~n"
+ " version : ~s~n",
+ [str(Fam), bkt(str(Name)), vsn(Vsn)]).
+
+print_mod_info(Mods) ->
+ io:format("Module info:~n", []),
+ lists:foreach(fun print_mod/1, Mods).
+
+print_mod({Mod, []}) ->
+ io:format(" ~w:~n", [Mod]);
+print_mod({Mod, [Vsn, AppVsn, Ver, {Year, Month, Day, Hour, Min, Sec}]}) ->
+ Time = io_lib:format("~w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w",
+ [Year, Month, Day, Hour, Min, Sec]),
+ io:format(" ~w:~n"
+ " vsn : ~s~n"
+ " app_vsn : ~s~n"
+ " compiled : ~s~n"
+ " compiler : ~s~n",
+ [Mod, str(Vsn), str(AppVsn), Time, Ver]).
+
+str(A)
+ when is_atom(A) ->
+ atom_to_list(A);
+str(S)
+ when is_list(S) ->
+ S;
+str(T) ->
+ io_lib:format("~p", [T]).
+
+bkt("" = S) ->
+ S;
+bkt(S) ->
+ [$[, S, $]].
+
+vsn(T) when is_tuple(T) ->
+ case [[$., integer_to_list(N)] || N <- tuple_to_list(T)] of
+ [[$.,S] | Rest] ->
+ [S | Rest];
+ [] = S ->
+ S
+ end;
+vsn(T) ->
+ str(T).
+
+%%% ----------------------------------------------------------
+%%% ----------------------------------------------------------
+
+%% p/1
+
+p(Info) ->
+ W = 2 + widest([K || {K,_} <- Info]),
+ lists:foreach(fun({K,V}) -> p(W,K,V) end, Info).
+
+p(Width, Key, Value) ->
+ io:format(": ~*s: ~p~n", [-Width, Key, Value]).
+
+%% sep/[01]
+
+sep() ->
+ sep($#).
+
+sep(true) ->
+ sep();
+sep(false) ->
+ ok;
+
+sep(Ch) ->
+ io:format("~c~65c~n", [Ch, $-]).
+
+%% widest/1
+
+widest(List) ->
+ lists:foldl(fun widest/2, 0, List).
+
+widest(T, Max)
+ when is_atom(T) ->
+ widest(atom_to_list(T), Max);
+
+widest(T, Max)
+ when is_integer(T) ->
+ widest(integer_to_list(T), Max);
+
+widest(T, Max)
+ when is_list(T) -> %% string
+ max(length(T), Max).
+
+pt(T) ->
+ io:format(": ~p~n", [T]).
+
+recsplit(SFun, Rec) ->
+ fun(Fs,Vs) -> SFun(element(1, Rec), Fs, Vs) end.
+
+max(A, B) ->
+ if A > B -> A; true -> B end.
+
+keyfetch(Key, List) ->
+ {Key,V} = lists:keyfind(Key, 1, List),
+ V.
+
+%% ft/4
+
+ft(undefined = No, _, _, _) ->
+ No;
+
+ft(_, Table, SFun, Fields) ->
+ ets:foldl(fun(R,A) ->
+ f(SFun, 0, Fields, R, A)
+ end,
+ 0,
+ Table).
+
+%% f/5
+
+f(SFun, Width, Fields, Rec, Count) ->
+ ff(SFun, Width, fields(Fields, Rec), Rec, Count).
+
+ff(SFun, Width, Fields, Rec, Count) ->
+ sep(0 == Count),
+ f(SFun, Width, Fields, Rec),
+ sep(),
+ Count+1.
+
+fields(N, _)
+ when is_integer(N), N >= 0 ->
+ lists:duplicate(N, ''); %% list values unadorned
+fields(Fields, R)
+ when is_function(Fields, 1) ->
+ fields(Fields(R), R);
+fields({Fields, Values} = T, _)
+ when length(Fields) == length(Values) ->
+ T;
+fields(Fields, _)
+ when is_list(Fields) ->
+ Fields. %% list field/value pairs, or tuples if []
+
+%% f/4
+
+%% Empty fields list: just print the entry.
+f(_, _, [], Rec)
+ when is_tuple(Rec) ->
+ pt(Rec);
+
+%% Otherwise list field names/values.
+f(SFun, Width, {Fields, Values}, _) ->
+ f(SFun, Width, Fields, Values);
+
+f(SFun, Width, Fields, Rec)
+ when is_tuple(Rec) ->
+ f(SFun, Width, Fields, values(Fields, Rec));
+
+f(_, _, [], []) ->
+ ok;
+
+f(SFun, Width, [HF | _] = Fields, Values) ->
+ {F, FT, V, VT} = SFun(Fields, Values),
+ if is_list(F) -> %% V is a record
+ break($>, HF),
+ f(SFun, Width, F, values(F,V)),
+ break($<, HF),
+ f(SFun, Width, FT, VT);
+ F == '' -> %% no field name: just list value
+ pt(V),
+ f(SFun, Width, FT, VT);
+ true -> %% list field/value.
+ W = max(Width, 1 + widest(Fields)),
+ p(W, F, V),
+ f(SFun, W, FT, VT)
+ end.
+
+values(Fields, Rec)
+ when length(Fields) == size(Rec) - 1 ->
+ ?VALUES(Rec);
+values(Fields, T)
+ when length(Fields) == size(T) ->
+ tuple_to_list(T).
+
+%% format_local/2
+
+format_local(Tables, SFun) ->
+ lists:foldl(fun(T,A) -> fl(SFun, T, A) end, 0, Tables).
+
+fl(SFun, {Table, Recs, Fields}, Count) ->
+ sep(),
+ io:format("# ~p~n", [Table]),
+ N = fmt(Recs, Fields, SFun),
+ sep(0 == N),
+ Count + N;
+
+fl(SFun, {Table, Fields}, Count) ->
+ fl(SFun, {Table, Table, Fields}, Count).
+
+%% fmt/3
+
+fmt(T, Fields, SFun) ->
+ case format(T, Fields, SFun) of
+ undefined ->
+ 0;
+ N ->
+ N
+ end.
+
+%% break/2
+
+break(C, T) ->
+ io:format("~c ~p~n", [C, T]).
+
+%% collect/2
+%%
+%% Output: {[{TableName, Recs}, ...], node()}
+
+collect(CFun, TableNames) ->
+ {lists:foldl(fun(N,A) -> c(CFun, N, A) end, [], TableNames), node()}.
+
+c(CFun, TableName, Acc) ->
+ case CFun(TableName) of
+ Recs when is_list(Recs) ->
+ [{TableName, Recs} | Acc];
+ _ ->
+ Acc
+ end.
+
+%% format_remote/3
+
+format_remote(Tables, SFun, {Replies, BadNodes}) ->
+ N = lists:foldl(fun(T,A) -> fr(Tables, SFun, T, A) end,
+ 0,
+ Replies),
+ sep(0 == N andalso [] /= BadNodes),
+ lists:foreach(fun(Node) -> io:format("# no reply from ~p~n", [Node]) end,
+ BadNodes),
+ sep([] /= BadNodes),
+ N.
+
+fr(Tables, SFun, {List, Node}, Count)
+ when is_list(List) -> %% guard against {badrpc, Reason}
+ lists:foldl(fun({T,Recs}, C) -> fr(Tables, SFun, Node, T, Recs,C) end,
+ Count,
+ List);
+fr(_, _, _, Count) ->
+ Count.
+
+fr(Tables, SFun, Node, Table, Recs, Count) ->
+ Fields = keyfetch(Table, Tables),
+ sep(),
+ io:format("# ~p@~p~n", [Table, Node]),
+ N = format(Recs, Fields, tblsplit(SFun, Table)),
+ sep(0 == N),
+ Count + N.
+
+tblsplit(SFun, Table)
+ when is_function(SFun, 3) ->
+ fun(Fs,Vs) -> SFun(Table, Fs, Vs) end;
+tblsplit(SFun, _)
+ when is_function(SFun, 2) ->
+ SFun.
+
+%% compact/1
+%%
+%% Strip whitespace from both ends of a string.
+
+compact(Str) ->
+ compact(Str, true).
+
+compact([Ch|Rest], B)
+ when Ch == $\n;
+ Ch == $ ;
+ Ch == $\t;
+ Ch == $\v;
+ Ch == $\r ->
+ compact(Rest, B);
+
+compact(Str, false) ->
+ Str;
+
+compact(Str, true) ->
+ lists:reverse(compact(lists:reverse(Str), false)).
diff --git a/lib/diameter/src/app/diameter_internal.hrl b/lib/diameter/src/app/diameter_internal.hrl
new file mode 100644
index 0000000000..9de3914830
--- /dev/null
+++ b/lib/diameter/src/app/diameter_internal.hrl
@@ -0,0 +1,95 @@
+%%
+%% %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%
+%%
+
+%% Our Erlang application.
+-define(APPLICATION, diameter).
+
+%% The one and only.
+-define(DIAMETER_VERSION, 1).
+
+%% Exception for use within a module with decent protection against
+%% catching something we haven't thrown. Not foolproof but close
+%% enough. ?MODULE is rudmentary protection against catching across
+%% module boundaries, a root of much evil: always catch ?FAILURE(X),
+%% never X.
+-define(FAILURE(Reason), {{?MODULE}, {Reason}}).
+-define(THROW(Reason), throw(?FAILURE(Reason))).
+
+%% A corresponding error when failure is the best option.
+-define(ERROR(T), erlang:error({T, ?MODULE, ?LINE})).
+
+%% Failure reports always get a stack trace.
+-define(STACK, erlang:get_stacktrace()).
+
+%% Info report for anything unexpected.
+-define(REPORT(Reason, Func, Args),
+ diameter_lib:report(Reason, {?MODULE, Func, Args})).
+
+%% Something to trace on.
+-define(LOG(Slogan, Details),
+ diameter_dbg:log(Slogan, ?MODULE, ?LINE, Details)).
+-define(LOGC(Bool, Slogan, Details), ((Bool) andalso ?LOG(Slogan, Details))).
+
+%% Compensate for no builtin ?FUNC for use in log reports.
+-define(FUNC, element(2, element(2, process_info(self(), current_function)))).
+
+%% Disjunctive match spec condition. 'false' is to ensure that there's at
+%% least one condition.
+-define(ORCOND(List), list_to_tuple(['orelse', false | List])).
+
+%% 3588, 2.4:
+-define(APP_ID_COMMON, 0).
+-define(APP_ID_RELAY, 16#FFFFFFFF).
+
+-define(BASE, diameter_gen_base_rfc3588).
+
+%%% ---------------------------------------------------------
+
+%%% RFC 3588, ch 2.6 Peer table
+-record(diameter_peer,
+ {host_id,
+ statusT,
+ is_dynamic,
+ expiration,
+ tls_enabled}).
+
+%%% RFC 3588, ch 2.7 Realm-based routing table
+-record(diameter_realm,
+ {name,
+ app_id,
+ local_action, % LOCAL | RELAY | PROXY | REDIRECT
+ server_id,
+ is_dynamic,
+ expiration}).
+
+%%%----------------------------------------------------------------------
+%%% Error/warning/info message macro(s)
+%%%----------------------------------------------------------------------
+
+-define(diameter_info(F, A),
+ (catch error_logger:info_msg("[ ~w : ~w : ~p ] ~n" ++ F ++ "~n",
+ [?APPLICATION, ?MODULE, self()|A]))).
+
+-define(diameter_warning(F, A),
+ (catch error_logger:warning_msg("[ ~w : ~w : ~p ] ~n" ++ F ++ "~n",
+ [?APPLICATION, ?MODULE, self()|A]))).
+
+-define(diameter_error(F, A),
+ (catch error_logger:error_msg("[ ~w : ~w : ~p ] ~n" ++ F ++ "~n",
+ [?APPLICATION, ?MODULE, self()|A]))).
diff --git a/lib/diameter/src/app/diameter_lib.erl b/lib/diameter/src/app/diameter_lib.erl
new file mode 100644
index 0000000000..b5c0e1bf6a
--- /dev/null
+++ b/lib/diameter/src/app/diameter_lib.erl
@@ -0,0 +1,266 @@
+%%
+%% %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_lib).
+
+-export([report/2, info_report/2,
+ error_report/2,
+ warning_report/2,
+ now_diff/1,
+ time/1,
+ eval/1,
+ ip4address/1,
+ ip6address/1,
+ ipaddr/1,
+ spawn_opts/2,
+ wait/1,
+ fold_tuple/3]).
+
+-include("diameter_internal.hrl").
+
+%% ---------------------------------------------------------------------------
+%% # info_report(Reason, MFA)
+%%
+%% Input: Reason = Arbitrary term indicating the reason for the report.
+%% MFA = {Module, Function, Args} to report.
+%%
+%% Output: true
+%% ---------------------------------------------------------------------------
+
+report(Reason, MFA) ->
+ info_report(Reason, MFA).
+
+info_report(Reason, {M,F,A}) ->
+ error_logger:info_report(" Reason: ~p~n"
+ " Pid: ~p~n"
+ " Node: ~p~n"
+ " Module: ~p~n"
+ " Function: ~p~n"
+ "Arguments: ~p~n",
+ [Reason, self(), node(), M, F, A]).
+
+%%% ---------------------------------------------------------------------------
+%%% # error_report(Reason, MFA)
+%%% # warning_report(Reason, MFA)
+%%%
+%%% Output: false
+%%% ---------------------------------------------------------------------------
+
+error_report(Reason, MFA) ->
+ report(fun error_logger:error_report/1, Reason, MFA).
+
+warning_report(Reason, MFA) ->
+ report(fun error_logger:warning_report/1, Reason, MFA).
+
+report(Fun, Reason, MFA) ->
+ Fun([{reason, Reason}, {who, self()}, {where, node()}, {what, MFA}]),
+ false.
+
+%%% ---------------------------------------------------------------------------
+%%% # now_diff(Time)
+%%%
+%%% Description: Return timer:now_diff(now(), Time) as an {H, M, S, MicroS}
+%%% tuple instead of as integer microseconds.
+%%% ---------------------------------------------------------------------------
+
+now_diff({_,_,_} = Time) ->
+ time(timer:now_diff(erlang:now(), Time)).
+
+%%% ---------------------------------------------------------------------------
+%%% # time(Time)
+%%%
+%%% Input: Time = {MegaSec, Sec, MicroSec}
+%%% | MicroSec
+%%%
+%%% Output: {H, M, S, MicroS}
+%%% ---------------------------------------------------------------------------
+
+time({_,_,_} = Time) -> %% time of day
+ %% 24 hours = 24*60*60*1000000 = 86400000000 microsec
+ time(timer:now_diff(Time, {0,0,0}) rem 86400000000);
+
+time(Micro) -> %% elapsed time
+ Seconds = Micro div 1000000,
+ H = Seconds div 3600,
+ M = (Seconds rem 3600) div 60,
+ S = Seconds rem 60,
+ {H, M, S, Micro rem 1000000}.
+
+%%% ---------------------------------------------------------------------------
+%%% # eval(Func)
+%%% ---------------------------------------------------------------------------
+
+eval({M,F,A}) ->
+ apply(M,F,A);
+
+eval([{M,F,A} | X]) ->
+ apply(M, F, X ++ A);
+
+eval([[F|A] | X]) ->
+ eval([F | X ++ A]);
+
+eval([F|A]) ->
+ apply(F,A);
+
+eval({F}) ->
+ eval(F);
+
+eval(F) ->
+ F().
+
+%%% ---------------------------------------------------------------------------
+%%% # ip4address(Addr)
+%%%
+%%% Input: string() (eg. "10.0.0.1")
+%%% | list of integer()
+%%% | tuple of integer()
+%%%
+%%% Output: {_,_,_,_} of integer
+%%%
+%%% Exceptions: error: {invalid_address, Addr, erlang:get_stacktrace()}
+%%% ---------------------------------------------------------------------------
+
+ip4address([_,_,_,_] = Addr) -> %% Length 4 string can't be an address.
+ ipaddr(list_to_tuple(Addr));
+
+%% Be brutal.
+ip4address(Addr) ->
+ try
+ {_,_,_,_} = ipaddr(Addr)
+ catch
+ error: _ ->
+ erlang:error({invalid_address, Addr, ?STACK})
+ end.
+
+%%% ---------------------------------------------------------------------------
+%%% # ip6address(Addr)
+%%%
+%%% Input: string() (eg. "1080::8:800:200C:417A")
+%%% | list of integer()
+%%% | tuple of integer()
+%%%
+%%% Output: {_,_,_,_,_,_,_,_} of integer
+%%%
+%%% Exceptions: error: {invalid_address, Addr, erlang:get_stacktrace()}
+%%% ---------------------------------------------------------------------------
+
+ip6address([_,_,_,_,_,_,_,_] = Addr) -> %% Length 8 string can't be an address.
+ ipaddr(list_to_tuple(Addr));
+
+%% Be brutal.
+ip6address(Addr) ->
+ try
+ {_,_,_,_,_,_,_,_} = ipaddr(Addr)
+ catch
+ error: _ ->
+ erlang:error({invalid_address, Addr, ?STACK})
+ end.
+
+%%% ---------------------------------------------------------------------------
+%%% # ipaddr(Addr)
+%%%
+%%% Input: string() | tuple of integer()
+%%%
+%%% Output: {_,_,_,_} | {_,_,_,_,_,_,_,_}
+%%%
+%%% Exceptions: error: {invalid_address, erlang:get_stacktrace()}
+%%% ---------------------------------------------------------------------------
+
+-spec ipaddr(string() | tuple())
+ -> inet:ip_address().
+
+%% Don't convert lists of integers since a length 8 list like
+%% [$1,$0,$.,$0,$.,$0,$.,$1] is ambiguous: is it "10.0.0.1" or
+%% "49:48:46:48:46:48:46:49"?
+%%
+%% RFC 2373 defines the format parsed for v6 addresses.
+
+%% Be brutal.
+ipaddr(Addr) ->
+ try
+ ip(Addr)
+ catch
+ error: _ ->
+ erlang:error({invalid_address, ?STACK})
+ end.
+
+%% Already a tuple: ensure non-negative integers of the right size.
+ip(T)
+ when size(T) == 4;
+ size(T) == 8 ->
+ Bs = 2*size(T),
+ [] = lists:filter(fun(N) when 0 =< N -> 0 < N bsr Bs end,
+ tuple_to_list(T)),
+ T;
+
+%% Or not: convert from '.'/':'-separated decimal/hex.
+ip(Addr) ->
+ {ok, A} = inet_parse:address(Addr), %% documented in inet(3)
+ A.
+
+%%% ---------------------------------------------------------------------------
+%%% # spawn_opts(Type, Opts)
+%%% ---------------------------------------------------------------------------
+
+%% TODO: config variables.
+
+spawn_opts(server, Opts) ->
+ opts(75000, Opts);
+spawn_opts(worker, Opts) ->
+ opts(5000, Opts).
+
+opts(HeapSize, Opts) ->
+ [{min_heap_size, HeapSize} | lists:keydelete(min_heap_size, 1, Opts)].
+
+%%% ---------------------------------------------------------------------------
+%%% # wait(MRefs)
+%%% ---------------------------------------------------------------------------
+
+wait(L) ->
+ w([erlang:monitor(process, P) || P <- L]).
+
+w([]) ->
+ ok;
+w(L) ->
+ receive
+ {'DOWN', MRef, process, _, _} ->
+ w(lists:delete(MRef, L))
+ end.
+
+%%% ---------------------------------------------------------------------------
+%%% # fold_tuple(N, T0, T)
+%%% ---------------------------------------------------------------------------
+
+%% Replace fields in T0 by those of T starting at index N, unless the
+%% new value is 'undefined'.
+%%
+%% eg. fold_tuple(2, Hdr, #diameter_header{end_to_end_id = 42})
+
+fold_tuple(_, T, undefined) ->
+ T;
+
+fold_tuple(N, T0, T) ->
+ element(2, lists:foldl(fun(X, {M,_} = A) -> {M+1, ft(X, A)} end,
+ {N, T0},
+ lists:nthtail(N-1, tuple_to_list(T)))).
+
+ft(undefined, T) ->
+ T;
+ft(X, {N, T}) ->
+ setelement(N, T, X).
diff --git a/lib/diameter/src/app/diameter_misc_sup.erl b/lib/diameter/src/app/diameter_misc_sup.erl
new file mode 100644
index 0000000000..4e40476f14
--- /dev/null
+++ b/lib/diameter/src/app/diameter_misc_sup.erl
@@ -0,0 +1,58 @@
+%%
+%% %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 supervisor of the static server processes.
+%%
+
+-module(diameter_misc_sup).
+
+-behaviour(supervisor).
+
+-export([start_link/0]). %% supervisor start
+
+%% supervisor callback
+-export([init/1]).
+
+-define(CHILDREN, [diameter_sync, %% serialization
+ diameter_stats, %% statistics counter management
+ diameter_reg, %% service/property publishing
+ diameter_peer, %% remote peer manager
+ diameter_config]). %% configuration/restart
+
+%% start_link/0
+
+start_link() ->
+ SupName = {local, ?MODULE},
+ supervisor:start_link(SupName, ?MODULE, []).
+
+%% init/1
+
+init([]) ->
+ Flags = {one_for_one, 1, 5},
+ Workers = lists:map(fun spec/1, ?CHILDREN),
+ {ok, {Flags, Workers}}.
+
+spec(Mod) ->
+ {Mod,
+ {Mod, start_link, []},
+ permanent,
+ 1000,
+ worker,
+ [Mod]}.
diff --git a/lib/diameter/src/app/diameter_peer.erl b/lib/diameter/src/app/diameter_peer.erl
new file mode 100644
index 0000000000..6b8971b8ea
--- /dev/null
+++ b/lib/diameter/src/app/diameter_peer.erl
@@ -0,0 +1,230 @@
+%%
+%% %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_peer).
+
+-behaviour(gen_server).
+
+%% Interface towards transport modules ...
+-export([recv/2,
+ up/1,
+ up/2]).
+
+%% ... and the stack.
+-export([start/3,
+ send/2,
+ close/1,
+ abort/1,
+ notify/2]).
+
+%% Server start.
+-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_lib("diameter/include/diameter.hrl").
+-include("diameter_internal.hrl").
+
+%% Registered name of the server.
+-define(SERVER, ?MODULE).
+
+%% Server state.
+-record(state, {id = now()}).
+
+%%% ---------------------------------------------------------------------------
+%%% # notify/2
+%%% ---------------------------------------------------------------------------
+
+notify(SvcName, T) ->
+ rpc:abcast(nodes(), ?SERVER, {notify, SvcName, T}).
+
+%%% ---------------------------------------------------------------------------
+%%% # start/3
+%%% ---------------------------------------------------------------------------
+
+start(T, Opts, #diameter_service{} = Svc) ->
+ {Mod, Cfg} = split_transport(Opts),
+ apply(Mod, start, [T, Svc, Cfg]).
+
+%%% ---------------------------------------------------------------------------
+%%% # up/[12]
+%%% ---------------------------------------------------------------------------
+
+up(Pid) -> %% accepting transport
+ ifc_send(Pid, {self(), connected}).
+
+up(Pid, Remote) -> %% connecting transport
+ ifc_send(Pid, {self(), connected, Remote}).
+
+%%% ---------------------------------------------------------------------------
+%%% # recv/2
+%%% ---------------------------------------------------------------------------
+
+recv(Pid, Pkt) ->
+ ifc_send(Pid, {recv, Pkt}).
+
+%%% ---------------------------------------------------------------------------
+%%% # send/2
+%%% ---------------------------------------------------------------------------
+
+send(Pid, #diameter_packet{transport_data = undefined,
+ bin = Bin}) ->
+ send(Pid, Bin);
+
+send(Pid, Pkt) ->
+ ifc_send(Pid, {send, Pkt}).
+
+%%% ---------------------------------------------------------------------------
+%%% # close/1
+%%% ---------------------------------------------------------------------------
+
+close(Pid) ->
+ ifc_send(Pid, {close, self()}).
+
+%%% ---------------------------------------------------------------------------
+%%% # abort/1
+%%% ---------------------------------------------------------------------------
+
+abort(Pid) ->
+ exit(Pid, shutdown).
+
+%% ---------------------------------------------------------------------------
+%% ---------------------------------------------------------------------------
+
+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(Role)
+%%% ----------------------------------------------------------
+
+init([]) ->
+ {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(Req, From, State) ->
+ warning_msg("received unexpected request from ~p:~n~w", [From, Req]),
+ {reply, nok, State}.
+
+%%% ----------------------------------------------------------
+%%% # handle_cast(Request, State)
+%%% ----------------------------------------------------------
+
+handle_cast(Msg, State) ->
+ warning_msg("received unexpected message:~n~w", [Msg]),
+ {noreply, State}.
+
+%%% ----------------------------------------------------------
+%%% # handle_info(Request, State)
+%%% ----------------------------------------------------------
+
+%% Remote service is distributing a message.
+handle_info({notify, SvcName, T}, S) ->
+ bang(diameter_service:whois(SvcName), T),
+ {noreply, S};
+
+handle_info(Info, State) ->
+ warning_msg("received unexpected info:~n~w", [Info]),
+ {noreply, State}.
+
+%% ----------------------------------------------------------
+%% terminate(Reason, State)
+%% ----------------------------------------------------------
+
+terminate(_Reason, _State) ->
+ ok.
+
+%% ----------------------------------------------------------
+%% code_change(OldVsn, State, Extra)
+%% ----------------------------------------------------------
+
+code_change(_OldVsn, State, _Extra) ->
+ {ok, State}.
+
+%% ---------------------------------------------------------
+%% INTERNAL FUNCTIONS
+%% ---------------------------------------------------------
+
+%% ifc_send/2
+%%
+%% Send something over the transport interface.
+
+ifc_send(Pid, T) ->
+ Pid ! {diameter, T}.
+
+%% bang/2
+
+bang(undefined = No, _) ->
+ 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) ->
+ gen_server:call(?SERVER, Request, infinity).
+
+%% warning_msg/2
+
+warning_msg(F, A) ->
+ ?diameter_warning("~p: " ++ F, [?MODULE | A]).
diff --git a/lib/diameter/src/app/diameter_peer_fsm.erl b/lib/diameter/src/app/diameter_peer_fsm.erl
new file mode 100644
index 0000000000..0252fb3809
--- /dev/null
+++ b/lib/diameter/src/app/diameter_peer_fsm.erl
@@ -0,0 +1,746 @@
+%%
+%% %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_peer_fsm_sup.erl b/lib/diameter/src/app/diameter_peer_fsm_sup.erl
new file mode 100644
index 0000000000..995eaf74d0
--- /dev/null
+++ b/lib/diameter/src/app/diameter_peer_fsm_sup.erl
@@ -0,0 +1,63 @@
+%%
+%% %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 supervisor of peer_fsm processes.
+%%
+
+-module(diameter_peer_fsm_sup).
+
+-behaviour(supervisor).
+
+-define(NAME, ?MODULE). %% supervisor name
+
+%%-----------------------------------------------------------------
+%% External exports
+%%-----------------------------------------------------------------
+
+-export([start_link/0, %% supervisor start
+ start_child/1]). %% peer fsm start
+
+-export([init/1]).
+
+%% start_link/0
+
+start_link() ->
+ SupName = {local, ?NAME},
+ supervisor:start_link(SupName, ?MODULE, []).
+
+%% start_child/1
+%%
+%% Start a peer_fsm process.
+
+start_child(T) ->
+ supervisor:start_child(?NAME, [T]).
+
+%% init/1
+
+init([]) ->
+ Mod = diameter_peer_fsm,
+ Flags = {simple_one_for_one, 0, 1},
+ ChildSpec = {Mod,
+ {Mod, start_link, []},
+ temporary,
+ 1000,
+ worker,
+ [Mod]},
+ {ok, {Flags, [ChildSpec]}}.
diff --git a/lib/diameter/src/app/diameter_reg.erl b/lib/diameter/src/app/diameter_reg.erl
new file mode 100644
index 0000000000..8e5f34c2c3
--- /dev/null
+++ b/lib/diameter/src/app/diameter_reg.erl
@@ -0,0 +1,331 @@
+%%
+%% %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) ->
+ {reply, nok, State}.
+
+%%% ----------------------------------------------------------
+%%% # handle_cast(Request, State)
+%%% ----------------------------------------------------------
+
+handle_cast(Msg, State)->
+ warning_msg("received unexpected message:~n~w", [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) ->
+ warning_msg("received unknown info:~n~w", [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).
+
+%% warning_msg/2
+
+warning_msg(F, A) ->
+ ?diameter_warning("~p: " ++ F, [?MODULE | A]).
diff --git a/lib/diameter/src/app/diameter_service.erl b/lib/diameter/src/app/diameter_service.erl
new file mode 100644
index 0000000000..82a8d7a994
--- /dev/null
+++ b/lib/diameter/src/app/diameter_service.erl
@@ -0,0 +1,2931 @@
+%%
+%% %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%
+%%
+
+%%
+%% Implements the process that represents a service.
+%%
+
+-module(diameter_service).
+-behaviour(gen_server).
+
+-export([start/1,
+ stop/1,
+ start_transport/2,
+ stop_transport/2,
+ info/2,
+ call/4]).
+
+%% towards diameter_watchdog
+-export([receive_message/3]).
+
+%% service supervisor
+-export([start_link/1]).
+
+-export([subscribe/1,
+ unsubscribe/1,
+ subscriptions/1,
+ subscriptions/0,
+ services/0,
+ services/1,
+ whois/1,
+ flush_stats/1]).
+
+%% test/debug
+-export([call_module/3,
+ state/1,
+ uptime/1]).
+
+%%% gen_server callbacks
+-export([init/1,
+ handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+ terminate/2,
+ code_change/3]).
+
+%% Other callbacks.
+-export([send/1]).
+
+-include_lib("diameter/include/diameter.hrl").
+-include("diameter_internal.hrl").
+-include("diameter_types.hrl").
+
+-define(STATE_UP, up).
+-define(STATE_DOWN, down).
+
+-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
+
+%% Used to be able to swap this with anything else dict-like but now
+%% rely on the fact that a service's #state{} record does not change
+%% in storing in it ?STATE table and not always going through the
+%% service process. In particular, rely on the fact that operations on
+%% a ?Dict don't change the handle to it.
+-define(Dict, diameter_dict).
+
+%% Table containing outgoing requests for which a reply has yet to be
+%% received.
+-define(REQUEST_TABLE, diameter_request).
+
+%% Maintains state in a table. In contrast to previously, a service's
+%% stat is not constant and is accessed outside of the service
+%% process.
+-define(STATE_TABLE, ?MODULE).
+
+%% Workaround for dialyzer's lack of understanding of match specs.
+-type match(T)
+ :: T | '_' | '$1' | '$2' | '$3' | '$4'.
+
+%% State of service gen_server.
+-record(state,
+ {id = now(),
+ 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?
+ shared_peers = ?Dict:new(), %% Alias -> [{TPid, Caps}, ...]
+ local_peers = ?Dict:new(), %% Alias -> [{TPid, Caps}, ...]
+ monitor = false :: false | pid()}). %% process to die with
+%% 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
+%% from ?STATE_TABLE from outside the service process. The pid in the
+%% 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(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),
+ 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.
+-record(conn,
+ {pid :: pid(),
+ apps :: [{0..16#FFFFFFFF, app_alias()}], %% {Id, Alias}
+ caps :: #diameter_caps{},
+ started = now(), %% at process start
+ peer :: pid()}). %% key into peerT
+
+%% Record stored in diameter_request for each outgoing request.
+-record(request,
+ {from, %% arg 2 of handle_call/3
+ 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()),
+ packet :: match(#diameter_packet{})}).
+
+%% Record call/4 options are parsed into.
+-record(options,
+ {filter = none :: 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)
+%%% ---------------------------------------------------------------------------
+
+start(SvcName) ->
+ diameter_service_sup:start_child(SvcName).
+
+start_link(SvcName) ->
+ Options = [{spawn_opt, diameter_lib:spawn_opts(server, [])}],
+ gen_server:start_link(?MODULE, [SvcName], Options).
+%% Put the arbitrary term SvcName in a list in case we ever want to
+%% send more than this and need to distinguish old from new.
+
+%%% ---------------------------------------------------------------------------
+%%% # stop(SvcName)
+%%% ---------------------------------------------------------------------------
+
+stop(SvcName) ->
+ case whois(SvcName) of
+ undefined ->
+ {error, not_started};
+ Pid ->
+ stop(call_service(Pid, stop), Pid)
+ end.
+
+stop(ok, Pid) ->
+ MRef = erlang:monitor(process, Pid),
+ receive {'DOWN', MRef, process, _, _} -> ok end;
+stop(No, _) ->
+ No.
+
+%%% ---------------------------------------------------------------------------
+%%% # start_transport(SvcName, {Ref, Type, Opts})
+%%% ---------------------------------------------------------------------------
+
+start_transport(SvcName, {_,_,_} = T) ->
+ call_service_by_name(SvcName, {start, T}).
+
+%%% ---------------------------------------------------------------------------
+%%% # stop_transport(SvcName, Refs)
+%%% ---------------------------------------------------------------------------
+
+stop_transport(_, []) ->
+ ok;
+stop_transport(SvcName, [_|_] = Refs) ->
+ call_service_by_name(SvcName, {stop, Refs}).
+
+%%% ---------------------------------------------------------------------------
+%%% # info(SvcName, Item)
+%%% ---------------------------------------------------------------------------
+
+info(SvcName, Item) ->
+ info_rc(call_service_by_name(SvcName, {info, Item})).
+
+info_rc({error, _}) ->
+ undefined;
+info_rc(Info) ->
+ Info.
+
+%%% ---------------------------------------------------------------------------
+%%% # 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.
+
+receive_message(TPid, Pkt, T)
+ when is_pid(TPid) ->
+ #diameter_packet{header = #diameter_header{is_request = R}} = Pkt,
+ recv(R, (not R) andalso lookup_request(Pkt, TPid), TPid, Pkt, T).
+
+%% Incoming request ...
+recv(true, false, TPid, Pkt, T) ->
+ try
+ spawn(fun() -> recv_request(TPid, Pkt, T) end)
+ catch
+ error: system_limit = E -> %% discard
+ ?LOG({error, E}, now())
+ end;
+
+%% ... answer to known request ...
+recv(false, #request{from = {_, Ref}, handler = Pid} = Req, _, Pkt, _) ->
+ Pid ! {answer, Ref, Req, Pkt};
+%% Note that failover could have happened prior to this message being
+%% received and triggering failback. That is, both a failover message
+%% and answer may be on their way to the handler process. In the worst
+%% case the request process gets notification of the failover and
+%% sends to the alternate peer before an answer arrives, so it's
+%% always the case that we can receive more than one answer after
+%% failover. The first answer received by the request process wins,
+%% any others are discarded.
+
+%% ... or not.
+recv(false, false, _, _, _) ->
+ ok.
+
+%%% ---------------------------------------------------------------------------
+%%% # call(SvcName, App, Msg, Options)
+%%% ---------------------------------------------------------------------------
+
+call(SvcName, App, Msg, Options)
+ when is_list(Options) ->
+ Rec = make_options(Options),
+ Ref = make_ref(),
+ Caller = {self(), Ref},
+ Fun = fun() -> exit({Ref, call(SvcName, App, Msg, Rec, Caller)}) end,
+ try spawn_monitor(Fun) of
+ {_, MRef} ->
+ recv(MRef, Ref, Rec#options.detach, false)
+ catch
+ error: system_limit = E ->
+ {error, E}
+ end.
+
+%% Don't rely on gen_server:call/3 for the timeout handling since it
+%% makes no guarantees about not leaving a reply message in the
+%% mailbox if we catch its exit at timeout. It currently *can* do so,
+%% which is also undocumented.
+
+recv(MRef, _, true, true) ->
+ erlang:demonitor(MRef, [flush]),
+ ok;
+
+recv(MRef, Ref, Detach, Sent) ->
+ receive
+ Ref -> %% send has been attempted
+ recv(MRef, Ref, Detach, true);
+ {'DOWN', MRef, process, _, Reason} ->
+ call_rc(Reason, Ref, Sent)
+ end.
+
+%% call/5 has returned ...
+call_rc({Ref, Ans}, Ref, _) ->
+ Ans;
+
+%% ... or not. In this case failure/encode are documented.
+call_rc(_, _, Sent) ->
+ {error, choose(Sent, failure, encode)}.
+
+%% call/5
+%%
+%% 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([#state{service_name = SvcName} = S], App, Msg, Opts, Caller) ->
+ case find_transport(App, Msg, Opts, S) of
+ {_,_,_} = T ->
+ send_request(T, Msg, Opts, Caller, SvcName);
+ false ->
+ {error, no_connection};
+ {error, _} = No ->
+ No
+ end;
+
+c([], _, _, _, _) ->
+ {error, no_service}.
+
+%% make_options/1
+
+make_options(Options) ->
+ lists:foldl(fun mo/2, #options{}, Options).
+
+mo({timeout, T}, Rec)
+ when is_integer(T), 0 =< T ->
+ Rec#options{timeout = T};
+
+mo({filter, F}, #options{filter = none} = Rec) ->
+ Rec#options{filter = F};
+mo({filter, F}, #options{filter = {all, Fs}} = Rec) ->
+ Rec#options{filter = {all, [F | Fs]}};
+mo({filter, F}, #options{filter = F0} = Rec) ->
+ Rec#options{filter = {all, [F0, F]}};
+
+mo({extra, L}, #options{extra = X} = Rec)
+ when is_list(L) ->
+ Rec#options{extra = X ++ L};
+
+mo(detach, Rec) ->
+ Rec#options{detach = true};
+
+mo(T, _) ->
+ ?ERROR({invalid_option, T}).
+
+%%% ---------------------------------------------------------------------------
+%%% # subscribe(SvcName)
+%%% # unsubscribe(SvcName)
+%%% ---------------------------------------------------------------------------
+
+subscribe(SvcName) ->
+ diameter_reg:add({?MODULE, subscriber, SvcName}).
+
+unsubscribe(SvcName) ->
+ diameter_reg:del({?MODULE, subscriber, SvcName}).
+
+subscriptions(Pat) ->
+ pmap(diameter_reg:match({?MODULE, subscriber, Pat})).
+
+subscriptions() ->
+ subscriptions('_').
+
+pmap(Props) ->
+ lists:map(fun({{?MODULE, _, Name}, Pid}) -> {Name, Pid} end, Props).
+
+%%% ---------------------------------------------------------------------------
+%%% # services(Pattern)
+%%% ---------------------------------------------------------------------------
+
+services(Pat) ->
+ pmap(diameter_reg:match({?MODULE, service, Pat})).
+
+services() ->
+ services('_').
+
+whois(SvcName) ->
+ case diameter_reg:match({?MODULE, service, SvcName}) of
+ [{_, Pid}] ->
+ Pid;
+ [] ->
+ undefined
+ end.
+
+%%% ---------------------------------------------------------------------------
+%%% # flush_stats/1
+%%%
+%%% Output: list of {{SvcName, Alias, Counter}, Value}
+%%% ---------------------------------------------------------------------------
+
+flush_stats(TPid) ->
+ diameter_stats:flush(TPid).
+
+%% ===========================================================================
+%% ===========================================================================
+
+state(Svc) ->
+ call_service(Svc, state).
+
+uptime(Svc) ->
+ call_service(Svc, uptime).
+
+%% call_module/3
+
+call_module(Service, AppMod, Request) ->
+ call_service(Service, {call_module, AppMod, Request}).
+
+%%% ---------------------------------------------------------------------------
+%%% # init([SvcName])
+%%% ---------------------------------------------------------------------------
+
+init([SvcName]) ->
+ process_flag(trap_exit, true), %% ensure terminate(shutdown, _)
+ i(SvcName, diameter_reg:add_new({?MODULE, service, SvcName})).
+
+i(SvcName, true) ->
+ {ok, i(SvcName)};
+i(_, false) ->
+ {stop, {shutdown, already_started}}.
+
+%%% ---------------------------------------------------------------------------
+%%% # handle_call(Req, From, State)
+%%% ---------------------------------------------------------------------------
+
+handle_call(state, _, S) ->
+ {reply, S, S};
+
+handle_call(uptime, _, #state{id = T} = S) ->
+ {reply, diameter_lib:now_diff(T), S};
+
+%% Start a transport.
+handle_call({start, {Ref, Type, Opts}}, _From, S) ->
+ {reply, start(Ref, {Type, Opts}, S), S};
+
+%% Stop transports.
+handle_call({stop, Refs}, _From, S) ->
+ shutdown(Refs, S),
+ {reply, ok, S};
+
+%% pick_peer with mutable state
+handle_call({pick_peer, Local, Remote, App}, _From, S) ->
+ #diameter_app{mutable = true} = App, %% assert
+ {reply, pick_peer(Local, Remote, self(), S#state.service_name, App), S};
+
+handle_call({call_module, AppMod, Req}, From, S) ->
+ call_module(AppMod, Req, From, S);
+
+handle_call({info, Item}, _From, S) ->
+ {reply, service_info(Item, S), S};
+
+handle_call(stop, _From, S) ->
+ shutdown(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.
+
+handle_call(Req, From, S) ->
+ ?REPORT(unknown_request, ?FUNC, [Req, From]),
+ {reply, nok, S}.
+
+%%% ---------------------------------------------------------------------------
+%%% # handle_cast(Req, State)
+%%% ---------------------------------------------------------------------------
+
+handle_cast(Req, S) ->
+ ?REPORT(unknown_request, ?FUNC, [Req]),
+ {noreply, S}.
+
+%%% ---------------------------------------------------------------------------
+%%% # handle_info(Req, State)
+%%% ---------------------------------------------------------------------------
+
+handle_info(T,S) ->
+ case transition(T,S) of
+ ok ->
+ {noreply, S};
+ #state{} = NS ->
+ {noreply, NS};
+ {stop, Reason} ->
+ {stop, {shutdown, Reason}, S}
+ end.
+
+%% transition/2
+
+%% Peer process is telling us to start a new accept process.
+transition({accepted, Pid, TPid}, S) ->
+ accepted(Pid, TPid, S),
+ ok;
+
+%% Peer process has a new open connection.
+transition({connection_up, Pid, T}, S) ->
+ connection_up(Pid, T, S);
+
+%% Peer process has left state open.
+transition({connection_down, Pid}, S) ->
+ connection_down(Pid, S);
+
+%% Peer process has returned to state open.
+transition({connection_up, Pid}, S) ->
+ connection_up(Pid, S);
+
+%% Accepting transport has lost connectivity.
+transition({close, Pid}, S) ->
+ close(Pid, S),
+ ok;
+
+%% Connecting transport is being restarted by watchdog.
+transition({reconnect, Pid}, S) ->
+ reconnect(Pid, S),
+ ok;
+
+%% 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.
+transition({'DOWN', _, process, Pid, Reason}, S)
+ when node(Pid) == node() ->
+ peer_down(Pid, Reason, S);
+
+%% Remote service wants to know about shared transports.
+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 process has died.
+transition({'DOWN', _, process, TPid, _}, S) ->
+ remote_peer_down(TPid, S);
+
+%% Restart after tc expiry.
+transition({tc_timeout, T}, S) ->
+ tc_timeout(T, S),
+ ok;
+
+%% Request process is telling us it may have missed a failover message
+%% after a transport went down and the service process looked up
+%% outstanding requests.
+transition({failover, TRef, Seqs}, S) ->
+ failover(TRef, Seqs, S),
+ ok;
+
+transition(Req, _) ->
+ ?REPORT(unknown_request, ?FUNC, [Req]),
+ ok.
+
+%%% ---------------------------------------------------------------------------
+%%% # terminate(Reason, State)
+%%% ---------------------------------------------------------------------------
+
+terminate(Reason, #state{service_name = Name} = S) ->
+ ets:delete(?STATE_TABLE, Name),
+ shutdown == Reason %% application shutdown
+ andalso shutdown(S).
+
+%%% ---------------------------------------------------------------------------
+%%% # code_change(FromVsn, State, Extra)
+%%% ---------------------------------------------------------------------------
+
+code_change(FromVsn,
+ #state{service_name = SvcName,
+ service = #diameter_service{applications = Apps}}
+ = S,
+ Extra) ->
+ lists:foreach(fun(A) ->
+ code_change(FromVsn, SvcName, Extra, A)
+ end,
+ Apps),
+ {ok, S}.
+
+code_change(FromVsn, SvcName, Extra, #diameter_app{alias = Alias} = A) ->
+ {ok, S} = cb(A, code_change, [FromVsn,
+ mod_state(Alias),
+ Extra,
+ SvcName]),
+ mod_state(Alias, S).
+
+%% ===========================================================================
+%% ===========================================================================
+
+cb([_|_] = M, F, A) ->
+ eval(M, F, A);
+cb(Rec, F, A) ->
+ {_, M} = app(Rec),
+ eval(M, F, A).
+
+app(#request{app = A, module = M}) ->
+ {A,M};
+app(#diameter_app{alias = A, module = M}) ->
+ {A,M}.
+
+eval([M|X], F, A) ->
+ apply(M, F, A ++ X).
+
+%% Callback with state.
+
+state_cb(#diameter_app{mutable = false, init_state = S}, {ModX, F, A}) ->
+ eval(ModX, F, A ++ [S]);
+
+state_cb(#diameter_app{mutable = true, alias = Alias}, {_,_,_} = MFA) ->
+ state_cb(MFA, Alias);
+
+state_cb({ModX,F,A}, Alias)
+ when is_list(ModX) ->
+ eval(ModX, F, A ++ [mod_state(Alias)]).
+
+choose(true, X, _) -> X;
+choose(false, _, X) -> X.
+
+ets_new(Tbl) ->
+ ets:new(Tbl, [{keypos, 2}]).
+
+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
+%% need for it now but it's no worse (except possibly that we don't
+%% see the table identifier being passed around) than an ets table so
+%% keep it.
+
+mod_state(Alias) ->
+ get({?MODULE, 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);
+
+s(true, Pid) ->
+ Pid ! {shutdown, self()}; %% 'DOWN' will cleanup as usual
+s(false, _) ->
+ ok.
+
+%%% ---------------------------------------------------------------------------
+%%% # shutdown/1
+%%% ---------------------------------------------------------------------------
+
+shutdown(#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),
+ %% Kill the watchdogs explicitly in case there was no transport.
+ wait(fun sw/2, PeerT).
+
+wait(Fun, T) ->
+ diameter_lib:wait(ets:foldl(Fun, [], T)).
+
+st(#peer{conn = B}, Acc)
+ when is_boolean(B) ->
+ Acc;
+st(#peer{conn = Pid}, Acc) ->
+ Pid ! shutdown,
+ [Pid | Acc].
+
+sw(#peer{pid = Pid}, Acc) ->
+ exit(Pid, shutdown),
+ [Pid | Acc].
+
+%%% ---------------------------------------------------------------------------
+%%% # call_service/2
+%%% ---------------------------------------------------------------------------
+
+call_service(Pid, Req)
+ when is_pid(Pid) ->
+ cs(Pid, Req);
+call_service(SvcName, Req) ->
+ call_service_by_name(SvcName, Req).
+
+call_service_by_name(SvcName, Req) ->
+ cs(whois(SvcName), Req).
+
+cs(Pid, Req)
+ when is_pid(Pid) ->
+ try
+ gen_server:call(Pid, Req, infinity)
+ catch
+ E: Reason when E == exit ->
+ {error, {E, Reason}}
+ end;
+
+cs(undefined, _) ->
+ {error, no_service}.
+
+%%% ---------------------------------------------------------------------------
+%%% # i/1
+%%%
+%%% Output: #state{}
+%%% ---------------------------------------------------------------------------
+
+%% Intialize the state of a service gen_server.
+
+i(SvcName) ->
+ %% Split the config into a server state and a list of transports.
+ {#state{} = S, CL} = lists:foldl(fun cfg_acc/2,
+ {false, []},
+ diameter_config:lookup(SvcName)),
+
+ %% Publish the state in order to be able to access it outside of
+ %% the service process. Originally table identifiers were only
+ %% known to the service process but we now want to provide the
+ %% option of application callbacks being 'stateless' in order to
+ %% avoid having to go through a common process. (Eg. An agent that
+ %% sends a request for every incoming request.)
+ true = ets:insert_new(?STATE_TABLE, S),
+
+ %% Start fsms for each transport.
+ lists:foreach(fun(T) -> start_fsm(T,S) end, CL),
+
+ init_shared(S),
+ S.
+
+cfg_acc({SvcName, #diameter_service{applications = Apps} = Rec, Opts},
+ {false, Acc}) ->
+ 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))},
+ {S, Acc};
+
+cfg_acc({_Ref, Type, _Opts} = T, {S, Acc})
+ when Type == connect;
+ Type == listen ->
+ {S, [T | Acc]}.
+
+mref(false = No) ->
+ No;
+mref(P) ->
+ erlang:monitor(process, P).
+
+init_shared(#state{use_shared_peers = true,
+ service_name = Svc}) ->
+ diameter_peer:notify(Svc, {service, self()});
+init_shared(#state{use_shared_peers = false}) ->
+ ok.
+
+init_mod(#diameter_app{alias = Alias,
+ init_state = S}) ->
+ mod_state(Alias, S).
+
+start_fsm({Ref, Type, Opts}, S) ->
+ start(Ref, {Type, Opts}, S).
+
+get_value(Key, Vs) ->
+ {_, V} = lists:keyfind(Key, 1, Vs),
+ V.
+
+%%% ---------------------------------------------------------------------------
+%%% # start/3
+%%% ---------------------------------------------------------------------------
+
+%% If the initial start/3 at service/transport start succeeds then
+%% subsequent calls to start/4 on the same service will also succeed
+%% since they involve the same call to merge_service/2. We merge here
+%% rather than earlier since the service may not yet be configured
+%% when the transport is configured.
+
+start(Ref, {T, Opts}, S)
+ when T == connect;
+ T == listen ->
+ try
+ {ok, start(Ref, type(T), Opts, S)}
+ catch
+ ?FAILURE(Reason) ->
+ {error, Reason}
+ end.
+%% TODO: don't actually raise any errors yet
+
+%% There used to be a difference here between the handling of
+%% configured listening and connecting transports but now we simply
+%% tell the transport_module to start an accepting or connecting
+%% process respectively, the transport implementation initiating
+%% listening on a port as required.
+type(listen) -> accept;
+type(accept) -> listen;
+type(connect = T) -> T.
+
+%% start/4
+
+start(Ref, Type, Opts, #state{peerT = PeerT,
+ connT = ConnT,
+ service_name = SvcName,
+ service = Svc})
+ when Type == connect;
+ Type == accept ->
+ Pid = monitor(s(Type, Ref, {ConnT,
+ Opts,
+ SvcName,
+ merge_service(Opts, Svc)})),
+ insert(PeerT, #peer{pid = Pid,
+ type = Type,
+ ref = Ref,
+ options = Opts}),
+ 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.
+
+s(Type, Ref, T) ->
+ diameter_watchdog:start({Type, Ref}, T).
+
+%% merge_service/2
+
+merge_service(Opts, Svc) ->
+ lists:foldl(fun ms/2, Svc, Opts).
+
+%% Limit the applications known to the fsm to those in the 'apps'
+%% option. That this might be empty is checked by the fsm. It's not
+%% checked at config-time since there's no requirement that the
+%% service be configured first. (Which could be considered a bit odd.)
+ms({applications, As}, #diameter_service{applications = Apps} = S)
+ when is_list(As) ->
+ S#diameter_service{applications
+ = [A || A <- Apps,
+ lists:member(A#diameter_app.alias, As)]};
+
+%% The fact that all capabilities can be configured on the transports
+%% means that the service doesn't necessarily represent a single
+%% locally implemented Diameter peer as identified by Origin-Host: a
+%% transport can configure its own Origin-Host. This means that the
+%% service little more than a placeholder for default capabilities
+%% plus a list of applications that individual transports can choose
+%% to support (or not).
+ms({capabilities, Opts}, #diameter_service{capabilities = Caps0} = Svc)
+ when is_list(Opts) ->
+ %% make_caps has already succeeded in diameter_config so it will succeed
+ %% again here.
+ {ok, Caps} = diameter_capx:make_caps(Caps0, Opts),
+ Svc#diameter_service{capabilities = Caps};
+
+ms(_, Svc) ->
+ Svc.
+
+%%% ---------------------------------------------------------------------------
+%%% # accepted/3
+%%% ---------------------------------------------------------------------------
+
+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
+
+fetch(Tid, Key) ->
+ [T] = ets:lookup(Tid, Key),
+ T.
+
+%%% ---------------------------------------------------------------------------
+%%% # connection_up/3
+%%%
+%%% Output: #state{}
+%%% ---------------------------------------------------------------------------
+
+%% Peer process has reached the open state.
+
+connection_up(Pid, {TPid, {Caps, SApps, Pkt}}, #state{peerT = PeerT,
+ connT = ConnT}
+ = S) ->
+ P = fetch(PeerT, Pid),
+ C = #conn{pid = TPid,
+ apps = SApps,
+ caps = Caps,
+ peer = Pid},
+
+ insert(ConnT, C),
+ connection_up([Pkt], P#peer{conn = TPid}, C, S).
+
+%%% ---------------------------------------------------------------------------
+%%% # connection_up/2
+%%%
+%%% Output: #state{}
+%%% ---------------------------------------------------------------------------
+
+%% Peer process has transitioned back into the open state. Note that there
+%% has been no new capabilties exchange in this case.
+
+connection_up(Pid, #state{peerT = PeerT,
+ connT = ConnT}
+ = S) ->
+ #peer{conn = TPid} = P = fetch(PeerT, Pid),
+ C = fetch(ConnT, TPid),
+ connection_up([], P, C, S).
+
+%% connection_up/4
+
+connection_up(T, P, C, #state{peerT = PeerT,
+ local_peers = LDict,
+ service_name = SvcName,
+ service
+ = #diameter_service{applications = Apps}}
+ = S) ->
+ #peer{conn = TPid, op_state = ?STATE_DOWN}
+ = P,
+ #conn{apps = SApps, caps = Caps}
+ = C,
+
+ insert(PeerT, P#peer{op_state = ?STATE_UP}),
+
+ 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, T, LDict) ->
+ lists:foldl(fun(A,D) -> ilp(A, T, D) end, LDict, SApps).
+
+ilp({Id, Alias}, {TC, SA}, LDict) ->
+ init_conn(Id, Alias, TC, SA),
+ ?Dict:append(Alias, TC, LDict).
+
+init_conn(Id, Alias, TC, {SvcName, Apps}) ->
+ #diameter_app{module = ModX,
+ id = Id} %% assert
+ = find_app(Alias, Apps),
+
+ peer_cb({ModX, peer_up, [SvcName, TC]}, Alias).
+
+find_app(Alias, Apps) ->
+ lists:keyfind(Alias, #diameter_app.alias, Apps).
+
+%% 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.
+peer_cb(MFA, Alias) ->
+ try state_cb(MFA, Alias) of
+ ModS ->
+ mod_state(Alias, ModS)
+ catch
+ E: Reason ->
+ ?ERROR({E, Reason, MFA, ?STACK})
+ end.
+
+%%% ---------------------------------------------------------------------------
+%%% # connection_down/2
+%%%
+%%% Output: #state{}
+%%% ---------------------------------------------------------------------------
+
+%% Peer process has transitioned out of the open state.
+
+connection_down(Pid, #state{peerT = PeerT,
+ connT = ConnT}
+ = S) ->
+ #peer{conn = TPid}
+ = P
+ = fetch(PeerT, Pid),
+
+ C = fetch(ConnT, TPid),
+ insert(PeerT, P#peer{op_state = ?STATE_DOWN}),
+ connection_down(P,C,S).
+
+%% connection_down/3
+
+connection_down(#peer{conn = TPid,
+ op_state = ?STATE_UP}
+ = P,
+ #conn{caps = Caps,
+ apps = SApps}
+ = C,
+ #state{service_name = SvcName,
+ service = #diameter_service{applications = Apps},
+ 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, T, LDict) ->
+ lists:foldl(fun(A,D) -> rlp(A, T, D) end, LDict, SApps).
+
+rlp({Id, Alias}, {TC, SA}, LDict) ->
+ L = ?Dict:fetch(Alias, LDict),
+ down_conn(Id, Alias, TC, SA),
+ ?Dict:store(Alias, lists:delete(TC, L), LDict).
+
+down_conn(Id, Alias, TC, {SvcName, Apps}) ->
+ #diameter_app{module = ModX,
+ id = Id} %% assert
+ = find_app(Alias, Apps),
+
+ peer_cb({ModX, peer_down, [SvcName, TC]}, Alias).
+
+%%% ---------------------------------------------------------------------------
+%%% # peer_down/3
+%%%
+%%% Output: #state{}
+%%% ---------------------------------------------------------------------------
+
+%% Peer process has died.
+
+peer_down(Pid, _Reason, #state{peerT = PeerT} = S) ->
+ P = fetch(PeerT, Pid),
+ ets:delete_object(PeerT, P),
+ restart(P,S),
+ peer_down(P,S).
+
+%% peer_down/2
+
+%% The peer has never come up ...
+peer_down(#peer{conn = B}, S)
+ when is_boolean(B) ->
+ S;
+
+%% ... 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),
+ 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
+
+restart(P,S) ->
+ q_restart(restart(P), S).
+
+%% restart/1
+
+%% Always try to reconnect.
+restart(#peer{ref = Ref,
+ type = connect = T,
+ options = Opts,
+ started = Time}) ->
+ {Time, {Ref, T, Opts}};
+
+%% Transport connection hasn't yet been accepted ...
+restart(#peer{ref = Ref,
+ type = accept = T,
+ options = Opts,
+ conn = false,
+ started = Time}) ->
+ {Time, {Ref, T, Opts}};
+
+%% ... or it has: a replacement transport has already been spawned.
+restart(#peer{type = accept}) ->
+ false.
+
+%% q_restart/2
+
+%% Start the reconnect timer.
+q_restart({Time, {_Ref, Type, Opts} = T}, S) ->
+ start_tc(tc(Time, default_tc(Type, Opts)), T, S);
+q_restart(false, _) ->
+ ok.
+
+%% RFC 3588, 2.1:
+%%
+%% When no transport connection exists with a peer, an attempt to
+%% connect SHOULD be periodically made. This behavior is handled via
+%% the Tc timer, 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.
+
+default_tc(connect, Opts) ->
+ proplists:get_value(reconnect_timer, Opts, ?DEFAULT_TC);
+default_tc(accept, _) ->
+ 0.
+
+%% Bound tc below if the peer was restarted recently to avoid
+%% continuous in case of faulty config or other problems.
+tc(Time, Tc) ->
+ choose(Tc > ?RESTART_TC
+ orelse timer:now_diff(now(), Time) > 1000*?RESTART_TC,
+ Tc,
+ ?RESTART_TC).
+
+start_tc(0, T, S) ->
+ tc_timeout(T, S);
+start_tc(Tc, T, _) ->
+ erlang:send_after(Tc, self(), {tc_timeout, T}).
+
+%% tc_timeout/2
+
+tc_timeout({Ref, _Type, _Opts} = T, #state{service_name = SvcName} = S) ->
+ tc(have_transport(SvcName, Ref), T, S).
+
+tc(true, {Ref, Type, Opts}, #state{service_name = SvcName}
+ = S) ->
+ send_event(SvcName, {reconnect, Ref, Opts}),
+ start(Ref, Type, Opts, S);
+tc(false = No, _, _) -> %% removed
+ No.
+
+%%% ---------------------------------------------------------------------------
+%%% # close/2
+%%% ---------------------------------------------------------------------------
+
+%% The watchdog doesn't start a new fsm in the accept case, it
+%% simply stays alive until someone tells it to die in order for
+%% another watchdog to be able to detect that it should transition
+%% from initial into reopen rather than okay. That someone is either
+%% the accepting watchdog upon reception of a CER from the previously
+%% connected peer, or us after reconnect_timer timeout.
+
+close(Pid, #state{service_name = SvcName,
+ peerT = PeerT}) ->
+ #peer{pid = Pid,
+ type = accept,
+ ref = Ref,
+ options = Opts}
+ = fetch(PeerT, Pid),
+
+ c(Pid, have_transport(SvcName, Ref), Opts).
+
+%% Tell watchdog to (maybe) die later ...
+c(Pid, true, Opts) ->
+ Tc = proplists:get_value(reconnect_timer, Opts, 2*?DEFAULT_TC),
+ erlang:send_after(Tc, Pid, close);
+
+%% ... or now.
+c(Pid, false, _Opts) ->
+ Pid ! close.
+
+%% The RFC's only document the behaviour of Tc, our reconnect_timer,
+%% for the establishment of connections but we also give
+%% reconnect_timer semantics for a listener, being the time within
+%% which a new connection attempt is expected of a connecting peer.
+%% The value should be greater than the peer's Tc + jitter.
+
+%%% ---------------------------------------------------------------------------
+%%% # reconnect/2
+%%% ---------------------------------------------------------------------------
+
+reconnect(Pid, #state{service_name = SvcName,
+ peerT = PeerT}) ->
+ #peer{ref = Ref,
+ type = connect,
+ options = Opts}
+ = fetch(PeerT, Pid),
+ send_event(SvcName, {reconnect, Ref, Opts}).
+
+%%% ---------------------------------------------------------------------------
+%%% # call_module/4
+%%% ---------------------------------------------------------------------------
+
+%% Backwards compatibility and never documented/advertised. May be
+%% removed.
+
+call_module(Mod, Req, From, #state{service
+ = #diameter_service{applications = Apps},
+ service_name = Svc}
+ = S) ->
+ case cm([A || A <- Apps, Mod == hd(A#diameter_app.module)],
+ Req,
+ From,
+ Svc)
+ of
+ {reply = T, RC} ->
+ {T, RC, S};
+ noreply = T ->
+ {T, S};
+ Reason ->
+ {reply, {error, Reason}, S}
+ end.
+
+cm([#diameter_app{module = ModX, alias = Alias}], Req, From, Svc) ->
+ MFA = {ModX, handle_call, [Req, From, Svc]},
+
+ try state_cb(MFA, Alias) of
+ {noreply = T, ModS} ->
+ mod_state(Alias, ModS),
+ T;
+ {reply = T, RC, ModS} ->
+ mod_state(Alias, ModS),
+ {T, RC};
+ T ->
+ diameter_lib:error_report({invalid, T}, MFA),
+ invalid
+ catch
+ E: Reason ->
+ diameter_lib:error_report({failure, {E, Reason, ?STACK}}, MFA),
+ failure
+ end;
+
+cm([], _, _, _) ->
+ unknown;
+
+cm([_,_|_], _, _, _) ->
+ multiple.
+
+%%% ---------------------------------------------------------------------------
+%%% # send_request/5
+%%% ---------------------------------------------------------------------------
+
+%% Send an outgoing request in its dedicated process.
+%%
+%% Note that both encode of the outgoing request and of the received
+%% answer happens in this process. It's also this process that replies
+%% to the caller. The service process only handles the state-retaining
+%% callbacks.
+%%
+%% 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) ->
+ #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.
+
+%% make_packet/1
+%%
+%% Turn an outgoing request as passed to call/4 into a diameter_packet
+%% record in preparation for a prepare_request callback. There are two
+%% cases: a diameter_packet as argument when we're calling call/4
+%% ourselves in order to relay a request or a bare message in case the
+%% call came by way of diameter:call/4.
+
+make_packet(Bin)
+ when is_binary(Bin) ->
+ #diameter_packet{header = diameter_codec:decode_header(Bin),
+ bin = Bin};
+
+make_packet(#diameter_packet{msg = [#diameter_header{} | _]} = Pkt) ->
+ Pkt;
+
+make_packet(#diameter_packet{header = Hdr} = Pkt) ->
+ Pkt#diameter_packet{header = make_header(Hdr)};
+
+make_packet(Msg) ->
+ make_packet(#diameter_packet{msg = Msg}).
+
+%% make_header/1
+
+make_header(undefined) ->
+ Seq = diameter_session:sequence(),
+ make_header(#diameter_header{end_to_end_id = Seq,
+ hop_by_hop_id = Seq});
+
+make_header(#diameter_header{version = undefined} = Hdr) ->
+ make_header(Hdr#diameter_header{version = ?DIAMETER_VERSION});
+
+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_header(#diameter_header{hop_by_hop_id = undefined} = H) ->
+ Seq = diameter_session:sequence(),
+ make_header(H#diameter_header{hop_by_hop_id = Seq});
+
+make_header(#diameter_header{} = Hdr) ->
+ Hdr;
+
+make_header(T) ->
+ ?ERROR({invalid_header, T}).
+
+%% make_packet/2
+%%
+%% Reconstruct a diameter_packet from the return value of
+%% prepare_request or prepare_retransmit callback.
+
+make_packet(Bin, _)
+ when is_binary(Bin) ->
+ make_packet(Bin);
+
+make_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}) ->
+ Pkt#diameter_packet{header = fold_record(Hdr0, Hdr)};
+
+make_packet(Msg, Pkt) ->
+ Pkt#diameter_packet{msg = Msg}.
+
+%% fold_record/2
+
+fold_record(undefined, R) ->
+ R;
+fold_record(Rec, R) ->
+ diameter_lib:fold_tuple(2, Rec, R).
+
+%% send_request/7
+
+send_request(Pkt, TPid, Caps, App, Opts, Caller, SvcName) ->
+ #diameter_app{alias = Alias,
+ dictionary = Dict,
+ module = ModX,
+ answer_errors = AE}
+ = App,
+
+ EPkt = encode(Dict, Pkt),
+
+ #options{filter = Filter,
+ timeout = Timeout}
+ = Opts,
+
+ Req = #request{packet = Pkt,
+ from = Caller,
+ handler = self(),
+ transport = TPid,
+ caps = Caps,
+ app = Alias,
+ filter = Filter,
+ dictionary = Dict,
+ module = ModX},
+
+ try
+ TRef = send_request(TPid, EPkt, Req, Timeout),
+ ack(Caller),
+ handle_answer(SvcName, AE, recv_answer(Timeout, SvcName, {TRef, Req}))
+ after
+ erase_request(EPkt)
+ end.
+
+%% Tell caller a send has been attempted.
+ack({Pid, Ref}) ->
+ Pid ! Ref.
+
+%% recv_answer/3
+
+recv_answer(Timeout,
+ SvcName,
+ {TRef, #request{from = {_, Ref}, packet = RPkt} = Req}
+ = T) ->
+
+ %% Matching on TRef below ensures we ignore messages that pertain
+ %% to a previous transport prior to failover. The answer message
+ %% includes the #request{} since it's not necessarily Req; that
+ %% is, from the last peer to which we've transmitted.
+
+ receive
+ {answer = A, Ref, Rq, Pkt} -> %% Answer from peer.
+ {A, Rq, Pkt};
+ {timeout = Reason, TRef, _} -> %% No timely reply
+ {error, Req, Reason};
+ {failover = Reason, TRef, false} -> %% No alternative peer.
+ {error, Req, Reason};
+ {failover, TRef, Transport} -> %% Resend to alternate peer.
+ try_retransmit(Timeout, SvcName, Req, Transport);
+ {failover, TRef} -> %% May have missed failover notification.
+ Seqs = diameter_codec:sequence_numbers(RPkt),
+ Pid = whois(SvcName),
+ is_pid(Pid) andalso (Pid ! {failover, TRef, Seqs}),
+ recv_answer(Timeout, SvcName, T)
+ end.
+%% Note that failover starts a new timer and that expiry of an old
+%% timer value is ignored. This means that an answer could be accepted
+%% from a peer after timeout in the case of failover.
+
+try_retransmit(Timeout, SvcName, Req, Transport) ->
+ try retransmit(Transport, Req, SvcName, Timeout) of
+ T -> recv_answer(Timeout, SvcName, T)
+ catch
+ ?FAILURE(Reason) -> {error, Req, Reason}
+ end.
+
+%% handle_error/3
+
+handle_error(Req, Reason, SvcName) ->
+ #request{module = ModX,
+ packet = Pkt,
+ transport = TPid,
+ caps = Caps}
+ = Req,
+ cb(ModX, handle_error, [Reason, msg(Pkt), SvcName, {TPid, Caps}]).
+
+msg(#diameter_packet{msg = undefined, bin = Bin}) ->
+ Bin;
+msg(#diameter_packet{msg = Msg}) ->
+ Msg.
+
+%% encode/2
+
+%% Note that prepare_request can return a diameter_packet containing
+%% header or transport_data. Even allow the returned record to contain
+%% an encoded binary. This isn't the usual case but could some in
+%% handy, for test at least. (For example, to send garbage.)
+
+%% The normal case: encode the returned message.
+encode(Dict, #diameter_packet{msg = Msg, bin = undefined} = Pkt) ->
+ D = pick_dictionary([Dict, ?BASE], Msg),
+ diameter_codec:encode(D, Pkt);
+
+%% Callback has returned an encoded binary: just send.
+encode(_, #diameter_packet{} = Pkt) ->
+ Pkt.
+
+%% pick_dictionary/2
+
+%% Pick the first dictionary that declares the application id in the
+%% specified header.
+pick_dictionary(Ds, [#diameter_header{application_id = Id} | _]) ->
+ pd(Ds, fun(D) -> Id = D:id() end);
+
+%% Pick the first dictionary that knows the specified message name.
+pick_dictionary(Ds, [MsgName|_]) ->
+ pd(Ds, fun(D) -> D:msg2rec(MsgName) end);
+
+%% Pick the first dictionary that knows the name of the specified
+%% message record.
+pick_dictionary(Ds, Rec) ->
+ Name = element(1, Rec),
+ pd(Ds, fun(D) -> D:rec2msg(Name) end).
+
+pd([D|Ds], F) ->
+ try
+ F(D),
+ D
+ catch
+ error:_ ->
+ pd(Ds, F)
+ end;
+
+pd([], _) ->
+ ?ERROR(no_dictionary).
+
+%% send_request/4
+
+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.
+ TRef = store_request(TPid, Bin, Req, Timeout),
+ send(TPid, Pkt),
+ TRef;
+
+%% Send using a remote transport: spawn a process on the remote node
+%% to relay the answer.
+send_request(TPid, #diameter_packet{} = Pkt, Req, Timeout) ->
+ TRef = erlang:start_timer(Timeout, self(), timeout),
+ T = {TPid, Pkt, Req, Timeout, TRef},
+ spawn(node(TPid), ?MODULE, send, [T]),
+ TRef.
+
+%% send/1
+
+send({TPid, Pkt, #request{handler = Pid} = Req, Timeout, TRef}) ->
+ Ref = send_request(TPid, Pkt, Req#request{handler = self()}, Timeout),
+ Pid ! reref(receive T -> T end, Ref, TRef).
+
+reref({T, Ref, R}, Ref, TRef) ->
+ {T, TRef, R};
+reref(T, _, _) ->
+ T.
+
+%% send/2
+
+send(Pid, Pkt) ->
+ Pid ! {send, Pkt}.
+
+%% retransmit/4
+
+retransmit({TPid, Caps, #diameter_app{alias = Alias} = App},
+ #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.
+
+%% retransmit/5
+
+retransmit(Pkt, TPid, Caps, #request{dictionary = Dict} = Req, Timeout) ->
+ EPkt = encode(Dict, Pkt),
+
+ NewReq = Req#request{transport = TPid,
+ packet = Pkt,
+ caps = Caps},
+
+ ?LOG(retransmission, NewReq),
+ TRef = send_request(TPid, EPkt, NewReq, Timeout),
+ {TRef, NewReq}.
+
+%% store_request/4
+
+store_request(TPid, Bin, Req, Timeout) ->
+ Seqs = diameter_codec:sequence_numbers(Bin),
+ TRef = erlang:start_timer(Timeout, self(), timeout),
+ ets:insert(?REQUEST_TABLE, {Seqs, Req, TRef}),
+ ets:member(?REQUEST_TABLE, TPid)
+ orelse (self() ! {failover, TRef}), %% possibly missed failover
+ TRef.
+
+%% lookup_request/2
+
+lookup_request(Msg, TPid)
+ when is_pid(TPid) ->
+ lookup(Msg, TPid, '_');
+
+lookup_request(Msg, TRef)
+ when is_reference(TRef) ->
+ lookup(Msg, '_', TRef).
+
+lookup(Msg, TPid, TRef) ->
+ Seqs = diameter_codec:sequence_numbers(Msg),
+ Spec = [{{Seqs, #request{transport = TPid, _ = '_'}, TRef},
+ [],
+ ['$_']}],
+ case ets:select(?REQUEST_TABLE, Spec) of
+ [{_, Req, _}] ->
+ Req;
+ [] ->
+ false
+ end.
+
+%% erase_request/1
+
+erase_request(Pkt) ->
+ ets:delete(?REQUEST_TABLE, diameter_codec:sequence_numbers(Pkt)).
+
+%% match_requests/1
+
+match_requests(TPid) ->
+ Pat = {'_', #request{transport = TPid, _ = '_'}, '_'},
+ ets:select(?REQUEST_TABLE, [{Pat, [], ['$_']}]).
+
+%% have_request/2
+
+have_request(Pkt, TPid) ->
+ Seqs = diameter_codec:sequence_numbers(Pkt),
+ Pat = {Seqs, #request{transport = TPid, _ = '_'}, '_'},
+ '$end_of_table' /= ets:select(?REQUEST_TABLE, [{Pat, [], ['$_']}], 1).
+
+%% request_peer_up/1
+
+request_peer_up(TPid) ->
+ ets:insert(?REQUEST_TABLE, {TPid}).
+
+%% request_peer_down/2
+
+request_peer_down(TPid, S) ->
+ ets:delete(?REQUEST_TABLE, TPid),
+ lists:foreach(fun(T) -> failover(T,S) end, match_requests(TPid)).
+%% Note that a request process can store its request after failover
+%% notifications are sent here: store_request/4 sends the notification
+%% in that case. Note also that we'll send as many notifications to a
+%% given handler as there are peers its sent to. All but one of these
+%% will be ignored.
+
+%%% ---------------------------------------------------------------------------
+%%% recv_request/3
+%%% ---------------------------------------------------------------------------
+
+recv_request(TPid, Pkt, {ConnT, SvcName, Apps}) ->
+ try ets:lookup(ConnT, TPid) of
+ [C] ->
+ recv_request(C, TPid, Pkt, SvcName, Apps);
+ [] -> %% transport has gone down
+ ok
+ catch
+ error: badarg -> %% service has gone down (and taken table with it)
+ ok
+ end.
+
+%% recv_request/5
+
+recv_request(#conn{apps = SApps, caps = Caps}, TPid, Pkt, SvcName, Apps) ->
+ #diameter_caps{origin_host = {OH,_},
+ origin_realm = {OR,_}}
+ = Caps,
+
+ #diameter_packet{header = #diameter_header{application_id = Id}}
+ = Pkt,
+
+ recv_request(find_recv_app(Id, SApps),
+ {SvcName, OH, OR},
+ TPid,
+ Apps,
+ Caps,
+ Pkt).
+
+%% find_recv_app/2
+
+%% No one should be sending the relay identifier.
+find_recv_app(?APP_ID_RELAY, _) ->
+ false;
+
+%% With any other id we either support it locally or as a relay.
+find_recv_app(Id, SApps) ->
+ keyfind([Id, ?APP_ID_RELAY], 1, SApps).
+
+%% keyfind/3
+
+keyfind([], _, _) ->
+ false;
+keyfind([Key | Rest], Pos, L) ->
+ case lists:keyfind(Key, Pos, L) of
+ false ->
+ keyfind(Rest, Pos, L);
+ T ->
+ T
+ end.
+
+%% recv_request/6
+
+recv_request({Id, Alias}, T, TPid, Apps, Caps, Pkt) ->
+ #diameter_app{dictionary = Dict}
+ = A
+ = find_app(Alias, Apps),
+ recv_request(T, {TPid, Caps}, A, 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, {_, OH, OR}, TPid, _, _, Pkt) ->
+ ?LOG({error, application}, Pkt),
+ reply(answer_message({OH, OR, 3007}, collect_avps(Pkt)), ?BASE, TPid, Pkt).
+
+collect_avps(Pkt) ->
+ case diameter_codec:collect_avps(Pkt) of
+ {_Bs, As} ->
+ As;
+ As ->
+ As
+ end.
+
+%% recv_request/4
+
+%% Wrong number of bits somewhere in the message: reply.
+%%
+%% 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.
+%%
+recv_request({_, OH, OR}, {TPid, _}, _, #diameter_packet{errors = [Bs | _],
+ bin = Bin,
+ avps = Avps}
+ = Pkt)
+ when is_bitstring(Bs) ->
+ ?LOG({error, invalid_avp_bits}, Bin),
+ reply(answer_message({OH, OR, 3009}, Avps), ?BASE, TPid, Pkt);
+
+%% Either we support this application but don't recognize the command
+%% or we're a relay and the command isn't proxiable.
+%%
+%% DIAMETER_COMMAND_UNSUPPORTED 3001
+%% The Request contained a Command-Code that the receiver did not
+%% recognize or support. This MUST be used when a Diameter node
+%% receives an experimental command that it does not understand.
+%%
+recv_request({_, OH, OR},
+ {TPid, _},
+ #diameter_app{id = Id},
+ #diameter_packet{header = #diameter_header{is_proxiable = P},
+ msg = M,
+ avps = Avps,
+ bin = Bin}
+ = Pkt)
+ when ?APP_ID_RELAY /= Id, undefined == M;
+ ?APP_ID_RELAY == Id, not P ->
+ ?LOG({error, command_unsupported}, Bin),
+ reply(answer_message({OH, OR, 3001}, Avps), ?BASE, TPid, Pkt);
+
+%% Error bit was set on a request.
+%%
+%% 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.
+%%
+recv_request({_, OH, OR},
+ {TPid, _},
+ _,
+ #diameter_packet{header = #diameter_header{is_error = true},
+ avps = Avps,
+ bin = Bin}
+ = Pkt) ->
+ ?LOG({error, error_bit}, Bin),
+ reply(answer_message({OH, OR, 3008}, Avps), ?BASE, TPid, Pkt);
+
+%% A message in a locally supported application or a proxiable message
+%% 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)).
+
+%% 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).
+
+%% examine/1
+%%
+%% Look for errors in a decoded message. Length errors result in
+%% decode failure in diameter_codec.
+
+examine(#diameter_packet{header = #diameter_header{version
+ = ?DIAMETER_VERSION}}
+ = Pkt) ->
+ Pkt;
+
+%% DIAMETER_UNSUPPORTED_VERSION 5011
+%% This error is returned when a request was received, whose version
+%% number is unsupported.
+
+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
+
+%% A reply may be an answer-message, constructed either here or by
+%% the handle_request callback. The header from the incoming request
+%% is passed into the encode so that it can retrieve the relevant
+%% command code in this case. It will also then ignore Dict and use
+%% the base encoder.
+request_cb({reply, Ans},
+ #diameter_app{dictionary = Dict},
+ _,
+ {TPid, _},
+ Pkt) ->
+ reply(Ans, Dict, TPid, Pkt);
+
+%% An 3xxx result code, for which the E-bit is set in the header.
+request_cb({protocol_error, RC}, _, T, {TPid, _}, Pkt)
+ when 3000 =< RC, RC < 4000 ->
+ protocol_error(RC, T, TPid, 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);
+
+%% 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
+%% will be detected by examining Route-Record AVP's, (3) a
+%% Route-Record AVP will be added to the outgoing request and (3) the
+%% End-to-End Identifier will default to that in the
+%% #diameter_header{} without the need for an end_to_end_identifier
+%% option.
+%%
+%% relay and proxy are similar in that they require the same handling
+%% with respect to Route-Record and End-to-End identifier. The
+%% difference is that a proxy advertises specific applications, while
+%% a relay advertises the relay application. If a callback doesn't
+%% want to distinguish between the cases in the callback return value
+%% then 'resend' is a neutral alternative.
+%%
+request_cb({A, Opts},
+ #diameter_app{id = Id}
+ = App,
+ T,
+ TC,
+ Pkt)
+ when A == relay, Id == ?APP_ID_RELAY;
+ A == proxy, Id /= ?APP_ID_RELAY;
+ A == resend ->
+ resend(Opts, App, T, TC, Pkt);
+
+request_cb(discard, _, _, _, _) ->
+ ok;
+
+request_cb({eval, RC, F}, App, T, TC, Pkt) ->
+ request_cb(RC, App, T, TC, Pkt),
+ diameter_lib:eval(F).
+
+%% protocol_error/4
+
+protocol_error(RC, {_, OH, OR}, TPid, #diameter_packet{avps = Avps} = Pkt) ->
+ ?LOG({error, RC}, Pkt),
+ reply(answer_message({OH, OR, RC}, Avps), ?BASE, TPid, Pkt).
+
+%% resend/5
+%%
+%% Resend a message as a relay or proxy agent.
+
+resend(Opts,
+ #diameter_app{} = App,
+ {_SvcName, OH, _OR} = T,
+ {_TPid, _Caps} = TC,
+ #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).
+
+%% DIAMETER_LOOP_DETECTED 3005
+%% An agent detected a loop while trying to get the message to the
+%% intended recipient. The message MAY be sent to an alternate peer,
+%% 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);
+
+%% 6.1.8. 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.
+
+resend(false,
+ Opts,
+ App,
+ {SvcName, _, _},
+ {TPid, #diameter_caps{origin_host = {_, OH}}},
+ #diameter_packet{header = Hdr0,
+ avps = Avps}
+ = Pkt) ->
+ Route = #diameter_avp{data = {?BASE, 'Route-Record', OH}},
+ Seq = diameter_session:sequence(),
+ Hdr = Hdr0#diameter_header{hop_by_hop_id = Seq},
+ Msg = [Hdr, Route | Avps],
+ %% Filter sender as ineligible receiver.
+ reply(call(SvcName, App, Msg, [{filter, {neg, {host, OH}}} | Opts]),
+ TPid,
+ Pkt).
+%% The incoming request is relayed with the addition of a
+%% Route-Record. Note the requirement on the return from call/4.
+%% This places a requirement on the values returned by the
+%% handle_answer and handle_error callbacks of the application module
+%% in question.
+%%
+%% RFC 6.3 says that a relay agent does not modify Origin-Host but
+%% says nothing about a proxy. Assume it should behave the same way.
+
+%% reply/3
+%%
+%% Relay a reply to a relayed request.
+
+%% Answer from the peer: reset the hop by hop identifier and send.
+reply(#diameter_packet{bin = B}
+ = Pkt,
+ TPid,
+ #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});
+%% TODO: counters
+
+%% Not. Ignoring the error feels harsh but there is no appropriate
+%% Result-Code for a protocol error (which this isn't really anyway)
+%% and the RFC doesn't provide any guidance how to act. A weakness
+%% here is that we don't deal well with a decode error: the request
+%% will simply timeout on the peer's end. Better would be to just send
+%% the answer (with modified hop by hop identifier) on regardless, at
+%% least in the relay case in which there's no examination of the
+%% answer. In the proxy case it's not clear that the callback won't
+%% examine the answer. Just be quiet here since a decode error causes
+%% the request process to crash (or not depending on the error and
+%% config and/or handle_answer callback).
+reply(_, _, _) ->
+ ok.
+
+%% is_loop/4
+%%
+%% Is there a Route-Record AVP with our Origin-Host?
+
+is_loop(Code,
+ Vid,
+ Bin,
+ [#diameter_avp{code = Code, vendor_id = Vid, data = Bin} | _]) ->
+ true;
+
+is_loop(_, _, _, []) ->
+ false;
+
+is_loop(Code, Vid, OH, [_ | Avps])
+ when is_binary(OH) ->
+ 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
+%%
+%% Send a locally originating reply.
+
+reply(Msg, Dict, TPid, #diameter_packet{errors = Es,
+ transport_data = TD}
+ = ReqPkt)
+ when [] == Es;
+ is_record(hd(Msg), diameter_header) ->
+ Pkt = diameter_codec:encode(Dict, make_reply_packet(Msg, ReqPkt)),
+ incr(send, Pkt, Dict, TPid), %% count result codes in sent answers
+ send(TPid, Pkt#diameter_packet{transport_data = TD});
+
+%% Simplify the handling of error cases by accepting a list consisting
+%% of an answer record followed by failed AVPs to be packed into a
+%% Failed-AVP field, either directly or into an AVP field. Only if
+%% the message is a tuple-list or record however, not a list
+%% with a list of #diameter_header{} and #diameter_avp{}.
+reply(Msg, Dict, TPid, #diameter_packet{errors = [H|_] = Es} = Pkt) ->
+ reply(rc(Msg, rc(H), [A || {_,A} <- Es], Dict),
+ Dict,
+ TPid,
+ Pkt#diameter_packet{errors = []}).
+
+%% make_reply_packet/2
+
+make_reply_packet(Bin, _)
+ when is_binary(Bin) ->
+ #diameter_packet{bin = Bin};
+
+make_reply_packet([#diameter_header{} | _] = Msg, _) ->
+ #diameter_packet{msg = Msg};
+
+make_reply_packet(Msg, #diameter_packet{header = ReqHdr}) ->
+ #diameter_header{end_to_end_id = EId,
+ hop_by_hop_id = Hid,
+ is_proxiable = P}
+ = ReqHdr,
+
+ Hdr = #diameter_header{version = ?DIAMETER_VERSION,
+ end_to_end_id = EId,
+ hop_by_hop_id = Hid,
+ is_proxiable = P,
+ is_retransmitted = false},
+ #diameter_packet{header = Hdr,
+ msg = Msg}.
+
+%% rc/1
+
+rc({RC, _}) ->
+ RC;
+rc(RC) ->
+ RC.
+
+%% rc/4
+
+rc(Rec, RC, Failed, Dict)
+ when is_integer(RC) ->
+ set(Rec, [{'Result-Code', RC} | failed_avp(Rec, Failed, Dict)], Dict).
+
+%% Reply as name and tuple list ...
+set([_|_] = Ans, Avps, _) ->
+ Ans ++ Avps; %% Values nearer tail take precedence.
+
+%% ... or record.
+set(Rec, Avps, Dict) ->
+ Dict:'#set-'(Avps, Rec).
+
+%% failed_avp/3
+
+failed_avp(_, [] = No, _) ->
+ No;
+
+failed_avp(Rec, Failed, Dict) ->
+ [fa(Rec, [{'AVP', Failed}], Dict)].
+
+%% Reply as name and tuple list ...
+fa([MsgName | Values], FailedAvp, Dict) ->
+ R = Dict:msg2rec(MsgName),
+ try
+ Dict:'#info-'(R, {index, 'Failed-AVP'}),
+ {'Failed-AVP', [FailedAvp]}
+ catch
+ error: _ ->
+ Avps = proplists:get_value('AVP', Values, []),
+ A = #diameter_avp{name = 'Failed-AVP',
+ value = FailedAvp},
+ {'AVP', [A|Avps]}
+ end;
+
+%% ... or record.
+fa(Rec, FailedAvp, Dict) ->
+ try
+ {'Failed-AVP', [FailedAvp]}
+ catch
+ error: _ ->
+ Avps = Dict:'get-'('AVP', Rec),
+ A = #diameter_avp{name = 'Failed-AVP',
+ value = FailedAvp},
+ {'AVP', [A|Avps]}
+ end.
+
+%% 3. Diameter Header
+%%
+%% E(rror) - If set, the message contains a protocol error,
+%% and the message will not conform to the ABNF
+%% 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.
+
+%% 3.2. Command Code ABNF specification
+%%
+%% 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.
+
+%% 7.1.3. Protocol Errors
+%%
+%% 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 and only these errors MUST
+%% only be used in answer messages whose 'E' bit is set.
+
+%% Thus, only construct answers to protocol errors. Other errors
+%% require an message-specific answer and must be handled by the
+%% application.
+
+%% 6.2. Diameter Answer Processing
+%%
+%% When a request is locally processed, the following procedures MUST be
+%% applied to create the associated answer, in addition to any
+%% additional procedures that MAY be discussed in the Diameter
+%% application defining the command:
+%%
+%% - The same Hop-by-Hop identifier in the request is used in the
+%% answer.
+%%
+%% - The local host's identity is encoded in the Origin-Host AVP.
+%%
+%% - The Destination-Host and Destination-Realm AVPs MUST NOT be
+%% present in the answer message.
+%%
+%% - The Result-Code AVP is added with its value indicating success or
+%% failure.
+%%
+%% - If the Session-Id is present in the request, it MUST be included
+%% in the answer.
+%%
+%% - Any Proxy-Info AVPs in the request MUST be added to the answer
+%% message, in the same order they were present in the request.
+%%
+%% - The 'P' bit is set to the same value as the one in the request.
+%%
+%% - 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
+%% the above processing rules.
+
+%% 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
+%% Error-Message AVP is not intended to be useful in real-time, and
+%% SHOULD NOT be expected to be parsed by network entities.
+
+%% answer_message/2
+
+answer_message({OH, OR, RC}, Avps) ->
+ {Code, _, Vid} = ?BASE:avp_header('Session-Id'),
+ ['answer-message', {'Origin-Host', OH},
+ {'Origin-Realm', OR},
+ {'Result-Code', RC}
+ | session_id(Code, Vid, Avps)].
+
+session_id(Code, Vid, Avps)
+ when is_list(Avps) ->
+ try
+ {value, #diameter_avp{} = Avp} = find_avp(Code, Vid, Avps),
+ Avp
+ catch
+ error: _ ->
+ []
+ end;
+
+session_id(Code, Vid, Avps)
+ when is_list(Avps) ->
+ try
+ {value, #diameter_avp{data = D}} = find_avp(Code, Vid, Avps),
+ [{'Session-Id', [?BASE:avp(decode, D, 'Session-Id')]}]
+ catch
+ error: _ ->
+ []
+ end.
+
+%% find_avp/3
+
+find_avp(Code, Vid, Avps)
+ when is_integer(Code), (undefined == Vid orelse is_integer(Vid)) ->
+ find(fun(A) -> is_avp(Code, Vid, A) end, Avps).
+
+%% The final argument here could be a list of AVP's, depending on the case,
+%% but we're only searching at the top level.
+is_avp(Code, Vid, #diameter_avp{code = Code, vendor_id = Vid}) ->
+ true;
+is_avp(_, _, _) ->
+ false.
+
+find(_, []) ->
+ false;
+find(Pred, [H|T]) ->
+ case Pred(H) of
+ true ->
+ {value, H};
+ false ->
+ find(Pred, T)
+ end.
+
+%% 7. Error Handling
+%%
+%% 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:
+%%
+%% - 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 containing the
+%% offending AVP.
+%%
+%% - An AVP that is received with an unrecognized value causes an
+%% answer to be returned with the Result-Code AVP set to
+%% DIAMETER_INVALID_AVP_VALUE, with the Failed-AVP AVP containing the
+%% AVP causing the error.
+%%
+%% - A command is received with an AVP that is omitted, yet is
+%% mandatory according to the command's ABNF. The receiver issues an
+%% answer with the Result-Code set to 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.
+%%
+%% 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
+%% specific errors that can be described by this AVP are described in
+%% the following section.
+
+%% 7.5. Failed-AVP AVP
+%%
+%% The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
+%% 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.
+%%
+%% 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
+%% occurrences.
+%%
+%% A Diameter message MAY 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
+%% required length for the omitted AVP will be added.
+
+%%% ---------------------------------------------------------------------------
+%%% # handle_answer/3
+%%% ---------------------------------------------------------------------------
+
+%% Process an answer message in call-specific process.
+
+handle_answer(SvcName, _, {error, Req, Reason}) ->
+ handle_error(Req, Reason, SvcName);
+
+handle_answer(SvcName,
+ AnswerErrors,
+ {answer, #request{dictionary = Dict} = Req, Pkt}) ->
+ a(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) ->
+ try
+ incr(in, Pkt, Dict, TPid)
+ of
+ _ ->
+ cb(Req, handle_answer, [Pkt, msg(P), SvcName, {TPid, Caps}])
+ catch
+ exit: {invalid_error_bit, _} = E ->
+ e(Pkt#diameter_packet{errors = [E]}, SvcName, AE, Req)
+ end;
+
+a(#diameter_packet{} = Pkt, SvcName, AE, Req) ->
+ e(Pkt, SvcName, AE, Req).
+
+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) ->
+ x(errors, handle_answer, [SvcName, Req, Pkt]);
+e(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
+%% header is what we expect. (TODO: Does the rfc says anything about
+%% this?)
+
+%% incr/4
+%%
+%% Increment a stats counter for an incoming or outgoing message.
+
+%% TODO: fix
+incr(_, #diameter_packet{msg = undefined}, _, _) ->
+ ok;
+
+incr(Dir, Pkt, Dict, TPid)
+ when is_pid(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)),
+ PE = is_protocol_error(RC),
+
+ %% Check that the E bit is set only for 3xxx result codes.
+ (not (E orelse PE))
+ 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}).
+
+%% incr/2
+
+incr(TPid, Counter) ->
+ diameter_stats:incr(Counter, TPid, 1).
+
+%% RFC 3588, 7.6:
+%%
+%% All Diameter answer messages defined in vendor-specific
+%% applications MUST include either one Result-Code AVP or one
+%% Experimental-Result AVP.
+%%
+%% Maintain statistics assuming one or the other, not both, which is
+%% surely the intent of the RFC.
+
+rc_counter(_, _, RC)
+ when is_integer(RC) ->
+ {'Result-Code', RC};
+rc_counter(D, Rec, _) ->
+ rcc(get_avp_value(D, 'Experimental-Result', Rec)).
+
+%% 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) ->
+ T;
+rcc({_,_,RC} = T)
+ when is_integer(RC) ->
+ T;
+rcc(_) ->
+ undefined.
+
+int([N])
+ when is_integer(N) ->
+ N;
+int(N)
+ when is_integer(N) ->
+ N;
+int(_) ->
+ undefined.
+
+is_protocol_error(RC) ->
+ 3000 =< RC andalso RC < 4000.
+
+-spec x(any(), atom(), list()) -> no_return().
+
+%% Warn and exit request process on errors in an incoming answer.
+x(Reason, F, A) ->
+ diameter_lib:warning_report(Reason, {?MODULE, F, A}),
+ x(Reason).
+
+x(T) ->
+ exit(T).
+
+%%% ---------------------------------------------------------------------------
+%%% # failover/[23]
+%%% ---------------------------------------------------------------------------
+
+%% Failover as a consequence of request_peer_down/2.
+failover({_, #request{handler = Pid} = Req, TRef}, S) ->
+ Pid ! {failover, TRef, rt(Req, S)}.
+
+%% Failover as a consequence of store_request/4.
+failover(TRef, Seqs, S)
+ when is_reference(TRef) ->
+ case lookup_request(Seqs, TRef) of
+ #request{} = Req ->
+ failover({Seqs, Req, TRef}, S);
+ false ->
+ ok
+ end.
+
+%% prepare_request returned a binary ...
+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).
+
+%%% ---------------------------------------------------------------------------
+%%% # report_status/5
+%%% ---------------------------------------------------------------------------
+
+report_status(Status,
+ #peer{ref = Ref,
+ conn = TPid,
+ type = Type,
+ options = Opts},
+ #conn{apps = [_|_] = As,
+ caps = Caps},
+ #state{service_name = SvcName}
+ = S,
+ Extra) ->
+ share_peer(Status, Caps, As, TPid, S),
+ Info = [Status, Ref, {TPid, Caps}, {type(Type), Opts} | Extra],
+ send_event(SvcName, list_to_tuple(Info)).
+
+%% send_event/2
+
+send_event(SvcName, Info) ->
+ send_event(#diameter_event{service = SvcName,
+ info = Info}).
+
+send_event(#diameter_event{service = SvcName} = E) ->
+ lists:foreach(fun({_, Pid}) -> Pid ! E end, subscriptions(SvcName)).
+
+%%% ---------------------------------------------------------------------------
+%%% # share_peer/5
+%%% ---------------------------------------------------------------------------
+
+share_peer(up, Caps, Aliases, TPid, #state{share_peers = true,
+ service_name = Svc}) ->
+ diameter_peer:notify(Svc, {peer, TPid, Aliases, Caps});
+
+share_peer(_, _, _, _, _) ->
+ ok.
+
+%%% ---------------------------------------------------------------------------
+%%% # share_peers/2
+%%% ---------------------------------------------------------------------------
+
+share_peers(Pid, #state{share_peers = true,
+ local_peers = PDict}) ->
+ ?Dict:fold(fun(A,Ps,ok) -> sp(Pid, A, Ps), ok end, ok, PDict);
+
+share_peers(_, #state{share_peers = false}) ->
+ ok.
+
+sp(Pid, Alias, Peers) ->
+ lists:foreach(fun({P,C}) -> Pid ! {peer, P, [Alias], C} end, Peers).
+
+%%% ---------------------------------------------------------------------------
+%%% # remote_peer_up/4
+%%% ---------------------------------------------------------------------------
+
+remote_peer_up(Pid, Aliases, Caps, #state{use_shared_peers = true,
+ service = Svc,
+ shared_peers = PDict}
+ = S) ->
+ #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)};
+
+remote_peer_up(_, _, _, #state{use_shared_peers = false} = S) ->
+ S.
+
+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).
+
+%%% ---------------------------------------------------------------------------
+%%% # 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))}.
+
+rpd(Pid, Alias, PDict) ->
+ ?Dict:update(Alias, fun(Ps) -> lists:keydelete(Pid, 1, Ps) end, PDict).
+
+%%% ---------------------------------------------------------------------------
+%%% find_transport/[34]
+%%%
+%%% Output: {TransportPid, #diameter_caps{}, #diameter_app{}}
+%%% | false
+%%% ---------------------------------------------------------------------------
+
+%% Initial call, from an arbitrary process.
+find_transport({alias, Alias}, Msg, Opts, #state{service = Svc} = S) ->
+ #diameter_service{applications = Apps} = Svc,
+ ft(find_send_app(Alias, Apps), Msg, Opts, S);
+
+%% Relay or proxy send.
+find_transport(#diameter_app{} = App, Msg, Opts, S) ->
+ ft(App, Msg, Opts, S).
+
+ft(#diameter_app{module = Mod, dictionary = D} = App, Msg, Opts, S) ->
+ #options{filter = Filter,
+ extra = Xtra}
+ = Opts,
+ pick_peer(App#diameter_app{module = Mod ++ Xtra},
+ get_destination(Msg, D),
+ Filter,
+ S);
+ft(false = No, _, _, _) ->
+ No.
+
+%% This can't be used if we're a relay and sending a message
+%% in an application not known locally. (TODO)
+find_send_app(Alias, Apps) ->
+ case lists:keyfind(Alias, #diameter_app.alias, Apps) of
+ #diameter_app{id = ?APP_ID_RELAY} ->
+ false;
+ T ->
+ T
+ end.
+
+%% Retransmission, in the service process.
+find_transport([_,_] = RH,
+ Req,
+ #state{service = #diameter_service{pid = Pid,
+ applications = Apps}}
+ = S)
+ when self() == Pid ->
+ #request{app = Alias,
+ filter = Filter,
+ module = ModX}
+ = Req,
+ #diameter_app{}
+ = App
+ = lists:keyfind(Alias, #diameter_app.alias, Apps),
+
+ pick_peer(App#diameter_app{module = ModX},
+ RH,
+ Filter,
+ S).
+
+%% get_destination/2
+
+get_destination(Msg, Dict) ->
+ [str(get_avp_value(Dict, 'Destination-Realm', Msg)),
+ str(get_avp_value(Dict, 'Destination-Host', Msg))].
+
+%% TODO:
+%%
+%% Should add some way of specifying destination directly so that the
+%% only requirement is that the prepare_request callback returns
+%% something specific. (eg. {host, DH}; that is, let the caller specify.)
+%%
+%% Also, there is no longer any need to call get_destination at all in
+%% the default case.
+
+str(T)
+ when T == undefined;
+ T == [] ->
+ undefined;
+str([X])
+ when is_list(X) ->
+ X;
+str(T) ->
+ T.
+
+%% get_avp_value/3
+%%
+%% Support outgoing messages in one of three forms:
+%%
+%% - a message record (as generated from a .dia spec) or
+%% - a list of an atom message name followed by 2-tuple, avp name/value pairs.
+%% - a list of a #diameter_header{} followed by #diameter_avp{} records,
+%%
+%% In the first two forms a dictionary module is used at encode to
+%% identify the type of the AVP and its arity in the message in
+%% 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.
+
+get_avp_value(Dict, Name, [#diameter_header{} | Avps]) ->
+ try
+ {Code, _, VId} = Dict:avp_header(Name),
+ [A|_] = lists:dropwhile(fun(#diameter_avp{code = C, vendor_id = V}) ->
+ C /= Code orelse V /= VId
+ end,
+ Avps),
+ avp_decode(Dict, Name, A)
+ catch
+ error: _ ->
+ undefined
+ end;
+
+get_avp_value(_, Name, [_MsgName | Avps]) ->
+ case lists:keyfind(Name, 1, Avps) of
+ {_, V} ->
+ V;
+ _ ->
+ undefined
+ end;
+
+get_avp_value(Dict, Name, Rec)
+ when is_tuple(Rec) ->
+ try
+ Dict:'#get-'(Name, Rec)
+ catch
+ error:_ ->
+ undefined
+ end.
+
+avp_decode(Dict, Name, #diameter_avp{value = undefined,
+ data = Bin}) ->
+ Dict:avp(decode, Bin, Name);
+avp_decode(_, _, #diameter_avp{value = V}) ->
+ V.
+
+%%% ---------------------------------------------------------------------------
+%%% # pick_peer(App, [DestRealm, DestHost], Filter, #state{})
+%%%
+%%% Output: {TransportPid, #diameter_caps{}, App}
+%%% | false
+%%% | {error, Reason}
+%%% ---------------------------------------------------------------------------
+
+%% Find transports to a given realm/host.
+
+pick_peer(#diameter_app{alias = Alias}
+ = App,
+ [_,_] = RH,
+ Filter,
+ #state{local_peers = L,
+ shared_peers = S,
+ service_name = SvcName,
+ service = #diameter_service{pid = Pid}}) ->
+ pick_peer(peers(Alias, RH, Filter, L),
+ peers(Alias, RH, Filter, S),
+ Pid,
+ SvcName,
+ App).
+
+%% pick_peer/5
+
+pick_peer([], [], _, _, _) ->
+ false;
+
+%% App state is mutable but we're not in the service process: go there.
+pick_peer(Local, Remote, Pid, _SvcName, #diameter_app{mutable = true} = App)
+ when self() /= Pid ->
+ call_service(Pid, {pick_peer, Local, Remote, App});
+
+%% App state isn't mutable or it is and we're in the service process:
+%% do the deed.
+pick_peer(Local,
+ Remote,
+ _Pid,
+ SvcName,
+ #diameter_app{module = ModX,
+ alias = Alias,
+ init_state = S,
+ mutable = M}
+ = App) ->
+ MFA = {ModX, pick_peer, [Local, Remote, SvcName]},
+
+ try state_cb(App, MFA) of
+ {ok, {TPid, #diameter_caps{} = Caps}} when is_pid(TPid) ->
+ {TPid, Caps, App};
+ {{TPid, #diameter_caps{} = Caps}, ModS} when is_pid(TPid), M ->
+ mod_state(Alias, ModS),
+ {TPid, Caps, App};
+ {false = No, ModS} when M ->
+ mod_state(Alias, ModS),
+ No;
+ {ok, false = No} ->
+ No;
+ false = No ->
+ No;
+ {{TPid, #diameter_caps{} = Caps}, S} when is_pid(TPid) ->
+ {TPid, Caps, App}; %% Accept returned state in the immutable
+ {false = No, S} -> %% case as long it isn't changed.
+ No;
+ T ->
+ diameter_lib:error_report({invalid, T, App}, MFA)
+ catch
+ E: Reason ->
+ diameter_lib:error_report({failure, {E, Reason, ?STACK}}, MFA)
+ end.
+
+%% peers/4
+
+peers(Alias, RH, Filter, Peers) ->
+ case ?Dict:find(Alias, Peers) of
+ {ok, L} ->
+ ps(L, RH, Filter, {[],[]});
+ error ->
+ []
+ end.
+
+%% Place a peer whose Destination-Host/Realm matches those of the
+%% request at the front of the result list.
+
+ps([], _, _, {Ys, Ns}) ->
+ lists:reverse(Ys, Ns);
+ps([{_TPid, #diameter_caps{} = Caps} = TC | Rest], RH, Filter, Acc) ->
+ ps(Rest, RH, Filter, pacc(caps_filter(Caps, RH, Filter),
+ caps_filter(Caps, RH, {all, [host, realm]}),
+ TC,
+ Acc)).
+
+pacc(true, true, TC, {Ts, Fs}) ->
+ {[TC|Ts], Fs};
+pacc(true, false, TC, {Ts, Fs}) ->
+ {Ts, [TC|Fs]};
+pacc(false, _, _, Acc) ->
+ Acc.
+
+%% caps_filter/3
+
+caps_filter(C, RH, {neg, F}) ->
+ not caps_filter(C, RH, F);
+
+caps_filter(C, RH, {all, L}) ->
+ lists:all(fun(F) -> caps_filter(C, RH, F) end, L);
+
+caps_filter(C, RH, {any, L}) ->
+ lists:any(fun(F) -> caps_filter(C, RH, F) end, L);
+
+caps_filter(#diameter_caps{origin_host = {_,H}}, [_,DH], host) ->
+ eq(undefined, DH, H);
+
+caps_filter(#diameter_caps{origin_realm = {_,R}}, [DR,_], realm) ->
+ eq(undefined, DR, R);
+
+caps_filter(C, _, Filter) ->
+ caps_filter(C, Filter).
+
+%% caps_filter/2
+
+caps_filter(_, none) ->
+ true;
+
+caps_filter(#diameter_caps{origin_host = {_,OH}}, {host, H}) ->
+ eq(any, H, OH);
+
+caps_filter(#diameter_caps{origin_realm = {_,OR}}, {realm, R}) ->
+ eq(any, R, OR);
+
+caps_filter(C, T) ->
+ try
+ {eval, F} = T,
+ diameter_lib:eval([F,C])
+ catch
+ _:_ -> false
+ end.
+
+eq(X, A, B) ->
+ X == A orelse A == B.
+
+%% transports/1
+
+transports(#state{peerT = PeerT}) ->
+ ets:select(PeerT, [{#peer{conn = '$1', _ = '_'},
+ [{'is_pid', '$1'}],
+ ['$1']}]).
+
+%%% ---------------------------------------------------------------------------
+%%% # service_info/2
+%%% ---------------------------------------------------------------------------
+
+%% The config passed to diameter:start_service/2.
+-define(CAP_INFO, ['Origin-Host',
+ 'Origin-Realm',
+ 'Vendor-Id',
+ 'Product-Name',
+ 'Origin-State-Id',
+ 'Host-IP-Address',
+ 'Supported-Vendor-Id',
+ 'Auth-Application-Id',
+ 'Inband-Security-Id',
+ 'Acct-Application-Id',
+ 'Vendor-Specific-Application-Id',
+ 'Firmware-Revision']).
+
+-define(ALL_INFO, [capabilities,
+ applications,
+ transport,
+ pending,
+ 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).
+
+service_info(Item, #state{service = Svc} = S, Complete) ->
+ case Item of
+ name ->
+ S#state.service_name;
+ 'Origin-Host' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.origin_host;
+ 'Origin-Realm' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.origin_realm;
+ 'Vendor-Id' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.vendor_id;
+ 'Product-Name' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.product_name;
+ 'Origin-State-Id' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.origin_state_id;
+ 'Host-IP-Address' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.host_ip_address;
+ 'Supported-Vendor-Id' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.supported_vendor_id;
+ 'Auth-Application-Id' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.auth_application_id;
+ 'Inband-Security-Id' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.inband_security_id;
+ 'Acct-Application-Id' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.acct_application_id;
+ 'Vendor-Specific-Application-Id' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.vendor_specific_application_id;
+ 'Firmware-Revision' ->
+ (Svc#diameter_service.capabilities)
+ #diameter_caps.firmware_revision;
+ capabilities -> service_info(?CAP_INFO, S);
+ applications -> info_apps(S);
+ transport -> info_transport(S);
+ pending -> info_pending(S);
+ statistics -> info_stats(S);
+ keys -> ?ALL_INFO ++ ?CAP_INFO; %% mostly for test
+ all -> service_info(?ALL_INFO, S);
+ _ when Complete -> service_info(complete(Item), S, false);
+ _ -> undefined
+ end.
+
+complete(Pre) ->
+ P = atom_to_list(Pre),
+ case [I || I <- [name | ?ALL_INFO] ++ ?CAP_INFO,
+ lists:prefix(P, atom_to_list(I))]
+ of
+ [I] -> I;
+ _ -> Pre
+ end.
+
+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,
+ [],
+ 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}) ->
+ dict:append(Ref,
+ [{type, Type},
+ {options, Opts},
+ {watchdog, {Pid, T, OS}}
+ | info_conn(ConnT, TPid)],
+ Acc).
+
+info_conn(ConnT, TPid) ->
+ info_conn(ets:lookup(ConnT, TPid)).
+
+info_conn([#conn{pid = Pid, apps = SApps, caps = Caps, started = T}]) ->
+ [{peer, {Pid, T}},
+ {apps, SApps},
+ {caps, info_caps(Caps)}];
+info_conn([] = No) ->
+ No.
+
+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}].
+
+info_pending(#state{} = S) ->
+ MatchSpec = [{{'$1',
+ #request{transport = '$2',
+ from = '$3',
+ app = '$4',
+ _ = '_'},
+ '_'},
+ [?ORCOND([{'==', T, '$2'} || T <- transports(S)])],
+ [{{'$1', [{{app, '$4'}},
+ {{transport, '$2'}},
+ {{from, '$3'}}]}}]}],
+
+ ets:select(?REQUEST_TABLE, MatchSpec).
diff --git a/lib/diameter/src/app/diameter_service_sup.erl b/lib/diameter/src/app/diameter_service_sup.erl
new file mode 100644
index 0000000000..153fff902f
--- /dev/null
+++ b/lib/diameter/src/app/diameter_service_sup.erl
@@ -0,0 +1,64 @@
+%%
+%% %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 supervisor of service processes.
+%%
+
+-module(diameter_service_sup).
+
+-behaviour(supervisor).
+
+-export([start_link/0, %% supervisor start
+ start_child/1]). %% service start
+
+%% supervisor callback
+-export([init/1]).
+
+-define(NAME, ?MODULE). %% supervisor name
+
+%% start_link/0
+
+start_link() ->
+ SupName = {local, ?NAME},
+ supervisor:start_link(SupName, ?MODULE, []).
+
+%% start_child/1
+%%
+%% A service and its related processes (transport, peer_fwm and
+%% watchdog) are all temporary since they're all restarted in
+%% application code. A Transport and peer_fsm is restarted by a
+%% watchdog as required by the RFC 3539 state machine, a watchdog is
+%% restarted by service, and services are restarted by diameter_config.
+
+start_child(ServiceName) ->
+ supervisor:start_child(?NAME, [ServiceName]).
+
+%% init/1
+
+init([]) ->
+ Mod = diameter_service,
+ Flags = {simple_one_for_one, 0, 1},
+ ChildSpec = {Mod,
+ {Mod, start_link, []},
+ temporary,
+ 1000,
+ worker,
+ [Mod]},
+ {ok, {Flags, [ChildSpec]}}.
diff --git a/lib/diameter/src/app/diameter_session.erl b/lib/diameter/src/app/diameter_session.erl
new file mode 100644
index 0000000000..bb91e97f39
--- /dev/null
+++ b/lib/diameter/src/app/diameter_session.erl
@@ -0,0 +1,172 @@
+%%
+%% %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_session).
+
+-export([sequence/0,
+ 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
+%%
+%% Output: 32-bit
+%% ---------------------------------------------------------------------------
+
+%% 3588, 3:
+%%
+%% 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.
+%%
+%% 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
+%% 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
+%% 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
+%% 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.
+
+-spec sequence()
+ -> 'Unsigned32'().
+
+sequence() ->
+ Instr = {_Pos = 2, _Incr = 1, _Threshold = ?INT32, _SetVal = 0},
+ ets:update_counter(diameter_sequence, sequence, Instr).
+
+%% ---------------------------------------------------------------------------
+%% # origin_state_id/0
+%% ---------------------------------------------------------------------------
+
+%% 3588, 8.16:
+%%
+%% 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.
+%%
+%% 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
+%% Origin-State-Id to the time of startup, or it MAY use an incrementing
+%% counter retained in non-volatile memory across restarts.
+
+-spec origin_state_id()
+ -> 'Unsigned32'().
+
+origin_state_id() ->
+ ets:lookup_element(diameter_sequence, origin_state_id, 2).
+
+%% ---------------------------------------------------------------------------
+%% # session_id/1
+%% ---------------------------------------------------------------------------
+
+%% 3588, 8.8:
+%%
+%% 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>;<high 32 bits>;<low 32 bits>[;<optional value>]
+%%
+%% <high 32 bits> and <low 32 bits> are decimal representations of the
+%% high and low 32 bits of a monotonically increasing 64-bit value. The
+%% 64-bit value is rendered in two part to simplify formatting by 32-bit
+%% processors. At startup, the high 32 bits of the 64-bit value MAY be
+%% initialized to the time, and the low 32 bits MAY be initialized to
+%% zero. This will for practical purposes 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.
+
+-spec session_id('DiameterIdentity'())
+ -> 'OctetString'().
+%% Note that Session-Id has type UTF8String and that any OctetString
+%% is a UTF8String.
+
+session_id(Host) ->
+ Instr = {_Pos = 2, _Incr = 1, _Threshold = ?INT64, _Set = 0},
+ N = ets:update_counter(diameter_sequence, session_base, Instr),
+ Hi = N bsr 32,
+ Lo = N band ?INT32,
+ [Host, ";", integer_to_list(Hi),
+ ";", integer_to_list(Lo),
+ ";", atom_to_list(node())].
+
+%% ---------------------------------------------------------------------------
+%% # init/0
+%% ---------------------------------------------------------------------------
+
+init() ->
+ Now = now(),
+ random:seed(Now),
+ Time = time32(Now),
+ Seq = (?INT32 band (Time bsl 20)) bor (random:uniform(1 bsl 20) - 1),
+ ets:insert(diameter_sequence, [{origin_state_id, Time},
+ {session_base, Time bsl 32},
+ {sequence, Seq}]),
+ Time.
+
+%% ---------------------------------------------------------
+%% INTERNAL FUNCTIONS
+%% ---------------------------------------------------------
+
+%% The minimum value represented by a Time value. (See diameter_types.)
+%% 32 bits extends to 2104.
+-define(TIME0, 62105714048). %% {{1968,1,20},{3,14,8}}
+
+time32(Now) ->
+ Time = calendar:now_to_universal_time(Now),
+ Diff = calendar:datetime_to_gregorian_seconds(Time) - ?TIME0,
+ Diff band ?INT32.
diff --git a/lib/diameter/src/app/diameter_stats.erl b/lib/diameter/src/app/diameter_stats.erl
new file mode 100644
index 0000000000..b52d4cdcfb
--- /dev/null
+++ b/lib/diameter/src/app/diameter_stats.erl
@@ -0,0 +1,347 @@
+%%
+%% %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) ->
+ warning_msg("received unexpected request from ~p:~n~w", [From, Req]),
+ {reply, nok, State}.
+
+%% ----------------------------------------------------------
+%% handle_cast(Request, State)
+%% ----------------------------------------------------------
+
+handle_cast({incr, Rec}, State) ->
+ update_counter(Rec),
+ {noreply, State};
+
+handle_cast(Msg, State) ->
+ warning_msg("received unexpected message:~n~w", [Msg]),
+ {noreply, State}.
+
+%% ----------------------------------------------------------
+%% handle_info(Request, State)
+%% ----------------------------------------------------------
+
+handle_info({'DOWN', _MRef, process, Pid, _}, State) ->
+ down(Pid),
+ {noreply, State};
+
+handle_info(Info, State) ->
+ warning_msg("received unknown info:~n~w", [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).
+
+%% warning_msg/2
+
+warning_msg(F, A) ->
+ ?diameter_warning("~p: " ++ F, [?MODULE | A]).
diff --git a/lib/diameter/src/app/diameter_sup.erl b/lib/diameter/src/app/diameter_sup.erl
new file mode 100644
index 0000000000..e5afd23dcd
--- /dev/null
+++ b/lib/diameter/src/app/diameter_sup.erl
@@ -0,0 +1,101 @@
+%%
+%% %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 top supervisor for the diameter application.
+%%
+
+-module(diameter_sup).
+
+-behaviour(supervisor).
+
+%% interface
+-export([start_link/0, %% supervisor start
+ tree/0]). %% supervision tree
+
+%% supervisor callback
+-export([init/1]).
+
+-define(CHILDREN, [diameter_misc_sup,
+ diameter_watchdog_sup,
+ diameter_peer_fsm_sup,
+ diameter_transport_sup,
+ diameter_service_sup]).
+
+-define(TABLES, [{diameter_sequence, [set]},
+ {diameter_service, [set, {keypos, 3}]},
+ {diameter_request, [bag]},
+ {diameter_config, [bag, {keypos, 2}]}]).
+
+%% start_link/0
+
+start_link() ->
+ SupName = {local, ?MODULE},
+ supervisor:start_link(SupName, ?MODULE, []).
+
+%% init/1
+
+init([]) ->
+ ets_new(?TABLES),
+ diameter_session:init(),
+ Flags = {one_for_one, 1, 5},
+ ChildSpecs = lists:map(fun spec/1, ?CHILDREN),
+ {ok, {Flags, ChildSpecs}}.
+
+%% spec/1
+
+spec(Mod) ->
+ {Mod,
+ {Mod, start_link, []},
+ permanent,
+ 1000,
+ supervisor,
+ [Mod]}.
+
+%% ets_new/1
+
+ets_new(List)
+ when is_list(List) ->
+ lists:foreach(fun ets_new/1, List);
+
+ets_new({Table, Opts}) ->
+ ets:new(Table, [named_table, public | Opts]).
+
+%% tree/0
+
+tree() ->
+ [{?MODULE, whereis(?MODULE), tree(?MODULE)}].
+
+tree(Sup) ->
+ lists:map(fun t/1, supervisor:which_children(Sup)).
+
+t({Name, Pid, supervisor, _}) ->
+ t(Name, Pid, tree(Pid));
+t({Name, Pid, worker, _}) ->
+ t(Name, Pid).
+
+t(undefined, Pid, Children) ->
+ {Pid, Children};
+t(Name, Pid, Children) ->
+ {Name, Pid, Children}.
+
+t(undefined, Pid) ->
+ Pid;
+t(Name, Pid) ->
+ {Name, Pid}.
diff --git a/lib/diameter/src/app/diameter_sync.erl b/lib/diameter/src/app/diameter_sync.erl
new file mode 100644
index 0000000000..f7777ae809
--- /dev/null
+++ b/lib/diameter/src/app/diameter_sync.erl
@@ -0,0 +1,555 @@
+%%
+%% %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 a server that serializes requests in named
+%% queues. A request is an MFA or fun and a name can be any term. A
+%% request is applied in a dedicated process that terminates when
+%% the request function returns.
+%%
+
+-module(diameter_sync).
+-behaviour(gen_server).
+
+-export([call/4, call/5,
+ cast/4, cast/5,
+ carp/1, carp/2]).
+
+%% supervisor callback
+-export([start_link/0]).
+
+%% gen_server interface
+-export([init/1,
+ terminate/2,
+ handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+ code_change/3]).
+
+%% test/debug
+-export([state/0,
+ uptime/0,
+ flush/1,
+ pending/0,
+ pending/1,
+ queues/0,
+ pids/1]).
+
+-include("diameter_internal.hrl").
+
+%% Locally registered server name.
+-define(SERVER, ?MODULE).
+
+%% Message to the server to queue a request ...
+-define(REQUEST(CallOrCast, Name, Req, Max, Timeout),
+ {request, CallOrCast, Name, Req, Max, Timeout}).
+
+%% ... and to retrieve the pid of the prevailing request process.
+-define(CARP(Name),
+ {carp, Name}).
+
+%% Forever ...
+-define(TIMEOUT, 30000).
+
+%% Server state.
+-record(state,
+ {time = now(),
+ pending = 0 :: non_neg_integer(), %% outstanding requests
+ monitor = new() :: ets:tid(), %% MonitorRef -> {Name, From}
+ queue = new() :: ets:tid()}). %% Name -> queue of {Pid, Ref}
+
+%% ----------------------------------------------------------
+%% # call(Node, Name, Req, Max, Timeout)
+%% # call(Name, Req, Max, Timeout)
+%%
+%% Input: Name = term() identifying the queue in which the request is
+%% to be evaluated.
+%% Req = {M,F,A}
+%% | {Fun, Arg}
+%% | [Fun | Args]
+%% | Fun
+%% Max = Upper bound for the number of outstanding requests
+%% in the named queue for Req to be queued.
+%% If more than this number are in the queue then
+%% 'rejected' is returned to the caller. Can be any
+%% term but integer() | infinity is sufficient.
+%% Timeout = 32 bit integer() number of milliseconds after which
+%% request is cancelled (if not already started), causing
+%% 'timeout' to be returned to the caller.
+%% | infinity
+%%
+%% Output: Req() | rejected | timeout
+%%
+%% Description: Serialize a request in a named queue. Note that if
+%% 'timeout' is returned and the request itself does not
+%% return this atom then request has not been evaluated.
+%% ----------------------------------------------------------
+
+call(Name, Req, Max, Timeout) ->
+ call(node(), Name, Req, Max, Timeout).
+
+call(Node, Name, Req, Max, Timeout) ->
+ gen_call({?SERVER, Node}, ?REQUEST(call, Name, Req, Max, Timeout)).
+
+%%% ----------------------------------------------------------
+%%% # cast(Node, Name, Req, Max, Timeout)
+%%% # cast(Name, Req, Max, Timeout)
+%%%
+%%% Output: ok | rejected | timeout
+%%%
+%%% Description: Serialize a request without returning the result to the
+%%% caller. Returns after the task is queued.
+%%% ----------------------------------------------------------
+
+cast(Name, Req, Max, Timeout) ->
+ cast(node(), Name, Req, Max, Timeout).
+
+cast(Node, Name, Req, Max, Timeout) ->
+ gen_call({?SERVER, Node}, ?REQUEST(cast, Name, Req, Max, Timeout)).
+
+%% 'timeout' is only return if the server process that processes
+%% requests isn't alive. Ditto for call/carp.
+
+%%% ----------------------------------------------------------
+%%% # carp(Node, Name)
+%%% # carp(Name)
+%%%
+%%% Output: {value, Pid} | false | timeout
+%%%
+%%% Description: Return the pid of the process processing the task
+%%% at the head of the named queue. Note that the value
+%%% returned by subsequent calls changes as tasks are
+%%% completed, each task executing in a dedicated
+%%% process. The exit value of this process will be
+%%% {value, Req()} if the task returns.
+%%% ----------------------------------------------------------
+
+%% The intention of this is to let a process enqueue a task that waits
+%% for a message before completing, the target pid being retrieved
+%% with carp/[12].
+
+carp(Name) ->
+ carp(node(), Name).
+
+carp(Node, Name) ->
+ gen_call({?SERVER, Node}, ?CARP(Name)).
+
+%%% ---------------------------------------------------------
+%%% EXPORTED INTERNAL FUNCTIONS
+%%% ---------------------------------------------------------
+
+state() ->
+ call(state).
+
+uptime() ->
+ call(uptime).
+
+flush(Name) ->
+ call({flush, Name}).
+
+pending() ->
+ call(pending).
+
+pending(Name) ->
+ call({pending, Name}).
+
+queues() ->
+ call(queues).
+
+pids(Name) ->
+ call({pids, Name}).
+
+%%% ----------------------------------------------------------
+%%% # start_link()
+%%% ----------------------------------------------------------
+
+start_link() ->
+ ServerName = {local, ?SERVER},
+ Module = ?MODULE,
+ Args = [],
+ Options = [{spawn_opt, diameter_lib:spawn_opts(server, [])}],
+ gen_server:start_link(ServerName, Module, Args, Options).
+
+%%% ----------------------------------------------------------
+%%% # init(_)
+%%% ----------------------------------------------------------
+
+init(_) ->
+ {ok, #state{}}.
+
+%%% ----------------------------------------------------------
+%%% # handle_call(Request, From, State)
+%%% ----------------------------------------------------------
+
+%% Enqueue a new request.
+handle_call(?REQUEST(Type, Name, Req, Max, Timeout),
+ From,
+ #state{queue = QD} = State) ->
+ T = find(Name, QD),
+ nq(queued(T) =< Max, T, {Type, From}, Name, Req, Timeout, State);
+
+handle_call(Request, _From, State) ->
+ {reply, call(Request, State), State}.
+
+%% call/2
+
+call(?CARP(Name), #state{queue = QD}) ->
+ pcar(find(Name, QD));
+
+call(state, State) ->
+ State;
+
+call(uptime, #state{time = T}) ->
+ diameter_lib:now_diff(T);
+
+call({flush, Name}, #state{queue = QD}) ->
+ cancel(find(Name, QD));
+
+call(pending, #state{pending = N}) ->
+ N;
+
+call({pending, Name}, #state{queue = QD}) ->
+ queued(find(Name, QD));
+
+call(queues, #state{queue = QD}) ->
+ fetch_keys(QD);
+
+call({pids, Name}, #state{queue = QD}) ->
+ plist(find(Name, QD));
+
+call(Req, _State) -> %% ignore
+ warning_msg("received unexpected request:~n~w", [Req]),
+ nok.
+
+%%% ----------------------------------------------------------
+%%% handle_cast(Request, State)
+%%% ----------------------------------------------------------
+
+handle_cast(Msg, State) ->
+ warning_msg("received unexpected message:~n~w", [Msg]),
+ {noreply, State}.
+
+%%% ----------------------------------------------------------
+%%% handle_info(Request, State)
+%%% ----------------------------------------------------------
+
+handle_info(Request, State) ->
+ {noreply, info(Request, State)}.
+
+%% info/2
+
+%% A request has completed execution or timed out.
+info({'DOWN', MRef, process, Pid, Info},
+ #state{pending = N,
+ monitor = MD,
+ queue = QD}
+ = State) ->
+ {Name, From} = fetch(MRef, MD),
+ reply(From, rc(Info)),
+ State#state{pending = N-1,
+ monitor = erase(MRef, MD),
+ queue = dq(fetch(Name, QD), Pid, Info, Name, QD)};
+
+info(Info, State) ->
+ warning_msg("received unknown info:~n~w", [Info]),
+ State.
+
+reply({call, From}, T) ->
+ gen_server:reply(From, T);
+reply(cast, _) ->
+ ok.
+
+rc({value, T}) ->
+ T;
+rc(_) ->
+ timeout.
+
+%%% ----------------------------------------------------------
+%%% code_change(OldVsn, State, Extra)
+%%% ----------------------------------------------------------
+
+code_change(_OldVsn, State, _Extra) ->
+ {ok, State}.
+
+%%% ----------------------------------------------------------
+%%% terminate(Reason, State)
+%%% ----------------------------------------------------------
+
+terminate(_Reason, _State)->
+ ok.
+
+%%% ---------------------------------------------------------
+%%% INTERNAL FUNCTIONS
+%%% ---------------------------------------------------------
+
+%% queued/1
+
+queued({ok, {N,_}}) ->
+ N;
+queued(error) ->
+ 0.
+
+%% nq/7
+
+%% Maximum number of pending requests exceeded ...
+nq(false, _, _, _Name, _Req, _Timeout, State) ->
+ {reply, rejected, State};
+
+%% ... or not.
+nq(true, T, From, Name, Req, Timeout, #state{pending = N,
+ monitor = MD,
+ queue = QD}
+ = State) ->
+ Ref = make_ref(),
+ Pid = init(Ref, Req, timeout(Timeout, T)),
+ MRef = erlang:monitor(process, Pid),
+ {noreply, State#state{pending = N+1,
+ monitor = store(MRef, {Name, from(From)}, MD),
+ queue = store(Name, nq(T, {Pid, Ref}), QD)}}.
+
+from({call, _} = T) ->
+ T;
+from({cast = T, From}) ->
+ gen_server:reply(From, ok),
+ T.
+
+%% nq/2
+
+%% Other requests in the queue: append.
+nq({ok, {N,Q}}, T) ->
+ {N+1, queue:in(T,Q)};
+
+%% Queue is empty: start execution.
+nq(error, T) ->
+ go(T),
+ {1, queue:from_list([T])}.
+
+%% Don't timeout if the request is evaluated immediately so as to
+%% avoid a race between getting a 'go' and a 'timeout'. Queueing a
+%% request in an empty queue always results in execution.
+timeout(_, error) ->
+ infinity;
+timeout(Timeout, _) ->
+ Timeout.
+
+%% dq/5
+%%
+%% A request process has terminated.
+
+dq({N,Q}, Pid, _Info, Name, QD) ->
+ {{value, T}, TQ} = queue:out(Q),
+ dq(N-1, Pid, T, TQ, Name, QD).
+
+%% dq/6
+
+%% Request was at the head of the queue: start another.
+dq(N, Pid, {Pid, _}, TQ, Name, QD) ->
+ dq(N, TQ, Name, QD);
+
+%% Or not: remove the offender from the queue.
+dq(N, Pid, T, TQ, Name, QD) ->
+ store(Name, {N, req(Pid, queue:from_list([T]), TQ)}, QD).
+
+%% dq/4
+
+%% Queue is empty: erase.
+dq(0, TQ, Name, QD) ->
+ true = queue:is_empty(TQ), %% assert
+ erase(Name, QD);
+
+%% Start the next request.
+dq(N, TQ, Name, QD) ->
+ go(queue:head(TQ)),
+ store(Name, {N, TQ}, QD).
+
+%% req/3
+%%
+%% Find and remove the queue element for the specified pid.
+
+req(Pid, HQ, Q) ->
+ {{value, T}, TQ} = queue:out(Q),
+ req(Pid, T, HQ, TQ).
+
+req(Pid, {Pid, _}, HQ, TQ) ->
+ queue:join(HQ, TQ);
+req(Pid, T, HQ, TQ) ->
+ req(Pid, queue:in(T,HQ), TQ).
+
+%% go/1
+
+go({Pid, Ref}) ->
+ Pid ! {Ref, ok}.
+
+%% init/4
+%%
+%% Start the dedicated process for handling a request. The exit value
+%% is as promised by carp/1.
+
+init(Ref, Req, Timeout) ->
+ spawn(fun() -> exit(i(Ref, Req, Timeout)) end).
+
+i(Ref, Req, Timeout) ->
+ Timer = send_timeout(Ref, Timeout),
+ MRef = erlang:monitor(process, ?SERVER),
+ receive
+ {Ref, ok} -> %% Do the deed.
+ %% Ensure we don't leave messages in the mailbox since the
+ %% request itself might receive. Alternatively, could have
+ %% done the eval in a new process but then we'd have to
+ %% relay messages arriving at this one.
+ cancel_timer(Timer),
+ erlang:demonitor(MRef, [flush]),
+ %% Ref is to ensure that we don't extract any message that
+ %% a client may have sent after retrieving self() with
+ %% carp/1, there being no guarantee that the message
+ %% banged by go/1 is received before the pid becomes
+ %% accessible.
+ {value, eval(Req)};
+ {Ref, timeout = T} ->
+ T;
+ {'DOWN', MRef, process, _Pid, _Info} = D -> %% server death
+ D
+ end.
+
+send_timeout(_Ref, infinity = No) ->
+ No;
+send_timeout(Ref, Ms) ->
+ Msg = {Ref, timeout},
+ TRef = erlang:send_after(Ms, self(), Msg),
+ {TRef, Msg}.
+
+cancel_timer(infinity = No) ->
+ No;
+cancel_timer({TRef, Msg}) ->
+ flush(Msg, erlang:cancel_timer(TRef)).
+
+flush(Msg, false) -> %% Message has already been sent ...
+ %% 'error' should never happen but crash if it does so as not to
+ %% hang the process.
+ ok = receive Msg -> ok after ?TIMEOUT -> error end;
+flush(_, _) -> %% ... or not.
+ ok.
+
+eval({M,F,A}) ->
+ apply(M,F,A);
+eval([Fun | Args]) ->
+ apply(Fun, Args);
+eval({Fun, A}) ->
+ Fun(A);
+eval(Fun) ->
+ Fun().
+
+%% pcar/1
+
+pcar({ok, {_,Q}}) ->
+ {Pid, _Ref} = queue:head(Q),
+ {value, Pid};
+pcar(error) ->
+ false.
+
+%% plist/1
+
+plist({ok, {_,Q}}) ->
+ lists:map(fun({Pid, _Ref}) -> Pid end, queue:to_list(Q));
+plist(error) ->
+ [].
+
+%% cancel/1
+%%
+%% Cancel all but the active request from the named queue. Return the
+%% number of requests cancelled.
+
+%% Just send timeout messages to each request to make them die. Note
+%% that these are guaranteed to arrive before a go message after the
+%% current request completes since both messages are sent from the
+%% server process.
+cancel({ok, {N,Q}}) ->
+ {_,TQ} = queue:split(1,Q),
+ foreach(fun({Pid, Ref}) -> Pid ! {Ref, timeout} end, N-1, TQ),
+ N-1;
+cancel(error) ->
+ 0.
+
+%% foreach/3
+
+foreach(_, 0, _) ->
+ ok;
+foreach(Fun, N, Q) ->
+ Fun(queue:head(Q)),
+ foreach(Fun, N-1, queue:tail(Q)).
+
+%% call/1
+
+%% gen_server:call/3 will exit if the target process dies.
+call(Request) ->
+ try
+ gen_server:call(?SERVER, Request, ?TIMEOUT)
+ catch
+ exit: Reason ->
+ {error, Reason}
+ end.
+
+%% dict-like table manipulation.
+
+erase(Key, Dict) ->
+ ets:delete(Dict, Key),
+ Dict.
+
+fetch(Key, Dict) ->
+ {ok, V} = find(Key, Dict),
+ V.
+
+fetch_keys(Dict) ->
+ ets:foldl(fun({K,_}, Acc) -> [K | Acc] end, [], Dict).
+
+find(Key, Dict) ->
+ case ets:lookup(Dict, Key) of
+ [{Key, V}] ->
+ {ok, V};
+ [] ->
+ error
+ end.
+
+new() ->
+ ets:new(?MODULE, [set]).
+
+store(Key, Value, Dict) ->
+ store({Key, Value}, Dict).
+
+store({_,_} = T, Dict) ->
+ ets:insert(Dict, T),
+ Dict.
+
+%% gen_call/1
+
+gen_call(Server, Req) ->
+ gen_call(Server, Req, infinity).
+
+gen_call(Server, Req, Timeout) ->
+ try
+ gen_server:call(Server, Req, Timeout)
+ catch
+ exit: _ ->
+ timeout
+ end.
+
+%% warning_msg/2
+
+warning_msg(F, A) ->
+ ?diameter_warning("~p: " ++ F, [?MODULE | A]).
diff --git a/lib/diameter/src/app/diameter_types.erl b/lib/diameter/src/app/diameter_types.erl
new file mode 100644
index 0000000000..6b1b1b8d39
--- /dev/null
+++ b/lib/diameter/src/app/diameter_types.erl
@@ -0,0 +1,537 @@
+%%
+%% %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_types).
+
+%%
+%% Encode/decode of RFC 3588 Data Formats, Basic (section 4.2) and
+%% Derived (section 4.3).
+%%
+
+%% Basic types.
+-export(['OctetString'/2,
+ 'Integer32'/2,
+ 'Integer64'/2,
+ 'Unsigned32'/2,
+ 'Unsigned64'/2,
+ 'Float32'/2,
+ 'Float64'/2]).
+
+%% Derived types.
+-export(['Address'/2,
+ 'Time'/2,
+ 'UTF8String'/2,
+ 'DiameterIdentity'/2,
+ 'DiameterURI'/2,
+ 'IPFilterRule'/2,
+ 'QoSFilterRule'/2]).
+
+-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)))).
+
+%% The Grouped and Enumerated types are dealt with directly in
+%% generated decode modules by way of diameter_gen.hrl and
+%% diameter_codec.erl. Padding and the setting of Length and other
+%% fields are also dealt with there.
+
+%% 3588:
+%%
+%% DIAMETER_INVALID_AVP_LENGTH 5014
+%% The request contained an AVP with an invalid length. A Diameter
+%% message indicating this error MUST include the offending AVPs
+%% within a Failed-AVP AVP.
+%%
+-define(INVALID_LENGTH(Bin), erlang:error({'DIAMETER', 5014, Bin})).
+
+%% -------------------------------------------------------------------------
+%% 3588, 4.2. Basic AVP Data Formats
+%%
+%% The Data field is zero or more octets and contains information
+%% specific to the Attribute. The format and length of the Data field
+%% is determined by the AVP Code and AVP Length fields. The format of
+%% the Data field MUST be one of the following base data types or a data
+%% 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'(decode, Bin)
+ when is_binary(Bin) ->
+ binary_to_list(Bin);
+
+'OctetString'(encode = M, zero) ->
+ 'OctetString'(M, []);
+
+'OctetString'(encode, Str) ->
+ iolist_to_binary(Str).
+
+%% --------------------
+
+'Integer32'(decode, <<X:32/signed>>) ->
+ X;
+
+'Integer32'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
+'Integer32'(encode = M, zero) ->
+ 'Integer32'(M, 0);
+
+'Integer32'(encode, I)
+ when ?SINT(32,I) ->
+ <<I:32/signed>>.
+
+%% --------------------
+
+'Integer64'(decode, <<X:64/signed>>) ->
+ X;
+
+'Integer64'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
+'Integer64'(encode = M, zero) ->
+ 'Integer64'(M, 0);
+
+'Integer64'(encode, I)
+ when ?SINT(64,I) ->
+ <<I:64/signed>>.
+
+%% --------------------
+
+'Unsigned32'(decode, <<X:32>>) ->
+ X;
+
+'Unsigned32'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
+'Unsigned32'(encode = M, zero) ->
+ 'Unsigned32'(M, 0);
+
+'Unsigned32'(encode, I)
+ when ?UINT(32,I) ->
+ <<I:32>>.
+
+%% --------------------
+
+'Unsigned64'(decode, <<X:64>>) ->
+ X;
+
+'Unsigned64'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
+'Unsigned64'(encode = M, zero) ->
+ 'Unsigned64'(M, 0);
+
+'Unsigned64'(encode, I)
+ when ?UINT(64,I) ->
+ <<I:64>>.
+
+%% --------------------
+
+%% Decent summaries of the IEEE floating point formats can be
+%% found at http://en.wikipedia.org/wiki/IEEE_754-1985 and
+%% http://www.psc.edu/general/software/packages/ieee/ieee.php.
+%%
+%% That the bit syntax uses these formats isn't well documented but
+%% this does indeed appear to be the case. However, the bit syntax
+%% only encodes numeric values, not the standard's (signed) infinity
+%% or NaN. It also encodes any large value as 'infinity', never 'NaN'.
+%% Treat these equivalently on decode for this reason.
+%%
+%% An alternative would be to decode infinity/NaN to the largest
+%% possible float but could likely lead to misleading results if
+%% arithmetic is performed on the decoded value. Better to be explicit
+%% that precision has been lost.
+
+'Float32'(decode, <<S:1, 255:8, _:23>>) ->
+ choose(S, infinity, '-infinity');
+
+'Float32'(decode, <<X:32/float>>) ->
+ X;
+
+'Float32'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
+'Float32'(encode = M, zero) ->
+ 'Float32'(M, 0.0);
+
+'Float32'(encode, infinity) ->
+ <<0:1, 255:8, 0:23>>;
+
+'Float32'(encode, '-infinity') ->
+ <<1:1, 255:8, 0:23>>;
+
+'Float32'(encode, X)
+ when is_float(X) ->
+ <<X:32/float>>.
+%% Note that this could also encode infinity/-infinity for large
+%% (signed) numeric values. Note also that precision is lost just in
+%% using the floating point syntax. For example:
+%%
+%% 1> B = <<3.14159:32/float>>.
+%% <<64,73,15,208>>
+%% 2> <<F:32/float>> = B.
+%% <<64,73,15,208>>
+%% 3> F.
+%% 3.141590118408203
+%%
+%% (The 64 bit type does better.)
+
+%% --------------------
+
+%% The 64 bit format is entirely analogous to the 32 bit format.
+
+'Float64'(decode, <<S:1, 2047:11, _:52>>) ->
+ choose(S, infinity, '-infinity');
+
+'Float64'(decode, <<X:64/float>>) ->
+ X;
+
+'Float64'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
+'Float64'(encode, infinity) ->
+ <<0:1, 2047:11, 0:52>>;
+
+'Float64'(encode, '-infinity') ->
+ <<1:1, 2047:11, 0:52>>;
+
+'Float64'(encode = M, zero) ->
+ 'Float64'(M, 0.0);
+
+'Float64'(encode, X)
+ when is_float(X) ->
+ <<X:64/float>>.
+
+%% -------------------------------------------------------------------------
+%% 3588, 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 AVP Derived Data Formats MUST include
+%% them in a section entitled "AVP Derived 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.
+%% --------------------
+
+'Address'(encode, zero) ->
+ <<0:48>>;
+
+'Address'(decode, <<1:16, B/binary>>)
+ when size(B) == 4 ->
+ list_to_tuple(binary_to_list(B));
+
+'Address'(decode, <<2:16, B/binary>>)
+ when size(B) == 16 ->
+ list_to_tuple(v6dec(B, []));
+
+'Address'(decode, <<A:16, _/binary>> = B)
+ when 1 == A;
+ 2 == A ->
+ ?INVALID_LENGTH(B);
+
+'Address'(encode, T) ->
+ ipenc(diameter_lib:ipaddr(T)).
+
+ipenc(T)
+ when is_tuple(T), size(T) == 4 ->
+ B = list_to_binary(tuple_to_list(T)),
+ <<1:16, B/binary>>;
+
+ipenc(T)
+ when is_tuple(T), size(T) == 8 ->
+ B = v6enc(lists:reverse(tuple_to_list(T)), <<>>),
+ <<2:16, B/binary>>.
+
+v6dec(<<N:16, B/binary>>, Acc) ->
+ v6dec(B, [N | Acc]);
+
+v6dec(<<>>, Acc) ->
+ lists:reverse(Acc).
+
+v6enc([N | Rest], B)
+ when ?UINT(16,N) ->
+ v6enc(Rest, <<N:16, B/binary>>);
+
+v6enc([], B) ->
+ B.
+
+%% --------------------
+
+%% A DiameterIdentity is a FQDN as definined in RFC 1035, which is at
+%% least one character.
+
+'DiameterIdentity'(encode = M, zero) ->
+ 'OctetString'(M, [0]);
+
+'DiameterIdentity'(encode = M, X) ->
+ <<_,_/binary>> = 'OctetString'(M, X);
+
+'DiameterIdentity'(decode = M, <<_,_/binary>> = X) ->
+ 'OctetString'(M, X).
+
+%% --------------------
+
+'DiameterURI'(decode, Bin)
+ when is_binary(Bin) ->
+ scan_uri(Bin);
+
+%% The minimal DiameterURI is "aaa://x", 7 characters.
+'DiameterURI'(encode = M, zero) ->
+ 'OctetString'(M, lists:duplicate(0,7));
+
+'DiameterURI'(encode, #diameter_uri{type = Type,
+ fqdn = D,
+ port = P,
+ transport = T,
+ protocol = Prot}
+ = U) ->
+ S = lists:append([atom_to_list(Type), "://", D,
+ ":", integer_to_list(P),
+ ";transport=", atom_to_list(T),
+ ";protocol=", atom_to_list(Prot)]),
+ U = scan_uri(S), %% assert
+ list_to_binary(S);
+
+'DiameterURI'(encode, Str) ->
+ Bin = iolist_to_binary(Str),
+ #diameter_uri{} = scan_uri(Bin), %% type check
+ Bin.
+
+%% --------------------
+
+%% This minimal rule is "deny in 0 from 0.0.0.0 to 0.0.0.0", 33 characters.
+'IPFilterRule'(encode = M, zero) ->
+ 'OctetString'(M, lists:duplicate(0,33));
+
+%% TODO: parse grammar.
+'IPFilterRule'(M, X) ->
+ 'OctetString'(M, X).
+
+%% --------------------
+
+%% This minimal rule is the same as for an IPFilterRule.
+'QoSFilterRule'(encode = M, zero = X) ->
+ 'IPFilterRule'(M, X);
+
+%% TODO: parse grammar.
+'QoSFilterRule'(M, X) ->
+ 'OctetString'(M, X).
+
+%% --------------------
+
+'UTF8String'(decode, Bin) ->
+ udec(Bin, []);
+
+'UTF8String'(encode = M, zero) ->
+ 'UTF8String'(M, []);
+
+'UTF8String'(encode, S) ->
+ uenc(S, []).
+
+udec(<<>>, Acc) ->
+ lists:reverse(Acc);
+
+udec(<<C/utf8, Rest/binary>>, Acc) ->
+ udec(Rest, [C | Acc]).
+
+uenc(E, Acc)
+ when E == [];
+ E == <<>> ->
+ list_to_binary(lists:reverse(Acc));
+
+uenc(<<C/utf8, Rest/binary>>, Acc) ->
+ uenc(Rest, [<<C/utf8>> | Acc]);
+
+uenc([[] | Rest], Acc) ->
+ uenc(Rest, Acc);
+
+uenc([[H|T] | Rest], Acc) ->
+ uenc([H, T | Rest], Acc);
+
+uenc([C | Rest], Acc) ->
+ uenc(Rest, [<<C/utf8>> | Acc]).
+
+%% --------------------
+
+%% RFC 3588, 4.3:
+%%
+%% Time
+%% The Time format is derived from the OctetString AVP Base 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 [SNTP].
+%%
+%% 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 [SNTP] describes a procedure to extend the time to 2104.
+%% This procedure MUST be supported by all DIAMETER nodes.
+
+%% RFC 2030, 3:
+%%
+%% As the NTP timestamp format has been in use for the last 17 years,
+%% it remains a possibility that it will be in use 40 years from now
+%% when the seconds field overflows. As it is probably inappropriate
+%% to archive NTP timestamps before bit 0 was set in 1968, a
+%% convenient way to extend the useful life of NTP timestamps is the
+%% following convention: If bit 0 is set, the UTC time is in the
+%% range 1968-2036 and UTC time is reckoned from 0h 0m 0s UTC on 1
+%% January 1900. If bit 0 is not set, the time is in the range 2036-
+%% 2104 and UTC time is reckoned from 6h 28m 16s UTC on 7 February
+%% 2036. Note that when calculating the correspondence, 2000 is not a
+%% leap year. Note also that leap seconds are not counted in the
+%% reckoning.
+%%
+%% The statement regarding year 2000 is wrong: errata id 518 at
+%% http://www.rfc-editor.org/errata_search.php?rfc=2030 notes this.
+
+-define(TIME_1900, 59958230400). %% {{1900,1,1},{0,0,0}}
+-define(TIME_2036, 64253197696). %% {{2036,2,7},{6,28,16}}
+%% TIME_2036 = TIME_1900 + (1 bsl 32)
+
+%% Time maps [0, 1 bsl 31) onto [TIME_1900 + 1 bsl 31, TIME_2036 + 1 bsl 31)
+%% by taking integers with the high-order bit set relative to TIME_1900
+%% and those without relative to TIME_2036. This corresponds to the
+%% following dates.
+-define(TIME_MIN, {{1968,1,20},{3,14,8}}). %% TIME_1900 + 1 bsl 31
+-define(TIME_MAX, {{2104,2,26},{9,42,24}}). %% TIME_2036 + 1 bsl 31
+
+'Time'(decode, <<Time:32>>) ->
+ Offset = msb(1 == Time bsr 31),
+ calendar:gregorian_seconds_to_datetime(Time + Offset);
+
+'Time'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
+'Time'(encode, {{_Y,_M,_D},{_HH,_MM,_SS}} = Datetime)
+ when ?TIME_MIN =< Datetime, Datetime < ?TIME_MAX ->
+ S = calendar:datetime_to_gregorian_seconds(Datetime),
+ T = S - msb(S < ?TIME_2036),
+ 0 = T bsr 32, %% sanity check
+ <<T:32>>;
+
+'Time'(encode, zero) ->
+ <<0:32>>.
+
+%% ===========================================================================
+%% ===========================================================================
+
+choose(0, X, _) -> X;
+choose(1, _, X) -> X.
+
+msb(true) -> ?TIME_1900;
+msb(false) -> ?TIME_2036.
+
+%% RFC 3588, 4.3:
+%%
+%% The DiameterURI MUST follow the Uniform Resource Identifiers (URI)
+%% syntax [URI] rules specified below:
+%%
+%% "aaa://" FQDN [ port ] [ transport ] [ protocol ]
+%%
+%% ; No transport security
+%%
+%% "aaas://" FQDN [ port ] [ transport ] [ protocol ]
+%%
+%% ; Transport security used
+%%
+%% FQDN = Fully Qualified Host Name
+%%
+%% port = ":" 1*DIGIT
+%%
+%% ; One of the ports used to listen for
+%% ; incoming connections.
+%% ; If absent,
+%% ; the default Diameter port (3868) is
+%% ; assumed.
+%%
+%% transport = ";transport=" transport-protocol
+%%
+%% ; One of the transports used to listen
+%% ; for incoming connections. If absent,
+%% ; the default SCTP [SCTP] protocol is
+%% ; assumed. UDP MUST NOT be used when
+%% ; the aaa-protocol field is set to
+%% ; diameter.
+%%
+%% transport-protocol = ( "tcp" / "sctp" / "udp" )
+%%
+%% protocol = ";protocol=" aaa-protocol
+%%
+%% ; If absent, the default AAA protocol
+%% ; is diameter.
+%%
+%% aaa-protocol = ( "diameter" / "radius" / "tacacs+" )
+
+scan_uri(Bin)
+ when is_binary(Bin) ->
+ scan_uri(binary_to_list(Bin));
+scan_uri("aaa://" ++ Rest) ->
+ scan_fqdn(Rest, #diameter_uri{type = aaa});
+scan_uri("aaas://" ++ Rest) ->
+ scan_fqdn(Rest, #diameter_uri{type = aaas}).
+
+scan_fqdn(S, U) ->
+ {[_|_] = F, Rest} = lists:splitwith(fun is_fqdn/1, S),
+ scan_opt_port(Rest, U#diameter_uri{fqdn = F}).
+
+scan_opt_port(":" ++ S, U) ->
+ {[_|_] = P, Rest} = lists:splitwith(fun is_digit/1, S),
+ scan_opt_transport(Rest, U#diameter_uri{port = list_to_integer(P)});
+scan_opt_port(S, U) ->
+ scan_opt_transport(S, U).
+
+scan_opt_transport(";transport=" ++ S, U) ->
+ {P, Rest} = transport(S),
+ scan_opt_protocol(Rest, U#diameter_uri{transport = P});
+scan_opt_transport(S, U) ->
+ scan_opt_protocol(S, U).
+
+scan_opt_protocol(";protocol=" ++ S, U) ->
+ {P, ""} = protocol(S),
+ U#diameter_uri{protocol = P};
+scan_opt_protocol("", U) ->
+ U.
+
+transport("tcp" ++ S) ->
+ {tcp, S};
+transport("sctp" ++ S) ->
+ {sctp, S};
+transport("udp" ++ S) ->
+ {udp, S}.
+
+protocol("diameter" ++ S) ->
+ {diameter, S};
+protocol("radius" ++ S) ->
+ {radius, S};
+protocol("tacacs+" ++ S) ->
+ {'tacacs+', S}.
+
+is_fqdn(C) ->
+ is_digit(C) orelse is_alpha(C) orelse C == $. orelse C == $-.
+
+is_alpha(C) ->
+ ($a =< C andalso C =< $z) orelse ($A =< C andalso C =< $Z).
+
+is_digit(C) ->
+ $0 =< C andalso C =< $9.
diff --git a/lib/diameter/src/app/diameter_types.hrl b/lib/diameter/src/app/diameter_types.hrl
new file mode 100644
index 0000000000..02bf8a74dd
--- /dev/null
+++ b/lib/diameter/src/app/diameter_types.hrl
@@ -0,0 +1,139 @@
+%%
+%% %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/diameter_watchdog.erl b/lib/diameter/src/app/diameter_watchdog.erl
new file mode 100644
index 0000000000..b7c1491f4b
--- /dev/null
+++ b/lib/diameter/src/app/diameter_watchdog.erl
@@ -0,0 +1,571 @@
+%%
+%% %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 state machine documented
+%% in Appendix A of RFC 3539.
+%%
+
+-module(diameter_watchdog).
+-behaviour(gen_server).
+
+%% towards diameter_service
+-export([start/2]).
+
+%% gen_server callbacks
+-export([init/1,
+ handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+ terminate/2,
+ code_change/3]).
+
+%% diameter_watchdog_sup callback
+-export([start_link/1]).
+
+-include_lib("diameter/include/diameter.hrl").
+-include("diameter_internal.hrl").
+
+-define(DEFAULT_TW_INIT, 30000). %% RFC 3539 ch 3.4.1
+
+-record(watchdog,
+ {%% PCB - Peer Control Block; see RFC 3539, Appendix A
+ status = initial :: initial | okay | suspect | down | reopen,
+ pending = false :: boolean(),
+ 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(),
+ tref :: reference(), %% reference for current watchdog timer
+ message_data}). %% term passed into diameter_service with message
+
+%% start/2
+
+start({_,_} = Type, T) ->
+ {ok, Pid} = diameter_watchdog_sup:start_child({Type, self(), T}),
+ 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({T, Pid, {ConnT, Opts, SvcName, #diameter_service{applications = Apps,
+ capabilities = Caps}
+ = Svc}}) ->
+ {M,S,U} = now(),
+ random:seed(M,S,U),
+ 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)),
+ tw = proplists:get_value(watchdog_timer,
+ Opts,
+ ?DEFAULT_TW_INIT),
+ message_data = {ConnT, SvcName, Apps}}.
+
+%% handle_call/3
+
+handle_call(_, _, State) ->
+ {reply, nok, State}.
+
+%% handle_cast/2
+
+handle_cast(_, State) ->
+ {noreply, State}.
+
+%% handle_info/2
+
+handle_info(T, State) ->
+ case transition(T, State) of
+ ok ->
+ {noreply, State};
+ #watchdog{status = X} = S ->
+ ?LOGC(X =/= State#watchdog.status, transition, X),
+ {noreply, S};
+ stop ->
+ ?LOG(stop, T),
+ {stop, {shutdown, T}, State}
+ end.
+
+%% terminate/2
+
+terminate(_, _) ->
+ ok.
+
+%% code_change/3
+
+code_change(_, State, _) ->
+ {ok, State}.
+
+%% ===========================================================================
+%% ===========================================================================
+
+%% transition/2
+%%
+%% The state transitions documented here are extracted from RFC 3539,
+%% the commentary is ours.
+
+%% Service or watchdog is telling the watchdog of an accepting
+%% transport to die after reconnect_timer expiry or reestablished
+%% connection (in another transport process) respectively.
+transition(close, #watchdog{status = down}) ->
+ {{accept, _}, _, _} = getr(restart), %% assert
+ stop;
+transition(close, #watchdog{}) ->
+ ok;
+
+%% Service is asking for the peer to be taken down gracefully.
+transition({shutdown, Pid}, #watchdog{parent = Pid,
+ transport = undefined,
+ status = S}) ->
+ down = S, %% sanity check
+ stop;
+transition({shutdown = T, Pid}, #watchdog{parent = Pid,
+ transport = TPid}) ->
+ TPid ! {T, self()},
+ ok;
+
+%% Parent process has died,
+transition({'DOWN', _, process, Pid, _Reason},
+ #watchdog{parent = Pid}) ->
+ stop;
+
+%% Transport has accepted a connection.
+transition({accepted = T, TPid}, #watchdog{transport = TPid,
+ parent = Pid}) ->
+ Pid ! {T, self(), TPid},
+ ok;
+
+%% Transport is telling us that its impending death isn't failure.
+transition({close, TPid, _Reason}, #watchdog{transport = TPid}) ->
+ stop;
+
+%% STATE Event Actions New State
+%% ===== ------ ------- ----------
+%% INITIAL Connection up SetWatchdog() OKAY
+
+%% By construction, the watchdog timer isn't set until we move into
+%% 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.
+
+transition({open, TPid, Hosts, T} = Open,
+ #watchdog{transport = TPid,
+ status = initial,
+ parent = Pid}
+ = S) ->
+ case okay(getr(restart), Hosts) of
+ okay ->
+ open(Pid, {TPid, T}),
+ set_watchdog(S#watchdog{status = okay});
+ reopen ->
+ transition(Open, S#watchdog{status = down})
+ end;
+
+%% DOWN Connection up NumDWA = 0
+%% SendWatchdog()
+%% SetWatchdog()
+%% Pending = TRUE REOPEN
+
+transition({open = P, TPid, _Hosts, T},
+ #watchdog{transport = TPid,
+ 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).
+ putr(P, {TPid, T}),
+ set_watchdog(send_watchdog(S#watchdog{status = reopen,
+ num_dwa = 0}));
+
+%% OKAY Connection down CloseConnection()
+%% Failover()
+%% SetWatchdog() DOWN
+%% SUSPECT Connection down CloseConnection()
+%% SetWatchdog() DOWN
+%% REOPEN Connection down CloseConnection()
+%% SetWatchdog() DOWN
+
+transition({'DOWN', _, process, TPid, _},
+ #watchdog{transport = TPid,
+ status = initial}) ->
+ stop;
+
+transition({'DOWN', _, process, Pid, _},
+ #watchdog{transport = Pid}
+ = S) ->
+ failover(S),
+ close(S),
+ set_watchdog(S#watchdog{status = down,
+ pending = false,
+ transport = undefined});
+%% Any outstanding pending (or other messages from the transport) will
+%% have arrived before 'DOWN' since the message comes from the same
+%% process. Note that we could also get this message in the initial
+%% state.
+
+%% Incoming message.
+transition({recv, TPid, Name, Pkt}, #watchdog{transport = TPid} = S) ->
+ recv(Name, Pkt, S);
+
+%% Current watchdog has timed out.
+transition({timeout, TRef, tw}, #watchdog{tref = TRef} = S) ->
+ set_watchdog(timeout(S));
+
+%% Timer was canceled after message was already sent.
+transition({timeout, _, tw}, #watchdog{}) ->
+ ok;
+
+%% State query.
+transition({state, Pid}, #watchdog{status = S}) ->
+ Pid ! {self(), S},
+ ok.
+
+%% ===========================================================================
+
+monitor(Pid) ->
+ erlang:monitor(process, Pid),
+ Pid.
+
+putr(Key, Val) ->
+ put({?MODULE, Key}, Val).
+
+getr(Key) ->
+ get({?MODULE, Key}).
+
+eraser(Key) ->
+ erase({?MODULE, Key}).
+
+%% encode/1
+
+encode(Msg) ->
+ #diameter_packet{bin = Bin} = diameter_codec:encode(?BASE, Msg),
+ Bin.
+
+%% okay/2
+
+okay({{accept, Ref}, _, _}, Hosts) ->
+ T = {?MODULE, connection, Ref, Hosts},
+ diameter_reg:add(T),
+ okay(diameter_reg:match(T));
+%% 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.)
+
+okay({{connect, _}, _, _}, _) ->
+ okay.
+
+%% The peer hasn't been connected recently ...
+okay([{_,P}]) ->
+ P = self(), %% assert
+ okay;
+
+%% ... or it has.
+okay(C) ->
+ [_|_] = [P ! close || {_,P} <- C, self() /= P],
+ reopen.
+
+%% set_watchdog/1
+
+set_watchdog(#watchdog{tw = TwInit,
+ tref = TRef}
+ = S) ->
+ cancel(TRef),
+ S#watchdog{tref = erlang:start_timer(tw(TwInit), self(), tw)}.
+
+cancel(undefined) ->
+ ok;
+cancel(TRef) ->
+ erlang:cancel_timer(TRef).
+
+tw(T)
+ when is_integer(T), T >= 6000 ->
+ T - 2000 + (random:uniform(4001) - 1); %% RFC3539 jitter of +/- 2 sec.
+tw({M,F,A}) ->
+ apply(M,F,A).
+
+%% open/2
+
+open(Pid, {_,_} = T) ->
+ Pid ! {connection_up, self(), T}.
+
+%% failover/1
+
+failover(#watchdog{status = okay,
+ parent = Pid}) ->
+ Pid ! {connection_down, self()};
+
+failover(_) ->
+ ok.
+
+%% close/1
+
+close(#watchdog{status = down}) ->
+ ok;
+
+close(#watchdog{parent = Pid}) ->
+ {{T, _}, _, _} = getr(restart),
+ T == accept andalso (Pid ! {close, self()}).
+
+%% send_watchdog/1
+
+send_watchdog(#watchdog{pending = false,
+ transport = TPid}
+ = S) ->
+ TPid ! {send, encode(getr(dwr))},
+ ?LOG(send, 'DWR'),
+ S#watchdog{pending = true}.
+
+%% recv/3
+
+recv(Name, Pkt, S) ->
+ try rcv(Name, S) of
+ #watchdog{} = NS ->
+ rcv(Name, Pkt, S),
+ NS
+ catch
+ throw: {?MODULE, throwaway, #watchdog{} = NS} ->
+ NS
+ end.
+
+%% rcv/3
+
+rcv(N, _, _)
+ when N == 'CER';
+ N == 'CEA';
+ N == 'DWR';
+ N == 'DWA';
+ N == 'DPR';
+ N == 'DPA' ->
+ false;
+
+rcv(_, Pkt, #watchdog{transport = TPid,
+ message_data = T}) ->
+ diameter_service:receive_message(TPid, Pkt, T).
+
+throwaway(S) ->
+ throw({?MODULE, throwaway, S}).
+
+%% rcv/2
+
+%% INITIAL Receive DWA Pending = FALSE
+%% Throwaway() INITIAL
+%% INITIAL Receive non-DWA Throwaway() INITIAL
+
+rcv('DWA', #watchdog{status = initial} = S) ->
+ throwaway(S#watchdog{pending = false});
+
+rcv(_, #watchdog{status = initial} = S) ->
+ throwaway(S);
+
+%% DOWN Receive DWA Pending = FALSE
+%% Throwaway() DOWN
+%% DOWN Receive non-DWA Throwaway() DOWN
+
+rcv('DWA', #watchdog{status = down} = S) ->
+ throwaway(S#watchdog{pending = false});
+
+rcv(_, #watchdog{status = down} = S) ->
+ throwaway(S);
+
+%% OKAY Receive DWA Pending = FALSE
+%% SetWatchdog() OKAY
+%% OKAY Receive non-DWA SetWatchdog() OKAY
+
+rcv('DWA', #watchdog{status = okay} = S) ->
+ set_watchdog(S#watchdog{pending = false});
+
+rcv(_, #watchdog{status = okay} = S) ->
+ set_watchdog(S);
+
+%% SUSPECT Receive DWA Pending = FALSE
+%% Failback()
+%% SetWatchdog() OKAY
+%% SUSPECT Receive non-DWA Failback()
+%% SetWatchdog() OKAY
+
+rcv('DWA', #watchdog{status = suspect} = S) ->
+ failback(S),
+ set_watchdog(S#watchdog{status = okay,
+ pending = false});
+
+rcv(_, #watchdog{status = suspect} = S) ->
+ failback(S),
+ set_watchdog(S#watchdog{status = okay});
+
+%% REOPEN Receive DWA & Pending = FALSE
+%% NumDWA == 2 NumDWA++
+%% Failback() OKAY
+
+rcv('DWA', #watchdog{status = reopen,
+ num_dwa = 2 = N,
+ parent = Pid}
+ = S) ->
+ open(Pid, eraser(open)),
+ S#watchdog{status = okay,
+ num_dwa = N+1,
+ pending = false};
+
+%% REOPEN Receive DWA & Pending = FALSE
+%% NumDWA < 2 NumDWA++ REOPEN
+
+rcv('DWA', #watchdog{status = reopen,
+ num_dwa = N}
+ = S) ->
+ S#watchdog{num_dwa = N+1,
+ pending = false};
+
+%% REOPEN Receive non-DWA Throwaway() REOPEN
+
+rcv(_, #watchdog{status = reopen} = S) ->
+ throwaway(S).
+
+%% failback/1
+
+failback(#watchdog{parent = Pid}) ->
+ Pid ! {connection_up, self()}.
+
+%% timeout/1
+%%
+%% The caller sets the watchdog on the return value.
+
+%% OKAY Timer expires & SendWatchdog()
+%% !Pending SetWatchdog()
+%% Pending = TRUE OKAY
+%% REOPEN Timer expires & SendWatchdog()
+%% !Pending SetWatchdog()
+%% Pending = TRUE REOPEN
+
+timeout(#watchdog{status = T,
+ pending = false}
+ = S)
+ when T == okay;
+ T == reopen ->
+ send_watchdog(S);
+
+%% OKAY Timer expires & Failover()
+%% Pending SetWatchdog() SUSPECT
+
+timeout(#watchdog{status = okay,
+ pending = true}
+ = S) ->
+ failover(S),
+ S#watchdog{status = suspect};
+
+%% SUSPECT Timer expires CloseConnection()
+%% SetWatchdog() DOWN
+%% REOPEN Timer expires & CloseConnection()
+%% Pending & SetWatchdog()
+%% NumDWA < 0 DOWN
+
+timeout(#watchdog{status = T,
+ pending = P,
+ num_dwa = N,
+ transport = TPid}
+ = S)
+ when T == suspect;
+ T == reopen, P, N < 0 ->
+ exit(TPid, shutdown),
+ close(S),
+ S#watchdog{status = down};
+
+%% REOPEN Timer expires & NumDWA = -1
+%% Pending & SetWatchdog()
+%% NumDWA >= 0 REOPEN
+
+timeout(#watchdog{status = reopen,
+ pending = true,
+ num_dwa = N}
+ = S)
+ when 0 =< N ->
+ S#watchdog{num_dwa = -1};
+
+%% DOWN Timer expires AttemptOpen()
+%% SetWatchdog() DOWN
+%% INITIAL Timer expires AttemptOpen()
+%% SetWatchdog() INITIAL
+
+%% RFC 3539, 3.4.1:
+%%
+%% [5] While the connection is in the closed state, the AAA client MUST
+%% NOT attempt to send further watchdog messages on the connection.
+%% However, after the connection is closed, the AAA client continues
+%% to periodically attempt to reopen the connection.
+%%
+%% The AAA client SHOULD wait for the transport layer to report
+%% connection failure before attempting again, but MAY choose to
+%% bound this wait time by the watchdog interval, Tw.
+
+%% Don't bound, restarting the peer process only when the previous
+%% process has died. We only need to handle state down since we start
+%% the first watchdog when transitioning out of initial.
+
+timeout(#watchdog{status = down} = S) ->
+ restart(S).
+
+%% restart/1
+
+restart(#watchdog{transport = undefined} = S) ->
+ restart(getr(restart), S);
+restart(S) ->
+ S.
+
+%% 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) ->
+ Pid ! {reconnect, self()},
+ S#watchdog{transport = monitor(diameter_peer_fsm:start(T, Opts, Svc))};
+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.
+
+%% dwr/1
+
+dwr(#diameter_caps{origin_host = OH,
+ origin_realm = OR,
+ origin_state_id = OSI}) ->
+ ['DWR', {'Origin-Host', OH},
+ {'Origin-Realm', OR},
+ {'Origin-State-Id', OSI}].
diff --git a/lib/diameter/src/app/diameter_watchdog_sup.erl b/lib/diameter/src/app/diameter_watchdog_sup.erl
new file mode 100644
index 0000000000..fc837fe4ef
--- /dev/null
+++ b/lib/diameter/src/app/diameter_watchdog_sup.erl
@@ -0,0 +1,60 @@
+%%
+%% %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%
+%%
+
+%%
+%% Supervisor for all watchdog processes.
+%%
+
+-module(diameter_watchdog_sup).
+
+-behaviour(supervisor).
+
+%% interface
+-export([start_link/0, %% supervisor start
+ start_child/1]). %% watchdog start
+
+-export([init/1]).
+
+-define(NAME, ?MODULE). %% supervisor name
+
+%% start_link/0
+
+start_link() ->
+ SupName = {local, ?NAME},
+ supervisor:start_link(SupName, ?MODULE, []).
+
+%% start_child/1
+%%
+%% Start a watchdog process.
+
+start_child(T) ->
+ supervisor:start_child(?NAME, [T]).
+
+%% init/1
+
+init([]) ->
+ Mod = diameter_watchdog,
+ Flags = {simple_one_for_one, 0, 1},
+ ChildSpec = {Mod,
+ {Mod, start_link, []},
+ temporary,
+ 1000,
+ worker,
+ [Mod]},
+ {ok, {Flags, [ChildSpec]}}.
diff --git a/lib/diameter/src/app/modules.mk b/lib/diameter/src/app/modules.mk
new file mode 100644
index 0000000000..a7a78b1a9d
--- /dev/null
+++ b/lib/diameter/src/app/modules.mk
@@ -0,0 +1,68 @@
+#-*-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
+
+MODULES = \
+ diameter \
+ diameter_app \
+ diameter_callback \
+ diameter_capx \
+ diameter_config \
+ diameter_dbg \
+ diameter_codec \
+ diameter_dict \
+ diameter_exprecs \
+ diameter_info \
+ 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
+
+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/compiler/.gitignore b/lib/diameter/src/compiler/.gitignore
new file mode 100644
index 0000000000..d9f072e262
--- /dev/null
+++ b/lib/diameter/src/compiler/.gitignore
@@ -0,0 +1,3 @@
+
+/depend.mk
+
diff --git a/lib/diameter/src/compiler/Makefile b/lib/diameter/src/compiler/Makefile
new file mode 100644
index 0000000000..8512eb515a
--- /dev/null
+++ b/lib/diameter/src/compiler/Makefile
@@ -0,0 +1,141 @@
+#
+# %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 "/%COMPILER_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
+ $(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) modules.mk 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
new file mode 100644
index 0000000000..213ba0d22c
--- /dev/null
+++ b/lib/diameter/src/compiler/diameter_codegen.erl
@@ -0,0 +1,788 @@
+%%
+%% %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_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.)
+%%
+
+-export([from_spec/4]).
+
+%% Internal exports (for test).
+-export([file/1,
+ file/2,
+ file/3]).
+
+-include_lib("diameter/src/app/diameter_internal.hrl").
+-include("diameter_forms.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)})])]}).
+
+
+from_spec(File, Spec, Opts, Mode) ->
+ Outdir = proplists:get_value(outdir, Opts, "."),
+ putr(verbose, lists:member(verbose, Opts)),
+ putr(debug, lists:member(debug, Opts)),
+ codegen(File, Spec, Outdir, Mode).
+
+%% Optional reports when running verbosely.
+report(What, Data) ->
+ report(getr(verbose), What, Data),
+ Data.
+
+report(true, Tag, Data) ->
+ io:format(">>~n>> ~p ~p~n", [Tag, Data]);
+report(false, _, _) ->
+ ok.
+
+putr(Key, Value) ->
+ put({?MODULE, Key}, Value).
+
+getr(Key) ->
+ get({?MODULE, Key}).
+
+%% ===========================================================================
+%% ===========================================================================
+
+%% Generate from parsed spec in a file.
+
+file(F) ->
+ file(F, spec).
+
+file(F, Mode) ->
+ file(F, ".", Mode).
+
+file(F, Outdir, Mode) ->
+ {ok, [Spec]} = file:consult(F),
+ from_spec(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.").
+
+w(Path, Spec, Fmt) ->
+ {ok, Fd} = file:open(Path, [write]),
+ io:fwrite(Fd, Fmt ++ "~n", [Spec]),
+ 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),
+ ok.
+
+mod(File, error) ->
+ filename:rootname(filename:basename(File));
+mod(_, {ok, Mod}) ->
+ atom_to_list(Mod).
+
+gen(spec, Spec, _Mod, Path) ->
+ write(Path ++ ".spec", 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, export, [{name, 0},
+ {id, 0},
+ {vendor_id, 0},
+ {vendor_name, 0},
+ {decode_avps, 2}, %% in diameter_gen.hrl
+ {encode_avps, 2}, %%
+ {msg_name, 2},
+ {msg_header, 1},
+ {rec2msg, 1},
+ {msg2rec, 1},
+ {name2rec, 1},
+ {avp_name, 2},
+ {avp_arity, 2},
+ {avp_header, 1},
+ {avp, 3},
+ {grouped_avp, 3},
+ {enumerated_avp, 3},
+ {empty_value, 1},
+ {dict, 0}]},
+ %% diameter.hrl is included for #diameter_avp
+ {?attribute, include_lib, "diameter/include/diameter.hrl"},
+ {?attribute, include_lib, "diameter/include/diameter_gen.hrl"},
+ f_name(Mod),
+ f_id(Spec),
+ f_vendor_id(Spec),
+ f_vendor_name(Spec),
+ f_msg_name(Spec),
+ f_msg_header(Spec),
+ f_rec2msg(Spec),
+ f_msg2rec(Spec),
+ f_name2rec(Spec),
+ f_avp_name(Spec),
+ f_avp_arity(Spec),
+ f_avp_header(Spec),
+ f_avp(Spec),
+ f_enumerated_avp(Spec),
+ f_empty_value(Spec),
+ f_dict(Spec),
+ {eof, ?LINE}],
+
+ gen_erl(Path, insert_hrl_forms(Spec, Forms)).
+
+gen_erl(Path, Forms) ->
+ getr(debug) andalso write(Path ++ ".forms", Forms),
+ write(Path ++ ".erl",
+ header() ++ erl_prettypr:format(erl_syntax:form_list(Forms))).
+
+insert_hrl_forms(Spec, Forms) ->
+ {H,T} = lists:splitwith(fun is_header/1, Forms),
+ H ++ make_hrl_forms(Spec) ++ T.
+
+is_header({attribute, _, export, _}) ->
+ false;
+is_header(_) ->
+ true.
+
+make_hrl_forms(Spec) ->
+ {_Prefix, MsgRecs, GrpRecs, ImportedGrpRecs}
+ = make_record_forms(Spec),
+
+ RecordForms = MsgRecs ++ GrpRecs ++ lists:flatmap(fun({_,Fs}) -> Fs end,
+ ImportedGrpRecs),
+
+ RecNames = lists:map(fun({attribute,_,record,{N,_}}) -> N end,
+ RecordForms),
+
+ %% export_records is used by the diameter_exprecs parse transform.
+ [{?attribute, export_records, RecNames} | RecordForms].
+
+make_record_forms(Spec) ->
+ Prefix = prefix(Spec),
+
+ MsgRecs = a_record(Prefix, fun msg_proj/1, get_value(messages, Spec)),
+ GrpRecs = a_record(Prefix, fun grp_proj/1, get_value(grouped, Spec)),
+
+ ImportedGrpRecs = [{M, a_record(Prefix, fun grp_proj/1, Gs)}
+ || {M,Gs} <- get_value(import_groups, Spec)],
+
+ {Prefix, MsgRecs, GrpRecs, ImportedGrpRecs}.
+
+msg_proj({Name, _, _, _, Avps}) ->
+ {Name, Avps}.
+
+grp_proj({Name, _, _, Avps}) ->
+ {Name, Avps}.
+
+%% a_record/3
+
+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)),
+ 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)};
+ true ->
+ {?record_field, ?ATOM(Name), ?NIL}
+ end.
+
+%%% ------------------------------------------------------------------------
+%%% # name/0
+%%% ------------------------------------------------------------------------
+
+f_name(Name) ->
+ {?function, name, 0,
+ [{?clause, [], [], [?ATOM(Name)]}]}.
+
+%%% ------------------------------------------------------------------------
+%%% # id/0
+%%% ------------------------------------------------------------------------
+
+f_id(Spec) ->
+ Id = orddict:fetch(id, Spec),
+ {?function, id, 0,
+ [{?clause, [], [], [?INTEGER(Id)]}]}.
+
+%%% ------------------------------------------------------------------------
+%%% # vendor_id/0
+%%% ------------------------------------------------------------------------
+
+f_vendor_id(Spec) ->
+ {Id, _} = orddict:fetch(vendor, Spec),
+ {?function, vendor_id, 0,
+ [{?clause, [], [], [?INTEGER(Id)]}]}.
+
+%%% ------------------------------------------------------------------------
+%%% # vendor_name/0
+%%% ------------------------------------------------------------------------
+
+f_vendor_name(Spec) ->
+ {_, Name} = orddict:fetch(vendor, Spec),
+ {?function, vendor_name, 0,
+ [{?clause, [], [], [?ATOM(Name)]}]}.
+
+%%% ------------------------------------------------------------------------
+%%% # msg_name/1
+%%% ------------------------------------------------------------------------
+
+f_msg_name(Spec) ->
+ {?function, msg_name, 2, msg_name(Spec)}.
+
+%% Return the empty name for any unknown command to which
+%% DIAMETER_COMMAND_UNSUPPORTED should be replied.
+
+msg_name(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))]},
+ {?clause, [?INTEGER(Code), ?ATOM(false)],
+ [],
+ [?ATOM(mname(Ans))]}].
+
+mname({N, _Abbr}) ->
+ N;
+mname(N) ->
+ N.
+
+%%% ------------------------------------------------------------------------
+%%% # msg2rec/1
+%%% ------------------------------------------------------------------------
+
+f_msg2rec(Spec) ->
+ {?function, msg2rec, 1, 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.
+
+c_msg2rec({N,A}, Pre) ->
+ [c_name2rec(N, N, Pre), c_name2rec(A, N, Pre)];
+c_msg2rec(N, Pre) ->
+ [c_name2rec(N, N, Pre)].
+
+%%% ------------------------------------------------------------------------
+%%% # rec2msg/1
+%%% ------------------------------------------------------------------------
+
+f_rec2msg(Spec) ->
+ {?function, rec2msg, 1, rec2msg(Spec)}.
+
+rec2msg(Spec) ->
+ Pre = prefix(Spec),
+ lists:map(fun(T) -> c_rec2msg(T, Pre) end, get_value(messages, Spec))
+ ++ [?UNEXPECTED(1)].
+
+c_rec2msg({N,_,_,_,_}, Pre) ->
+ {?clause, [?ATOM(rec_name(N, Pre))], [], [?ATOM(N)]}.
+
+%%% ------------------------------------------------------------------------
+%%% # name2rec/1
+%%% ------------------------------------------------------------------------
+
+f_name2rec(Spec) ->
+ {?function, name2rec, 1, name2rec(Spec)}.
+
+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)
+ ++ [{?clause, [?VAR('T')], [], [?CALL(msg2rec, [?VAR('T')])]}].
+
+c_name2rec(Name, Rname, Pre) ->
+ {?clause, [?ATOM(Name)], [], [?ATOM(rec_name(Rname, Pre))]}.
+
+avps({_Mod, Avps}) ->
+ Avps.
+
+%%% ------------------------------------------------------------------------
+%%% # avp_name/1
+%%% ------------------------------------------------------------------------
+
+f_avp_name(Spec) ->
+ {?function, avp_name, 2, avp_name(Spec)}.
+
+%% 3588, 4.1:
+%%
+%% AVP Code
+%% The AVP Code, combined with the Vendor-Id field, identifies the
+%% attribute uniquely. AVP numbers 1 through 255 are reserved for
+%% backward compatibility with RADIUS, without setting the Vendor-Id
+%% field. AVP numbers 256 and above are used for Diameter, which are
+%% allocated by IANA (see Section 11.1).
+
+avp_name(Spec) ->
+ Avps = get_value(avp_types, Spec)
+ ++ 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)),
+
+ lists:map(fun(T) -> c_avp_name(T, Vid, Vs) end, Avps)
+ ++ [{?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(T, Code, false, _, undefined = U) ->
+ {?clause, [?INTEGER(Code), ?ATOM(U)],
+ [],
+ [?TERM(T)]};
+
+c_avp_name(T, Code, true, Vid, V)
+ when is_integer(Vid) ->
+ {?clause, [?INTEGER(Code), ?INTEGER(choose(V == undefined, Vid, V))],
+ [],
+ [?TERM(T)]}.
+
+%%% ------------------------------------------------------------------------
+%%% # avp_arity/2
+%%% ------------------------------------------------------------------------
+
+f_avp_arity(Spec) ->
+ {?function, avp_arity, 2, avp_arity(Spec)}.
+
+avp_arity(Spec) ->
+ Msgs = get_value(messages, Spec),
+ Groups = get_value(grouped, Spec)
+ ++ lists:flatmap(fun avps/1, get_value(import_groups, Spec)),
+ c_avp_arity(Msgs ++ Groups)
+ ++ [{?clause, [?VAR('_'), ?VAR('_')], [], [?INTEGER(0)]}].
+
+c_avp_arity(L)
+ when is_list(L) ->
+ lists:flatmap(fun c_avp_arity/1, L);
+
+c_avp_arity({N,_,_,_,As}) ->
+ c_avp_arity(N,As);
+c_avp_arity({N,_,_,As}) ->
+ c_avp_arity(N,As).
+
+c_avp_arity(Name, Avps) ->
+ lists:map(fun(A) -> c_arity(Name, A) end, Avps).
+
+c_arity(Name, Avp) ->
+ {AvpName, Arity} = avp_info(Avp),
+ {?clause, [?ATOM(Name), ?ATOM(AvpName)], [], [?TERM(Arity)]}.
+
+%%% ------------------------------------------------------------------------
+%%% # avp/3
+%%% ------------------------------------------------------------------------
+
+f_avp(Spec) ->
+ {?function, avp, 3, avp(Spec) ++ [?UNEXPECTED(3)]}.
+
+avp(Spec) ->
+ Native = get_value(avp_types, Spec),
+ Custom = get_value(custom_types, Spec),
+ Imported = get_value(import_avps, Spec),
+ avp([{N,T} || {N,_,T,_,_} <- Native], Imported, Custom).
+
+avp(Native, Imported, Custom) ->
+ Dict = orddict:from_list(Native),
+
+ report(native, Dict),
+ report(imported, Imported),
+ report(custom, Custom),
+
+ 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,
+ Native))
+ ++ lists:flatmap(fun c_imported_avp/1, Imported)
+ ++ lists:flatmap(fun(C) -> c_custom_avp(C, Dict) end, Custom).
+
+c_base_avp({AvpName, T}) ->
+ {?clause, [?VAR('T'), ?VAR('Data'), ?ATOM(AvpName)],
+ [],
+ [base_avp(AvpName, T)]}.
+
+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')]);
+
+base_avp(_, Type) ->
+ ?APPLY(diameter_types, Type, [?VAR('T'), ?VAR('Data')]).
+
+c_imported_avp({Mod, Avps}) ->
+ lists:map(fun(A) -> imported_avp(Mod, A) end, Avps).
+
+imported_avp(_Mod, {AvpName, _, 'Grouped' = T, _, _}) ->
+ c_base_avp({AvpName, T});
+
+imported_avp(Mod, {AvpName, _, _, _, _}) ->
+ {?clause, [?VAR('T'), ?VAR('Data'), ?ATOM(AvpName)],
+ [],
+ [?APPLY(Mod, avp, [?VAR('T'),
+ ?VAR('Data'),
+ ?ATOM(AvpName)])]}.
+
+c_custom_avp({Mod, Avps}, Dict) ->
+ lists:map(fun(N) -> custom_avp(Mod, N, orddict:fetch(N, Dict)) end, Avps).
+
+custom_avp(Mod, AvpName, Type) ->
+ {?clause, [?VAR('T'), ?VAR('Data'), ?ATOM(AvpName)],
+ [],
+ [?APPLY(Mod, AvpName, [?VAR('T'), ?ATOM(Type), ?VAR('Data')])]}.
+
+%%% ------------------------------------------------------------------------
+%%% # enumerated_avp/3
+%%% ------------------------------------------------------------------------
+
+f_enumerated_avp(Spec) ->
+ {?function, enumerated_avp, 3, enumerated_avp(Spec) ++ [?UNEXPECTED(3)]}.
+
+enumerated_avp(Spec) ->
+ lists:flatmap(fun c_enumerated_avp/1, get_value(enums, Spec)).
+
+c_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>>)],
+ [],
+ [?TERM(I)]},
+ {?clause, [?ATOM(encode), ?ATOM(AvpName), ?INTEGER(I)],
+ [],
+ [?TERM(<<I:32/integer>>)]}].
+
+%%% ------------------------------------------------------------------------
+%%% msg_header/1
+%%% ------------------------------------------------------------------------
+
+f_msg_header(Spec) ->
+ {?function, msg_header, 1, msg_header(Spec) ++ [?UNEXPECTED(1)]}.
+
+msg_header(Spec) ->
+ ApplId = orddict:fetch(id, Spec),
+
+ lists:map(fun({M,C,F,_,_}) -> c_msg_header(M, C, F, ApplId) end,
+ get_value(messages, Spec)).
+
+%% Note that any application id in the message header spec is ignored.
+
+c_msg_header(Name, Code, Flags, ApplId) ->
+ {?clause, [?ATOM(Name)],
+ [],
+ [?TERM({Code, encode_msg_flags(Flags), ApplId})]}.
+
+encode_msg_flags(Flags) ->
+ lists:foldl(fun emf/2, 0, Flags).
+
+emf('REQ', N) -> N bor 2#10000000;
+emf('PXY', N) -> N bor 2#01000000;
+emf('ERR', N) -> N bor 2#00100000.
+
+%%% ------------------------------------------------------------------------
+%%% # avp_header/1
+%%% ------------------------------------------------------------------------
+
+f_avp_header(Spec) ->
+ {?function, avp_header, 1, avp_header(Spec) ++ [?UNEXPECTED(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)),
+
+ lists:flatmap(fun(A) -> c_avp_header({Vid, Vs}, A) end,
+ Native ++ Imported).
+
+c_avp_header({Vid, Vs}, {Name, Code, _Type, Flags, _Encr}) ->
+ [{?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(Vs, Mod, {Name, _, _, Flags, _}) ->
+ 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.
+
+vid(Name, Flags, Vs, Vid) ->
+ v(lists:member('V', Flags), Name, Vs, Vid).
+
+v(true, Name, Vs, Vid) ->
+ proplists:get_value(Name, Vs, Vid);
+v(false, _, _, _) ->
+ undefined.
+
+%%% ------------------------------------------------------------------------
+%%% # empty_value/0
+%%% ------------------------------------------------------------------------
+
+f_empty_value(Spec) ->
+ {?function, empty_value, 1, empty_value(Spec)}.
+
+empty_value(Spec) ->
+ Groups = get_value(grouped, Spec)
+ ++ lists:flatmap(fun avps/1, get_value(import_groups, Spec)),
+ Enums = get_value(enums, Spec)
+ ++ lists:flatmap(fun avps/1, get_value(import_enums, Spec)),
+ lists:map(fun c_empty_value/1, Groups ++ Enums)
+ ++ [{?clause, [?VAR('Name')], [], [?CALL(empty, [?VAR('Name')])]}].
+
+c_empty_value({Name, _, _, _}) ->
+ {?clause, [?ATOM(Name)],
+ [],
+ [?CALL(empty_group, [?ATOM(Name)])]};
+
+c_empty_value({Name, _}) ->
+ {?clause, [?ATOM(Name)],
+ [],
+ [?TERM(<<0:32/integer>>)]}.
+
+%%% ------------------------------------------------------------------------
+%%% # dict/0
+%%% ------------------------------------------------------------------------
+
+f_dict(Spec) ->
+ {?function, dict, 0,
+ [{?clause, [], [], [?TERM(Spec)]}]}.
+
+%%% ------------------------------------------------------------------------
+%%% # gen_hrl/3
+%%% ------------------------------------------------------------------------
+
+gen_hrl(Path, Mod, Spec) ->
+ {ok, Fd} = file:open(Path, [write]),
+
+ {Prefix, MsgRecs, GrpRecs, ImportedGrpRecs}
+ = make_record_forms(Spec),
+
+ file:write(Fd, hrl_header(Mod)),
+
+ forms("Message records", Fd, MsgRecs),
+ forms("Grouped AVP records", Fd, GrpRecs),
+
+ lists:foreach(fun({M,Fs}) ->
+ forms("Grouped AVP records from " ++ atom_to_list(M),
+ Fd,
+ Fs)
+ end,
+ ImportedGrpRecs),
+
+ PREFIX = to_upper(Prefix),
+
+ write("ENUM Macros",
+ Fd,
+ m_enums(PREFIX, false, get_value(enums, Spec))),
+ write("RESULT CODE Macros",
+ Fd,
+ m_enums(PREFIX, false, get_value(result_codes, Spec))),
+
+ lists:foreach(fun({M,Es}) ->
+ write("ENUM Macros from " ++ atom_to_list(M),
+ Fd,
+ m_enums(PREFIX, true, Es))
+ end,
+ get_value(import_enums, Spec)),
+
+ file:close(Fd).
+
+forms(_, _, []) ->
+ ok;
+forms(Banner, Fd, Forms) ->
+ write(Banner, Fd, prettypr(Forms)).
+
+write(_, _, []) ->
+ ok;
+write(Banner, Fd, Str) ->
+ banner(Fd, Banner),
+ io:fwrite(Fd, "~s~n", [Str]).
+
+prettypr(Forms) ->
+ erl_prettypr:format(erl_syntax:form_list(Forms)).
+
+banner(Fd, Heading) ->
+ file:write(Fd, banner(Heading)).
+
+banner(Heading) ->
+ ("\n\n"
+ "%%% -------------------------------------------------------\n"
+ "%%% " ++ Heading ++ ":\n"
+ "%%% -------------------------------------------------------\n\n").
+
+z(S) ->
+ string:join(string:tokens(S, "\s\t"), "\s").
+
+m_enums(Prefix, Wrap, Enums) ->
+ lists:map(fun(T) -> m_enum(Prefix, Wrap, T) end, 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))), "'"],
+ wrap(B,
+ N,
+ ["-define(", N, ", ", integer_to_list(I), ").\n"])
+ end,
+ Values).
+
+wrap(true, Name, Def) ->
+ ["-ifndef(", Name, ").\n", Def, "-endif.\n"];
+wrap(false, _, Def) ->
+ Def.
+
+to_upper(A) when is_atom(A) ->
+ to_upper(atom_to_list(A));
+to_upper(S) ->
+ lists:map(fun tu/1, S).
+
+tu(C) when C >= $a, C =< $z ->
+ C + $A - $a;
+tu(C) ->
+ C.
+
+header() ->
+ ("%% -------------------------------------------------------------------\n"
+ "%% This is a generated file.\n"
+ "%% -------------------------------------------------------------------\n"
+ "\n"
+ "%%\n"
+ "%% Copyright (c) Ericsson AB. All rights reserved.\n"
+ "%%\n"
+ "%% The information in this document is the property of Ericsson.\n"
+ "%%\n"
+ "%% Except as specifically authorized in writing by Ericsson, the\n"
+ "%% receiver of this document shall keep the information contained\n"
+ "%% herein confidential and shall protect the same in whole or in\n"
+ "%% part from disclosure and dissemination to third parties.\n"
+ "%%\n"
+ "%% Disclosure and disseminations to the receivers employees shall\n"
+ "%% only be made on a strict need to know basis.\n"
+ "%%\n\n").
+
+hrl_header(Name) ->
+ header() ++ "-hrl_name('" ++ Name ++ ".hrl').\n".
+
+%% avp_info/1
+
+avp_info(Entry) -> %% {Name, Arity}
+ case Entry of
+ {'<',A,'>'} -> {A, 1};
+ {A} -> {A, 1};
+ [A] -> {A, {0,1}};
+ {Q,T} ->
+ {A,_} = avp_info(T),
+ {A, arity(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.
+
+prefix(Spec) ->
+ case orddict:find(prefix, Spec) of
+ {ok, P} ->
+ atom_to_list(P) ++ "_";
+ error ->
+ ""
+ end.
+
+rec_name(Name, Prefix) ->
+ list_to_atom(Prefix ++ atom_to_list(Name)).
diff --git a/lib/diameter/src/compiler/diameter_forms.hrl b/lib/diameter/src/compiler/diameter_forms.hrl
new file mode 100644
index 0000000000..4125e2331c
--- /dev/null
+++ b/lib/diameter/src/compiler/diameter_forms.hrl
@@ -0,0 +1,52 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2010. 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%
+%%
+
+%%
+%% Macros used when building abstract code.
+%%
+
+%% 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(INTEGER(N), {integer, ?LINE, N}).
+-define(VAR(V), {var, ?LINE, V}).
+-define(NIL, {nil, ?LINE}).
+
+-define(CALL(F,A), {?call, ?ATOM(F), A}).
+-define(APPLY(M,F,A), {?call, {?remote, ?ATOM(M), ?ATOM(F)}, A}).
+-define(FIELDS(Fs), [{?record_field, ?ATOM(F), V} || {F,V} <- Fs]).
+
+%% Literal term.
+-define(TERM(T), erl_parse:abstract(T, ?LINE)).
diff --git a/lib/diameter/src/compiler/diameter_make.erl b/lib/diameter/src/compiler/diameter_make.erl
new file mode 100644
index 0000000000..4431b88c4d
--- /dev/null
+++ b/lib/diameter/src/compiler/diameter_make.erl
@@ -0,0 +1,120 @@
+%%
+%% %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%
+%%
+
+%%
+%% Driver for the encoder generator utility.
+%%
+
+-module(diameter_make).
+
+-export([spec/0,
+ hrl/0,
+ erl/0]).
+
+-spec spec() -> no_return().
+-spec hrl() -> no_return().
+-spec erl() -> no_return().
+
+spec() ->
+ make(spec).
+
+hrl() ->
+ make(hrl).
+
+erl() ->
+ make(erl).
+
+%% make/1
+
+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).
+
+%% from_file/3
+
+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.
+
+%% to_spec/2
+
+%% 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.
+
+%% from_spec/4
+
+from_spec(File, Spec, Mode, Opts) ->
+ try
+ diameter_codegen:from_spec(File, Spec, Opts, Mode)
+ catch
+ error: Reason ->
+ io:format("==> ~p codegen failure:~n~p~n~p~n",
+ [Mode, File, {Reason, erlang:get_stacktrace()}]),
+ halt(1)
+ 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_spec_scan.erl b/lib/diameter/src/compiler/diameter_spec_scan.erl
new file mode 100644
index 0000000000..bc0448882a
--- /dev/null
+++ b/lib/diameter/src/compiler/diameter_spec_scan.erl
@@ -0,0 +1,157 @@
+%%
+%% %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
new file mode 100644
index 0000000000..322d53a199
--- /dev/null
+++ b/lib/diameter/src/compiler/diameter_spec_util.erl
@@ -0,0 +1,1052 @@
+%%
+%% %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 = enums_defined(Spec), %% sanity checks
+ true = groups_defined(Spec), %%
+ true = customs_defined(Spec), %%
+ Full = import_enums(import_groups(import_avps(insert_codes(Spec),
+ Options))),
+ 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) ->
+ is_defined(Spec, 'Enumerated', enums).
+
+groups_defined(Spec) ->
+ is_defined(Spec, 'Grouped', grouped).
+
+is_defined(Spec, Type, Key) ->
+ Avps = get_value(avp_types, Spec),
+ lists:all(fun(T) -> true = is_local(name(Key, T), Type, Avps) end,
+ get_value(Key, Spec)).
+
+name(enums, {N,_}) -> N;
+name(grouped, {N,_,_,_}) -> N.
+
+is_local(Name, Type, Avps) ->
+ case lists:keyfind(Name, 1, Avps) of
+ {Name, _, Type, _, _} ->
+ true;
+ {Name, _, T, _, _} ->
+ ?ERROR({avp_has_wrong_type, Name, Type, T});
+ false ->
+ ?ERROR({avp_not_defined, Name, Type})
+ end.
+
+customs_defined(Spec) ->
+ Avps = get_value(avp_types, Spec),
+ lists:all(fun(A) -> true = is_local(A, Avps) end,
+ lists:flatmap(fun last/1, get_value(custom_types, Spec))).
+
+is_local(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
+
+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/modules.mk b/lib/diameter/src/compiler/modules.mk
new file mode 100644
index 0000000000..17a311dacf
--- /dev/null
+++ b/lib/diameter/src/compiler/modules.mk
@@ -0,0 +1,27 @@
+#-*-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
+
+HRL_FILES = \
+ diameter_forms.hrl
+
diff --git a/lib/diameter/src/subdirs.mk b/lib/diameter/src/subdirs.mk
new file mode 100644
index 0000000000..3026224e00
--- /dev/null
+++ b/lib/diameter/src/subdirs.mk
@@ -0,0 +1,21 @@
+#-*-makefile-*- ; force emacs to enter makefile-mode
+
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2010. 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%
+
+SUB_DIRS = compiler app transport
+SUB_DIRECTORIES = $(SUB_DIRS) \ No newline at end of file
diff --git a/lib/diameter/src/transport/.gitignore b/lib/diameter/src/transport/.gitignore
new file mode 100644
index 0000000000..d9f072e262
--- /dev/null
+++ b/lib/diameter/src/transport/.gitignore
@@ -0,0 +1,3 @@
+
+/depend.mk
+
diff --git a/lib/diameter/src/transport/Makefile b/lib/diameter/src/transport/Makefile
new file mode 100644
index 0000000000..5dc1772796
--- /dev/null
+++ b/lib/diameter/src/transport/Makefile
@@ -0,0 +1,141 @@
+#
+# %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) modules.mk 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
new file mode 100644
index 0000000000..d925d62545
--- /dev/null
+++ b/lib/diameter/src/transport/diameter_etcp.erl
@@ -0,0 +1,311 @@
+%%
+%% %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 a transport_module that uses Erlang message
+%% passing for transport.
+%%
+
+-module(diameter_etcp).
+
+-behaviour(gen_server).
+
+%% transport_module interface.
+-export([start/3]).
+
+%% gen_tcp-ish interface used by diameter_tcp.
+-export([listen/2,
+ accept/1,
+ connect/3,
+ send/2,
+ close/1,
+ setopts/2,
+ port/1]).
+
+%% child start
+-export([start_link/1]).
+
+%% gen_server callbacks
+-export([init/1,
+ handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+ code_change/3,
+ terminate/2]).
+
+%% Server states.
+
+-record(listener,
+ {acceptors = [] :: [pid()]}).
+
+-record(connection,
+ {parent :: pid(),
+ peer :: {connect, reference()} %% {connect, MRef}
+ | accept
+ | pid()}).
+
+%% start/3
+
+%% 'module' option makes diameter_tcp call here instead of gen_tcp/inet.
+start(T, Svc, Opts)
+ when is_list(Opts) ->
+ diameter_etcp_sup:start(),
+ diameter_tcp:start(T, Svc, [{module, ?MODULE} | Opts]).
+
+%% listen/2
+%%
+%% Spawn a process that represents the listening socket. The local
+%% port number can be any term, not just an integer. The listener
+%% process registers its host/port with diameter_reg and this is the
+%% handle with which connect/3 finds the appropriate listening
+%% process.
+
+listen(LPort, Opts) ->
+ Parent = self(),
+ diameter_etcp_sup:start_child({listen, Parent, LPort, Opts}).
+
+%% accept/1
+%%
+%% Output: pid()
+
+accept(LPid) ->
+ start(fun(Ref, Parent) -> acceptor(LPid, Ref, Parent) end).
+
+%% connect/3
+%%
+%% Output: pid()
+
+%% RAddr here can either be a 4/8-tuple address or {Node, Addr}.
+connect(RAddr, RPort, _Opts) ->
+ start(fun(Ref, Parent) -> connector(RAddr, RPort, Ref, Parent) end).
+
+%% send/2
+
+send(Pid, Bin) ->
+ Pid ! {send, Bin},
+ ok.
+
+%% close/1
+
+close(Pid) ->
+ Pid ! close,
+ monitor(Pid),
+ receive {'DOWN', _, process, Pid, _} -> ok end.
+
+%% setopts/2
+
+setopts(_, _) ->
+ ok.
+
+%% port/1
+
+port(_) ->
+ 3868. %% We have no local port: fake it.
+
+%% start_link/1
+
+start_link(T) ->
+ gen_server:start_link(?MODULE, T, []).
+
+%% ---------------------------------------------------------------------------
+%% # init/1
+%% ---------------------------------------------------------------------------
+
+%% Maintain a list of acceptor pids as the process state. Each accept
+%% adds a pid to the list, each connect removes one.
+init({listen, Parent, LPort, Opts}) ->
+ monitor(Parent),
+ {ip, LAddr} = lists:keyfind(ip, 1, Opts),
+ true = diameter_reg:add_new({?MODULE, listener, LAddr, LPort}),
+ {ok, #listener{}};
+
+init({connect, Fun, Ref, Parent}) ->
+ {ok, #connection{parent = Parent,
+ peer = Fun(Ref, Parent)}}.
+
+%% ---------------------------------------------------------------------------
+%% # handle_call/3
+%% ---------------------------------------------------------------------------
+
+handle_call(_, _, State) ->
+ {reply, nok, State}.
+
+%% ---------------------------------------------------------------------------
+%% # handle_cast/2
+%% ---------------------------------------------------------------------------
+
+handle_cast(_, State) ->
+ {noreply, State}.
+
+%% ---------------------------------------------------------------------------
+%% # handle_info/2
+%% ---------------------------------------------------------------------------
+
+handle_info(T, #listener{acceptors = L} = S) ->
+ {noreply, S#listener{acceptors = l(T,L)}};
+
+handle_info(T, State) ->
+ {noreply, transition(T, State)}.
+
+%% ---------------------------------------------------------------------------
+%% # code_change/3
+%% ---------------------------------------------------------------------------
+
+code_change(_, State, _) ->
+ {ok, State}.
+
+%% ---------------------------------------------------------------------------
+%% # terminate/2
+%% ---------------------------------------------------------------------------
+
+terminate(_, _) ->
+ ok.
+
+%% ---------------------------------------------------------------------------
+
+monitor(Pid) ->
+ erlang:monitor(process, Pid).
+
+putr(Key, Val) ->
+ put({?MODULE, Key}, Val).
+
+eraser(Key) ->
+ erase({?MODULE, Key}).
+
+%% l/2
+
+l({'DOWN', _, process, _, _} = T, _) ->
+ x(T);
+
+%% New accepting process.
+l({accept, APid}, As) ->
+ As ++ [APid];
+
+%% Peer wants to connect but we have no acceptor ...
+l({connect, Peer}, [] = As) ->
+ Peer ! {refused, self()},
+ As;
+
+%% ... or we do.
+l({connect, Peer}, [APid | Rest]) ->
+ Peer ! {accepted, APid},
+ Rest.
+
+x(T) ->
+ exit({shutdown, T}).
+
+%% start/1
+
+start(Fun) ->
+ Ref = make_ref(),
+ {ok, Pid}
+ = T
+ = diameter_etcp_sup:start_child({connect, Fun, Ref, self()}),
+ MRef = monitor(Pid),
+ receive
+ {ok, Ref} ->
+ T;
+ {'DOWN', MRef, process, _, Reason} ->
+ {error, Reason}
+ end.
+
+%% acceptor/3
+
+acceptor(LPid, Ref, Parent) ->
+ LPid ! {accept, self()}, %% announce that we're accepting
+ putr(ref, {ok, Ref}),
+ monitor(Parent),
+ monitor(LPid),
+ accept.
+
+%% connector/4
+
+connector(RAddr, RPort, Ref, Parent) ->
+ c(match(RAddr, RPort), Ref, Parent).
+
+c([], _, _) ->
+ x(refused);
+
+c([{_,LPid}], Ref, Parent) ->
+ LPid ! {connect, self()},
+ putr(ref, {ok, Ref}),
+ monitor(Parent),
+ {connect, monitor(LPid)}.
+
+match({Node, RAddr}, RPort) ->
+ rpc:call(Node, diameter_reg, match, [{?MODULE, listener, RAddr, RPort}]);
+
+match(RAddr, RPort) ->
+ match({node(), RAddr}, RPort).
+
+%% transition/2
+
+%% Unexpected parent or peer death.
+transition({'DOWN', _, process, _, _} = T, S) ->
+ element(2,S) ! {tcp_error, self(), T},
+ x(T);
+
+%% Connector is receiving acceptor pid from listener.
+transition({accepted, Peer}, #connection{parent = Parent,
+ peer = {connect, MRef}}) ->
+ monitor(Peer),
+ erlang:demonitor(MRef, [flush]),
+ Peer ! {connect, self()},
+ Parent ! {ok, _} = eraser(ref),
+ #connection{parent = Parent,
+ peer = Peer};
+
+%% Connector is receiving connection refusal from listener.
+transition({refused, _} = T, #connection{peer = {connect, _}}) ->
+ x(T);
+
+%% Acceptor is receiving peer connect.
+transition({connect, Peer}, #connection{parent = Parent,
+ peer = accept}) ->
+ monitor(Peer),
+ Parent ! {ok, _} = eraser(ref),
+ #connection{parent = Parent,
+ peer = Peer};
+
+%% Incoming message.
+transition({recv, Bin}, #connection{parent = Parent} = S) ->
+ Parent ! {tcp, self(), Bin},
+ S;
+
+%% Outgoing message.
+transition({send, Bin}, #connection{peer = Peer} = S) ->
+ Peer ! {recv, Bin},
+ S;
+
+%% diameter_etcp:close/1 call when a peer is connected ...
+transition(close = T, #connection{peer = Peer})
+ when is_pid(Peer) ->
+ Peer ! {close, self()},
+ x(T);
+
+%% ... or not.
+transition(close = T, #connection{}) ->
+ x(T);
+
+%% Peer is closing the connection.
+transition({close, Peer} = T, #connection{parent = Parent,
+ peer = Peer})
+ when is_pid(Peer) ->
+ Parent ! {tcp_closed, self()},
+ x(T).
diff --git a/lib/diameter/src/transport/diameter_etcp_sup.erl b/lib/diameter/src/transport/diameter_etcp_sup.erl
new file mode 100644
index 0000000000..bd089cf041
--- /dev/null
+++ b/lib/diameter/src/transport/diameter_etcp_sup.erl
@@ -0,0 +1,64 @@
+%%
+%% %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_etcp_sup).
+
+-behaviour(supervisor).
+
+%% interface
+-export([start/0,
+ start_child/1]).
+
+%% internal exports
+-export([start_link/1,
+ init/1]).
+
+%% start/0
+%%
+%% Start the etcp top supervisor.
+
+start() ->
+ diameter_transport_sup:start_child(?MODULE, ?MODULE).
+
+%% start_child/1
+%%
+%% Start a worker under the etcp supervisor.
+
+start_child(T) ->
+ supervisor:start_child(?MODULE, [T]).
+
+%% start_link/1
+%%
+%% Callback from diameter_transport_sup as a result of start/0.
+%% Starts a child supervisor under the transport supervisor.
+
+start_link(?MODULE) ->
+ SupName = {local, ?MODULE},
+ supervisor:start_link(SupName, ?MODULE, []).
+
+init([]) ->
+ Mod = diameter_etcp,
+ Flags = {simple_one_for_one, 0, 1},
+ ChildSpec = {Mod,
+ {Mod, start_link, []},
+ temporary,
+ 1000,
+ worker,
+ [Mod]},
+ {ok, {Flags, [ChildSpec]}}.
diff --git a/lib/diameter/src/transport/diameter_sctp.erl b/lib/diameter/src/transport/diameter_sctp.erl
new file mode 100644
index 0000000000..92aa8488a0
--- /dev/null
+++ b/lib/diameter/src/transport/diameter_sctp.erl
@@ -0,0 +1,624 @@
+%%
+%% %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_sctp).
+
+-behaviour(gen_server).
+
+%% interface
+-export([start/3]).
+
+%% child start from supervisor
+-export([start_link/1]).
+
+%% child start from here
+-export([init/1]).
+
+%% gen_server callbacks
+-export([handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+ code_change/3,
+ terminate/2]).
+
+-include_lib("kernel/include/inet_sctp.hrl").
+-include_lib("diameter/include/diameter.hrl").
+
+-define(ERROR(T), erlang:error({T, ?MODULE, ?LINE})).
+
+%% The default port for a listener.
+-define(DEFAULT_PORT, 3868). %% RFC 3588, ch 2.1
+
+%% How long a listener with no associations lives before offing
+%% itself.
+-define(LISTENER_TIMEOUT, 30000).
+
+%% How long to wait for a transport process to attach after
+%% association establishment.
+-define(ACCEPT_TIMEOUT, 5000).
+
+-type uint() :: non_neg_integer().
+
+%% Accepting/connecting transport process state.
+-record(transport,
+ {parent :: pid(),
+ mode :: {accept, pid()}
+ | {connect, {list(inet:ip_address()), uint(), list()}}
+ %% {RAs, RP, Errors}
+ | connect,
+ socket :: gen_sctp:sctp_socket(),
+ assoc_id :: gen_sctp:assoc_id(), %% association identifier
+ peer :: {[inet:ip_address()], uint()}, %% {RAs, RP}
+ streams :: {uint(), uint()}, %% {InStream, OutStream} counts
+ os = 0 :: uint()}). %% next output stream
+
+%% Listener process state.
+-record(listener,
+ {ref :: reference(),
+ socket :: gen_sctp:sctp_socket(),
+ count = 0 :: uint(),
+ tmap = ets:new(?MODULE, []) :: ets:tid(),
+ %% {MRef, Pid|AssocId}, {AssocId, Pid}
+ pending = {0, ets:new(?MODULE, [ordered_set])},
+ tref :: reference()}).
+%% Field tmap is used to map an incoming message or event to the
+%% relevent transport process. Field pending implements a queue of
+%% transport processes to which an association has been assigned (at
+%% comm_up and written into tmap) but for which diameter hasn't yet
+%% spawned a transport process: a short-lived state of affairs as a
+%% new transport is spawned as a consequence of a peer being taken up,
+%% transport processes being spawned by the listener on demand. In
+%% case diameter starts a transport before comm_up on a new
+%% association, pending is set to an improper list with the spawned
+%% transport as head and the queue as tail.
+
+%% ---------------------------------------------------------------------------
+%% # start/3
+%% ---------------------------------------------------------------------------
+
+start(T, #diameter_service{capabilities = Caps}, Opts)
+ when is_list(Opts) ->
+ diameter_sctp_sup:start(), %% start supervisors on demand
+ Addrs = Caps#diameter_caps.host_ip_address,
+ s(T, Addrs, lists:map(fun ip/1, Opts)).
+
+ip({ifaddr, A}) ->
+ {ip, A};
+ip(T) ->
+ T.
+
+%% A listener spawns transports either as a consequence of this call
+%% when there is not yet an association to associate with it, or at
+%% comm_up on a new association in which case the call retrieves a
+%% transport from the pending queue.
+s({accept, Ref} = A, Addrs, Opts) ->
+ {LPid, LAs} = listener(Ref, {Opts, Addrs}),
+ try gen_server:call(LPid, {A, self()}, infinity) of
+ {ok, TPid} -> {ok, TPid, LAs}
+ catch
+ exit: Reason -> {error, Reason}
+ end;
+%% This implementation is due to there being no accept call in
+%% 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}).
+
+%% start_link/1
+
+start_link(T) ->
+ proc_lib:start_link(?MODULE,
+ init,
+ [T],
+ infinity,
+ diameter_lib:spawn_opts(server, [])).
+
+%% ---------------------------------------------------------------------------
+%% # init/1
+%% ---------------------------------------------------------------------------
+
+init(T) ->
+ gen_server:enter_loop(?MODULE, [], i(T)).
+
+%% i/1
+
+%% A process owning a listening socket.
+i({listen, Ref, {Opts, Addrs}}) ->
+ {LAs, Sock} = AS = open(Addrs, Opts, ?DEFAULT_PORT),
+ proc_lib:init_ack({ok, self(), LAs}),
+ ok = gen_sctp:listen(Sock, true),
+ true = diameter_reg:add_new({?MODULE, listener, {Ref, AS}}),
+ start_timer(#listener{ref = Ref,
+ socket = Sock});
+
+%% A connecting transport.
+i({connect, Pid, Opts, Addrs}) ->
+ {[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),
+ proc_lib:init_ack({ok, self(), LAs}),
+ erlang:monitor(process, Pid),
+ #transport{parent = Pid,
+ mode = {connect, connect(Sock, RAs, RP, [])},
+ socket = Sock};
+
+%% An accepting transport spawned by diameter.
+i({accept, Pid, LPid, Sock}) ->
+ proc_lib:init_ack({ok, self()}),
+ erlang:monitor(process, Pid),
+ erlang:monitor(process, LPid),
+ #transport{parent = Pid,
+ mode = {accept, LPid},
+ socket = Sock};
+
+%% An accepting transport spawned at association establishment.
+i({accept, Ref, LPid, Sock, Id}) ->
+ proc_lib:init_ack({ok, self()}),
+ MRef = erlang:monitor(process, LPid),
+ %% Wait for a signal that the transport has been started before
+ %% processing other messages.
+ receive
+ {Ref, Pid} -> %% transport started
+ #transport{parent = Pid,
+ mode = {accept, LPid},
+ socket = Sock};
+ {'DOWN', MRef, process, _, _} = T -> %% listener down
+ close(Sock, Id),
+ x(T)
+ after ?ACCEPT_TIMEOUT ->
+ close(Sock, Id),
+ x(timeout)
+ end.
+
+%% close/2
+
+close(Sock, Id) ->
+ gen_sctp:eof(Sock, #sctp_assoc_change{assoc_id = Id}).
+%% Having to pass a record here is hokey.
+
+%% listener/2
+
+listener(LRef, T) ->
+ l(diameter_reg:match({?MODULE, listener, {LRef, '_'}}), LRef, T).
+
+%% Existing process with the listening socket ...
+l([{{?MODULE, listener, {_, AS}}, LPid}], _, _) ->
+ {LAs, _Sock} = AS,
+ {LPid, LAs};
+
+%% ... or not: start one.
+l([], LRef, T) ->
+ {ok, LPid, LAs} = diameter_sctp_sup:start_child({listen, LRef, T}),
+ {LPid, LAs}.
+
+%% open/3
+
+open(Addrs, Opts, PortNr) ->
+ {LAs, Os} = addrs(Addrs, Opts),
+ {LAs, case gen_sctp:open(gen_opts(portnr(Os, PortNr))) of
+ {ok, Sock} ->
+ Sock;
+ {error, Reason} ->
+ x({open, Reason})
+ end}.
+
+addrs(Addrs, Opts) ->
+ case proplists:split(Opts, [ip]) of
+ {[[]], _} ->
+ {Addrs, Opts ++ [{ip, A} || A <- Addrs]};
+ {[As], Os} ->
+ LAs = [diameter_lib:ipaddr(A) || {ip, A} <- As],
+ {LAs, Os ++ [{ip, A} || A <- LAs]}
+ end.
+
+portnr(Opts, PortNr) ->
+ case proplists:get_value(port, Opts) of
+ undefined ->
+ [{port, PortNr} | Opts];
+ _ ->
+ Opts
+ end.
+
+%% x/1
+
+x(Reason) ->
+ exit({shutdown, Reason}).
+
+%% gen_opts/1
+
+gen_opts(Opts) ->
+ {L,_} = proplists:split(Opts, [binary, list, mode, active, sctp_events]),
+ [[],[],[],[],[]] == L orelse ?ERROR({reserved_options, Opts}),
+ [binary, {active, once} | Opts].
+
+%% ---------------------------------------------------------------------------
+%% # handle_call/3
+%% ---------------------------------------------------------------------------
+
+handle_call({{accept, Ref}, Pid}, _, #listener{ref = Ref,
+ count = N}
+ = S) ->
+ {TPid, NewS} = accept(Pid, S),
+ {reply, {ok, TPid}, NewS#listener{count = N+1}};
+
+handle_call(_, _, State) ->
+ {reply, nok, State}.
+
+%% ---------------------------------------------------------------------------
+%% # handle_cast/2
+%% ---------------------------------------------------------------------------
+
+handle_cast(_, State) ->
+ {noreply, State}.
+
+%% ---------------------------------------------------------------------------
+%% # handle_info/2
+%% ---------------------------------------------------------------------------
+
+handle_info(T, #transport{} = S) ->
+ {noreply, #transport{} = t(T,S)};
+
+handle_info(T, #listener{} = S) ->
+ {noreply, #listener{} = l(T,S)}.
+
+%% ---------------------------------------------------------------------------
+%% # code_change/3
+%% ---------------------------------------------------------------------------
+
+code_change(_, State, _) ->
+ {ok, State}.
+
+%% ---------------------------------------------------------------------------
+%% # terminate/2
+%% ---------------------------------------------------------------------------
+
+terminate(_, #transport{assoc_id = undefined}) ->
+ ok;
+
+terminate(_, #transport{socket = Sock,
+ mode = {accept, _},
+ assoc_id = Id}) ->
+ close(Sock, Id);
+
+terminate(_, #transport{socket = Sock}) ->
+ gen_sctp:close(Sock);
+
+terminate(_, #listener{socket = Sock}) ->
+ gen_sctp:close(Sock).
+
+%% ---------------------------------------------------------------------------
+
+%% start_timer/1
+
+start_timer(#listener{count = 0} = S) ->
+ S#listener{tref = erlang:start_timer(?LISTENER_TIMEOUT, self(), close)};
+start_timer(S) ->
+ S.
+
+%% l/2
+%%
+%% Transition listener state.
+
+%% Incoming message from SCTP.
+l({sctp, Sock, _RA, _RP, Data} = Msg, #listener{socket = Sock} = S) ->
+ setopts(Sock),
+ case find(Data, S) of
+ {TPid, NewS} ->
+ TPid ! Msg,
+ NewS;
+ false ->
+ S
+ end;
+
+%% Transport is asking message to be sent. See send/3 for why the send
+%% isn't directly from the transport.
+l({send, AssocId, StreamId, Bin}, #listener{socket = Sock} = S) ->
+ send(Sock, AssocId, StreamId, Bin),
+ S;
+
+%% Accepting transport has died. One that's awaiting an association ...
+l({'DOWN', MRef, process, TPid, _}, #listener{pending = [TPid | Q],
+ tmap = T,
+ count = N}
+ = S) ->
+ ets:delete(T, MRef),
+ ets:delete(T, TPid),
+ start_timer(S#listener{count = N-1,
+ pending = Q});
+
+%% ... ditto and a new transport has already been started ...
+l({'DOWN', _, process, _, _} = T, #listener{pending = [TPid | Q]}
+ = S) ->
+ #listener{pending = NQ}
+ = NewS
+ = l(T, S#listener{pending = Q}),
+ NewS#listener{pending = [TPid | NQ]};
+
+%% ... or not.
+l({'DOWN', MRef, process, TPid, _}, #listener{socket = Sock,
+ tmap = T,
+ count = N,
+ pending = {P,Q}}
+ = S) ->
+ [{MRef, Id}] = ets:lookup(T, MRef), %% Id = TPid | AssocId
+ ets:delete(T, MRef),
+ ets:delete(T, Id),
+ Id == TPid orelse close(Sock, Id),
+ case ets:lookup(Q, TPid) of
+ [{TPid, _}] -> %% transport in the pending queue ...
+ ets:delete(Q, TPid),
+ S#listener{pending = {P-1, Q}};
+ [] -> %% ... or not
+ start_timer(S#listener{count = N-1})
+ end;
+
+%% Timeout after the last accepting process has died.
+l({timeout, TRef, close = T}, #listener{tref = TRef,
+ count = 0}) ->
+ x(T);
+l({timeout, _, close}, #listener{} = S) ->
+ S.
+
+%% t/2
+%%
+%% Transition transport state.
+
+t(T,S) ->
+ case transition(T,S) of
+ ok ->
+ S;
+ #transport{} = NS ->
+ NS;
+ stop ->
+ x(T)
+ end.
+
+%% transition/2
+
+%% Incoming message.
+transition({sctp, Sock, _RA, _RP, Data}, #transport{socket = Sock,
+ mode = {accept, _}}
+ = S) ->
+ recv(Data, S);
+
+transition({sctp, Sock, _RA, _RP, Data}, #transport{socket = Sock} = S) ->
+ setopts(Sock),
+ recv(Data, S);
+
+%% Outgoing message.
+transition({diameter, {send, Msg}}, S) ->
+ send(Msg, S);
+
+%% Request to close the transport connection.
+transition({diameter, {close, Pid}}, #transport{parent = Pid}) ->
+ stop;
+
+%% Listener process has died.
+transition({'DOWN', _, process, Pid, _}, #transport{mode = {accept, Pid}}) ->
+ stop;
+
+%% Parent process has died.
+transition({'DOWN', _, process, Pid, _}, #transport{parent = Pid}) ->
+ stop.
+
+%% Crash on anything unexpected.
+
+%% accept/2
+%%
+%% 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},
+ {ok, TPid} = diameter_sctp_sup:start_child(Arg),
+ MRef = erlang:monitor(process, TPid),
+ ets:insert(T, [{MRef, TPid}, {TPid, MRef}]),
+ {TPid, S#listener{pending = [TPid | Q]}};
+%% Placing the transport in the pending field makes it available to
+%% the next association. The stack starts a new accepting transport
+%% only after this one brings the connection up (or dies).
+
+%% Accepting transport has died. This can happen if a new transport is
+%% started before the DOWN has arrived.
+accept(Pid, #listener{pending = [TPid | {0,_} = Q]} = S) ->
+ false = is_process_alive(TPid), %% assert
+ accept(Pid, S#listener{pending = Q});
+
+%% Pending associations: attach to the first in the queue.
+accept(Pid, #listener{ref = Ref, pending = {N,Q}} = S) ->
+ TPid = ets:first(Q),
+ TPid ! {Ref, Pid},
+ ets:delete(Q, TPid),
+ {TPid, S#listener{pending = {N-1, Q}}}.
+
+%% send/2
+
+%% Outbound Diameter message on a specified stream ...
+send(#diameter_packet{bin = Bin, transport_data = {stream, SId}}, S) ->
+ send(SId, Bin, S),
+ S;
+
+%% ... or not: rotate through all steams.
+send(Bin, #transport{streams = {_, OS},
+ os = N}
+ = S)
+ when is_binary(Bin) ->
+ send(N, Bin, S),
+ S#transport{os = (N + 1) rem 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).
+
+%% send/4
+
+send(Sock, AssocId, Stream, Bin) ->
+ case gen_sctp:send(Sock, AssocId, Stream, Bin) of
+ ok ->
+ ok;
+ {error, Reason} ->
+ x({send, Reason})
+ end.
+
+%% recv/2
+
+%% Association established ...
+recv({[], #sctp_assoc_change{state = comm_up,
+ outbound_streams = OS,
+ inbound_streams = IS,
+ assoc_id = Id}},
+ #transport{assoc_id = undefined}
+ = S) ->
+ up(S#transport{assoc_id = Id,
+ streams = {IS, OS}});
+
+%% ... or not: try the next address.
+recv({[], #sctp_assoc_change{} = E},
+ #transport{assoc_id = undefined,
+ socket = Sock,
+ mode = {connect = C, {[RA|RAs], RP, Es}}}
+ = S) ->
+ S#transport{mode = {C, connect(Sock, RAs, RP, [{RA,E} | Es])}};
+
+%% Lost association after establishment.
+recv({[], #sctp_assoc_change{}}, _) ->
+ stop;
+
+%% Inbound Diameter message.
+recv({[#sctp_sndrcvinfo{stream = Id}], Bin}, #transport{parent = Pid})
+ when is_binary(Bin) ->
+ diameter_peer:recv(Pid, #diameter_packet{transport_data = {stream, Id},
+ bin = Bin}),
+ ok;
+
+recv({[], #sctp_shutdown_event{assoc_id = Id}},
+ #transport{assoc_id = Id}) ->
+ stop.
+
+%% up/1
+
+up(#transport{parent = Pid,
+ mode = {connect = C, {[RA | _], RP, _}}}
+ = S) ->
+ diameter_peer:up(Pid, {RA,RP}),
+ S#transport{mode = C};
+
+up(#transport{parent = Pid,
+ mode = {accept, _}}
+ = S) ->
+ diameter_peer:up(Pid),
+ S.
+
+%% find/2
+
+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).
+
+%% New association and a transport waiting for one: use it.
+f([],
+ {_, #sctp_assoc_change{state = comm_up,
+ assoc_id = Id}},
+ #listener{tmap = T,
+ pending = [TPid | {_,_} = Q]}
+ = S) ->
+ [{TPid, MRef}] = ets:lookup(T, TPid),
+ ets:insert(T, [{MRef, Id}, {Id, TPid}]),
+ ets:delete(T, TPid),
+ {TPid, S#listener{pending = Q}};
+
+%% New association and no transport start yet: spawn one and place it
+%% in the queue.
+f([],
+ {_, #sctp_assoc_change{state = comm_up,
+ assoc_id = Id}},
+ #listener{ref = Ref,
+ socket = Sock,
+ tmap = T,
+ pending = {N,Q}}
+ = S) ->
+ Arg = {accept, Ref, self(), Sock, Id},
+ {ok, TPid} = diameter_sctp_sup:start_child(Arg),
+ MRef = erlang:monitor(process, TPid),
+ ets:insert(T, [{MRef, Id}, {Id, TPid}]),
+ ets:insert(Q, {TPid, now()}),
+ {TPid, S#listener{pending = {N+1, Q}}};
+
+%% Known association ...
+f([{_, TPid}], _, S) ->
+ {TPid, S};
+
+%% ... or not: discard.
+f([], _, _) ->
+ false.
+
+%% assoc_id/1
+
+assoc_id(#sctp_shutdown_event{assoc_id = Id}) -> %% undocumented
+ Id;
+assoc_id(#sctp_assoc_change{assoc_id = Id}) ->
+ Id;
+assoc_id(#sctp_sndrcvinfo{assoc_id = Id}) ->
+ Id;
+assoc_id(#sctp_paddr_change{assoc_id = Id}) ->
+ Id;
+assoc_id(#sctp_adaptation_event{assoc_id = Id}) ->
+ Id.
+
+%% connect/4
+
+connect(_, [], _, Reasons) ->
+ x({connect, lists:reverse(Reasons)});
+
+connect(Sock, [Addr | AT] = As, Port, Reasons) ->
+ case gen_sctp:connect_init(Sock, Addr, Port, []) of
+ ok ->
+ {As, Port, Reasons};
+ {error, _} = E ->
+ connect(Sock, AT, Port, [{Addr, E} | Reasons])
+ end.
+
+%% setopts/1
+
+setopts(Sock) ->
+ case inet:setopts(Sock, [{active, once}]) of
+ ok -> ok;
+ X -> x({setopts, Sock, X}) %% possibly on peer disconnect
+ end.
diff --git a/lib/diameter/src/transport/diameter_sctp_sup.erl b/lib/diameter/src/transport/diameter_sctp_sup.erl
new file mode 100644
index 0000000000..3bdae02d68
--- /dev/null
+++ b/lib/diameter/src/transport/diameter_sctp_sup.erl
@@ -0,0 +1,74 @@
+%%
+%% %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_sctp_sup).
+
+-behaviour(supervisor).
+
+%% interface
+-export([start/0,
+ start_child/1]).
+
+%% internal exports
+-export([start_link/1,
+ init/1]).
+
+%% Start multiple supervisors only because a child can't start another
+%% child before supervisor:start_child/2 has returned.
+-define(TRANSPORT_SUP, diameter_sctp_transport_sup).
+-define(LISTENER_SUP, diameter_sctp_listener_sup).
+
+%% start/0
+%%
+%% Start the TCP-specific supervisors.
+
+start() ->
+ diameter_transport_sup:start_child(?TRANSPORT_SUP, ?MODULE),
+ diameter_transport_sup:start_child(?LISTENER_SUP, ?MODULE).
+
+%% start_child/1
+%%
+%% Start a worker under one of the child supervisors.
+
+start_child(T) ->
+ SupRef = case element(1,T) of
+ connect -> ?TRANSPORT_SUP;
+ accept -> ?TRANSPORT_SUP;
+ listen -> ?LISTENER_SUP
+ end,
+ supervisor:start_child(SupRef, [T]).
+
+%% start_link/1
+%%
+%% Callback from diameter_transport_sup as a result of start/0.
+%% Starts a child supervisor under the transport supervisor.
+
+start_link(Name) ->
+ supervisor:start_link({local, Name}, ?MODULE, []).
+
+init([]) ->
+ Mod = diameter_sctp,
+ Flags = {simple_one_for_one, 0, 1},
+ ChildSpec = {Mod,
+ {Mod, start_link, []},
+ temporary,
+ 1000,
+ worker,
+ [Mod]},
+ {ok, {Flags, [ChildSpec]}}.
diff --git a/lib/diameter/src/transport/diameter_tcp.erl b/lib/diameter/src/transport/diameter_tcp.erl
new file mode 100644
index 0000000000..653c114471
--- /dev/null
+++ b/lib/diameter/src/transport/diameter_tcp.erl
@@ -0,0 +1,531 @@
+%%
+%% %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_tcp).
+
+-behaviour(gen_server).
+
+%% interface
+-export([start/3]).
+
+%% child start from supervisor
+-export([start_link/1]).
+
+%% child start from here
+-export([init/1]).
+
+%% gen_server callbacks
+-export([handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+ code_change/3,
+ terminate/2]).
+
+-include_lib("diameter/include/diameter.hrl").
+
+-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).
+
+%% 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
+%% a process owning the listening port.
+
+%% Listener process state.
+-record(listener, {socket :: inet:socket(),
+ count = 1 :: non_neg_integer(),
+ tref :: reference()}).
+
+%% Monitor process state.
+-record(monitor,
+ {parent :: pid(),
+ transport = self() :: pid()}).
+
+-type tref() :: reference(). %% timer reference
+-type length() :: 0..16#FFFFFF. %% message length from Diameter header
+-type size() :: non_neg_integer(). %% accumulated binary size
+-type frag() :: {length(), size(), binary(), list(binary())}
+ | binary().
+
+%% Accepting/connecting transport process state.
+-record(transport,
+ {socket :: inet:socket(), %% accept or connect socket
+ parent :: pid(), %% of process that started us
+ module :: module(), %% gen_tcp-like module
+ frag = <<>> :: binary() | {tref(), frag()}}). %% message fragment
+
+%% 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
+%% uses this to set itself as the module to call, its start/3 just
+%% calling start/3 here with the option set.
+
+%% ---------------------------------------------------------------------------
+%% # start/3
+%% ---------------------------------------------------------------------------
+
+start({T, Ref}, #diameter_service{capabilities = Caps}, Opts) ->
+ diameter_tcp_sup:start(), %% start tcp supervisors on demand
+ {Mod, Rest} = split(Opts),
+ Addrs = Caps#diameter_caps.host_ip_address,
+ Arg = {T, Ref, Mod, self(), Rest, Addrs},
+ diameter_tcp_sup:start_child(Arg).
+
+split([{module, M} | Opts]) ->
+ {M, Opts};
+split(Opts) ->
+ {gen_tcp, Opts}.
+
+%% start_link/1
+
+start_link(T) ->
+ proc_lib:start_link(?MODULE,
+ init,
+ [T],
+ infinity,
+ diameter_lib:spawn_opts(server, [])).
+
+%% ---------------------------------------------------------------------------
+%% # init/1
+%% ---------------------------------------------------------------------------
+
+init(T) ->
+ gen_server:enter_loop(?MODULE, [], i(T)).
+
+%% i/1
+
+%% A transport process.
+i({T, Ref, Mod, Pid, Opts, Addrs})
+ when T == accept;
+ T == connect ->
+ erlang:monitor(process, Pid),
+ %% Since accept/connect might block indefinitely, spawn a process
+ %% 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),
+ MPid ! {stop, self()}, %% tell the monitor to die
+ setopts(Mod, Sock),
+ #transport{parent = Pid,
+ module = Mod,
+ socket = Sock};
+
+%% A monitor process to kill the transport if the parent dies.
+i(#monitor{parent = Pid, transport = TPid} = S) ->
+ proc_lib:init_ack({ok, self()}),
+ erlang:monitor(process, Pid),
+ erlang:monitor(process, TPid),
+ S;
+%% In principle a link between the transport and killer processes
+%% could do the same thing: have the accepting/connecting process be
+%% killed when the killer process dies as a consequence of parent
+%% death. However, a link can be unlinked and this is exactly what
+%% gen_tcp seems to so. Links should be left to supervisors.
+
+i({listen, LRef, APid, {Mod, Opts, Addrs}}) ->
+ {[LA, LP], Rest} = proplists:split(Opts, [ip, port]),
+ LAddr = get_addr(LA, Addrs),
+ LPort = get_port(LP),
+ {ok, LSock} = Mod:listen(LPort, gen_opts(LAddr, Rest)),
+ 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
+
+i(accept, Ref, Mod, Pid, Opts, Addrs) ->
+ {LAddr, LSock} = listener(Ref, {Mod, Opts, Addrs}),
+ proc_lib:init_ack({ok, self(), [LAddr]}),
+ Sock = ok(accept(Mod, LSock)),
+ diameter_peer:up(Pid),
+ Sock;
+
+i(connect, _, 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))),
+ diameter_peer:up(Pid, {RAddr, RPort}),
+ Sock.
+
+ok({ok, T}) ->
+ T;
+ok(No) ->
+ x(No).
+
+x(Reason) ->
+ exit({shutdown, Reason}).
+
+%% listener/2
+
+listener(LRef, T) ->
+ l(diameter_reg:match({?MODULE, listener, {LRef, '_'}}), LRef, T).
+
+%% Existing process with the listening socket ...
+l([{{?MODULE, listener, {_, AS}}, LPid}], _, _) ->
+ LPid ! {accept, self()},
+ AS;
+
+%% ... or not: start one.
+l([], LRef, T) ->
+ {ok, _, AS} = diameter_tcp_sup:start_child({listen, LRef, self(), T}),
+ AS.
+
+%% get_addr/2
+
+get_addr(As, Def) ->
+ diameter_lib:ipaddr(addr(As, Def)).
+
+%% Take the first address from the service if several are unspecified.
+addr([], [Addr | _]) ->
+ Addr;
+addr([{_, Addr}], _) ->
+ Addr;
+addr(As, Addrs) ->
+ ?ERROR({invalid_addrs, As, Addrs}).
+
+%% get_port/1
+
+get_port([{_, Port}]) ->
+ Port;
+get_port([]) ->
+ ?DEFAULT_PORT;
+get_port(Ps) ->
+ ?ERROR({invalid_ports, Ps}).
+
+%% gen_opts/2
+
+gen_opts(LAddr, Opts) ->
+ {L,_} = proplists:split(Opts, [binary, packet, active]),
+ [[],[],[]] == L orelse ?ERROR({reserved_options, Opts}),
+ [binary,
+ {packet, 0},
+ {active, once},
+ {ip, LAddr}
+ | Opts].
+
+%% ---------------------------------------------------------------------------
+%% # handle_call/3
+%% ---------------------------------------------------------------------------
+
+handle_call(_, _, State) ->
+ {reply, nok, State}.
+
+%% ---------------------------------------------------------------------------
+%% # handle_cast/2
+%% ---------------------------------------------------------------------------
+
+handle_cast(_, State) ->
+ {noreply, State}.
+
+%% ---------------------------------------------------------------------------
+%% # handle_info/2
+%% ---------------------------------------------------------------------------
+
+handle_info(T, #transport{} = S) ->
+ {noreply, #transport{} = t(T,S)};
+
+handle_info(T, #listener{} = S) ->
+ {noreply, #listener{} = l(T,S)};
+
+handle_info(T, #monitor{} = S) ->
+ m(T,S),
+ x(T).
+
+%% ---------------------------------------------------------------------------
+%% # code_change/3
+%% ---------------------------------------------------------------------------
+
+code_change(_, State, _) ->
+ {ok, State}.
+
+%% ---------------------------------------------------------------------------
+%% # terminate/2
+%% ---------------------------------------------------------------------------
+
+terminate(_, _) ->
+ ok.
+
+%% ---------------------------------------------------------------------------
+
+%% start_timer/1
+
+start_timer(#listener{count = 0} = S) ->
+ S#listener{tref = erlang:start_timer(?LISTENER_TIMEOUT, self(), close)};
+start_timer(S) ->
+ S.
+
+%% m/2
+%%
+%% Transition monitor state.
+
+%% Transport is telling us to die.
+m({stop, TPid}, #monitor{transport = TPid}) ->
+ ok;
+
+%% Transport has died.
+m({'DOWN', _, process, TPid, _}, #monitor{transport = TPid}) ->
+ ok;
+
+%% Transport parent has died.
+m({'DOWN', _, process, Pid, _}, #monitor{parent = Pid,
+ transport = TPid}) ->
+ exit(TPid, {shutdown, parent}).
+
+%% l/2
+%%
+%% Transition listener state.
+
+%% Another accept transport is attaching.
+l({accept, TPid}, #listener{count = N} = S) ->
+ erlang:monitor(process, TPid),
+ S#listener{count = N+1};
+
+%% Accepting process has died.
+l({'DOWN', _, process, _, _}, #listener{count = N} = S) ->
+ start_timer(S#listener{count = N-1});
+
+%% Timeout after the last accepting process has died.
+l({timeout, TRef, close = T}, #listener{tref = TRef,
+ count = 0}) ->
+ x(T);
+l({timeout, _, close}, #listener{} = S) ->
+ S.
+
+%% t/2
+%%
+%% Transition transport state.
+
+t(T,S) ->
+ case transition(T,S) of
+ ok ->
+ S;
+ #transport{} = NS ->
+ NS;
+ {stop, Reason} ->
+ x(Reason);
+ stop ->
+ x(T)
+ end.
+
+%% transition/2
+
+%% Incoming message.
+transition({tcp, Sock, Data}, #transport{socket = Sock,
+ module = M}
+ = S) ->
+ setopts(M, Sock),
+ recv(Data, S);
+
+transition({tcp_closed, Sock}, #transport{socket = Sock}) ->
+ stop;
+
+transition({tcp_error, Sock, _Reason} = T, #transport{socket = Sock} = S) ->
+ ?ERROR({T,S});
+
+%% Outgoing message.
+transition({diameter, {send, Bin}}, #transport{socket = Sock,
+ module = M}) ->
+ case send(M, Sock, Bin) of
+ ok ->
+ ok;
+ {error, Reason} ->
+ {stop, {send, Reason}}
+ end;
+
+%% Request to close the transport connection.
+transition({diameter, {close, Pid}}, #transport{parent = Pid,
+ socket = Sock,
+ module = M}) ->
+ M:close(Sock),
+ stop;
+
+%% Timeout for reception of outstanding packets.
+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),
+ ok;
+
+%% Parent process has died.
+transition({'DOWN', _, process, Pid, _}, #transport{parent = Pid}) ->
+ stop.
+
+%% Crash on anything unexpected.
+
+%% 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)}.
+
+%% recv/3
+
+%% No previous fragment.
+recv(Pid, <<>>, Bin) ->
+ rcv(Pid, Bin);
+
+recv(Pid, {TRef, Head}, Bin) ->
+ erlang:cancel_timer(TRef),
+ rcv(Pid, Head, Bin).
+
+%% rcv/3
+
+%% Not even the first four bytes of the header.
+rcv(Pid, Head, Bin)
+ when is_binary(Head) ->
+ rcv(Pid, <<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/5
+
+%% Extract a message for which we have all bytes.
+rcv(Pid, Len, N, Head, Acc)
+ when Len =< N ->
+ rcv(Pid, rcv1(Pid, Len, bin(Head, Acc)));
+
+%% Wait for more packets.
+rcv(_, Len, N, Head, Acc) ->
+ {start_timer(), {Len, N, Head, Acc}}.
+
+%% rcv/2
+
+%% Nothing left.
+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)
+ when Len < 20 ->
+ diameter_peer:recv(Pid, Bin),
+ <<>>;
+
+%% Enough bytes to extract a message.
+rcv(Pid, <<_:1/binary, Len:24, _/binary>> = Bin)
+ when Len =< size(Bin) ->
+ rcv(Pid, rcv1(Pid, Len, Bin));
+
+%% Or not: wait for more packets.
+rcv(_, <<_:1/binary, Len:24, _/binary>> = Head) ->
+ {start_timer(), {Len, size(Head), Head, []}};
+
+%% Not even 4 bytes yet.
+rcv(_, Head) ->
+ {start_timer(), Head}.
+
+%% rcv1/3
+
+rcv1(Pid, Len, Bin) ->
+ <<Msg:Len/binary, Rest/binary>> = Bin,
+ diameter_peer:recv(Pid, Msg),
+ Rest.
+
+%% bin/[12]
+
+bin(Head, Acc) ->
+ list_to_binary([Head | lists:reverse(Acc)]).
+
+bin({_, _, Head, Acc}) ->
+ bin(Head, Acc);
+bin(Bin)
+ when is_binary(Bin) ->
+ Bin.
+
+%% start_timer/0
+
+%% An erroneously large message length may leave us with a fragment
+%% that lingers if the peer doesn't have anything more to send. Start
+%% a timer to force reception if an incoming message doesn't arrive
+%% first. This won't stop a peer from sending a large bogus value and
+%% following it up however but such a state of affairs can only go on
+%% for so long since an unanswered DWR will eventually be the result.
+%%
+%% An erroneously small message length causes problems as well but
+%% since all messages with length problems are discarded this should
+%% also eventually lead to watchdog failover.
+
+start_timer() ->
+ erlang:start_timer(?FRAGMENT_TIMEOUT, self(), flush).
+
+flush(TRef, #transport{parent = Pid, frag = {TRef, Head}} = S) ->
+ diameter_peer:recv(Pid, bin(Head)),
+ S#transport{frag = <<>>};
+flush(_, S) ->
+ S.
+
+%% accept/2
+
+accept(gen_tcp, LSock) ->
+ gen_tcp:accept(LSock);
+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).
+
+%% send/3
+
+send(gen_tcp, Sock, Bin) ->
+ gen_tcp:send(Sock, Bin);
+send(M, Sock, Bin) ->
+ M:send(Sock, Bin).
+
+%% setopts/3
+
+setopts(gen_tcp, Sock, Opts) ->
+ inet:setopts(Sock, Opts);
+setopts(M, Sock, Opts) ->
+ M:setopts(Sock, Opts).
+
+%% setopts/2
+
+setopts(M, Sock) ->
+ case setopts(M, Sock, [{active, once}]) of
+ ok -> ok;
+ X -> x({setopts, M, Sock, X}) %% possibly on peer disconnect
+ end.
+
+%% lport/2
+
+lport(gen_tcp, Sock) ->
+ inet:port(Sock);
+lport(M, Sock) ->
+ M:port(Sock).
diff --git a/lib/diameter/src/transport/diameter_tcp_sup.erl b/lib/diameter/src/transport/diameter_tcp_sup.erl
new file mode 100644
index 0000000000..1016fa2d9b
--- /dev/null
+++ b/lib/diameter/src/transport/diameter_tcp_sup.erl
@@ -0,0 +1,78 @@
+%%
+%% %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_tcp_sup).
+
+-behaviour(supervisor).
+
+%% interface
+-export([start/0,
+ start_child/1]).
+
+%% internal exports
+-export([start_link/1,
+ init/1]).
+
+%% Start multiple supervisors only because a child can't start another
+%% child before supervisor:start_child/2 has returned, although two is
+%% really sufficient (listeners and monitors can be under the same).
+-define(TRANSPORT_SUP, diameter_tcp_transport_sup).
+-define(LISTENER_SUP, diameter_tcp_listener_sup).
+-define(MONITOR_SUP, diameter_tcp_monitor_sup).
+
+%% start/0
+%%
+%% Start the TCP-specific supervisors.
+
+start() ->
+ diameter_transport_sup:start_child(?TRANSPORT_SUP, ?MODULE),
+ diameter_transport_sup:start_child(?LISTENER_SUP, ?MODULE),
+ diameter_transport_sup:start_child(?MONITOR_SUP, ?MODULE).
+
+%% start_child/1
+%%
+%% Start a worker under one of the child supervisors.
+
+start_child(T) ->
+ SupRef = case element(1,T) of
+ accept -> ?TRANSPORT_SUP;
+ connect -> ?TRANSPORT_SUP;
+ listen -> ?LISTENER_SUP;
+ monitor -> ?MONITOR_SUP
+ end,
+ supervisor:start_child(SupRef, [T]).
+
+%% start_link/1
+%%
+%% Callback from diameter_transport_sup as a result of start/0.
+%% Starts a child supervisor under the transport supervisor.
+
+start_link(Name) ->
+ supervisor:start_link({local, Name}, ?MODULE, []).
+
+init([]) ->
+ Mod = diameter_tcp,
+ Flags = {simple_one_for_one, 0, 1},
+ ChildSpec = {Mod,
+ {Mod, start_link, []},
+ temporary,
+ 1000,
+ worker,
+ [Mod]},
+ {ok, {Flags, [ChildSpec]}}.
diff --git a/lib/diameter/src/transport/diameter_transport_sup.erl b/lib/diameter/src/transport/diameter_transport_sup.erl
new file mode 100644
index 0000000000..6457ab78b0
--- /dev/null
+++ b/lib/diameter/src/transport/diameter_transport_sup.erl
@@ -0,0 +1,68 @@
+%%
+%% %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%
+%%
+
+%%
+%% Top supervisor for transport processes.
+%%
+
+-module(diameter_transport_sup).
+
+-behaviour(supervisor).
+
+-export([start_link/0, %% supervisor start
+ start_child/2]).
+
+%% supervisor callback
+-export([init/1]).
+
+%% ---------------------------------------------------------------------------
+
+%% start_link/0
+%%
+%% Start the transport top supervisor. This is started as a child at
+%% at application start, from diameter_sup.erl. Protocol-specific
+%% supervisors are started as children of this supervisor dynamically
+%% by calling start_child/2. (Eg. diameter_tcp_sup:start/0, which
+%% is called from diameter_tcp:start/3 to start supervisors the
+%% first time a TCP transport process is started.)
+
+start_link() ->
+ SupName = {local, ?MODULE},
+ supervisor:start_link(SupName, ?MODULE, []).
+
+%% start_child/2
+%%
+%% Start a protocol-specific supervisor under the top supervisor.
+
+start_child(Name, Module) ->
+ Spec = {Name,
+ {Module, start_link, [Name]},
+ permanent,
+ 1000,
+ supervisor,
+ [Module]},
+ supervisor:start_child(?MODULE, Spec).
+
+%% ---------------------------------------------------------------------------
+
+%% Top supervisor callback.
+init([]) ->
+ Flags = {one_for_one, 0, 1},
+ Workers = [], %% Each protocol starts its supervisor on demand.
+ {ok, {Flags, Workers}}.
diff --git a/lib/diameter/src/transport/modules.mk b/lib/diameter/src/transport/modules.mk
new file mode 100644
index 0000000000..a0dc3cf2c0
--- /dev/null
+++ b/lib/diameter/src/transport/modules.mk
@@ -0,0 +1,29 @@
+#-*-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/subdirs.mk b/lib/diameter/subdirs.mk
new file mode 100644
index 0000000000..1e292d0ed1
--- /dev/null
+++ b/lib/diameter/subdirs.mk
@@ -0,0 +1,20 @@
+#-*-makefile-*- ; force emacs to enter makefile-mode
+
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2010. 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%
+
+SUB_DIRS = src doc/src
diff --git a/lib/diameter/test/Makefile b/lib/diameter/test/Makefile
new file mode 100644
index 0000000000..daae70b1e2
--- /dev/null
+++ b/lib/diameter/test/Makefile
@@ -0,0 +1,408 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2010. 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)
+
+
+# ----------------------------------------------------
+# Release directory specification
+# ----------------------------------------------------
+RELSYSDIR = $(RELEASE_PATH)/diameter_test
+
+ifeq ($(findstring win32,$(TARGET)),win32)
+
+MAKEFILE_SRC = Makefile.win32.src
+
+else
+
+MAKEFILE_SRC = Makefile.src
+
+endif
+
+ifeq ($(TT_DIR),)
+TT_DIR = /tmp
+endif
+
+
+# ----------------------------------------------------
+# Target Specs
+# ----------------------------------------------------
+
+include modules.mk
+
+EBIN = .
+
+HRL_FILES = diameter_test_lib.hrl
+
+ERL_FILES = $(MODULES:%=%.erl)
+
+SOURCE = $(HRL_FILES) $(ERL_FILES)
+
+TARGET_FILES = $(MODULES:%=%.$(EMULATOR))
+
+APP_CASES = app appup
+
+TRANSPORT_CASES = tcp
+
+ALL_CASES = \
+ $(APP_CASES) \
+ compiler conf sync session stats reg peer \
+ $(TRANSPORT_CASES)
+
+
+EMAKEFILE = Emakefile
+ifneq ($(ERL_TOP),)
+MAKE_EMAKE = $(wildcard $(ERL_TOP)/make/make_emakefile)
+else
+MAKE_EMAKE = $(wildcard $(DIAMETER_TOP)/make/make_emakefile)
+endif
+
+ifeq ($(MAKE_EMAKE),)
+BUILDTARGET = $(TARGET_FILES)
+RELTEST_FILES = $(TEST_SPEC_FILE) $(COVER_SPEC_FILE) $(SOURCE)
+else
+BUILDTARGET = emakebuild
+RELTEST_FILES = $(EMAKEFILE) $(TEST_SPEC_FILE) $(COVER_SPEC_FILE) $(SOURCE)
+endif
+
+
+# ----------------------------------------------------
+# FLAGS
+# ----------------------------------------------------
+
+include ../src/app/diameter.mk
+
+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 -DDIAMETER_hipe_special=true
+endif
+
+ifneq ($(ERL_TOP),)
+ERL_COMPILE_FLAGS += \
+ $(DIAMETER_ERL_COMPILE_FLAGS) \
+ -pa $(ERL_TOP)/lib/test_server/ebin \
+ -I$(ERL_TOP)/lib/test_server/include
+else
+ERL_COMPILE_FLAGS += \
+ $(DIAMETER_ERL_COMPILE_FLAGS) \
+ -pa $(TEST_SERVER_DIR)/ebin \
+ -I$(TEST_SERVER_DIR)/include
+endif
+
+ERL_PATH = \
+ -pa ../../$(APPLICATION)/ebin \
+ -pa ../../et/ebin
+
+ifndef SUITE
+SUITE = diameter_SUITE
+endif
+
+ESTOP = -s init stop
+
+ifeq ($(DONT_STOP),true)
+MAYBE_ESTOP =
+else
+MAYBE_ESTOP = $(ESTOP)
+endif
+
+ETVIEW = -s et_viewer
+ifeq ($(USE_ET_VIEWER),true)
+MAYBE_ETVIEW =
+else
+MAYBE_ETVIEW = $(ETVIEW)
+endif
+
+ifeq ($(MERL),)
+MERL = $(ERL)
+endif
+
+ARGS += -noshell
+
+ifeq ($(DISABLE_TC_TIMEOUT),true)
+ARGS += -diameter_test_timeout
+endif
+
+
+DIAMETER_TEST_SERVER = diameter_test_server
+
+
+# ----------------------------------------------------
+# Targets
+# ----------------------------------------------------
+
+tests debug opt: $(BUILDTARGET)
+
+targets: $(TARGET_FILES)
+
+.PHONY: emakebuild
+
+emakebuild: $(EMAKEFILE)
+
+$(EMAKEFILE):
+ $(MAKE_EMAKE) $(ERL_COMPILE_FLAGS) -o$(EBIN) '*_SUITE_make' | grep -v Warning > $(EMAKEFILE)
+ $(MAKE_EMAKE) $(ERL_COMPILE_FLAGS) -o$(EBIN) $(MODULES) | grep -v Warning >> $(EMAKEFILE)
+
+clean:
+ rm -f $(EMAKEFILE)
+ rm -f $(TARGET_FILES)
+ rm -f errs core *~
+
+docs:
+
+info:
+ @echo "MAKE_EMAKE = $(MAKE_EMAKE)"
+ @echo "EMAKEFILE = $(EMAKEFILE)"
+ @echo "BUILDTARGET = $(BUILDTARGET)"
+ @echo ""
+ @echo "ERL_COMPILE_FLAGS = $(ERL_COMPILE_FLAGS)"
+ @echo "ERL = $(ERL)"
+ @echo "ERLC = $(ERLC)"
+ @echo "MERL = $(MERL)"
+ @echo ""
+ @echo "ARGS = $(ARGS)"
+ @echo ""
+ @echo "HRL_FILES = $(HRL_FILES)"
+ @echo "ERL_FILES = $(ERL_FILES)"
+ @echo "TARGET_FILES = $(TARGET_FILES)"
+ @echo ""
+
+help:
+ @echo ""
+ @echo "This Makefile controls the test of the $(APPLICATION) application. "
+ @echo ""
+ @echo "There are two separate ways to perform the test of $(APPLICATION)."
+ @echo ""
+ @echo " a) Run the official OTP test-server (which we do not describe here)"
+ @echo ""
+ @echo " b) Run the test-server provided with this application. "
+ @echo " There are a number of targets to run the entire or parts"
+ @echo " of this applications ($(APPLICATION)) test-suite"
+ @echo ""
+ @echo "Targets:"
+ @echo ""
+ @echo " help"
+ @echo " Print this info"
+ @echo ""
+ @echo " info"
+ @echo " Prints various environment variables. "
+ @echo " May be useful when debugging the Makefile. "
+ @echo ""
+ @echo " tests | debug | opt "
+ @echo " Compile all test-code. "
+ @echo ""
+ @echo " clean "
+ @echo " Remove all targets. "
+ @echo ""
+ @echo " test"
+ @echo " Run the entire $(APPLICATION) test-suite. "
+ @echo ""
+ @echo " app"
+ @echo " Run the $(APPLICATION) application sub-test-suite. "
+ @echo ""
+ @echo " appup"
+ @echo " Run the $(APPLICATION) application upgrade (appup) sub-test-suite. "
+ @echo ""
+ @echo " compiler"
+ @echo " Run the $(APPLICATION) compiler sub-test-suite(s). "
+ @echo ""
+ @echo " conf"
+ @echo " Run the $(APPLICATION) config sub-test-suite. "
+ @echo " Checks various aspects of the $(APPLICATION) configuration. "
+ @echo ""
+ @echo " sync"
+ @echo " Run the $(APPLICATION) sync sub-test-suite. "
+ @echo ""
+ @echo " session"
+ @echo " Run the $(APPLICATION) session sub-test-suite. "
+ @echo ""
+ @echo " stats"
+ @echo " Run the $(APPLICATION) stats sub-test-suite. "
+ @echo ""
+ @echo " reg"
+ @echo " Run the $(APPLICATION) reg sub-test-suite. "
+ @echo ""
+ @echo " peer"
+ @echo " Run the $(APPLICATION) peer sub-test-suite"
+ @echo ""
+ @echo " ptab"
+ @echo " Run the $(APPLICATION) persistent-table sub-test-suite"
+ @echo ""
+ @echo " tcp"
+ @echo " Run the $(APPLICATION) tcp sub-test-suite"
+ @echo ""
+ @echo ""
+
+
+# ----------------------------------------------------
+# Special Targets
+# ----------------------------------------------------
+
+all: make
+ @echo "make sure epmd is new"
+ @epmd -kill > /dev/null
+ @echo "Running all sub-suites separatelly"
+ @for i in $(ALL_CASES); do \
+ echo "SUITE: $$i"; \
+ clearmake -V $$i > $$i.log; \
+ done
+
+aall: make
+ @echo "make sure epmd is new"
+ @epmd -kill > /dev/null
+ @echo "Running all app sub-suites separatelly"
+ @for i in $(APP_CASES); do \
+ echo "SUITE: $$i"; \
+ clearmake -V $$i > $$i.log; \
+ done
+ echo "done"
+
+tall: make
+ @echo "make sure epmd is new"
+ @epmd -kill > /dev/null
+ @echo "Running all transport sub-suites separatelly"
+ @for i in $(TRANSPORT_CASES); do \
+ echo "SUITE: $$i"; \
+ clearmake -V $$i > $$i.log; \
+ done
+
+make: targets
+
+test: make
+ $(MERL) $(ARGS) -sname diameter_test $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t $(SUITE) \
+ $(MAYBE_ESTOP)
+
+utest: make
+ $(MERL) $(ARGS) -sname diameter_utest $(ERL_PATH) \
+ $(MAYBE_ETVIEW) \
+ -s $(DIAMETER_TEST_SERVER) t $(SUITE) \
+ $(ESTOP)
+
+# ftest: make
+# $(MERL) $(ARGS) -sname diameter_ftest $(ERL_PATH) \
+# -s diameter_filter \
+# -s $(DIAMETER_TEST_SERVER) t $(SUITE) \
+# $(ESTOP)
+#
+
+##########################
+
+# tickets: make
+# $(MERL) $(ARGS) -sname diameter_tickets $(ERL_PATH) \
+# -s $(DIAMETER_TEST_SERVER) tickets $(SUITE) \
+# $(ESTOP)
+#
+
+app: make
+ $(MERL) $(ARGS) -sname diameter_app $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_app_test \
+ $(ESTOP)
+
+appup: make
+ $(MERL) $(ARGS) -sname diameter_appup $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_appup_test \
+ $(ESTOP)
+
+compiler: make
+ $(MERL) $(ARGS) -sname diameter_compiler $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_compiler_test \
+ $(ESTOP)
+
+conf: make
+ $(MERL) $(ARGS) -sname diameter_config $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_config_test \
+ $(ESTOP)
+
+sync: make
+ $(MERL) $(ARGS) -sname diameter_sync $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_sync_test \
+ $(ESTOP)
+
+session: make
+ $(MERL) $(ARGS) -sname diameter_session $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_session_test \
+ $(ESTOP)
+
+stats: make
+ $(MERL) $(ARGS) -sname diameter_stats $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_stats_test \
+ $(ESTOP)
+
+reg: make
+ $(MERL) $(ARGS) -sname diameter_reg $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_reg_test \
+ $(ESTOP)
+
+peer: make
+ $(MERL) $(ARGS) -sname diameter_peer $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_peer_test \
+ $(ESTOP)
+
+ptab: make
+ $(MERL) $(ARGS) -sname diameter_persistent_table $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_persistent_table_test \
+ $(ESTOP)
+
+tcp: make
+ $(MERL) $(ARGS) -sname diameter_tcp $(ERL_PATH) \
+ -s $(DIAMETER_TEST_SERVER) t diameter_tcp_test \
+ $(ESTOP)
+
+
+node:
+ $(MERL) -sname diameter $(ERL_PATH)
+
+
+# ----------------------------------------------------
+# Release Targets
+# ----------------------------------------------------
+
+ifneq ($(ERL_TOP),)
+include $(ERL_TOP)/make/otp_release_targets.mk
+else
+include $(DIAMETER_TOP)/make/release_targets.mk
+endif
+
+release_spec:
+
+release_docs_spec:
+
+release_tests_spec: tests
+ $(INSTALL_DIR) $(RELSYSDIR)
+ $(INSTALL_DATA) $(RELTEST_FILES) $(RELSYSDIR)
+# $(INSTALL_DATA) $(TEST_SPEC_FILE) $(COVER_SPEC_FILE) \
+# $(HRL_FILES) $(ERL_FILES) \
+# $(RELSYSDIR)
+#
+ chmod -f -R u+w $(RELSYSDIR)
+
diff --git a/lib/diameter/test/diameter.cover b/lib/diameter/test/diameter.cover
new file mode 100644
index 0000000000..5fde6c7d01
--- /dev/null
+++ b/lib/diameter/test/diameter.cover
@@ -0,0 +1,6 @@
+%% -*- erlang -*-
+{exclude,
+ [
+ ]
+}.
+
diff --git a/lib/diameter/test/diameter.spec b/lib/diameter/test/diameter.spec
new file mode 100644
index 0000000000..a6e71762eb
--- /dev/null
+++ b/lib/diameter/test/diameter.spec
@@ -0,0 +1,9 @@
+{suites, "../diameter_test", all}.
+%%{skip, {diameter_compiler_test, all, "Not yet implemented"}}.
+%%{skip, {diameter_config_test, all, "Not yet implemented"}}.
+%%{skip, {diameter_peer_test, all, "Not yet implemented"}}.
+%%{skip, {diameter_reg_test, all, "Not yet implemented"}}.
+%%{skip, {diameter_session_test, all, "Not yet implemented"}}.
+%%{skip, {diameter_stats_test, all, "Not yet implemented"}}.
+%%{skip, {diameter_sync_test, all, "Not yet implemented"}}.
+%%{skip, {diameter_tcp_test, all, "Not yet implemented"}}.
diff --git a/lib/diameter/test/diameter_SUITE.erl b/lib/diameter/test/diameter_SUITE.erl
new file mode 100644
index 0000000000..443cf90e92
--- /dev/null
+++ b/lib/diameter/test/diameter_SUITE.erl
@@ -0,0 +1,108 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Test application config
+%%----------------------------------------------------------------------
+
+-module(diameter_SUITE).
+
+-export([
+ suite/0,
+ all/0,
+ groups/0,
+
+ init_per_testcase/2,
+ fin_per_testcase/2,
+
+ init_per_suite/1,
+ end_per_suite/1,
+
+ init_per_group/2,
+ end_per_group/2,
+
+ init/0
+ ]).
+
+-export([t/0, t/1]).
+
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+init() ->
+ process_flag(trap_exit, true),
+ ?FLUSH().
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Top test case
+
+suite() ->
+ [{ct_hooks, [{ts_install_cth, [{nodenames,1}]}]}].
+
+all() ->
+ [
+ {group, app},
+ {group, appup},
+ {group, compiler},
+ {group, config},
+ {group, sync},
+ {group, session},
+ {group, stats},
+ {group, reg},
+ {group, peer},
+ {group, tcp}
+ ].
+
+groups() ->
+ [{app, [], [{diameter_app_test, all}]},
+ {appup, [], [{diameter_appup_test, all}]},
+ {compiler, [], [{diameter_compiler_test, all}]},
+ {config, [], [{diameter_config_test, all}]},
+ {sync, [], [{diameter_sync_test, all}]},
+ {session, [], [{diameter_session_test, all}]},
+ {stats, [], [{diameter_stats_test, all}]},
+ {reg, [], [{diameter_reg_test, all}]},
+ {peer, [], [{diameter_peer_test, all}]},
+ {tcp, [], [{diameter_tcp_test, all}]}].
+
+
+init_per_suite(Config) ->
+ Config.
+
+end_per_suite(_Config) ->
+ ok.
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
diff --git a/lib/diameter/test/diameter_app_test.erl b/lib/diameter/test/diameter_app_test.erl
new file mode 100644
index 0000000000..7173c39caf
--- /dev/null
+++ b/lib/diameter/test/diameter_app_test.erl
@@ -0,0 +1,393 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the application specifics of the Diameter application
+%%----------------------------------------------------------------------
+-module(diameter_app_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2,
+
+ fields/1,
+ modules/1,
+ exportall/1,
+ app_depend/1,
+ undef_funcs/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(undef_funcs = Case, Config) ->
+ NewConfig = [{tc_timeout, ?MINUTES(10)} | Config],
+ diameter_test_server:init_per_testcase(Case, NewConfig);
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [
+ fields,
+ modules,
+ exportall,
+ app_depend,
+ undef_funcs
+ ].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ io:format("~w:init_per_suite -> entry with"
+ "~n Config: ~p"
+ "~n", [?MODULE, Config]),
+ case is_app(diameter) of
+ {ok, AppFile} ->
+ io:format("AppFile: ~n~p~n", [AppFile]),
+ %% diameter:print_version_info(),
+ [{app_file, AppFile}|Config];
+ {error, Reason} ->
+ ?FAIL(Reason)
+ end.
+
+is_app(App) ->
+ LibDir = code:lib_dir(App),
+ File = filename:join([LibDir, "ebin", atom_to_list(App) ++ ".app"]),
+ case file:consult(File) of
+ {ok, [{application, App, AppFile}]} ->
+ {ok, AppFile};
+ Error ->
+ {error, {invalid_format, Error}}
+ end.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+fields(suite) ->
+ [];
+fields(doc) ->
+ [];
+fields(Config) when is_list(Config) ->
+ AppFile = ?KEY1SEARCH(app_file, Config),
+ Fields = [vsn, description, modules, registered, applications],
+ case check_fields(Fields, AppFile, []) of
+ [] ->
+ ok;
+ Missing ->
+ ?FAIL({missing_fields, Missing})
+ end.
+
+check_fields([], _AppFile, Missing) ->
+ Missing;
+check_fields([Field|Fields], AppFile, Missing) ->
+ check_fields(Fields, AppFile, check_field(Field, AppFile, Missing)).
+
+check_field(Name, AppFile, Missing) ->
+ io:format("checking field: ~p~n", [Name]),
+ case lists:keymember(Name, 1, AppFile) of
+ true ->
+ Missing;
+ false ->
+ [Name|Missing]
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+modules(suite) ->
+ [];
+modules(doc) ->
+ [];
+modules(Config) when is_list(Config) ->
+ AppFile = ?KEY1SEARCH(app_file, Config),
+ Mods = ?KEY1SEARCH(modules, AppFile),
+ EbinList = get_ebin_mods(diameter),
+ case missing_modules(Mods, EbinList, []) of
+ [] ->
+ ok;
+ Missing ->
+ throw({error, {missing_modules, Missing}})
+ end,
+ Allowed = [diameter_codegen,
+ diameter_make,
+ diameter_spec_scan,
+ diameter_spec_util],
+ case extra_modules(Mods, EbinList, Allowed, []) of
+ [] ->
+ ok;
+ Extra ->
+ throw({error, {extra_modules, Extra}})
+ end,
+ {ok, Mods}.
+
+get_ebin_mods(App) ->
+ LibDir = code:lib_dir(App),
+ EbinDir = filename:join([LibDir,"ebin"]),
+ {ok, Files0} = file:list_dir(EbinDir),
+ Files1 = [lists:reverse(File) || File <- Files0],
+ [list_to_atom(lists:reverse(Name)) || [$m,$a,$e,$b,$.|Name] <- Files1].
+
+
+missing_modules([], _Ebins, Missing) ->
+ Missing;
+missing_modules([Mod|Mods], Ebins, Missing) ->
+ case lists:member(Mod, Ebins) of
+ true ->
+ missing_modules(Mods, Ebins, Missing);
+ false ->
+ io:format("missing module: ~p~n", [Mod]),
+ missing_modules(Mods, Ebins, [Mod|Missing])
+ end.
+
+
+extra_modules(_Mods, [], Allowed, Extra) ->
+ Extra--Allowed;
+extra_modules(Mods, [Mod|Ebins], Allowed, Extra) ->
+ case lists:member(Mod, Mods) of
+ true ->
+ extra_modules(Mods, Ebins, Allowed, Extra);
+ false ->
+ io:format("supefluous module: ~p~n", [Mod]),
+ extra_modules(Mods, Ebins, Allowed, [Mod|Extra])
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+exportall(suite) ->
+ [];
+exportall(doc) ->
+ [];
+exportall(Config) when is_list(Config) ->
+ AppFile = ?KEY1SEARCH(app_file, Config),
+ Mods = ?KEY1SEARCH(modules, AppFile),
+ check_export_all(Mods).
+
+
+check_export_all([]) ->
+ ok;
+check_export_all([Mod|Mods]) ->
+ case (catch apply(Mod, module_info, [compile])) of
+ {'EXIT', {undef, _}} ->
+ check_export_all(Mods);
+ O ->
+ case lists:keysearch(options, 1, O) of
+ false ->
+ check_export_all(Mods);
+ {value, {options, List}} ->
+ case lists:member(export_all, List) of
+ true ->
+ throw({error, {export_all, Mod}});
+ false ->
+ check_export_all(Mods)
+ end
+ end
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+app_depend(suite) ->
+ [];
+app_depend(doc) ->
+ [];
+app_depend(Config) when is_list(Config) ->
+ AppFile = ?KEY1SEARCH(app_file, Config),
+ Apps = ?KEY1SEARCH(applications, AppFile),
+ check_apps(Apps).
+
+
+check_apps([]) ->
+ ok;
+check_apps([App|Apps]) ->
+ case is_app(App) of
+ {ok, _} ->
+ check_apps(Apps);
+ Error ->
+ throw({error, {missing_app, {App, Error}}})
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+undef_funcs(suite) ->
+ [];
+undef_funcs(doc) ->
+ [];
+undef_funcs(Config) when is_list(Config) ->
+ ?SKIP(diameter_not_known_by_xref),
+ App = diameter,
+ AppFile = ?KEY1SEARCH(app_file, Config),
+ Mods = ?KEY1SEARCH(modules, AppFile),
+ Root = code:root_dir(),
+ LibDir = code:lib_dir(App),
+ EbinDir = filename:join([LibDir,"ebin"]),
+ XRefTestName = undef_funcs_make_name(App, xref_test_name),
+ try
+ begin
+ XRef = xref_start(XRefTestName),
+ xref_set_defaults(XRef, [{verbose,false},{warnings,false}]),
+ XRefName = undef_funcs_make_name(App, xref_name),
+ XRefName = xref_add_release(XRef, Root, XRefName),
+ xref_replace_application(XRef, App, EbinDir),
+ Undefs = xref_analyze(XRef),
+ xref_stop(XRef),
+ analyze_undefined_function_calls(Undefs, Mods, [])
+ end
+ catch
+ throw:{error, Reason} ->
+ ?FAIL(Reason)
+ end.
+
+
+xref_start(XRefTestName) ->
+ case (catch xref:start(XRefTestName)) of
+ {ok, XRef} ->
+ XRef;
+ {error, Reason} ->
+ throw({error, {failed_starting_xref, Reason}});
+ Error ->
+ throw({error, {failed_starting_xref, Error}})
+ end.
+
+xref_set_defaults(XRef, Defs) ->
+ case (catch xref:set_default(XRef, Defs)) of
+ ok ->
+ ok;
+ Error ->
+ throw({error, {failed_setting_defaults, Defs, Error}})
+ end.
+
+xref_add_release(XRef, Root, Name) ->
+ case (catch xref:add_release(XRef, Root, {name, Name})) of
+ {ok, XRefName} ->
+ XRefName;
+ {error, Reason} ->
+ throw({error, {failed_adding_release, Reason}});
+ Error ->
+ throw({error, {failed_adding_release, Error}})
+ end.
+
+xref_replace_application(XRef, App, EbinDir) ->
+ case (catch xref:replace_application(XRef, App, EbinDir)) of
+ {ok, App} ->
+ ok;
+ {error, XRefMod, Reason} ->
+ throw({error, {failed_replacing_app, XRefMod, Reason}});
+ Error ->
+ throw({error, {failed_replacing_app, Error}})
+ end.
+
+xref_analyze(XRef) ->
+ case (catch xref:analyze(XRef, undefined_function_calls)) of
+ {ok, Undefs} ->
+ Undefs;
+ {error, Reason} ->
+ throw({error, {failed_detecting_func_calls, Reason}});
+ Error ->
+ throw({error, {failed_detecting_func_calls, Error}})
+ end.
+
+xref_stop(XRef) ->
+ xref:stop(XRef).
+
+analyze_undefined_function_calls([], _, []) ->
+ ok;
+analyze_undefined_function_calls([], _, AppUndefs) ->
+ exit({suite_failed, {undefined_function_calls, AppUndefs}});
+analyze_undefined_function_calls([{{Mod, _F, _A}, _C} = AppUndef|Undefs],
+ AppModules, AppUndefs) ->
+ %% Check that this module is our's
+ case lists:member(Mod,AppModules) of
+ true ->
+ {Calling,Called} = AppUndef,
+ {Mod1,Func1,Ar1} = Calling,
+ {Mod2,Func2,Ar2} = Called,
+ io:format("undefined function call: "
+ "~n ~w:~w/~w calls ~w:~w/~w~n",
+ [Mod1,Func1,Ar1,Mod2,Func2,Ar2]),
+ analyze_undefined_function_calls(Undefs, AppModules,
+ [AppUndef|AppUndefs]);
+ false ->
+ io:format("dropping ~p~n", [Mod]),
+ analyze_undefined_function_calls(Undefs, AppModules, AppUndefs)
+ end.
+
+%% This function is used simply to avoid cut-and-paste errors later...
+undef_funcs_make_name(App, PostFix) ->
+ list_to_atom(atom_to_list(App) ++ "_" ++ atom_to_list(PostFix)).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+%% fail(Reason) ->
+%% exit({suite_failed, Reason}).
+
+%% ?KEY1SEARCH(Key, L) ->
+%% case lists:keysearch(Key, 1, L) of
+%% undefined ->
+%% fail({not_found, Key, L});
+%% {value, {Key, Value}} ->
+%% Value
+%% end.
diff --git a/lib/diameter/test/diameter_appup_test.erl b/lib/diameter/test/diameter_appup_test.erl
new file mode 100644
index 0000000000..97a089e01a
--- /dev/null
+++ b/lib/diameter/test/diameter_appup_test.erl
@@ -0,0 +1,539 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the application specifics of the Diameter application
+%%----------------------------------------------------------------------
+-module(diameter_appup_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2,
+
+ appup/1
+ ]).
+
+-export([t/0, t/1]).
+
+-compile({no_auto_import,[error/1]}).
+
+-include("diameter_test_lib.hrl").
+
+-define(APPLICATION, diameter).
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [appup].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ AppFile = file_name(?APPLICATION, ".app"),
+ AppupFile = file_name(?APPLICATION, ".appup"),
+ [{app_file, AppFile}, {appup_file, AppupFile}|Config].
+
+
+file_name(App, Ext) ->
+ LibDir = code:lib_dir(App),
+ filename:join([LibDir, "ebin", atom_to_list(App) ++ Ext]).
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+appup(suite) ->
+ [];
+appup(doc) ->
+ "perform a simple check of the appup file";
+appup(Config) when is_list(Config) ->
+ AppupFile = key1search(appup_file, Config),
+ AppFile = key1search(app_file, Config),
+ Modules = modules(AppFile),
+ check_appup(AppupFile, Modules).
+
+modules(File) ->
+ case file:consult(File) of
+ {ok, [{application,diameter,Info}]} ->
+ case lists:keysearch(modules,1,Info) of
+ {value, {modules, Modules}} ->
+ Modules;
+ false ->
+ fail({bad_appinfo, Info})
+ end;
+ Error ->
+ fail({bad_appfile, Error})
+ end.
+
+
+check_appup(AppupFile, Modules) ->
+ case file:consult(AppupFile) of
+ {ok, [{V, UpFrom, DownTo}]} ->
+ check_appup(V, UpFrom, DownTo, Modules);
+ Else ->
+ fail({bad_appupfile, Else})
+ end.
+
+
+check_appup(V, UpFrom, DownTo, Modules) ->
+ check_version(V),
+ check_depends(up, UpFrom, Modules),
+ check_depends(down, DownTo, Modules),
+ check_module_subset(UpFrom),
+ check_module_subset(DownTo),
+ ok.
+
+
+check_depends(_, [], _) ->
+ ok;
+check_depends(UpDown, [Dep|Deps], Modules) ->
+ check_depend(UpDown, Dep, Modules),
+ check_depends(UpDown, Deps, Modules).
+
+
+check_depend(up = UpDown, {add_application, ?APPLICATION} = Instr, Modules) ->
+ d("check_instructions(~w) -> entry with"
+ "~n Instruction: ~p"
+ "~n Modules: ~p", [UpDown, Instr, Modules]),
+ ok;
+check_depend(down = UpDown, {remove_application, ?APPLICATION} = Instr,
+ Modules) ->
+ d("check_instructions(~w) -> entry with"
+ "~n Instruction: ~p"
+ "~n Modules: ~p", [UpDown, Instr, Modules]),
+ ok;
+check_depend(UpDown, {V, Instructions}, Modules) ->
+ d("check_instructions(~w) -> entry with"
+ "~n V: ~p"
+ "~n Modules: ~p", [UpDown, V, Modules]),
+ check_version(V),
+ case check_instructions(UpDown,
+ Instructions, Instructions, [], [], Modules) of
+ {_Good, []} ->
+ ok;
+ {_, Bad} ->
+ fail({bad_instructions, Bad, UpDown})
+ end.
+
+
+check_instructions(_, [], _, Good, Bad, _) ->
+ {lists:reverse(Good), lists:reverse(Bad)};
+check_instructions(UpDown, [Instr|Instrs], AllInstr, Good, Bad, Modules) ->
+ d("check_instructions(~w) -> entry with"
+ "~n Instr: ~p", [UpDown,Instr]),
+ case (catch check_instruction(UpDown, Instr, AllInstr, Modules)) of
+ ok ->
+ check_instructions(UpDown, Instrs, AllInstr,
+ [Instr|Good], Bad, Modules);
+ {error, Reason} ->
+ d("check_instructions(~w) -> bad instruction: "
+ "~n Reason: ~p", [UpDown,Reason]),
+ check_instructions(UpDown, Instrs, AllInstr, Good,
+ [{Instr, Reason}|Bad], Modules)
+ end.
+
+%% A new module is added
+check_instruction(up, {add_module, Module}, _, Modules)
+ when is_atom(Module) ->
+ d("check_instruction -> entry when up-add_module instruction with"
+ "~n Module: ~p", [Module]),
+ check_module(Module, Modules);
+
+%% An old module is re-added
+check_instruction(down, {add_module, Module}, _, Modules)
+ when is_atom(Module) ->
+ d("check_instruction -> entry when down-add_module instruction with"
+ "~n Module: ~p", [Module]),
+ case (catch check_module(Module, Modules)) of
+ {error, {unknown_module, Module, Modules}} ->
+ ok;
+ ok ->
+ error({existing_readded_module, Module})
+ end;
+
+%% Removing a module on upgrade:
+%% - the module has been removed from the app-file.
+%% - check that no module depends on this (removed) module
+check_instruction(up, {remove, {Module, Pre, Post}}, _, Modules)
+ when is_atom(Module) andalso is_atom(Pre) andalso is_atom(Post) ->
+ d("check_instruction -> entry when up-remove instruction with"
+ "~n Module: ~p"
+ "~n Pre: ~p"
+ "~n Post: ~p", [Module, Pre, Post]),
+ case (catch check_module(Module, Modules)) of
+ {error, {unknown_module, Module, Modules}} ->
+ check_purge(Pre),
+ check_purge(Post);
+ ok ->
+ error({existing_removed_module, Module})
+ end;
+
+%% Removing a module on downgrade: the module exist
+%% in the app-file.
+check_instruction(down, {remove, {Module, Pre, Post}}, AllInstr, Modules)
+ when is_atom(Module) andalso is_atom(Pre) andalso is_atom(Post) ->
+ d("check_instruction -> entry when down-remove instruction with"
+ "~n Module: ~p"
+ "~n Pre: ~p"
+ "~n Post: ~p", [Module, Pre, Post]),
+ case (catch check_module(Module, Modules)) of
+ ok ->
+ check_purge(Pre),
+ check_purge(Post),
+ check_no_remove_depends(Module, AllInstr);
+ {error, {unknown_module, Module, Modules}} ->
+ error({nonexisting_removed_module, Module})
+ end;
+
+check_instruction(_, {load_module, Module, Pre, Post, Depend},
+ AllInstr, Modules)
+ when is_atom(Module) andalso is_atom(Pre) andalso is_atom(Post) andalso is_list(Depend) ->
+ d("check_instruction -> entry when load_module instruction with"
+ "~n Module: ~p"
+ "~n Pre: ~p"
+ "~n Post: ~p"
+ "~n Depend: ~p", [Module, Pre, Post, Depend]),
+ check_module(Module, Modules),
+ check_module_depend(Module, Depend, Modules),
+ check_module_depend(Module, Depend, updated_modules(AllInstr, [])),
+ check_purge(Pre),
+ check_purge(Post);
+
+check_instruction(_, {update, Module, Change, Pre, Post, Depend},
+ AllInstr, Modules)
+ when is_atom(Module) andalso is_atom(Pre) andalso is_atom(Post) andalso is_list(Depend) ->
+ d("check_instruction -> entry when update instruction with"
+ "~n Module: ~p"
+ "~n Change: ~p"
+ "~n Pre: ~p"
+ "~n Post: ~p"
+ "~n Depend: ~p", [Module, Change, Pre, Post, Depend]),
+ check_module(Module, Modules),
+ check_module_depend(Module, Depend, Modules),
+ check_module_depend(Module, Depend, updated_modules(AllInstr, [])),
+ check_change(Change),
+ check_purge(Pre),
+ check_purge(Post);
+
+check_instruction(_, {update, Module, supervisor}, _, Modules)
+ when is_atom(Module) ->
+ check_module(Module, Modules);
+
+check_instruction(_, {apply, {Module, Function, Args}}, _, Modules)
+ when is_atom(Module) andalso is_atom(Function) andalso is_list(Args) ->
+ d("check_instruction -> entry when down-apply instruction with"
+ "~n Module: ~p"
+ "~n Function: ~p"
+ "~n Args: ~p", [Module, Function, Args]),
+ check_module(Module, Modules),
+ check_apply(Module, Function, Args);
+
+check_instruction(_, {restart_application, ?APPLICATION}, _AllInstr, _Modules) ->
+ ok;
+
+check_instruction(_, Instr, _AllInstr, _Modules) ->
+ d("check_instruction -> entry when unknown instruction with"
+ "~n Instr: ~p", [Instr]),
+ error({error, {unknown_instruction, Instr}}).
+
+
+%% If Module X depends on Module Y, then module Y must have an update
+%% instruction of some sort (otherwise the depend is faulty).
+updated_modules([], Modules) ->
+ d("update_modules -> entry when done with"
+ "~n Modules: ~p", [Modules]),
+ Modules;
+updated_modules([Instr|Instrs], Modules) ->
+ d("update_modules -> entry with"
+ "~n Instr: ~p"
+ "~n Modules: ~p", [Instr,Modules]),
+ Module = instruction_module(Instr),
+ d("update_modules -> Module: ~p", [Module]),
+ updated_modules(Instrs, [Module|Modules]).
+
+instruction_module({add_module, Module}) ->
+ Module;
+instruction_module({remove, {Module, _, _}}) ->
+ Module;
+instruction_module({load_module, Module, _, _, _}) ->
+ Module;
+instruction_module({update, Module, _, _, _, _}) ->
+ Module;
+instruction_module({apply, {Module, _, _}}) ->
+ Module;
+instruction_module(Instr) ->
+ d("instruction_module -> entry when unknown instruction with"
+ "~n Instr: ~p", [Instr]),
+ error({error, {unknown_instruction, Instr}}).
+
+
+%% Check that the modules handled in an instruction set for version X
+%% is a subset of the instruction set for version X-1.
+check_module_subset(Instructions) ->
+ do_check_module_subset(modules_of(Instructions)).
+
+do_check_module_subset([]) ->
+ ok;
+do_check_module_subset([_]) ->
+ ok;
+do_check_module_subset([{_V1, Mods1}|T]) ->
+ {V2, Mods2} = hd(T),
+ %% Check that the modules in V1 is a subset of V2
+ case do_check_module_subset2(Mods1, Mods2) of
+ ok ->
+ do_check_module_subset(T);
+ {error, Modules} ->
+ fail({subset_missing_instructions, V2, Modules})
+ end.
+
+do_check_module_subset2(Mods1, Mods2) ->
+ do_check_module_subset2(Mods1, Mods2, []).
+
+do_check_module_subset2([], _, []) ->
+ ok;
+do_check_module_subset2([], _, Acc) ->
+ {error, lists:reverse(Acc)};
+do_check_module_subset2([Mod|Mods], Mods2, Acc) ->
+ case lists:member(Mod, Mods2) of
+ true ->
+ do_check_module_subset2(Mods, Mods2, Acc);
+ false ->
+ do_check_module_subset2(Mods, Mods2, [Mod|Acc])
+ end.
+
+
+modules_of(Instructions) ->
+ modules_of(Instructions, []).
+
+modules_of([], Acc) ->
+ lists:reverse(Acc);
+modules_of([{V,Instructions}|T], Acc) ->
+ Mods = modules_of2(Instructions, []),
+ modules_of(T, [{V, Mods}|Acc]).
+
+modules_of2([], Acc) ->
+ lists:reverse(Acc);
+modules_of2([Instr|Instructions], Acc) ->
+ case module_of(Instr) of
+ {value, Mod} ->
+ modules_of2(Instructions, [Mod|Acc]);
+ false ->
+ modules_of2(Instructions, Acc)
+ end.
+
+module_of({add_module, Module}) ->
+ {value, Module};
+module_of({remove, {Module, _Pre, _Post}}) ->
+ {value, Module};
+module_of({load_module, Module, _Pre, _Post, _Depend}) ->
+ {value, Module};
+module_of({update, Module, _Change, _Pre, _Post, _Depend}) ->
+ {value, Module};
+module_of(_) ->
+ false.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% The version is a string consting of numbers separated by dots: "."
+%% Example: "3.3.3"
+%%
+check_version(V) when is_list(V) ->
+ case do_check_version(string:tokens(V, [$.])) of
+ ok ->
+ ok;
+ {error, BadVersionPart} ->
+ throw({error, {bad_version, V, BadVersionPart}})
+ end;
+check_version(V) ->
+ error({bad_version, V}).
+
+do_check_version([]) ->
+ ok;
+do_check_version([H|T]) ->
+ case (catch list_to_integer(H)) of
+ I when is_integer(I) ->
+ do_check_version(T);
+ _ ->
+ {error, H}
+ end.
+
+check_module(M, Modules) when is_atom(M) ->
+ case lists:member(M,Modules) of
+ true ->
+ ok;
+ false ->
+ error({unknown_module, M, Modules})
+ end;
+check_module(M, _) ->
+ error({bad_module, M}).
+
+
+check_module_depend(M, [], _) when is_atom(M) ->
+ d("check_module_depend -> entry with"
+ "~n M: ~p", [M]),
+ ok;
+check_module_depend(M, Deps, Modules) when is_atom(M) andalso is_list(Deps) ->
+ d("check_module_depend -> entry with"
+ "~n M: ~p"
+ "~n Deps: ~p"
+ "~n Modules: ~p", [M, Deps, Modules]),
+ case [Dep || Dep <- Deps, lists:member(Dep, Modules) == false] of
+ [] ->
+ ok;
+ Unknown ->
+ error({unknown_depend_modules, Unknown})
+ end;
+check_module_depend(_M, D, _Modules) ->
+ d("check_module_depend -> entry when bad depend with"
+ "~n D: ~p", [D]),
+ error({bad_depend, D}).
+
+
+check_no_remove_depends(_Module, []) ->
+ ok;
+check_no_remove_depends(Module, [Instr|Instrs]) ->
+ check_no_remove_depend(Module, Instr),
+ check_no_remove_depends(Module, Instrs).
+
+check_no_remove_depend(Module, {load_module, Mod, _Pre, _Post, Depend}) ->
+ case lists:member(Module, Depend) of
+ true ->
+ error({removed_module_in_depend, load_module, Mod, Module});
+ false ->
+ ok
+ end;
+check_no_remove_depend(Module, {update, Mod, _Change, _Pre, _Post, Depend}) ->
+ case lists:member(Module, Depend) of
+ true ->
+ error({removed_module_in_depend, update, Mod, Module});
+ false ->
+ ok
+ end;
+check_no_remove_depend(_, _) ->
+ ok.
+
+
+check_change(soft) ->
+ ok;
+check_change({advanced, _Something}) ->
+ ok;
+check_change(Change) ->
+ error({bad_change, Change}).
+
+
+check_purge(soft_purge) ->
+ ok;
+check_purge(brutal_purge) ->
+ ok;
+check_purge(Purge) ->
+ error({bad_purge, Purge}).
+
+
+check_apply(Module, Function, Args) ->
+ case (catch Module:module_info()) of
+ Info when is_list(Info) ->
+ check_exported(Function, Args, Info);
+ {'EXIT', {undef, _}} ->
+ error({not_existing_module, Module})
+ end.
+
+check_exported(Function, Args, Info) ->
+ case lists:keysearch(exports, 1, Info) of
+ {value, {exports, FuncList}} ->
+ Arity = length(Args),
+ Arities = [A || {F, A} <- FuncList, F == Function],
+ case lists:member(Arity, Arities) of
+ true ->
+ ok;
+ false ->
+ error({not_exported_function, Function, Arity})
+ end;
+ _ ->
+ error({bad_export, Info})
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+error(Reason) ->
+ throw({error, Reason}).
+
+fail(Reason) ->
+ exit({suite_failed, Reason}).
+
+key1search(Key, L) ->
+ case lists:keysearch(Key, 1, L) of
+ undefined ->
+ fail({not_found, Key, L});
+ {value, {Key, Value}} ->
+ Value
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+d(F, A) ->
+ d(false, F, A).
+
+d(true, F, A) ->
+ io:format(F ++ "~n", A);
+d(_, _, _) ->
+ ok.
+
+
diff --git a/lib/diameter/test/diameter_compiler_test.erl b/lib/diameter/test/diameter_compiler_test.erl
new file mode 100644
index 0000000000..ae4c9c668d
--- /dev/null
+++ b/lib/diameter/test/diameter_compiler_test.erl
@@ -0,0 +1,104 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the dia compiler of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_compiler_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2
+
+ %% foo/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case example
+%%
+
+%% foo(suite) ->
+%% [];
+%% foo(doc) ->
+%% [];
+%% foo(Config) when is_list(Config) ->
+%% ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/lib/diameter/test/diameter_config_test.erl b/lib/diameter/test/diameter_config_test.erl
new file mode 100644
index 0000000000..c44fb654ab
--- /dev/null
+++ b/lib/diameter/test/diameter_config_test.erl
@@ -0,0 +1,105 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the config server of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_config_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2
+
+ %% foo/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case example
+%%
+
+%% foo(suite) ->
+%% [];
+%% foo(doc) ->
+%% [];
+%% foo(Config) when is_list(Config) ->
+%% ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/lib/diameter/test/diameter_etcp_test.beam b/lib/diameter/test/diameter_etcp_test.beam
new file mode 100644
index 0000000000..efaaec69d5
--- /dev/null
+++ b/lib/diameter/test/diameter_etcp_test.beam
Binary files differ
diff --git a/lib/diameter/test/diameter_peer_test.erl b/lib/diameter/test/diameter_peer_test.erl
new file mode 100644
index 0000000000..27e75e26ef
--- /dev/null
+++ b/lib/diameter/test/diameter_peer_test.erl
@@ -0,0 +1,104 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the peer component of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_peer_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2
+
+ %% foo/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case example
+%%
+
+%% foo(suite) ->
+%% [];
+%% foo(doc) ->
+%% [];
+%% foo(Config) when is_list(Config) ->
+%% ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/lib/diameter/test/diameter_reg_test.erl b/lib/diameter/test/diameter_reg_test.erl
new file mode 100644
index 0000000000..0469b833cb
--- /dev/null
+++ b/lib/diameter/test/diameter_reg_test.erl
@@ -0,0 +1,104 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the reg component of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_reg_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2
+
+ %% foo/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case example
+%%
+
+%% foo(suite) ->
+%% [];
+%% foo(doc) ->
+%% [];
+%% foo(Config) when is_list(Config) ->
+%% ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/lib/diameter/test/diameter_session_test.erl b/lib/diameter/test/diameter_session_test.erl
new file mode 100644
index 0000000000..a32647d83d
--- /dev/null
+++ b/lib/diameter/test/diameter_session_test.erl
@@ -0,0 +1,104 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the session component of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_session_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2
+
+ %% foo/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case example
+%%
+
+%% foo(suite) ->
+%% [];
+%% foo(doc) ->
+%% [];
+%% foo(Config) when is_list(Config) ->
+%% ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/lib/diameter/test/diameter_stats_test.erl b/lib/diameter/test/diameter_stats_test.erl
new file mode 100644
index 0000000000..8b666edf50
--- /dev/null
+++ b/lib/diameter/test/diameter_stats_test.erl
@@ -0,0 +1,104 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the stats component of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_stats_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2
+
+ %% foo/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case example
+%%
+
+%% foo(suite) ->
+%% [];
+%% foo(doc) ->
+%% [];
+%% foo(Config) when is_list(Config) ->
+%% ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/lib/diameter/test/diameter_sync_test.erl b/lib/diameter/test/diameter_sync_test.erl
new file mode 100644
index 0000000000..618fa5021b
--- /dev/null
+++ b/lib/diameter/test/diameter_sync_test.erl
@@ -0,0 +1,104 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the sync component of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_sync_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2
+
+ %% foo/1
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case example
+%%
+
+%% foo(suite) ->
+%% [];
+%% foo(doc) ->
+%% [];
+%% foo(Config) when is_list(Config) ->
+%% ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/lib/diameter/test/diameter_tcp_test.erl b/lib/diameter/test/diameter_tcp_test.erl
new file mode 100644
index 0000000000..01b5dc5293
--- /dev/null
+++ b/lib/diameter/test/diameter_tcp_test.erl
@@ -0,0 +1,482 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2010. 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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the tcp transport component of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_tcp_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/0,
+ groups/0,
+ init_per_suite/1, end_per_suite/1,
+ suite_init/1, suite_fin/1,
+ init_per_group/2, end_per_group/2,
+
+ start_and_stop_transport_plain/1,
+ start_and_listen/1,
+ simple_connect/1,
+ simple_send_and_recv/1
+
+ ]).
+
+-export([t/0, t/1]).
+
+%% diameter_peer (internal) callback API
+-export([up/1, up/3, recv/2]).
+
+-include("diameter_test_lib.hrl").
+-include_lib("diameter/include/diameter.hrl").
+%% -include_lib("diameter/src/tcp/diameter_tcp.hrl").
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ [
+ {group, start},
+ {group, simple}
+ ].
+
+groups() ->
+ [
+ {start, [], [start_and_stop_transport_plain, start_and_listen]},
+ {simple, [], [simple_connect, simple_send_and_recv]}
+ ].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(X) -> init_per_suite(X).
+
+init_per_suite(suite) -> [];
+init_per_suite(doc) -> [];
+init_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(X) -> end_per_suite(X).
+
+end_per_suite(suite) -> [];
+end_per_suite(doc) -> [];
+end_per_suite(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case(s)
+%%
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Plain start and stop of TCP transport
+%%
+
+start_and_stop_transport_plain(suite) ->
+ [];
+start_and_stop_transport_plain(doc) ->
+ [];
+start_and_stop_transport_plain(Config) when is_list(Config) ->
+
+ ?SKIP(not_yet_implemented),
+
+ %% This has been changed *a lot* since it was written...
+
+ process_flag(trap_exit, true),
+ Transport = ensure_transport_started(),
+ TcpTransport = ensure_tcp_transport_started(),
+ ensure_tcp_transport_stopped(TcpTransport),
+ ensure_transport_stopped(Transport),
+ i("done"),
+ ok.
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Start TCP transport and then create a listen socket
+%%
+
+start_and_listen(suite) ->
+ [];
+start_and_listen(doc) ->
+ [];
+start_and_listen(Config) when is_list(Config) ->
+
+ ?SKIP(not_yet_implemented),
+
+ %% This has been changed *a lot* since it was written...
+
+ process_flag(trap_exit, true),
+ Transport = ensure_transport_started(),
+ TcpTransport = ensure_tcp_transport_started(),
+
+ case listen([{port, 0}]) of
+ {ok, Acceptor} when is_pid(Acceptor) ->
+ Ref = erlang:monitor(process, Acceptor),
+ [{Acceptor, Info}] = diameter_tcp:which_listeners(),
+ case lists:keysearch(socket, 1, Info) of
+ {value, {_, Listen}} ->
+ i("Listen socket: ~p"
+ "~n Opts: ~p"
+ "~n Stats: ~p"
+ "~n Name: ~p",
+ [Listen,
+ ok(inet:getopts(Listen, [keepalive, delay_send])),
+ ok(inet:getstat(Listen)),
+ ok(inet:sockname(Listen))
+ ]),
+ ok;
+ _ ->
+ ?FAIL({bad_listener_info, Acceptor, Info})
+ end,
+ Crash = simulate_crash,
+ exit(Acceptor, Crash),
+ receive
+ {'DOWN', Ref, process, Acceptor, Crash} ->
+ ?SLEEP(1000),
+ case diameter_tcp:which_listeners() of
+ [{NewAcceptor, _NewInfo}] ->
+ diameter_tcp_accept:stop(NewAcceptor),
+ ?SLEEP(1000),
+ case diameter_tcp:which_listeners() of
+ [] ->
+ ok;
+ UnexpectedListeners ->
+ ?FAIL({unexpected_listeners, empty, UnexpectedListeners})
+ end;
+ UnexpectedListeners ->
+ ?FAIL({unexpected_listeners, non_empty, UnexpectedListeners})
+ end
+ after 5000 ->
+ ?FAIL({failed_killing, Acceptor})
+ end;
+ Error ->
+ ?FAIL({failed_creating_acceptor, Error})
+ end,
+ ensure_tcp_transport_stopped(TcpTransport),
+ ensure_transport_stopped(Transport),
+ i("done"),
+ ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% TCP transport connecting
+%%
+
+simple_connect(suite) ->
+ [];
+simple_connect(doc) ->
+ [];
+simple_connect(Config) when is_list(Config) ->
+
+ ?SKIP(not_yet_implemented),
+
+ %% This has been changed *a lot* since it was written...
+
+ process_flag(trap_exit, true),
+ Transport = ensure_transport_started(),
+ TcpTransport = ensure_tcp_transport_started(),
+ {_Acceptor, Port} = ensure_tcp_listener(),
+
+ {ok, Hostname} = inet:gethostname(),
+
+ i("try connect"),
+ Opts = [{host, Hostname}, {port, Port}, {module, ?MODULE}],
+ Conn = case connect(Opts) of
+ {ok, C} ->
+ C;
+ Error ->
+ ?FAIL({failed_connecting, Error})
+ end,
+ i("connected: ~p", [Conn]),
+
+ %% Up for connect
+ receive
+ {diameter, {up, Host, Port}} ->
+ i("Received expected connect up (~p:~p)", [Host, Port]),
+ ok
+ after 5000 ->
+ ?FAIL(connect_up_confirmation_timeout)
+ end,
+
+ %% Up for accept
+ receive
+ {diameter, {up, _ConnPid}} ->
+ i("Received expected accept up"),
+ ok
+ after 5000 ->
+ ?FAIL(acceptor_up_confirmation_timeout)
+ end,
+
+ i("try disconnect"),
+ diameter_tcp:disconnect(Conn),
+ ensure_tcp_transport_stopped(TcpTransport),
+ ensure_transport_stopped(Transport),
+ i("done"),
+ ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Plain start and stop of TCP transport
+%%
+
+simple_send_and_recv(suite) ->
+ [];
+simple_send_and_recv(doc) ->
+ [];
+simple_send_and_recv(Config) when is_list(Config) ->
+
+ ?SKIP(not_yet_implemented),
+
+ %% This has been changed *a lot* since it was written...
+
+ process_flag(trap_exit, true),
+ %% --------------------------------------------------
+ %% Start the TCP transport sub-system
+ %%
+
+ Transport = ensure_transport_started(),
+ TcpTransport = ensure_tcp_transport_started(),
+
+ {_Acceptor, Port} = ensure_tcp_listener(),
+
+ {ok, Hostname} = inet:gethostname(),
+
+ i("try connect"),
+ Opts = [{host, Hostname}, {port, Port}, {module, ?MODULE}],
+ Conn = case connect(Opts) of
+ {ok, C1} ->
+ C1;
+ Error ->
+ ?FAIL({failed_connecting, Error})
+ end,
+ i("connected: ~p", [Conn]),
+
+ %% Up for connect
+ receive
+ {diameter, {up, Host, Port}} ->
+ i("Received expected connect up (~p:~p)", [Host, Port]),
+ ok
+ after 5000 ->
+ ?FAIL(connect_up_confirmation_timeout)
+ end,
+
+ %% Up for accept
+ APid =
+ receive
+ {diameter, {up, C2}} ->
+ i("Received expected accept up"),
+ C2
+ after 5000 ->
+ ?FAIL(acceptor_up_confirmation_timeout)
+ end,
+
+ %% --------------------------------------------------
+ %% Start some stuff needed for the codec to run
+ %%
+
+ i("start persistent table"),
+ {ok, _Pers} = diameter_persistent_table:start_link(),
+
+ i("start session"),
+ {ok, _Session} = diameter_session:start_link(),
+
+ i("try decode a (DWR) message"),
+ Base = diameter_gen_base_rfc3588,
+ DWR = ['DWR',
+ {'Origin-Host', Hostname},
+ {'Origin-Realm', "whatever-realm"},
+ {'Origin-State-Id', [10]}],
+
+ #diameter_packet{msg = Msg} = diameter_codec:encode(Base, DWR),
+
+
+ %% --------------------------------------------------
+ %% Now try to send the message
+ %%
+ %% This is not the codec-test suite, so we dont really care what we
+ %% send, as long as it encoded/decodes correctly in the transport
+ %%
+
+ i("try send from connect side"),
+ ok = diameter_tcp:send_message(Conn, Msg),
+
+ %% Wait for data on Accept side
+ APkt =
+ receive
+ {diameter, {recv, A}} ->
+ i("[accept] Received expected data message: ~p", [A]),
+ A
+ after 5000 ->
+ ?FAIL(acceptor_up_confirmation_timeout)
+ end,
+
+ %% Send the same message back, just to have something to send...
+ i("try send (\"reply\") from accept side"),
+ ok = diameter_tcp:send_message(APid, APkt),
+
+ %% Wait for data on Connect side
+ receive
+ {diameter, {recv, B}} ->
+ i("[connect] Received expected data message: ~p", [B]),
+ ok
+ after 5000 ->
+ ?FAIL(acceptor_up_confirmation_timeout)
+ end,
+
+ i("we are done - now close shop"),
+ diameter_session:stop(),
+ diameter_persistent_table:stop(),
+
+ ensure_tcp_transport_stopped(TcpTransport),
+ ensure_transport_stopped(Transport),
+ i("done"),
+ ok.
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+ensure_transport_started() ->
+%% i("start diameter transport (top) supervisor"),
+ case diameter_transport_sup:start_link() of
+ {ok, TransportSup} ->
+ TransportSup;
+ Error ->
+ ?FAIL({failed_starting_transport_sup, Error})
+ end.
+
+ensure_transport_stopped(Pid) when is_pid(Pid) ->
+%% i("stop diameter transport (top) supervisor"),
+ Stop = fun(P) -> exit(P, kill) end,
+ ensure_stopped(Pid, Stop, failed_stopping_transport_sup).
+
+ensure_tcp_transport_started() ->
+%% i("start diameter TCP transport"),
+ case diameter_tcp:start_transport() of
+ {ok, TcpTransport} when is_pid(TcpTransport) ->
+ TcpTransport;
+ Error ->
+ ?FAIL({failed_starting_transport, Error})
+ end.
+
+ensure_tcp_transport_stopped(Pid) when is_pid(Pid) ->
+%% i("stop diameter TCP transport supervisor"),
+ Stop = fun(P) -> diameter_tcp:stop_transport(P) end,
+ ensure_stopped(Pid, Stop, failed_stopping_tcp_transport).
+
+
+ensure_tcp_listener() ->
+%% i("create diameter TCP transport listen socket"),
+ case listen([{port, 0}]) of
+ {ok, Acceptor} ->
+ [{Acceptor, Info}] = diameter_tcp:which_listeners(),
+ case lists:keysearch(socket, 1, Info) of
+ {value, {_, Listen}} ->
+ {ok, Port} = inet:port(Listen),
+ {Acceptor, Port};
+ _ ->
+ ?FAIL({failed_retrieving_listen_socket, Info})
+ end;
+ Error ->
+ ?FAIL({failed_creating_listen_socket, Error})
+ end.
+
+
+ensure_stopped(Pid, Stop, ReasonTag) when is_pid(Pid) ->
+%% i("ensure_stopped -> create monitor to ~p", [Pid]),
+ Ref = erlang:monitor(process, Pid),
+%% i("ensure_stopped -> try stop"),
+ Stop(Pid),
+%% i("ensure_stopped -> await DOWN message"),
+ receive
+ {'DOWN', Ref, process, Pid, _} ->
+%% i("ensure_stopped -> received DOWN message"),
+ ok
+ after 5000 ->
+%% i("ensure_stopped -> timeout"),
+ ?FAIL({ReasonTag, Pid})
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+listen(Opts) ->
+ diameter_tcp:listen([{module, ?MODULE} | Opts]).
+
+connect(Opts) ->
+ diameter_tcp:connect([{module, ?MODULE} | Opts]).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+up(Pid, Host, Port) ->
+ Pid ! {diameter, {up, Host, Port}},
+ ok.
+
+up(Pid) ->
+ Pid ! {diameter, {up, self()}},
+ ok.
+
+recv(Pid, Pkt) ->
+ Pid ! {diameter, {recv, Pkt}}.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+i(F) ->
+ i(F, []).
+
+i(F, A) ->
+ io:format(F ++ "~n", A).
+
+
+ok({ok, Whatever}) ->
+ Whatever;
+ok(Crap) ->
+ Crap.
+
+
diff --git a/lib/diameter/test/diameter_test_lib.erl b/lib/diameter/test/diameter_test_lib.erl
new file mode 100644
index 0000000000..16b3b9d216
--- /dev/null
+++ b/lib/diameter/test/diameter_test_lib.erl
@@ -0,0 +1,478 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 1999-2009. 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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Lightweight test server
+%%----------------------------------------------------------------------
+%%
+
+-module(diameter_test_lib).
+
+-export([
+ sleep/1,
+
+ hours/1,
+ minutes/1,
+ seconds/1,
+
+ key1search/2,
+
+ non_pc_tc_maybe_skip/4,
+ os_based_skip/1,
+
+ fail/3,
+ skip/3,
+ fatal_skip/3,
+
+ log/4,
+ error/3,
+
+ flush/0,
+
+ proxy_start/1, proxy_start/2,
+ proxy_init/2,
+
+ still_alive/1,
+
+ prepare_test_case/5,
+ lookup_config/2,
+
+ mk_nodes/2, start_nodes/3,
+
+ display_system_info/1, display_system_info/2, display_system_info/3,
+ display_alloc_info/0,
+ alloc_info/0,
+
+ report_event/3
+
+ ]).
+
+-include("diameter_test_lib.hrl").
+
+-record('REASON', {mod, line, desc}).
+
+
+%% ----------------------------------------------------------------
+%% Time related function
+%%
+
+sleep(infinity) ->
+ receive
+ after infinity ->
+ ok
+ end;
+sleep(MSecs) ->
+ receive
+ after trunc(MSecs) ->
+ ok
+ end,
+ ok.
+
+
+hours(N) -> trunc(N * 1000 * 60 * 60).
+minutes(N) -> trunc(N * 1000 * 60).
+seconds(N) -> trunc(N * 1000).
+
+
+%% ----------------------------------------------------------------
+
+key1search(Key, L) ->
+ case lists:keysearch(Key, 1, L) of
+ undefined ->
+ fail({not_found, Key, L}, ?MODULE, ?LINE);
+ {value, {Key, Value}} ->
+ Value
+ end.
+
+
+%% ----------------------------------------------------------------
+%% Conditional skip of testcases
+%%
+
+non_pc_tc_maybe_skip(Config, Condition, File, Line)
+ when is_list(Config) andalso is_function(Condition) ->
+ %% Check if we shall skip the skip
+ case os:getenv("TS_OS_BASED_SKIP") of
+ "false" ->
+ ok;
+ _ ->
+ case lists:keysearch(ts, 1, Config) of
+ {value, {ts, megaco}} ->
+ %% Always run the testcase if we are using our own
+ %% test-server...
+ ok;
+ _ ->
+ case (catch Condition()) of
+ true ->
+ skip(non_pc_testcase, File, Line);
+ _ ->
+ ok
+ end
+ end
+ end.
+
+
+os_based_skip(any) ->
+ true;
+os_based_skip(Skippable) when is_list(Skippable) ->
+ {OsFam, OsName} =
+ case os:type() of
+ {_Fam, _Name} = FamAndName ->
+ FamAndName;
+ Fam ->
+ {Fam, undefined}
+ end,
+ case lists:member(OsFam, Skippable) of
+ true ->
+ true;
+ false ->
+ case lists:keysearch(OsFam, 1, Skippable) of
+ {value, {OsFam, OsName}} ->
+ true;
+ {value, {OsFam, OsNames}} when is_list(OsNames) ->
+ lists:member(OsName, OsNames);
+ _ ->
+ false
+ end
+ end;
+os_based_skip(_) ->
+ false.
+
+
+%%----------------------------------------------------------------------
+
+error(Actual, Mod, Line) ->
+ global:send(megaco_global_logger, {failed, Mod, Line}),
+ log("<ERROR> Bad result: ~p~n", [Actual], Mod, Line),
+ Label = lists:concat([Mod, "(", Line, ") unexpected result"]),
+ report_event(60, Label, [{line, Mod, Line}, {error, Actual}]),
+ case global:whereis_name(megaco_test_case_sup) of
+ undefined ->
+ ignore;
+ Pid ->
+ Fail = #'REASON'{mod = Mod, line = Line, desc = Actual},
+ Pid ! {fail, self(), Fail}
+ end,
+ Actual.
+
+log(Format, Args, Mod, Line) ->
+ case global:whereis_name(megaco_global_logger) of
+ undefined ->
+ io:format(user, "~p~p(~p): " ++ Format,
+ [self(), Mod, Line] ++ Args);
+ Pid ->
+ io:format(Pid, "~p~p(~p): " ++ Format,
+ [self(), Mod, Line] ++ Args)
+ end.
+
+skip(Actual, File, Line) ->
+ log("Skipping test case~n", [], File, Line),
+ String = lists:flatten(io_lib:format("Skipping test case ~p(~p): ~p~n",
+ [File, Line, Actual])),
+ exit({skipped, String}).
+
+fatal_skip(Actual, File, Line) ->
+ error(Actual, File, Line),
+ exit(shutdown).
+
+
+fail(Actual, File, Line) ->
+ log("Test case failing~n", [], File, Line),
+ String = lists:flatten(io_lib:format("Test case failing ~p (~p): ~p~n",
+ [File, Line, Actual])),
+ exit({suite_failed, String}).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Flush the message queue and return its messages
+
+flush() ->
+ receive
+ Msg ->
+ [Msg | flush()]
+ after 1000 ->
+ []
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% The proxy process
+
+proxy_start(ProxyId) ->
+ spawn_link(?MODULE, proxy_init, [ProxyId, self()]).
+
+proxy_start(Node, ProxyId) ->
+ spawn_link(Node, ?MODULE, proxy_init, [ProxyId, self()]).
+
+proxy_init(ProxyId, Controller) ->
+ process_flag(trap_exit, true),
+ ?LOG("[~p] proxy started by ~p~n",[ProxyId, Controller]),
+ proxy_loop(ProxyId, Controller).
+
+proxy_loop(OwnId, Controller) ->
+ receive
+ {'EXIT', Controller, Reason} ->
+ p("proxy_loop -> received exit from controller"
+ "~n Reason: ~p"
+ "~n", [Reason]),
+ exit(Reason);
+ {apply, Fun} ->
+ p("proxy_loop -> received apply request~n", []),
+ Res = Fun(),
+ p("proxy_loop -> apply result: "
+ "~n ~p"
+ "~n", [Res]),
+ Controller ! {res, OwnId, Res},
+ proxy_loop(OwnId, Controller);
+ OtherMsg ->
+ p("proxy_loop -> received unknown message: "
+ "~n OtherMsg: ~p"
+ "~n", [OtherMsg]),
+ Controller ! {msg, OwnId, OtherMsg},
+ proxy_loop(OwnId, Controller)
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Check if process is alive and kicking
+still_alive(Pid) ->
+ case catch erlang:is_process_alive(Pid) of % New BIF in Erlang/OTP R5
+ true ->
+ true;
+ false ->
+ false;
+ {'EXIT', _} -> % Pre R5 backward compatibility
+ case process_info(Pid, message_queue_len) of
+ undefined -> false;
+ _ -> true
+ end
+ end.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+mk_nodes(0, Nodes) ->
+ Nodes;
+mk_nodes(N, []) ->
+ mk_nodes(N - 1, [node()]);
+mk_nodes(N, Nodes) when N > 0 ->
+ Head = hd(Nodes),
+ [Name, Host] = node_to_name_and_host(Head),
+ Nodes ++ [mk_node(I, Name, Host) || I <- lists:seq(1, N)].
+
+mk_node(N, Name, Host) ->
+ list_to_atom(lists:concat([Name ++ integer_to_list(N) ++ "@" ++ Host])).
+
+%% Returns [Name, Host]
+node_to_name_and_host(Node) ->
+ string:tokens(atom_to_list(Node), [$@]).
+
+start_nodes([Node | Nodes], File, Line) ->
+ case net_adm:ping(Node) of
+ pong ->
+ start_nodes(Nodes, File, Line);
+ pang ->
+ [Name, Host] = node_to_name_and_host(Node),
+ case slave:start_link(Host, Name) of
+ {ok, NewNode} when NewNode =:= Node ->
+ Path = code:get_path(),
+ {ok, Cwd} = file:get_cwd(),
+ true = rpc:call(Node, code, set_path, [Path]),
+ ok = rpc:call(Node, file, set_cwd, [Cwd]),
+ true = rpc:call(Node, code, set_path, [Path]),
+ {_, []} = rpc:multicall(global, sync, []),
+ start_nodes(Nodes, File, Line);
+ Other ->
+ fatal_skip({cannot_start_node, Node, Other}, File, Line)
+ end
+ end;
+start_nodes([], _File, _Line) ->
+ ok.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+display_alloc_info() ->
+ io:format("Allocator memory information:~n", []),
+ AllocInfo = alloc_info(),
+ display_alloc_info(AllocInfo).
+
+display_alloc_info([]) ->
+ ok;
+display_alloc_info([{Alloc, Mem}|AllocInfo]) ->
+ io:format(" ~15w: ~10w~n", [Alloc, Mem]),
+ display_alloc_info(AllocInfo).
+
+alloc_info() ->
+ case erlang:system_info(allocator) of
+ {_Allocator, _Version, Features, _Settings} ->
+ alloc_info(Features);
+ _ ->
+ []
+ end.
+
+alloc_info(Allocators) ->
+ Allocs = [temp_alloc, sl_alloc, std_alloc, ll_alloc, eheap_alloc,
+ ets_alloc, binary_alloc, driver_alloc],
+ alloc_info(Allocators, Allocs, []).
+
+alloc_info([], _, Acc) ->
+ lists:reverse(Acc);
+alloc_info([Allocator | Allocators], Allocs, Acc) ->
+ case lists:member(Allocator, Allocs) of
+ true ->
+ Instances0 = erlang:system_info({allocator, Allocator}),
+ Instances =
+ if
+ is_list(Instances0) ->
+ [Instance || Instance <- Instances0,
+ element(1, Instance) =:= instance];
+ true ->
+ []
+ end,
+ AllocatorMem = alloc_mem_info(Instances),
+ alloc_info(Allocators, Allocs, [{Allocator, AllocatorMem} | Acc]);
+
+ false ->
+ alloc_info(Allocators, Allocs, Acc)
+ end.
+
+alloc_mem_info(Instances) ->
+ alloc_mem_info(Instances, []).
+
+alloc_mem_info([], Acc) ->
+ lists:sum([Mem || {instance, _, Mem} <- Acc]);
+alloc_mem_info([{instance, N, Info}|Instances], Acc) ->
+ InstanceMemInfo = alloc_instance_mem_info(Info),
+ alloc_mem_info(Instances, [{instance, N, InstanceMemInfo} | Acc]).
+
+alloc_instance_mem_info(InstanceInfo) ->
+ MBCS = alloc_instance_mem_info(mbcs, InstanceInfo),
+ SBCS = alloc_instance_mem_info(sbcs, InstanceInfo),
+ MBCS + SBCS.
+
+alloc_instance_mem_info(Key, InstanceInfo) ->
+ case lists:keysearch(Key, 1, InstanceInfo) of
+ {value, {Key, Info}} ->
+ case lists:keysearch(blocks_size, 1, Info) of
+ {value, {blocks_size, Mem, _, _}} ->
+ Mem;
+ _ ->
+ 0
+ end;
+ _ ->
+ 0
+ end.
+
+
+display_system_info(WhenStr) ->
+ display_system_info(WhenStr, undefined, undefined).
+
+display_system_info(WhenStr, undefined, undefined) ->
+ display_system_info(WhenStr, "");
+display_system_info(WhenStr, Mod, Func) ->
+ ModFuncStr = lists:flatten(io_lib:format(" ~w:~w", [Mod, Func])),
+ display_system_info(WhenStr, ModFuncStr).
+
+display_system_info(WhenStr, ModFuncStr) ->
+ Fun = fun(F) -> case (catch F()) of
+ {'EXIT', _} ->
+ undefined;
+ Res ->
+ Res
+ end
+ end,
+ ProcCount = Fun(fun() -> erlang:system_info(process_count) end),
+ ProcLimit = Fun(fun() -> erlang:system_info(process_limit) end),
+ ProcMemAlloc = Fun(fun() -> erlang:memory(processes) end),
+ ProcMemUsed = Fun(fun() -> erlang:memory(processes_used) end),
+ ProcMemBin = Fun(fun() -> erlang:memory(binary) end),
+ ProcMemTot = Fun(fun() -> erlang:memory(total) end),
+ %% error_logger:info_msg(
+ io:format("~n"
+ "~n*********************************************"
+ "~n"
+ "System info ~s~s => "
+ "~n Process count: ~w"
+ "~n Process limit: ~w"
+ "~n Process memory alloc: ~w"
+ "~n Process memory used: ~w"
+ "~n Memory for binaries: ~w"
+ "~n Memory total: ~w"
+ "~n"
+ "~n*********************************************"
+ "~n"
+ "~n", [WhenStr, ModFuncStr,
+ ProcCount, ProcLimit, ProcMemAlloc, ProcMemUsed,
+ ProcMemBin, ProcMemTot]),
+ ok.
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+prepare_test_case(Actions, N, Config, File, Line) ->
+ OrigNodes = lookup_config(nodes, Config),
+ TestNodes = lookup_config(nodenames, Config), %% For testserver
+ This = node(),
+ SomeNodes = OrigNodes ++ (TestNodes -- OrigNodes),
+ AllNodes = [This | (SomeNodes -- [This])],
+ Nodes = pick_n_nodes(N, AllNodes, File, Line),
+ start_nodes(Nodes, File, Line),
+ do_prepare_test_case(Actions, Nodes, Config, File, Line).
+
+do_prepare_test_case([init | Actions], Nodes, Config, File, Line) ->
+ process_flag(trap_exit, true),
+ megaco_test_lib:flush(),
+ do_prepare_test_case(Actions, Nodes, Config, File, Line);
+do_prepare_test_case([{stop_app, App} | Actions], Nodes, Config, File, Line) ->
+ _Res = rpc:multicall(Nodes, application, stop, [App]),
+ do_prepare_test_case(Actions, Nodes, Config, File, Line);
+do_prepare_test_case([], Nodes, _Config, _File, _Line) ->
+ Nodes.
+
+pick_n_nodes(all, AllNodes, _File, _Line) ->
+ AllNodes;
+pick_n_nodes(N, AllNodes, _File, _Line)
+ when is_integer(N) andalso (length(AllNodes) >= N) ->
+ AllNodes -- lists:nthtail(N, AllNodes);
+pick_n_nodes(N, AllNodes, File, Line) ->
+ fatal_skip({too_few_nodes, N, AllNodes}, File, Line).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+lookup_config(Key, Config) ->
+ case lists:keysearch(Key, 1, Config) of
+ {value, {Key, Val}} ->
+ Val;
+ _ ->
+ []
+ end.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+report_event(_Severity, _Label, _Content) ->
+ %% diameter:report_event(Severity, Label, Content).
+ hopefully_traced.
+
+
+p(F,A) ->
+ io:format("~p" ++ F ++ "~n", [self()|A]).
diff --git a/lib/diameter/test/diameter_test_lib.hrl b/lib/diameter/test/diameter_test_lib.hrl
new file mode 100644
index 0000000000..8b1352f801
--- /dev/null
+++ b/lib/diameter/test/diameter_test_lib.hrl
@@ -0,0 +1,106 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2010. 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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Define common macros for testing
+%%----------------------------------------------------------------------
+%%
+
+-define(FLUSH(), diameter_test_lib:flush()).
+
+-define(SLEEP(MSEC), diameter_test_lib:sleep(MSEC)).
+-define(M(), diameter_test_lib:millis()).
+-define(MDIFF(A,B), diameter_test_lib:millis_diff(A,B)).
+
+-define(HOURS(T), diameter_test_lib:hours(T)).
+-define(MINUTES(T), diameter_test_lib:minutes(T)).
+-define(SECONDS(T), diameter_test_lib:seconds(T)).
+
+-define(KEY1SEARCH(Key, L), diameter_test_lib:key1search(Key, L)).
+
+
+-define(APPLY(Proxy, Fun),
+ Proxy ! {apply, Fun}).
+
+-define(LOG(Format, Args),
+ diameter_test_lib:log(Format, Args, ?MODULE, ?LINE)).
+
+-define(ERROR(Reason),
+ diameter_test_lib:error(Reason, ?MODULE, ?LINE)).
+
+-define(OS_BASED_SKIP(Skippable),
+ diameter_test_lib:os_based_skip(Skippable)).
+
+-define(NON_PC_TC_MAYBE_SKIP(Config, Condition),
+ diameter_test_lib:non_pc_tc_maybe_skip(Config, Condition, ?MODULE, ?LINE)).
+
+-define(FAIL(Reason),
+ diameter_test_lib:fail(Reason, ?MODULE, ?LINE)).
+
+-define(SKIP(Reason),
+ diameter_test_lib:skip(Reason, ?MODULE, ?LINE)).
+
+-define(VERIFYL(Expected, Expr),
+ fun(A,B) when list(A), list(B) ->
+ A1 = lists:sort(A),
+ B1 = lists:sort(B),
+ case A1 of
+ B1 -> ?LOG("Ok, ~p~n", [B]);
+ _ -> ?ERROR(B)
+ end,
+ B;
+ (A,A) ->
+ ?LOG("Ok, ~p~n", [A]),
+ A;
+ (A,B) ->
+ ?ERROR(B),
+ B
+ end(Expected, (catch Expr))).
+
+-define(VERIFY(Expected, Expr),
+ fun() ->
+ AcTuAlReS = (catch (Expr)),
+ case AcTuAlReS of
+ Expected -> ?LOG("Ok, ~p~n", [AcTuAlReS]);
+ _ -> ?ERROR(AcTuAlReS)
+ end,
+ AcTuAlReS
+ end()).
+
+-define(RECEIVE(Expected),
+ ?VERIFY(Expected, ?FLUSH())).
+
+-define(MULTI_RECEIVE(Expected),
+ ?VERIFY(lists:sort(Expected), lists:sort(?FLUSH()))).
+
+-define(ACQUIRE_NODES(N, Config),
+ diameter_test_lib:prepare_test_case([init, {stop_app, diameter}],
+ N, Config, ?FILE, ?LINE)).
+
+
+-define(REPORT_IMPORTANT(Label, Content), ?REPORT_EVENT(20, Label, Content)).
+-define(REPORT_VERBOSE(Label, Content), ?REPORT_EVENT(40, Label, Content)).
+-define(REPORT_DEBUG(Label, Content), ?REPORT_EVENT(60, Label, Content)).
+-define(REPORT_TRACE(Label, Content), ?REPORT_EVENT(80, Label, Content)).
+
+-define(REPORT_EVENT(Severity, Label, Content),
+ diameter_test_lib:report_event(Severity, Label,
+ [{line, ?MODULE, ?LINE} | Content])).
+
diff --git a/lib/diameter/test/diameter_test_server.erl b/lib/diameter/test/diameter_test_server.erl
new file mode 100644
index 0000000000..e2ff73fb8e
--- /dev/null
+++ b/lib/diameter/test/diameter_test_server.erl
@@ -0,0 +1,551 @@
+%%
+%% %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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Lightweight test server
+%%----------------------------------------------------------------------
+
+-module(diameter_test_server).
+
+-export([
+ t/1, t/2,
+
+ init_per_testcase/2,
+ fin_per_testcase/2
+ ]).
+
+-include("diameter_test_lib.hrl").
+
+
+-define(GLOGGER, diameter_global_logger).
+
+
+%% ----------------------------------------------------------------
+%%
+
+t([Case]) when is_atom(Case) ->
+ t(Case);
+t(Case) ->
+ process_flag(trap_exit, true),
+ MEM = fun() -> case (catch erlang:memory()) of
+ {'EXIT', _} ->
+ [];
+ Res ->
+ Res
+ end
+ end,
+ Alloc1 = diameter_test_lib:alloc_info(),
+ Mem1 = MEM(),
+ Res = lists:flatten(t(Case, default_config())),
+ Alloc2 = diameter_test_lib:alloc_info(),
+ Mem2 = MEM(),
+ %% io:format("Res: ~p~n", [Res]),
+ display_result(Res, Alloc1, Mem1, Alloc2, Mem2),
+ Res.
+
+
+groups(Mod) when is_atom(Mod) ->
+ try Mod:groups() of
+ Groups when is_list(Groups) ->
+ Groups;
+ BadGroups ->
+ exit({bad_groups, Mod, BadGroups})
+ catch
+ _:_ ->
+ []
+ end.
+
+init_suite(Mod, Config) ->
+ io:format("~w:init_suite -> entry with"
+ "~n Mod: ~p"
+ "~n Config: ~p"
+ "~n", [?MODULE, Mod, Config]),
+ Mod:init_per_suite(Config).
+
+end_suite(Mod, Config) ->
+ Mod:end_per_suite(Config).
+
+init_group(Mod, Group, Config) ->
+ Mod:init_per_group(Group, Config).
+
+end_group(Mod, Group, Config) ->
+ Mod:init_per_group(Group, Config).
+
+%% This is for sub-SUITEs
+t({_Mod, {NewMod, all}, _Groups}, _Config) when is_atom(NewMod) ->
+ io:format("~w:t(all) -> entry with"
+ "~n NewMod: ~p"
+ "~n", [?MODULE, NewMod]),
+ t(NewMod);
+t({Mod, {group, Name} = Group, Groups}, Config)
+ when is_atom(Mod) andalso is_atom(Name) andalso is_list(Groups) ->
+ io:format("~w:t(group) -> entry with"
+ "~n Mod: ~p"
+ "~n Name: ~p"
+ "~n Groups: ~p"
+ "~n Config: ~p"
+ "~n", [?MODULE, Mod, Name, Groups, Config]),
+ case lists:keysearch(Name, 1, Groups) of
+ {value, {Name, _Props, GroupsAndCases}} ->
+ try init_group(Mod, Name, Config) of
+ Config2 when is_list(Config2) ->
+ Res = [t({Mod, Case, Groups}, Config2) ||
+ Case <- GroupsAndCases],
+ (catch end_group(Mod, Name, Config2)),
+ Res;
+ Error ->
+ io:format(" => group (~w) init failed: ~p~n",
+ [Name, Error]),
+ [{failed, {Mod, Group}, Error}]
+ catch
+ exit:{skipped, SkipReason} ->
+ io:format(" => skipping group: ~p~n", [SkipReason]),
+ [{skipped, {Mod, Group}, SkipReason, 0}];
+ exit:{undef, _} ->
+ [t({Mod, Case, Groups}, Config) ||
+ Case <- GroupsAndCases];
+ T:E ->
+ [{failed, {Mod, Group}, {T,E}, 0}]
+ end;
+ false ->
+ exit({unknown_group, Mod, Name, Groups})
+ end;
+t({Mod, Fun, _}, Config)
+ when is_atom(Mod) andalso is_atom(Fun) ->
+ io:format("~w:t -> entry with"
+ "~n Mod: ~p"
+ "~n Fun: ~p"
+ "~n Config: ~p"
+ "~n", [?MODULE, Mod, Fun, Config]),
+ case catch apply(Mod, Fun, [suite]) of
+ [] ->
+ io:format("Eval: ~p:", [{Mod, Fun}]),
+ Res = eval(Mod, Fun, Config),
+ {R, _, _, _} = Res,
+ io:format(" ~p~n", [R]),
+ Res;
+
+ Cases when is_list(Cases) ->
+ io:format("Expand: ~p ...~n", [{Mod, Fun}]),
+ Map = fun(Case) when is_atom(Case) -> {Mod, Case};
+ (Case) -> Case
+ end,
+ t(lists:map(Map, Cases), Config);
+
+ {'EXIT', {undef, _}} ->
+ io:format("Undefined: ~p~n", [{Mod, Fun}]),
+ [{nyi, {Mod, Fun}, ok, 0}];
+
+ Error ->
+ io:format("Ignoring: ~p: ~p~n", [{Mod, Fun}, Error]),
+ [{failed, {Mod, Fun}, Error, 0}]
+ end;
+t(Mod, Config) when is_atom(Mod) ->
+ io:format("~w:t -> entry with"
+ "~n Mod: ~p"
+ "~n Config: ~p"
+ "~n", [?MODULE, Mod, Config]),
+ %% This is assumed to be a test suite, so we start by calling
+ %% the top test suite function(s) (all/0 and groups/0).
+ case (catch Mod:all()) of
+ Cases when is_list(Cases) ->
+ %% The list may contain atoms (actual test cases) and
+ %% group-tuples (a tuple naming a group of test cases).
+ %% A group is defined by the (optional) groups/0 function.
+ io:format("~w:t -> suite all ok"
+ "~n Cases: ~p"
+ "~n", [?MODULE, Cases]),
+ Groups = groups(Mod),
+ io:format("~w:t -> "
+ "~n Groups: ~p"
+ "~n", [?MODULE, Groups]),
+ try init_suite(Mod, Config) of
+ Config2 when is_list(Config2) ->
+ io:format("~w:t -> suite init ok"
+ "~n Config2: ~p"
+ "~n", [?MODULE, Config2]),
+ Res = [t({Mod, Case, Groups}, Config2) || Case <- Cases],
+ (catch end_suite(Mod, Config2)),
+ Res;
+ Error ->
+ io:format(" => suite init failed: ~p~n", [Error]),
+ [{failed, {Mod, init_per_suite}, Error}]
+ catch
+ exit:{skipped, SkipReason} ->
+ io:format(" => skipping suite: ~p~n", [SkipReason]),
+ [{skipped, {Mod, init_per_suite}, SkipReason, 0}];
+ exit:{undef, _} ->
+ io:format("~w:t -> suite init failed. exit undef(1)~n", [?MODULE]),
+ [t({Mod, Case, Groups}, Config) || Case <- Cases];
+ exit:undef ->
+ io:format("~w:t -> suite init failed. exit undef(2)~n", [?MODULE]),
+ [t({Mod, Case, Groups}, Config) || Case <- Cases];
+ T:E ->
+ io:format("~w:t -> suite init failed. "
+ "~n T: ~p"
+ "~n E: ~p"
+ "~n", [?MODULE, T,E]),
+ [{failed, {Mod, init_per_suite}, {T,E}, 0}]
+ end;
+ {'EXIT', {undef, _}} ->
+ io:format("Undefined: ~p~n", [{Mod, all}]),
+ [{nyi, {Mod, all}, ok, 0}];
+
+ Crap ->
+ io:format("~w:t -> suite all failed: "
+ "~n Crap: ~p"
+ "~n", [?MODULE, Crap]),
+ Crap
+ end;
+t(Bad, _Config) ->
+ io:format("~w:t -> entry with"
+ "~n Bad: ~p"
+ "~n", [?MODULE, Bad]),
+ [{badarg, Bad, ok, 0}].
+
+eval(Mod, Fun, Config) ->
+ TestCase = {?MODULE, Mod, Fun},
+ Label = lists:concat(["TEST CASE: ", Fun]),
+ ?REPORT_VERBOSE(Label ++ " started", [TestCase, Config]),
+ global:register_name(diameter_test_case_sup, self()),
+ Flag = process_flag(trap_exit, true),
+ put(diameter_test_server, true),
+ Config2 = Mod:init_per_testcase(Fun, Config),
+ Self = self(),
+ Pid = spawn_link(fun() -> do_eval(Self, Mod, Fun, Config2) end),
+ R = wait_for_evaluator(Pid, Mod, Fun, Config2, []),
+ Mod:fin_per_testcase(Fun, Config2),
+ erase(diameter_test_server),
+ global:unregister_name(diameter_test_case_sup),
+ process_flag(trap_exit, Flag),
+ R.
+
+wait_for_evaluator(Pid, Mod, Fun, Config, Errors) ->
+ wait_for_evaluator(Pid, Mod, Fun, Config, Errors, 0).
+wait_for_evaluator(Pid, Mod, Fun, Config, Errors, AccTime) ->
+ TestCase = {?MODULE, Mod, Fun},
+ Label = lists:concat(["TEST CASE: ", Fun]),
+ receive
+ {done, Pid, ok, Time} when Errors =:= [] ->
+ ?REPORT_VERBOSE(Label ++ " ok",
+ [{test_case, TestCase}, {config, Config}]),
+ {ok, {Mod, Fun}, Errors, Time};
+ {done, Pid, ok, Time} ->
+ ?REPORT_VERBOSE(Label ++ " failed",
+ [{test_case, TestCase}, {config, Config}]),
+ {failed, {Mod, Fun}, Errors, Time};
+ {done, Pid, {ok, _}, Time} when Errors =:= [] ->
+ ?REPORT_VERBOSE(Label ++ " ok",
+ [{test_case, TestCase}, {config, Config}]),
+ {ok, {Mod, Fun}, Errors, Time};
+ {done, Pid, {ok, _}, Time} ->
+ ?REPORT_VERBOSE(Label ++ " failed",
+ [{test_case, TestCase}, {config, Config}]),
+ {failed, {Mod, Fun}, Errors, Time};
+ {done, Pid, Fail, Time} ->
+ ?REPORT_IMPORTANT(Label ++ " failed",
+ [{test_case, TestCase},
+ {config, Config},
+ {return, Fail},
+ {errors, Errors}]),
+ {failed, {Mod, Fun}, Fail, Time};
+ {'EXIT', Pid, {skipped, Reason}, Time} ->
+ ?REPORT_IMPORTANT(Label ++ " skipped",
+ [{test_case, TestCase},
+ {config, Config},
+ {skipped, Reason}]),
+ {skipped, {Mod, Fun}, Errors, Time};
+ {'EXIT', Pid, Reason, Time} ->
+ ?REPORT_IMPORTANT(Label ++ " crashed",
+ [{test_case, TestCase},
+ {config, Config},
+ {'EXIT', Reason}]),
+ {crashed, {Mod, Fun}, [{'EXIT', Reason} | Errors], Time};
+ {fail, Pid, Reason, Time} ->
+ wait_for_evaluator(Pid, Mod, Fun, Config,
+ Errors ++ [Reason], AccTime + Time)
+ end.
+
+do_eval(ReplyTo, Mod, Fun, Config) ->
+ diameter_test_lib:display_system_info("before", Mod, Fun),
+ case timer:tc(Mod, Fun, [Config]) of
+ {Time, {'EXIT', {skipped, Reason}}} ->
+ display_tc_time(Time),
+ diameter_test_lib:display_system_info("after (skipped)", Mod, Fun),
+ ReplyTo ! {'EXIT', self(), {skipped, Reason}, Time};
+ {Time, {'EXIT', Reason}} ->
+ display_tc_time(Time),
+ diameter_test_lib:display_system_info("after (crashed)", Mod, Fun),
+ ReplyTo ! {'EXIT', self(), Reason, Time};
+ {Time, Other} ->
+ display_tc_time(Time),
+ diameter_test_lib:display_system_info("after", Mod, Fun),
+ ReplyTo ! {done, self(), Other, Time}
+ end,
+ unlink(ReplyTo),
+ exit(shutdown).
+
+
+display_tc_time(Time) ->
+ io:format("~n"
+ "~n*********************************************"
+ "~n"
+ "~nTest case completion time: ~.3f sec (~w)"
+ "~n", [(Time / 1000000), Time]),
+ ok.
+
+
+display_result(Res, Alloc1, Mem1, Alloc2, Mem2) ->
+ io:format("~nAllocator info: ~n", []),
+ display_alloc(Alloc1, Alloc2),
+ io:format("~nMemory info: ~n", []),
+ display_memory(Mem1, Mem2),
+ display_result(Res).
+
+display_alloc([], []) ->
+ io:format("-~n", []),
+ ok;
+display_alloc(A1, A2) ->
+ do_display_alloc(A1, A2).
+
+do_display_alloc([], _) ->
+ ok;
+do_display_alloc([{Alloc, Mem1}|AllocInfo1], AllocInfo2) ->
+ Mem2 =
+ case lists:keysearch(Alloc, 1, AllocInfo2) of
+ {value, {_, Val}} ->
+ Val;
+ false ->
+ undefined
+ end,
+ io:format("~15w: ~10w -> ~w~n", [Alloc, Mem1, Mem2]),
+ do_display_alloc(AllocInfo1, AllocInfo2).
+
+display_memory([], []) ->
+ io:format("-~n", []),
+ ok;
+display_memory(Mem1, Mem2) ->
+ do_display_memory(Mem1, Mem2).
+
+
+do_display_memory([], _) ->
+ ok;
+do_display_memory([{Key, Mem1}|MemInfo1], MemInfo2) ->
+ Mem2 =
+ case lists:keysearch(Key, 1, MemInfo2) of
+ {value, {_, Val}} ->
+ Val;
+ false ->
+ undefined
+ end,
+ io:format("~15w: ~10w -> ~w~n", [Key, Mem1, Mem2]),
+ do_display_memory(MemInfo1, MemInfo2).
+
+display_result([]) ->
+ io:format("OK~n", []);
+display_result(Res) when is_list(Res) ->
+ Ok = [{MF, Time} || {ok, MF, _, Time} <- Res],
+ Nyi = [MF || {nyi, MF, _, _Time} <- Res],
+ Skipped = [{MF, Reason} || {skipped, MF, Reason, _Time} <- Res],
+ Failed = [{MF, Reason} || {failed, MF, Reason, _Time} <- Res],
+ Crashed = [{MF, Reason} || {crashed, MF, Reason, _Time} <- Res],
+ display_summery(Ok, Nyi, Skipped, Failed, Crashed),
+ display_ok(Ok),
+ display_skipped(Skipped),
+ display_failed(Failed),
+ display_crashed(Crashed).
+
+display_summery(Ok, Nyi, Skipped, Failed, Crashed) ->
+ io:format("~nTest case summery:~n", []),
+ display_summery(Ok, "successfull"),
+ display_summery(Nyi, "not yet implemented"),
+ display_summery(Skipped, "skipped"),
+ display_summery(Failed, "failed"),
+ display_summery(Crashed, "crashed"),
+ io:format("~n", []).
+
+display_summery(Res, Info) ->
+ io:format(" ~w test cases ~s~n", [length(Res), Info]).
+
+display_ok([]) ->
+ ok;
+display_ok(Ok) ->
+ io:format("Ok test cases:~n", []),
+ F = fun({{M, F}, Time}) ->
+ io:format(" ~w : ~w => ~.2f sec~n", [M, F, Time / 1000000])
+ end,
+ lists:foreach(F, Ok),
+ io:format("~n", []).
+
+display_skipped([]) ->
+ ok;
+display_skipped(Skipped) ->
+ io:format("Skipped test cases:~n", []),
+ F = fun({MF, Reason}) -> io:format(" ~p => ~p~n", [MF, Reason]) end,
+ lists:foreach(F, Skipped),
+ io:format("~n", []).
+
+
+display_failed([]) ->
+ ok;
+display_failed(Failed) ->
+ io:format("Failed test cases:~n", []),
+ F = fun({MF, Reason}) -> io:format(" ~p => ~p~n", [MF, Reason]) end,
+ lists:foreach(F, Failed),
+ io:format("~n", []).
+
+display_crashed([]) ->
+ ok;
+display_crashed(Crashed) ->
+ io:format("Crashed test cases:~n", []),
+ F = fun({MF, Reason}) -> io:format(" ~p => ~p~n", [MF, Reason]) end,
+ lists:foreach(F, Crashed),
+ io:format("~n", []).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Test server callbacks
+init_per_testcase(_Case, Config) ->
+ Pid = group_leader(),
+ Name = ?GLOGGER,
+ case global:whereis_name(Name) of
+ undefined ->
+ global:register_name(?GLOGGER, Pid);
+ Pid ->
+ io:format("~w:init_per_testcase -> "
+ "already registered to ~p~n", [?MODULE, Pid]),
+ ok;
+ OtherPid when is_pid(OtherPid) ->
+ io:format("~w:init_per_testcase -> "
+ "already registered to other ~p (~p)~n",
+ [?MODULE, OtherPid, Pid]),
+ exit({already_registered, {?GLOGGER, OtherPid, Pid}})
+ end,
+ set_kill_timer(Config).
+
+fin_per_testcase(_Case, Config) ->
+ Name = ?GLOGGER,
+ case global:whereis_name(Name) of
+ undefined ->
+ io:format("~w:fin_per_testcase -> already un-registered~n",
+ [?MODULE]),
+ ok;
+ Pid when is_pid(Pid) ->
+ global:unregister_name(?GLOGGER),
+ ok
+ end,
+ reset_kill_timer(Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Set kill timer
+
+set_kill_timer(Config) ->
+ case init:get_argument(diameter_test_timeout) of
+ {ok, _} ->
+ Config;
+ _ ->
+ Time =
+ case lookup_config(tc_timeout, Config) of
+ [] ->
+ timer:minutes(5);
+ ConfigTime when is_integer(ConfigTime) ->
+ ConfigTime
+ end,
+ Dog =
+ case get(diameter_test_server) of
+ true ->
+ Self = self(),
+ spawn_link(fun() -> watchdog(Self, Time) end);
+ _ ->
+ test_server:timetrap(Time)
+ end,
+ [{kill_timer, Dog}|Config]
+
+
+ end.
+
+reset_kill_timer(Config) ->
+ DogKiller =
+ case get(diameter_test_server) of
+ true ->
+ fun(P) when is_pid(P) -> P ! stop;
+ (_) -> ok
+ end;
+ _ ->
+ fun(Ref) -> test_server:timetrap_cancel(Ref) end
+ end,
+ case lists:keysearch(kill_timer, 1, Config) of
+ {value, {kill_timer, Dog}} ->
+ DogKiller(Dog),
+ lists:keydelete(kill_timer, 1, Config);
+ _ ->
+ Config
+ end.
+
+watchdog(Pid, Time) ->
+ erlang:now(),
+ receive
+ stop ->
+ ok
+ after Time ->
+ case (catch process_info(Pid)) of
+ undefined ->
+ ok;
+ Info ->
+ ?LOG("<ERROR> Watchdog in test case timed out "
+ "for ~p after ~p min"
+ "~n~p"
+ "~n",
+ [Pid, Time div (1000*60), Info]),
+ exit(Pid, kill)
+ end
+ end.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+lookup_config(Key, Config) ->
+ diameter_test_lib:lookup_config(Key, Config).
+
+default_config() ->
+ [{nodes, default_nodes()}, {ts, diameter}].
+
+default_nodes() ->
+ mk_nodes(2, []).
+
+mk_nodes(0, Nodes) ->
+ Nodes;
+mk_nodes(N, []) ->
+ mk_nodes(N - 1, [node()]);
+mk_nodes(N, Nodes) when N > 0 ->
+ Head = hd(Nodes),
+ [Name, Host] = node_to_name_and_host(Head),
+ Nodes ++ [mk_node(I, Name, Host) || I <- lists:seq(1, N)].
+
+mk_node(N, Name, Host) ->
+ list_to_atom(lists:concat([Name ++ integer_to_list(N) ++ "@" ++ Host])).
+
+%% Returns [Name, Host]
+node_to_name_and_host(Node) ->
+ string:tokens(atom_to_list(Node), [$@]).
+
+
+
+
diff --git a/lib/diameter/test/modules.mk b/lib/diameter/test/modules.mk
new file mode 100644
index 0000000000..fa8b4a8eda
--- /dev/null
+++ b/lib/diameter/test/modules.mk
@@ -0,0 +1,47 @@
+#-*-makefile-*- ; force emacs to enter makefile-mode
+
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2010. All Rights Reserved.
+#
+# The contents of this file are subject to the Erlang Public License,
+# Version 1.1, (the "License"); you may not use this file except in
+# compliance with the License. You should have received a copy of the
+# Erlang Public License along with this software. If not, it can be
+# retrieved online at http://www.erlang.org/.
+#
+# Software distributed under the License is distributed on an "AS IS"
+# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+# the License for the specific language governing rights and limitations
+# under the License.
+#
+# %CopyrightEnd%
+
+TEST_SPEC_FILE = diameter.spec
+
+COVER_SPEC_FILE = diameter.cover
+
+BEHAVIOUR_MODULES =
+
+MODULES = \
+ $(BEHAVIOUR_MODULES) \
+ diameter_SUITE \
+ diameter_app_test \
+ diameter_appup_test \
+ diameter_compiler_test \
+ diameter_config_test \
+ diameter_peer_test \
+ diameter_reg_test \
+ diameter_session_test \
+ diameter_stats_test \
+ diameter_sync_test \
+ diameter_tcp_test \
+ diameter_test_lib \
+ diameter_test_server
+
+
+INTERNAL_HRL_FILES = \
+ diameter_test_lib.hrl
+
+
+
diff --git a/lib/diameter/test/slask/diameter_persistent_table_test.erl b/lib/diameter/test/slask/diameter_persistent_table_test.erl
new file mode 100644
index 0000000000..25bbe41347
--- /dev/null
+++ b/lib/diameter/test/slask/diameter_persistent_table_test.erl
@@ -0,0 +1,495 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2010. 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%
+%%
+
+%%
+%%----------------------------------------------------------------------
+%% Purpose: Verify the persistent-table component of the Diameter application
+%%----------------------------------------------------------------------
+%%
+-module(diameter_persistent_table_test).
+
+-export([
+ init_per_testcase/2, fin_per_testcase/2,
+
+ all/1,
+ suite_init/1, suite_fin/1,
+
+ simple_start_and_stop/1,
+ table_create_and_delete/1
+
+ ]).
+
+-export([t/0, t/1]).
+
+-include("diameter_test_lib.hrl").
+
+-record(command, {id, desc, cmd, verify}).
+
+
+t() -> diameter_test_server:t(?MODULE).
+t(Case) -> diameter_test_server:t({?MODULE, Case}).
+
+
+%% Test server callbacks
+init_per_testcase(Case, Config) ->
+ diameter_test_server:init_per_testcase(Case, Config).
+
+fin_per_testcase(Case, Config) ->
+ diameter_test_server:fin_per_testcase(Case, Config).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all(suite) ->
+ Cases =
+ [
+ simple_start_and_stop,
+ table_create_and_delete
+ ],
+ {req, [], {conf, suite_init, Cases, suite_fin}}.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite_init(suite) -> [];
+suite_init(doc) -> [];
+suite_init(Config) when is_list(Config) ->
+ Config.
+
+
+suite_fin(suite) -> [];
+suite_fin(doc) -> [];
+suite_fin(Config) when is_list(Config) ->
+ Config.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Test case(s)
+%%
+
+simple_start_and_stop(suite) ->
+ [];
+simple_start_and_stop(doc) ->
+ [];
+simple_start_and_stop(Config) when is_list(Config) ->
+ diameter:enable_trace(100, io),
+ case diameter_persistent_table:start_link() of
+ {ok, Pid} ->
+ unlink(Pid);
+ {error, Reason} ->
+ exit({failed_starting, Reason})
+ end,
+
+ ok = diameter_persistent_table:stop(),
+ ok.
+
+
+table_create_and_delete(suite) ->
+ [];
+table_create_and_delete(doc) ->
+ [];
+table_create_and_delete(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+
+ %% Command range values
+ Initial = 100,
+ ClientCreation = 200,
+ Nice = 300,
+ Evil = 400,
+ End = 500,
+
+ Verbosity = min,
+ %% Verbosity = max,
+
+ Data01 = lists:sort([{a, 10}, {b, 20}, {c, 30}]),
+ Data02 = lists:sort([{x, 100}, {y, 200}, {z, 300}]),
+
+ Commands =
+ [
+ %% Initial commands
+ initial_command( Initial + 0,
+ "enable trace",
+ fun() -> diameter:enable_trace(Verbosity, io) end,
+ ok),
+ initial_command( Initial + 1,
+ "start persistent-table process",
+ fun() ->
+ case diameter_persistent_table:start_link() of
+ {ok, Pid} when is_pid(Pid) ->
+ ok;
+ Error ->
+ Error
+ end
+ end,
+ ok),
+
+ client_create_command( ClientCreation + 1,
+ "1",
+ client01),
+
+ client_create_command( ClientCreation + 2,
+ "2",
+ client02),
+
+ nice_command( Nice + 1,
+ "client 1 create table 1",
+ fun() ->
+ create_table(client01, tab01, []),
+ diameter_persistent_table:which_tables()
+ end,
+ fun([tab01] = Tabs) ->
+ {ok, Tabs};
+ (Unexpected) ->
+ {error, {bad_tables, Unexpected}}
+ end),
+
+ nice_command( Nice + 2,
+ "client 1 create table 2",
+ fun() ->
+ create_table(client01, tab02, []),
+ diameter_persistent_table:which_tables()
+ end,
+ fun([tab01, tab02] = Tabs) ->
+ {ok, Tabs};
+ ([tab02, tab01] = Tabs) ->
+ {ok, Tabs};
+ (Unexpected) ->
+ {error, {bad_tables, Unexpected}}
+ end),
+
+ nice_command( Nice + 3,
+ "client 2 create table 1",
+ fun() ->
+ create_table(client02, tab03, []),
+ diameter_persistent_table:which_tables(whereis(client02))
+ end,
+ fun([tab03] = Tabs) ->
+ {ok, Tabs};
+ (Unexpected) ->
+ {error, {bad_tables, Unexpected}}
+ end),
+
+ nice_command( Nice + 4,
+ "client 1 delete table 1",
+ fun() ->
+ delete_table(client01, tab01),
+ diameter_persistent_table:which_tables(whereis(client01))
+ end,
+ fun([tab02] = Tabs) ->
+ {ok, Tabs};
+ (Unexpected) ->
+ {error, {bad_tables, Unexpected}}
+ end),
+
+ nice_command( Nice + 5,
+ "client 1 fill in some data in tab02",
+ fun() ->
+ populate_table(client01, tab02, Data01),
+ lists:sort(ets:tab2list(tab02))
+ end,
+ fun(Data) when Data =:= Data01 ->
+ {ok, Data};
+ (Unexpected) ->
+ {error, {bad_data, Unexpected}}
+ end),
+
+ nice_command( Nice + 6,
+ "client 2 fill in some data in tab03",
+ fun() ->
+ populate_table(client02, tab03, Data02),
+ lists:sort(ets:tab2list(tab03))
+ end,
+ fun(Data) when Data =:= Data02 ->
+ {ok, Data};
+ (Unexpected) ->
+ {error, {bad_data, Unexpected}}
+ end),
+
+ nice_command( Nice + 7,
+ "simulate client 1 crash",
+ fun() ->
+ simulate_crash(client01)
+ end,
+ fun(ok) ->
+ {ok, crashed};
+ (Unexpected) ->
+ {error, {bad_simulation_result, Unexpected}}
+ end),
+
+ client_create_command( Nice + 8,
+ "1 restarted",
+ client01),
+
+ nice_command( Nice + 9,
+ "client 1 create tab02 - verify data",
+ fun() ->
+ create_table(client01, tab02, []),
+ lists:sort(ets:tab2list(tab02))
+ end,
+ fun(Data) when Data =:= Data01 ->
+ {ok, Data};
+ (Unexpected) ->
+ {error, {bad_data, Unexpected}}
+ end),
+
+ evil_command( Evil + 1,
+ "try (and fail) to delete the non-existing table tab04",
+ fun() ->
+ delete_table(client02, tab04)
+ end,
+ fun({error, {unknown_table, tab04}}) ->
+ {ok, tab04};
+ (X) ->
+ {error, {bad_result, X}}
+ end),
+
+ evil_command( Evil + 2,
+ "try (and fail) to delete a not owned table tab02",
+ fun() ->
+ delete_table(client02, tab02)
+ end,
+ fun({error, {not_owner, tab02}}) ->
+ {ok, tab02};
+ (X) ->
+ {error, {bad_result, X}}
+ end),
+
+ evil_command( Evil + 3,
+ "try (and fail) to create an already existing *and* owned table - tab03",
+ fun() ->
+ create_table(client02, tab03, [])
+ end,
+ fun({error, {already_owner, tab03}}) ->
+ {ok, tab03};
+ (X) ->
+ {error, {bad_result, X}}
+ end),
+
+ evil_command( Evil + 4,
+ "try (and fail) to create an already existing not owned table - tab02",
+ fun() ->
+ create_table(client02, tab02, [])
+ end,
+ fun({error, {not_owner, _Owner, tab02}}) ->
+ {ok, tab02};
+ (X) ->
+ {error, {bad_result, X}}
+ end),
+
+ end_command( End + 1,
+ "stop client01",
+ fun() -> stop_client(client01) end),
+
+ end_command( End + 2,
+ "stop client02",
+ fun() -> stop_client(client02) end),
+
+ end_command( End + 2,
+ "stop persistent-table",
+ fun() -> diameter_persistent_table:stop() end),
+
+ evil_command( Evil + 5,
+ "try (and fail) to stop a not running persistent-table process",
+ fun() ->
+ diameter_persistent_table:stop()
+ end,
+ fun({'EXIT', {noproc, _}}) ->
+ {ok, not_running};
+ (X) ->
+ {error, {bad_result, X}}
+ end)
+
+ ],
+
+ exec(Commands).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%
+%% Command engine
+%%
+
+exec([]) ->
+ ok;
+exec([#command{id = No,
+ desc = Desc,
+ cmd = Cmd,
+ verify = Verify}|Commands]) ->
+ io:format("Executing command ~2w: ~s: ", [No, Desc]),
+ case (catch Verify((catch Cmd()))) of
+ {ok, OK} ->
+ io:format("ok => ~p~n", [OK]),
+ exec(Commands);
+ {error, Reason} ->
+ io:format("error => ~p~n", [Reason]),
+ {error, {bad_result, No, Reason}};
+ Error ->
+ io:format("exit => ~p~n", [Error]),
+ {error, {unexpected_result, No, Error}}
+ end.
+
+initial_command(No, Desc0, Cmd, VerifyVal) when is_function(Cmd) ->
+ Desc = lists:flatten(io_lib:format("Initial - ~s", [Desc0])),
+ command(No, Desc, Cmd, VerifyVal).
+
+client_create_command(No, Desc0, Name) ->
+ Desc = lists:flatten(io_lib:format("Client create - ~s", [Desc0])),
+ Self = self(),
+ Cmd = fun() -> start_client(Self, Name) end,
+ command(No, Desc, Cmd, ok).
+
+nice_command(No, Desc0, Cmd, Verify)
+ when is_function(Cmd) andalso is_function(Verify) ->
+ Desc = lists:flatten(io_lib:format("Nice - ~s", [Desc0])),
+ command(No, Desc, Cmd, Verify).
+
+evil_command(No, Desc0, Cmd, Verify)
+ when is_function(Cmd) andalso is_function(Verify) ->
+ Desc = lists:flatten(io_lib:format("Evil - ~s", [Desc0])),
+ command(No, Desc, Cmd, Verify).
+
+end_command(No, Desc0, Cmd) when is_function(Cmd) ->
+ Desc = lists:flatten(io_lib:format("End - ~s", [Desc0])),
+ command(No, Desc, Cmd, ok).
+
+command(No, Desc, Cmd, Verify)
+ when (is_integer(No) andalso
+ is_list(Desc) andalso
+ is_function(Cmd) andalso
+ is_function(Verify)) ->
+ #command{id = No,
+ desc = Desc,
+ cmd = Cmd,
+ verify = Verify};
+command(No, Desc, Cmd, VerifyVal)
+ when (is_integer(No) andalso
+ is_list(Desc) andalso
+ is_function(Cmd)) ->
+ Verify =
+ fun(Val) ->
+ case Val of
+ VerifyVal ->
+ {ok, Val};
+ _ ->
+ {error, Val}
+ end
+ end,
+ #command{id = No,
+ desc = Desc,
+ cmd = Cmd,
+ verify = Verify}.
+
+
+start_client(Parent, Name) ->
+ ClientPid = spawn_link(fun() -> client_init(Parent, Name) end),
+ receive
+ {ClientPid, started} ->
+ ClientPid,
+ ok;
+ {'EXIT', ClientPid, Reason} ->
+ {error, {failed_starting_client, Reason}}
+ end.
+
+stop_client(Client) ->
+ Pid = whereis(Client),
+ Pid ! stop,
+ receive
+ {'EXIT', Pid, normal} ->
+ ok
+ end.
+
+create_table(Client, Tab, Opts) ->
+ Self = self(),
+ Pid = whereis(Client),
+ Pid ! {create_table, Tab, Opts, Self},
+ receive
+ {Pid, created} ->
+ ok;
+ {Pid, {create_failed, Error}} ->
+ Error
+ end.
+
+delete_table(Client, Tab) ->
+ Self = self(),
+ Pid = whereis(Client),
+ Pid ! {delete_table, Tab, Self},
+ receive
+ {Pid, deleted} ->
+ ok;
+ {Pid, {delete_failed, Error}} ->
+ Error
+ end.
+
+populate_table(Client, Tab, Data) ->
+ Self = self(),
+ Pid = whereis(Client),
+ Pid ! {populate_table, Tab, Data, Self},
+ receive
+ {Pid, populated} ->
+ ok
+ end.
+
+simulate_crash(Client) ->
+ Pid = whereis(Client),
+ Pid ! simulate_crash,
+ receive
+ {'EXIT', Pid, simulated_crash} ->
+ ok
+ end.
+
+client_init(Parent, Name) ->
+ erlang:register(Name, self()),
+ process_flag(trap_exit, true),
+ Parent ! {self(), started},
+ client_loop().
+
+client_loop() ->
+ receive
+ stop ->
+ exit(normal);
+
+ {create_table, T, Opts, From} when is_atom(T) andalso is_list(Opts) ->
+ case diameter_persistent_table:create(T, Opts) of
+ ok ->
+ From ! {self(), created};
+ Error ->
+ From ! {self(), {create_failed, Error}}
+ end,
+ client_loop();
+
+ {delete_table, T, From} ->
+ case diameter_persistent_table:delete(T) of
+ ok ->
+ From ! {self(), deleted};
+ Error ->
+ From ! {self(), {delete_failed, Error}}
+ end,
+ client_loop();
+
+ {populate_table, Tab, Data, From} ->
+ ets:insert(Tab, Data),
+ From ! {self(), populated},
+ client_loop();
+
+ simulate_crash ->
+ exit(simulated_crash)
+ end.
+
diff --git a/lib/diameter/vsn.mk b/lib/diameter/vsn.mk
new file mode 100644
index 0000000000..9f822e4e85
--- /dev/null
+++ b/lib/diameter/vsn.mk
@@ -0,0 +1,25 @@
+#-*-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%
+
+APPLICATION = diameter
+DIAMETER_VSN = 0.9
+PRE_VSN =
+APP_VSN = "$(APPLICATION)-$(DIAMETER_VSN)$(PRE_VSN)"
+
+TICKETS =
diff --git a/lib/edoc/doc/src/notes.xml b/lib/edoc/doc/src/notes.xml
index c18a126264..630271b115 100644
--- a/lib/edoc/doc/src/notes.xml
+++ b/lib/edoc/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2007</year><year>2010</year>
+ <year>2007</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/edoc/src/edoc.hrl b/lib/edoc/src/edoc.hrl
index 43657b3b8f..31cf45ade9 100644
--- a/lib/edoc/src/edoc.hrl
+++ b/lib/edoc/src/edoc.hrl
@@ -37,7 +37,7 @@
-define(SOURCE_DIR, "src").
-define(EBIN_DIR, "ebin").
-define(EDOC_DIR, "doc").
--define(REPORT_MISSING_TYPE, false).
+-define(REPORT_MISSING_TYPES, false).
-include("edoc_doclet.hrl").
diff --git a/lib/edoc/src/edoc_specs.erl b/lib/edoc/src/edoc_specs.erl
index 45016ef85a..519ade726f 100644
--- a/lib/edoc/src/edoc_specs.erl
+++ b/lib/edoc/src/edoc_specs.erl
@@ -1,4 +1,4 @@
-%
+%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2011. All Rights Reserved.
@@ -428,8 +428,8 @@ get_typevars(Ts) ->
expand_records(Entries, TypeDefs, DT, Opts, File, Module) ->
TypeList = [{type_name(T), T, not_seen} || T <- TypeDefs],
true = ets:insert(DT, TypeList),
- Warn = proplists:get_value(report_missing_type, Opts,
- ?REPORT_MISSING_TYPE) =:= true,
+ Warn = proplists:get_value(report_missing_types, Opts,
+ ?REPORT_MISSING_TYPES) =:= true,
P = #parms{tab = DT, warn = Warn, file = File, line = 0},
ExportedTypes = [Name ||
{export_type,Ts} <- Module#module.attributes,
diff --git a/lib/edoc/src/edoc_tags.erl b/lib/edoc/src/edoc_tags.erl
index def39ee34c..8ee8f87b5f 100644
--- a/lib/edoc/src/edoc_tags.erl
+++ b/lib/edoc/src/edoc_tags.erl
@@ -331,8 +331,8 @@ parse_typedef(Data, Line, _Env, Where) ->
NAs = length(As),
case edoc_types:is_predefined(T, NAs) of
true ->
- case
- edoc_types:is_new_predefined(T, NAs)
+ case
+ edoc_types:is_new_predefined(T, NAs)
orelse edoc_types:is_predefined_otp_type(T, NAs)
of
false ->
@@ -406,17 +406,20 @@ throw_error(L, D) ->
-record(parms, {tab, warn, file, line}).
-check_types(Entries0, Opts, File) ->
- Entries = edoc_data:hidden_filter(Entries0, Opts),
+check_types(Entries, Opts, File) ->
Tags = edoc_data:get_all_tags(Entries),
+ TypeTags = [Tag || #tag{data = {#t_typedef{},_}}=Tag <- Tags],
+ Entries2 = edoc_data:hidden_filter(Entries, Opts),
+ Tags2 = edoc_data:get_all_tags(Entries2),
+ SpecTags = [Tag || #tag{data = #t_spec{}}=Tag <- Tags2],
DT = ets:new(types, [bag]),
_ = [add_type(DT, Name, As, File, Line) ||
#tag{line = Line,
- data = {#t_typedef{name = Name, args = As},_}} <- Tags],
- Warn = proplists:get_value(report_missing_type, Opts,
- ?REPORT_MISSING_TYPE) =:= true,
+ data = {#t_typedef{name = Name, args = As},_}} <- TypeTags],
+ Warn = proplists:get_value(report_missing_types, Opts,
+ ?REPORT_MISSING_TYPES) =:= true,
P = #parms{tab = DT, warn = Warn, file = File, line = 0},
- try check_types(Tags, P)
+ try check_types3(TypeTags++SpecTags, P, [])
after true = ets:delete(DT)
end.
@@ -431,60 +434,64 @@ add_type(DT, Name, Args, File, Line) ->
ets:insert(DT, {Name, NArgs})
end.
-check_types([], _P)->
+check_types3([], _P, _Ls)->
ok;
-check_types([Tag | Tags], P) ->
- check_type(Tag, P, Tags).
+check_types3([Tag | Tags], P, Ls) ->
+ check_type(Tag, P, Ls, Tags).
-check_type(#tag{line = L, data = Data}, P0, Ts) ->
+check_type(#tag{line = L, data = Data}, P0, Ls, Ts) ->
P = P0#parms{line = L},
case Data of
{#t_typedef{type = Type, defs = Defs},_} ->
- check_type(Type, P, Defs++Ts);
+ check_type(Type, P, Ls, Defs++Ts);
#t_spec{type = Type, defs = Defs} ->
- check_type(Type, P, Defs++Ts);
+ LocalTypes =
+ [{N,length(Args)} ||
+ #t_def{name = #t_type{name = N, args = Args}} <- Defs],
+ check_type(Type, P, LocalTypes, Defs),
+ check_types3(Ts, P, Ls);
_->
- check_types(Ts, P0)
+ check_types3(Ts, P0, Ls)
end;
-check_type(#t_def{type = Type}, P, Ts) ->
- check_type(Type, P, Ts);
-check_type(#t_type{name = Name, args = Args}, P, Ts) ->
- check_used_type(Name, Args, P),
- check_types(Args++Ts, P);
-check_type(#t_var{}, P, Ts) ->
- check_types(Ts, P);
-check_type(#t_fun{args = Args, range = Range}, P, Ts) ->
- check_type(Range, P, Args++Ts);
-check_type(#t_tuple{types = Types}, P, Ts) ->
- check_types(Types ++Ts, P);
-check_type(#t_list{type = Type}, P, Ts) ->
- check_type(Type, P, Ts);
-check_type(#t_nil{}, P, Ts) ->
- check_types(Ts, P);
-check_type(#t_paren{type = Type}, P, Ts) ->
- check_type(Type, P, Ts);
-check_type(#t_nonempty_list{type = Type}, P, Ts) ->
- check_type(Type, P, Ts);
-check_type(#t_atom{}, P, Ts) ->
- check_types(Ts, P);
-check_type(#t_integer{}, P, Ts) ->
- check_types(Ts, P);
-check_type(#t_integer_range{}, P, Ts) ->
- check_types(Ts, P);
-check_type(#t_binary{}, P, Ts) ->
- check_types(Ts, P);
-check_type(#t_float{}, P, Ts) ->
- check_types(Ts, P);
-check_type(#t_union{types = Types}, P, Ts) ->
- check_types(Types++Ts, P);
-check_type(#t_record{fields = Fields}, P, Ts) ->
- check_types(Fields++Ts, P);
-check_type(#t_field{type = Type}, P, Ts) ->
- check_type(Type, P, Ts);
-check_type(undefined, P, Ts) ->
- check_types(Ts, P).
-
-check_used_type(#t_name{name = N, module = Mod}=Name, Args, P) ->
+check_type(#t_def{type = Type}, P, Ls, Ts) ->
+ check_type(Type, P, Ls, Ts);
+check_type(#t_type{name = Name, args = Args}, P, Ls, Ts) ->
+ check_used_type(Name, Args, P, Ls),
+ check_types3(Args++Ts, P, Ls);
+check_type(#t_var{}, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls);
+check_type(#t_fun{args = Args, range = Range}, P, Ls, Ts) ->
+ check_type(Range, P, Ls, Args++Ts);
+check_type(#t_tuple{types = Types}, P, Ls, Ts) ->
+ check_types3(Types ++Ts, P, Ls);
+check_type(#t_list{type = Type}, P, Ls, Ts) ->
+ check_type(Type, P, Ls, Ts);
+check_type(#t_nil{}, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls);
+check_type(#t_paren{type = Type}, P, Ls, Ts) ->
+ check_type(Type, P, Ls, Ts);
+check_type(#t_nonempty_list{type = Type}, P, Ls, Ts) ->
+ check_type(Type, P, Ls, Ts);
+check_type(#t_atom{}, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls);
+check_type(#t_integer{}, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls);
+check_type(#t_integer_range{}, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls);
+check_type(#t_binary{}, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls);
+check_type(#t_float{}, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls);
+check_type(#t_union{types = Types}, P, Ls, Ts) ->
+ check_types3(Types++Ts, P, Ls);
+check_type(#t_record{fields = Fields}, P, Ls, Ts) ->
+ check_types3(Fields++Ts, P, Ls);
+check_type(#t_field{type = Type}, P, Ls, Ts) ->
+ check_type(Type, P, Ls, Ts);
+check_type(undefined, P, Ls, Ts) ->
+ check_types3(Ts, P, Ls).
+
+check_used_type(#t_name{name = N, module = Mod}=Name, Args, P, LocalTypes) ->
NArgs = length(Args),
TypeName = {Name, NArgs},
DT = P#parms.tab,
@@ -493,6 +500,7 @@ check_used_type(#t_name{name = N, module = Mod}=Name, Args, P) ->
orelse lists:member(TypeName, ets:lookup(DT, Name))
orelse edoc_types:is_predefined(N, NArgs)
orelse edoc_types:is_predefined_otp_type(N, NArgs)
+ orelse lists:member(TypeName, LocalTypes)
of
true ->
ok;
diff --git a/lib/erl_docgen/priv/bin/specs_gen.escript b/lib/erl_docgen/priv/bin/specs_gen.escript
index 840fed6dd5..982afece7f 100644
--- a/lib/erl_docgen/priv/bin/specs_gen.escript
+++ b/lib/erl_docgen/priv/bin/specs_gen.escript
@@ -2,7 +2,7 @@
%% -*- erlang -*-
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010. All Rights Reserved.
+%% 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
@@ -29,7 +29,7 @@
%%% "-I<dir>" Directory to be searched when including a file.
%%% "-module Module"
%%% Module name to use when there is no File argument.
-%%% A temporary file will be created.
+%%% A empty specifications file will be created.
%%% Exactly one of -module Module and File must be given.
%%%
%%% The name of the generated file is "specs_<module>.xml". Its exact
@@ -67,34 +67,73 @@ usage() ->
halt(1).
call_edoc(FileSpec, InclFs, Dir) ->
- Incl = [{includes, InclFs}],
- Pre = [{preprocess, true}],
- Choice = [{dialyzer_specs, all}],
- DirOpt = [{dir, Dir}],
- Pretty = [{pretty_print, erl_pp}],
- Layout = [{layout, otp_specs},
- {file_suffix, ".specs"},
- {stylesheet, ""}],
- Warn = [{report_missing_type, false},
- {report_type_mismatch, false}],
- OptionList = (DirOpt ++ Choice ++ Pre ++ Warn ++ Pretty ++ Layout ++ Incl),
- {File, TmpFile} = case FileSpec of
- {file, File0} ->
- {File0, false};
- {module, Module} ->
- {create_tmp_file(Dir, Module), true}
- end,
- try edoc:files([File], OptionList) of
- ok ->
- clean_up(Dir, File, TmpFile),
- rename(Dir, File)
+ ReadOpts = [{includes, InclFs}, {preprocess, true}],
+ ExtractOpts = [{report_missing_type, false}],
+ LayoutOpts = [{pretty_printer, erl_pp}, {layout, otp_specs}],
+ File = case FileSpec of
+ {file, File0} -> File0;
+ {module, Module0} -> Module0
+ end,
+ try
+ Fs = case FileSpec of
+ {file, _} ->
+ Fs0 = read_file(File, ReadOpts),
+ clauses(Fs0);
+ {module, Module} ->
+ [{attribute,0,module,list_to_atom(Module)}]
+ end,
+ Doc = extract(File, Fs, ExtractOpts),
+ Text = edoc:layout(Doc, LayoutOpts),
+ ok = write_text(Text, File, Dir),
+ rename(Dir, File)
catch
_:_ ->
io:format("EDoc could not process file '~s'\n", [File]),
- clean_up(Dir, File, TmpFile),
+ clean_up(Dir),
halt(3)
end.
+read_file(File, Opts) ->
+ edoc:read_source(File, Opts).
+
+extract(File, Forms, Opts) ->
+ Env = edoc_lib:get_doc_env([], [], [], _Opts=[]),
+ {_Module, Doc} = edoc_extract:source(Forms, File, Env, Opts),
+ Doc.
+
+clauses(Fs) ->
+ clauses(Fs, no).
+
+clauses([], no) ->
+ [];
+clauses([F | Fs], Spec) ->
+ case F of
+ {attribute,_,spec,_} ->
+ clauses(Fs, F);
+ {function,_,_N,_A,_Cls} when Spec =/= no->
+ {attribute,_,spec,{Name,FunTypes}} = Spec,
+ %% [throw({no,Name,{_N,_A}}) || Name =/= {_N,_A}],
+ %% EDoc doesn't care if a function appears more than once;
+ %% this is how overloaded specs are handled:
+ (lists:append([[setelement(4, Spec, {Name,[T]}),F] ||
+ T <- FunTypes])
+ ++ clauses(Fs, no));
+ _ ->
+ [F | clauses(Fs, Spec)]
+ end.
+
+write_text(Text, File, Dir) ->
+ Base = filename:basename(File, ".erl"),
+ OutFile = filename:join(Dir, Base) ++ ".specs",
+ case file:write_file(OutFile, Text) of
+ ok ->
+ ok;
+ {error, R} ->
+ R1 = file:format_error(R),
+ io:format("could not write file '~s': ~s\n", [File, R1]),
+ halt(2)
+ end.
+
rename(Dir, F) ->
Mod = filename:basename(F, ".erl"),
Old = filename:join(Dir, Mod ++ ".specs"),
@@ -108,22 +147,10 @@ rename(Dir, F) ->
halt(2)
end.
-clean_up(Dir, File, TmpFile) ->
- [file:delete(File) || TmpFile],
+clean_up(Dir) ->
_ = [file:delete(filename:join(Dir, F)) ||
F <- ["packages-frame.html",
"overview-summary.html",
"modules-frame.html",
"index.html", "erlang.png", "edoc-info"]],
ok.
-
-create_tmp_file(Dir, Module) ->
- TmpFile = filename:join(Dir, Module++".erl"),
- case file:write_file(TmpFile, "-module(" ++ Module ++ ").\n") of
- ok ->
- TmpFile;
- {error, R} ->
- R1 = file:format_error(R),
- io:format("could not write file '~s': ~s\n", [TmpFile, R1]),
- halt(2)
- end.
diff --git a/lib/erl_docgen/priv/xsl/db_html.xsl b/lib/erl_docgen/priv/xsl/db_html.xsl
index c6375ea621..982572aeef 100644
--- a/lib/erl_docgen/priv/xsl/db_html.xsl
+++ b/lib/erl_docgen/priv/xsl/db_html.xsl
@@ -22,12 +22,15 @@
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+ xmlns:exsl="http://exslt.org/common"
+ extension-element-prefixes="exsl"
xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<xsl:include href="db_html_params.xsl"/>
<!-- Start of Dialyzer type/spec tags.
- See also the template matching "name" and the template "menu.funcs"
+ See also the templates matching "name" and "seealso" as well as
+ the template "menu.funcs"
-->
<xsl:param name="specs_file" select="''"/>
@@ -38,49 +41,58 @@
<xsl:key name="mod2app" match="module" use="@name"/>
<xsl:template name="err">
+ <xsl:param name="f"/>
<xsl:param name="m"/>
<xsl:param name="n"/>
<xsl:param name="a"/>
<xsl:param name="s"/>
<xsl:message terminate="yes">
- Error <xsl:if test="$m != ''"><xsl:value-of select ="$m"/>:</xsl:if>
- <xsl:value-of
- select="$n"/>/<xsl:value-of
- select="$a"/>: <xsl:value-of select="$s"/>
+ Error <xsl:if test="$f != ''">in <xsl:value-of select ="$f"/>:</xsl:if>
+ <xsl:if test="$m != ''"><xsl:value-of select ="$m"/>:</xsl:if>
+ <xsl:value-of select="$n"/>
+ <xsl:if test="$a != ''">/<xsl:value-of
+ select ="$a"/></xsl:if>: <xsl:value-of select="$s"/>
</xsl:message>
</xsl:template>
- <xsl:template name="spec_name">
+ <xsl:template name="find_spec">
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="mod" select="@mod"/>
<xsl:variable name="name" select="@name"/>
<xsl:variable name="arity" select="@arity"/>
- <xsl:variable name="clause" select="@clause"/>
+ <xsl:variable name="clause_i" select="@clause_i"/>
<xsl:variable name="spec0" select=
"$i/specs/module[@name=$curModule]/spec
[name=$name and arity=$arity
and (string-length($mod) = 0 or module = $mod)]"/>
- <xsl:variable name="spec" select="$spec0[string-length($clause) = 0
- or position() = $clause]"/>
- <xsl:if test="count($spec) = 0">
+ <xsl:variable name="spec" select="$spec0[string-length($clause_i) = 0
+ or position() = $clause_i]"/>
+
+ <xsl:if test="count($spec) != 1">
+ <xsl:variable name="why">
+ <xsl:choose>
+ <xsl:when test="count($spec) > 1">ambiguous spec</xsl:when>
+ <xsl:when test="count($spec) = 0">unknown spec</xsl:when>
+ </xsl:choose>
+ </xsl:variable>
<xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
<xsl:with-param name="m" select="$mod"/>
<xsl:with-param name="n" select="$name"/>
<xsl:with-param name="a" select="$arity"/>
- <xsl:with-param name="s">unknown spec</xsl:with-param>
+ <xsl:with-param name="s" select="$why"/>
</xsl:call-template>
</xsl:if>
+ <xsl:copy-of select="$spec"/>
+ </xsl:template>
- <xsl:variable name="arity_clause">
- <xsl:choose>
- <xsl:when test="string-length(@clause) > 0">
- <xsl:value-of select="@arity"/>/<xsl:value-of select="@clause"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="@arity"/>
- </xsl:otherwise>
- </xsl:choose>
+ <xsl:template name="spec_name">
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="spec0">
+ <xsl:call-template name="find_spec"/>
</xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
<xsl:choose>
<xsl:when test="ancestor::cref">
@@ -89,72 +101,189 @@
</xsl:message>
</xsl:when>
<xsl:when test="ancestor::erlref">
- <a name="{$name}-{$arity_clause}"></a>
- <xsl:choose>
- <xsl:when test="string(@with_guards) = 'no'">
- <xsl:apply-templates select="$spec/contract/clause/head"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:call-template name="contract">
- <xsl:with-param name="contract" select="$spec/contract"/>
- </xsl:call-template>
- </xsl:otherwise>
+ <xsl:choose>
+ <xsl:when test="preceding-sibling::name[position() = 1
+ and @name = $name and @arity = $arity]">
+ <!-- Avoid duplicated anchors.-->
+ </xsl:when>
+ <xsl:otherwise>
+ <a name="{$name}-{$arity}"></a>
+ </xsl:otherwise>
</xsl:choose>
+
+ <xsl:variable name="global_types" select="ancestor::erlref/datatypes"/>
+ <xsl:variable name="local_types"
+ select="../type[string-length(@name) > 0]"/>
+ <xsl:apply-templates select="$spec/contract/clause/head">
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:apply-templates>
</xsl:when>
</xsl:choose>
</xsl:template>
- <xsl:template name="contract">
- <xsl:param name="contract"/>
- <xsl:call-template name="clause">
- <xsl:with-param name="clause" select="$contract/clause"/>
- </xsl:call-template>
- </xsl:template>
-
- <xsl:template name="clause">
- <xsl:param name="clause"/>
- <xsl:variable name="type_desc" select="../type_desc"/>
- <xsl:for-each select="$clause">
- <xsl:apply-templates select="head"/>
- <xsl:if test="count(guard) > 0">
- <xsl:call-template name="guard">
- <xsl:with-param name="guard" select="guard"/>
- <xsl:with-param name="type_desc" select="$type_desc"/>
- </xsl:call-template>
- </xsl:if>
- </xsl:for-each>
- </xsl:template>
-
<xsl:template match="head">
+ <xsl:param name="local_types"/>
+ <xsl:param name="global_types"/>
<span class="bold_code">
- <xsl:apply-templates/>
+ <xsl:apply-templates mode="local_type">
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:apply-templates>
</span>
<br/>
</xsl:template>
- <xsl:template name="guard">
- <xsl:param name="guard"/>
+ <!-- The *last* <name name="..." arity=".."/> -->
+ <xsl:template match="name" mode="types">
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="spec0">
+ <xsl:call-template name="find_spec"/>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
+ <xsl:variable name="clause" select="$spec/contract/clause"/>
+
+ <xsl:variable name="global_types" select="ancestor::erlref/datatypes"/>
+ <xsl:variable name="type_desc" select="../type_desc"/>
+ <!-- $type is data types to be presented as guards ("local types") -->
+ <xsl:variable name="type"
+ select="../type[string-length(@name) > 0
+ or string-length(@variable) > 0]"/>
+ <xsl:variable name="type_variables"
+ select ="$type[string-length(@variable) > 0]"/>
+ <xsl:variable name="local_types"
+ select ="$type[string-length(@name) > 0]"/>
+ <xsl:variable name="output_subtypes" select="count($type_variables) = 0"/>
+
+ <!-- It is assumed there is no support for overloaded specs
+ (there is no spec with more than one clause) -->
+ <xsl:if test="count($clause/guard) > 0 or count($type) > 0">
+ <div class="REFBODY"><p>Types:</p>
+
+ <xsl:choose>
+ <xsl:when test="$output_subtypes">
+ <xsl:call-template name="subtype">
+ <xsl:with-param name="subtype" select="$clause/guard/subtype"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:call-template>
+ </xsl:when>
+ <xsl:otherwise>
+ <xsl:call-template name="type_variables">
+ <xsl:with-param name="type_variables" select="$type_variables"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ <xsl:with-param name="fname" select="$name"/>
+ <xsl:with-param name="arity" select="$arity"/>
+ </xsl:call-template>
+
+ </xsl:otherwise>
+ </xsl:choose>
+
+ <xsl:call-template name="local_type">
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:call-template>
+ </div>
+
+ </xsl:if>
+ </xsl:template>
+
+ <!-- Handle <type variable="..." name_i="..."/> -->
+ <xsl:template name="type_variables">
+ <xsl:param name="type_variables"/>
<xsl:param name="type_desc"/>
- <div class="REFBODY"><p>Types:</p>
+ <xsl:param name="local_types"/>
+ <xsl:param name="global_types"/>
+ <xsl:param name="fname"/>
+ <xsl:param name="arity"/>
+
+ <xsl:variable name="names" select="../name[string-length(@arity) > 0]"/>
+ <xsl:for-each select="$type_variables">
+ <xsl:variable name="name_i">
+ <xsl:choose>
+ <xsl:when test="string-length(@name_i) > 0">
+ <xsl:value-of select="@name_i"/>
+ </xsl:when>
+ <xsl:otherwise>
+ <xsl:value-of select="count($names)"/>
+ </xsl:otherwise>
+ </xsl:choose>
+ </xsl:variable>
+ <xsl:variable name="spec0">
+ <xsl:for-each select="$names[position() = $name_i]">
+ <xsl:call-template name="find_spec"/>
+ </xsl:for-each>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
+ <xsl:variable name="clause" select="$spec/contract/clause"/>
+ <xsl:variable name="variable" select="@variable"/>
+ <xsl:variable name="subtype"
+ select="$clause/guard/subtype[typename = $variable]"/>
+
+ <xsl:if test="count($subtype) = 0">
+ <xsl:call-template name="err">
+ <xsl:with-param name="f" select="ancestor::erlref/module"/>
+ <xsl:with-param name="n" select="$fname"/>
+ <xsl:with-param name="a" select="$arity"/>
+ <xsl:with-param name="s">unknown type variable <xsl:value-of select="$variable"/>
+ </xsl:with-param>
+ </xsl:call-template>
+ </xsl:if>
+
<xsl:call-template name="subtype">
- <xsl:with-param name="subtype" select="$guard/subtype"/>
- <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="subtype" select="$subtype"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
</xsl:call-template>
- </div>
+ </xsl:for-each>
</xsl:template>
<xsl:template name="subtype">
<xsl:param name="subtype"/>
<xsl:param name="type_desc"/>
+ <xsl:param name="local_types"/>
+ <xsl:param name="global_types"/>
+
<xsl:for-each select="$subtype">
<xsl:variable name="tname" select="typename"/>
- <xsl:variable name="tdesc" select="$type_desc[@name = $tname]"/>
<div class="REFTYPES">
<span class="bold_code">
- <xsl:apply-templates select="string"/>
+ <xsl:apply-templates select="string" mode="local_type">
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:apply-templates>
</span>
</div>
- <xsl:apply-templates select="$type_desc[@name = $tname]"/>
+ <xsl:apply-templates select="$type_desc[@variable = $tname]"/>
+ </xsl:for-each>
+ </xsl:template>
+
+ <xsl:template name="local_type">
+ <xsl:param name="type_desc"/>
+ <xsl:param name="local_types"/>
+ <xsl:param name="global_types"/>
+
+ <xsl:for-each select="$local_types">
+ <div class="REFTYPES">
+ <xsl:call-template name="type_name">
+ <xsl:with-param name="mode" select="'local_type'"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:call-template>
+ </div>
+ <xsl:variable name="tname" select="@name"/>
+ <xsl:variable name="tnvars" select="@n_vars"/>
+ <xsl:apply-templates select=
+ "$type_desc[@name = $tname
+ and (@n_vars = $tnvars
+ or string-length(@n_vars) = 0 and
+ string-length($tnvars) = 0)]"/>
</xsl:for-each>
</xsl:template>
@@ -193,130 +322,175 @@
<xsl:apply-templates select="desc"/>
</xsl:template>
- <xsl:template match="typehead">
- <span class="bold_code">
- <xsl:apply-templates/>
- </span><br/>
- </xsl:template>
-
- <!-- local_defs -->
- <xsl:template match="local_defs">
- <div class="REFBODY">
- <xsl:apply-templates>
- </xsl:apply-templates>
- </div>
- </xsl:template>
-
- <xsl:template match="local_def">
- <div class="REFTYPES">
- <span class="bold_code">
- <xsl:apply-templates/>
- </span>
- </div>
- </xsl:template>
+ <!-- The "mode" attribute of apply has been used to separate the case
+ when datatypes are copied into specifications' subtypes.
+ A local type has no anchor. There are no links to local types
+ from local types or guards/head of the same specification.
+ -->
<xsl:template name="type_name">
+ <xsl:param name="mode"/> <!-- '' if <datatype> -->
+ <xsl:param name="local_types" select="/.."/>
+ <xsl:param name="global_types" select="/.."/>
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="mod" select="@mod"/>
<xsl:variable name="name" select="@name"/>
- <xsl:variable name="n_vars">
- <xsl:choose>
- <xsl:when test="string-length(@n_vars) > 0">
- <xsl:value-of select="@n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="0"/>
- </xsl:otherwise>
- </xsl:choose>
- </xsl:variable>
+ <xsl:variable name="n_vars" select="@n_vars"/>
<xsl:choose>
<xsl:when test="string-length($name) > 0">
<xsl:variable name="type" select=
"$i/specs/module[@name=$curModule]/type
- [name=$name and n_vars=$n_vars
+ [name=$name
+ and (string-length($n_vars) = 0 or n_vars = $n_vars)
and (string-length($mod) = 0 or module = $mod)]"/>
<xsl:if test="count($type) != 1">
+ <xsl:variable name="why">
+ <xsl:choose>
+ <xsl:when test="count($type) > 1">ambiguous type</xsl:when>
+ <xsl:when test="count($type) = 0">unknown type</xsl:when>
+ </xsl:choose>
+ </xsl:variable>
<xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
<xsl:with-param name="m" select="$mod"/>
<xsl:with-param name="n" select="$name"/>
<xsl:with-param name="a" select="$n_vars"/>
- <xsl:with-param name="s">unknown type</xsl:with-param>
+ <xsl:with-param name="s" select="$why"/>
</xsl:call-template>
</xsl:if>
- <xsl:apply-templates select="$type/typedecl"/>
+ <xsl:choose>
+ <xsl:when test="$mode = ''">
+ <xsl:apply-templates select="$type/typedecl"/>
+ </xsl:when>
+ <xsl:when test="$mode = 'local_type'">
+ <xsl:apply-templates select="$type/typedecl" mode="local_type">
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:apply-templates>
+ </xsl:when>
+ </xsl:choose>
</xsl:when>
- <xsl:otherwise>
+ <xsl:otherwise> <!-- <datatype> with <name> -->
<span class="bold_code">
- <xsl:value-of select="."/>
+ <xsl:apply-templates/>
</span>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
+ <xsl:template match="typehead">
+ <span class="bold_code">
+ <xsl:apply-templates/>
+ </span><br/>
+ </xsl:template>
+
+ <xsl:template match="typehead" mode="local_type">
+ <xsl:param name="local_types"/>
+ <xsl:param name="global_types"/>
+ <span class="bold_code">
+ <xsl:apply-templates mode="local_type">
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="global_types" select="$global_types"/>
+ </xsl:apply-templates>
+ </span><br/>
+ </xsl:template>
+
+ <!-- Not used right now -->
+ <!-- local_defs -->
+ <xsl:template match="local_defs">
+ <div class="REFBODY">
+ <xsl:apply-templates>
+ </xsl:apply-templates>
+ </div>
+ </xsl:template>
+
+ <!-- Not used right now -->
+ <xsl:template match="local_def">
+ <div class="REFTYPES">
+ <span class="bold_code">
+ <xsl:apply-templates/>
+ </span>
+ </div>
+ </xsl:template>
+
<!-- Used both in <datatype> and in <func>! -->
<xsl:template match="anno">
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="anno" select="normalize-space(text())"/>
<xsl:variable name="namespec"
- select="ancestor::desc/preceding-sibling::name"/>
+ select="ancestor::type_desc/preceding-sibling::name
+ | ancestor::desc/preceding-sibling::name"/>
<xsl:if test="count($namespec) = 0 and string-length($specs_file) > 0">
<xsl:call-template name="err">
- <xsl:with-param name="s">cannot find 'name' (<xsl:value-of select="$anno"/>)
+ <xsl:with-param name="f" select="$curModule"/>
+ <xsl:with-param name="s">cannot find tag 'name' (anno <xsl:value-of select="$anno"/>)
</xsl:with-param>
</xsl:call-template>
</xsl:if>
- <xsl:variable name="mod" select="$namespec/@mod"/>
- <xsl:variable name="name" select="$namespec/@name"/>
- <xsl:variable name="arity" select="$namespec/@arity"/>
- <xsl:variable name="clause" select="$namespec/@clause"/>
- <xsl:variable name="tmp_n_vars" select="$namespec/@n_vars"/>
- <xsl:variable name="n_vars">
- <xsl:choose>
- <xsl:when test="string-length($tmp_n_vars) > 0">
- <xsl:value-of select="$tmp_n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="0"/>
- </xsl:otherwise>
- </xsl:choose>
+ <!-- Search "local types" as well -->
+ <xsl:variable name="local_types"
+ select="ancestor::desc/preceding-sibling::type
+ [string-length(@name) > 0]"/>
+ <xsl:variable name="has_anno_in_local_type">
+ <xsl:for-each select="$local_types">
+ <xsl:call-template name="anno_name">
+ <xsl:with-param name="curModule" select="$curModule"/>
+ <xsl:with-param name="anno" select="$anno"/>
+ </xsl:call-template>
+ </xsl:for-each>
+ </xsl:variable>
+
+ <xsl:variable name="has_anno">
+ <xsl:for-each select="$namespec">
+ <xsl:call-template name="anno_name">
+ <xsl:with-param name="curModule" select="$curModule"/>
+ <xsl:with-param name="anno" select="$anno"/>
+ </xsl:call-template>
+ </xsl:for-each>
</xsl:variable>
+
+ <xsl:if test="$has_anno = '' and $has_anno_in_local_type = ''">
+ <xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
+ <xsl:with-param name="m" select="$namespec/@mod"/>
+ <xsl:with-param name="n" select="$namespec/@name"/>
+ <xsl:with-param name="a" select="'-'"/>
+ <xsl:with-param name="s">unknown annotation <xsl:value-of select="$anno"/>
+ </xsl:with-param>
+ </xsl:call-template>
+ </xsl:if>
+ <xsl:value-of select="$anno"/>
+ </xsl:template>
+
+ <xsl:template name="anno_name">
+ <xsl:param name="curModule"/>
+ <xsl:param name="anno"/>
+ <xsl:variable name="mod" select="@mod"/>
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="n_vars" select="@n_vars"/>
+ <xsl:variable name="clause_i" select="@clause_i"/>
+
<xsl:variable name="spec0" select=
"$i/specs/module[@name=$curModule]/spec
[name=$name and arity=$arity
and (string-length($mod) = 0 or module = $mod)]"/>
<xsl:variable name="spec_annos" select=
- "$spec0[string-length($clause) = 0
- or position() = $clause]/anno[.=$anno]"/>
+ "$spec0[string-length($clause_i) = 0
+ or position() = $clause_i]/anno[.=$anno]"/>
<xsl:variable name="type_annos" select=
"$i/specs/module[@name=$curModule]/type
- [name=$name and n_vars=$n_vars
+ [name=$name
+ and (string-length($n_vars) = 0 or n_vars=$n_vars)
and (string-length($mod) = 0 or module = $mod)]/anno[.=$anno]"/>
-
- <xsl:if test="count($spec_annos) = 0
- and count($type_annos) = 0
- and string-length($specs_file) > 0">
- <xsl:variable name="n">
- <xsl:choose>
- <xsl:when test="string-length($arity) = 0">
- <xsl:value-of select="$n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="$arity"/>
- </xsl:otherwise>
- </xsl:choose>
- </xsl:variable>
- <xsl:call-template name="err">
- <xsl:with-param name="m" select="$mod"/>
- <xsl:with-param name="n" select="$name"/>
- <xsl:with-param name="a" select="$n"/>
- <xsl:with-param name="s">unknown annotation <xsl:value-of select="$anno"/>
- </xsl:with-param>
- </xsl:call-template>
+ <xsl:if test="count($spec_annos) != 0
+ or count($type_annos) != 0
+ or string-length($specs_file) = 0">
+ <xsl:value-of select="true()"/>
</xsl:if>
- <xsl:value-of select="$anno"/>
</xsl:template>
<!-- Used for indentation of formatted types and specs -->
@@ -324,6 +498,50 @@
<xsl:text>&#160;</xsl:text>
</xsl:template>
+ <xsl:template match="nbsp" mode="local_type">
+ <xsl:apply-templates select="."/>
+ </xsl:template>
+
+ <xsl:template match="br" mode="local_type">
+ <xsl:apply-templates select="."/>
+ </xsl:template>
+
+ <xsl:template match="marker" mode="local_type">
+ <xsl:param name="local_types"/>
+ <xsl:param name="global_types"/>
+ <!-- Craete no anchor -->
+ <!-- It would be possible to create a link to the global type
+ (if there is one), but that would mean even more code...
+ -->
+ <xsl:apply-templates/>
+ </xsl:template>
+
+ <!-- Does not look at @n_vars -->
+ <xsl:template match="seealso" mode="local_type">
+ <xsl:param name="local_types"/>
+ <xsl:param name="global_types"/>
+
+ <xsl:variable name="filepart"><xsl:value-of select="substring-before(@marker, '#')"/></xsl:variable>
+ <xsl:variable name="linkpart"><xsl:value-of select="translate(substring-after(@marker, '#'), '/', '-')"/></xsl:variable>
+
+ <xsl:choose>
+ <xsl:when test="string-length($filepart) > 0">
+ <xsl:call-template name="seealso"/>
+ </xsl:when>
+ <xsl:when test="count($local_types[concat('type-', @name) = $linkpart]) = 0">
+ <xsl:call-template name="seealso"/>
+ </xsl:when>
+ <xsl:when test="count($global_types/datatype/name[concat('type-', @name) = $linkpart]) > 0">
+ <!-- The type is both local and global; link to the global type -->
+ <xsl:call-template name="seealso"/>
+ </xsl:when>
+ <xsl:otherwise>
+ <!-- No link to local type -->
+ <xsl:apply-templates/>
+ </xsl:otherwise>
+ </xsl:choose>
+ </xsl:template>
+
<!-- End of Dialyzer type/spec tags -->
<!-- Page layout -->
@@ -1178,14 +1396,7 @@
<xsl:choose>
<xsl:when test="string-length(@arity) > 0">
<!-- Dialyzer spec -->
- <xsl:choose>
- <xsl:when test="string-length(@clause) > 0">
- <xsl:value-of select="@arity"/>/<xsl:value-of select="@clause"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="@arity"/>
- </xsl:otherwise>
- </xsl:choose>
+ <xsl:value-of select="@arity"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="calc-arity">
@@ -1221,11 +1432,19 @@
</xsl:choose>
</xsl:variable>
- <li title="{$fname}-{$arity}">
- <a href="{$basename}.html#{$fname}-{$arity}">
- <xsl:value-of select="$fname"/>/<xsl:value-of select="$arity"/>
- </a>
- </li>
+ <xsl:choose>
+ <xsl:when test="preceding-sibling::name[position() = 1
+ and @name = $fname and @arity = $arity]">
+ <!-- Skip. Only works for Dialyzer specs. -->
+ </xsl:when>
+ <xsl:otherwise>
+ <li title="{$fname}-{$arity}">
+ <a href="{$basename}.html#{$fname}-{$arity}">
+ <xsl:value-of select="$fname"/>/<xsl:value-of select="$arity"/>
+ </a>
+ </li>
+ </xsl:otherwise>
+ </xsl:choose>
</xsl:when>
</xsl:choose>
@@ -1470,7 +1689,10 @@
<xsl:template match="func">
<xsl:param name="partnum"/>
- <p><xsl:apply-templates select="name"/></p>
+ <p><xsl:apply-templates select="name"/>
+ <xsl:apply-templates
+ select="name[string-length(@arity) > 0 and position()=last()]"
+ mode="types"/></p>
<xsl:apply-templates select="fsummary|type|desc">
<xsl:with-param name="partnum" select="$partnum"/>
@@ -1478,7 +1700,6 @@
</xsl:template>
-
<xsl:template match="name">
<xsl:choose>
<!-- @arity is mandatory when referring to a specification -->
@@ -1488,6 +1709,11 @@
<xsl:when test="ancestor::datatype">
<xsl:call-template name="type_name"/>
</xsl:when>
+ <xsl:when test="string-length(text()) = 0 and ancestor::erlref">
+ <xsl:message terminate="yes">
+ Error <xsl:value-of select="@name"/>: arity is mandatory when referring to specifications!
+ </xsl:message>
+ </xsl:when>
<xsl:otherwise>
<xsl:call-template name="name"/>
</xsl:otherwise>
@@ -1556,12 +1782,17 @@
<xsl:template match="type">
<xsl:param name="partnum"/>
- <div class="REFBODY"><p>Types:</p>
+ <!-- The case where @name != 0 is taken care of in "type_name" -->
+ <xsl:if test="string-length(@name) = 0 and string-length(@variable) = 0">
- <xsl:apply-templates>
- <xsl:with-param name="partnum" select="$partnum"/>
- </xsl:apply-templates>
- </div>
+ <div class="REFBODY"><p>Types:</p>
+
+ <xsl:apply-templates>
+ <xsl:with-param name="partnum" select="$partnum"/>
+ </xsl:apply-templates>
+ </div>
+
+ </xsl:if>
</xsl:template>
@@ -1612,7 +1843,10 @@
</xsl:template>
<xsl:template match="seealso">
+ <xsl:call-template name="seealso"/>
+ </xsl:template>
+ <xsl:template name="seealso">
<xsl:variable name="filepart"><xsl:value-of select="substring-before(@marker, '#')"/></xsl:variable>
<xsl:variable name="linkpart"><xsl:value-of select="translate(substring-after(@marker, '#'), '/', '-')"/></xsl:variable>
@@ -1633,16 +1867,16 @@
<xsl:variable name="app"
select="$m2a/mod2app/module[@name=$filepart]"/>
-->
- <xsl:variable name="reftext" select="text()"/>
+ <xsl:variable name="this" select="."/>
<xsl:for-each select="$m2a">
<xsl:variable name="app" select="key('mod2app', $filepart)"/>
<xsl:choose>
<xsl:when test="string-length($app) > 0">
- <span class="bold_code"><a href="javascript:erlhref('{$topdocdir}/../','{$app}','{$filepart}.html');"><xsl:value-of select="$reftext"/></a></span>
+ <span class="bold_code"><a href="javascript:erlhref('{$topdocdir}/../','{$app}','{$filepart}.html#{$linkpart}');"><xsl:value-of select="$this"/></a></span>
</xsl:when>
<xsl:otherwise>
<!-- Unknown application; no link -->
- <xsl:value-of select="$reftext"/>
+ <xsl:value-of select="$this"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
diff --git a/lib/erl_docgen/priv/xsl/db_man.xsl b/lib/erl_docgen/priv/xsl/db_man.xsl
index 2a8fb9fe3e..25b62f68c5 100644
--- a/lib/erl_docgen/priv/xsl/db_man.xsl
+++ b/lib/erl_docgen/priv/xsl/db_man.xsl
@@ -3,7 +3,7 @@
#
# %CopyrightBegin%
#
- # Copyright Ericsson AB 2009-2010. All Rights Reserved.
+ # 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
@@ -21,13 +21,16 @@
-->
<xsl:stylesheet version="1.0"
- xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+ xmlns:exsl="http://exslt.org/common"
+ extension-element-prefixes="exsl">
<xsl:preserve-space elements="code pre"/>
<xsl:strip-space elements="*"/>
<xsl:output method="text" encoding="UTF-8" indent="no"/>
- <!-- Start of Dialyzer type/spec tags. See also the template matching "name"
+ <!-- Start of Dialyzer type/spec tags. See also the templates
+ matching "name" and "seealso"
-->
<!-- Note: specs data for *one* module (as opposed to html and pdf) -->
@@ -35,38 +38,58 @@
<xsl:variable name="i" select="document($specs_file)"></xsl:variable>
<xsl:template name="err">
+ <xsl:param name="f"/>
<xsl:param name="m"/>
<xsl:param name="n"/>
<xsl:param name="a"/>
<xsl:param name="s"/>
<xsl:message terminate="yes">
- Error <xsl:if test="$m != ''"><xsl:value-of select ="$m"/>:</xsl:if>
- <xsl:value-of
- select="$n"/>/<xsl:value-of
- select="$a"/>: <xsl:value-of select="$s"/>
+ Error <xsl:if test="$f != ''">in <xsl:value-of select ="$f"/>:</xsl:if>
+ <xsl:if test="$m != ''"><xsl:value-of select ="$m"/>:</xsl:if>
+ <xsl:value-of select="$n"/>
+ <xsl:if test="$a != ''">/<xsl:value-of
+ select ="$a"/></xsl:if>: <xsl:value-of select="$s"/>
</xsl:message>
</xsl:template>
- <xsl:template name="spec_name">
+ <xsl:template name="find_spec">
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="mod" select="@mod"/>
<xsl:variable name="name" select="@name"/>
<xsl:variable name="arity" select="@arity"/>
- <xsl:variable name="clause" select="@clause"/>
+ <xsl:variable name="clause_i" select="@clause_i"/>
<xsl:variable name="spec0" select=
"$i/module[@name=$curModule]/spec
[name=$name and arity=$arity
and (string-length($mod) = 0 or module = $mod)]"/>
- <xsl:variable name="spec" select="$spec0[string-length($clause) = 0
- or position() = $clause]"/>
- <xsl:if test="count($spec) = 0">
+ <xsl:variable name="spec" select="$spec0[string-length($clause_i) = 0
+ or position() = $clause_i]"/>
+
+ <xsl:if test="count($spec) != 1">
+ <xsl:variable name="why">
+ <xsl:choose>
+ <xsl:when test="count($spec) > 1">ambiguous spec</xsl:when>
+ <xsl:when test="count($spec) = 0">unknown spec</xsl:when>
+ </xsl:choose>
+ </xsl:variable>
<xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
<xsl:with-param name="m" select="$mod"/>
<xsl:with-param name="n" select="$name"/>
<xsl:with-param name="a" select="$arity"/>
- <xsl:with-param name="s">unknown spec</xsl:with-param>
+ <xsl:with-param name="s" select="$why"/>
</xsl:call-template>
</xsl:if>
+ <xsl:copy-of select="$spec"/>
+ </xsl:template>
+
+ <xsl:template name="spec_name">
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="spec0">
+ <xsl:call-template name="find_spec"/>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
<xsl:choose>
<xsl:when test="ancestor::cref">
@@ -75,42 +98,12 @@
</xsl:message>
</xsl:when>
<xsl:when test="ancestor::erlref">
- <xsl:choose>
- <xsl:when test="string(@with_guards) = 'no'">
- <xsl:apply-templates select="$spec/contract/clause/head"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:call-template name="contract">
- <xsl:with-param name="contract" select="$spec/contract"/>
- </xsl:call-template>
- </xsl:otherwise>
- </xsl:choose>
+ <xsl:apply-templates select="$spec/contract/clause/head"/>
<xsl:text>&#10;.br</xsl:text>
</xsl:when>
</xsl:choose>
</xsl:template>
- <xsl:template name="contract">
- <xsl:param name="contract"/>
- <xsl:call-template name="clause">
- <xsl:with-param name="clause" select="$contract/clause"/>
- </xsl:call-template>
- </xsl:template>
-
- <xsl:template name="clause">
- <xsl:param name="clause"/>
- <xsl:variable name="type_desc" select="../type_desc"/>
- <xsl:for-each select="$clause">
- <xsl:apply-templates select="head"/>
- <xsl:if test="count(guard) > 0">
- <xsl:call-template name="guard">
- <xsl:with-param name="guard" select="guard"/>
- <xsl:with-param name="type_desc" select="$type_desc"/>
- </xsl:call-template>
- </xsl:if>
- </xsl:for-each>
- </xsl:template>
-
<xsl:template match="head">
<xsl:text>&#10;.nf&#10;</xsl:text>
<xsl:text>&#10;.B&#10;</xsl:text>
@@ -119,29 +112,141 @@
<xsl:text>&#10;.fi</xsl:text>
</xsl:template>
- <xsl:template name="guard">
- <xsl:param name="guard"/>
+ <!-- The *last* <name name="..." arity=".."/> -->
+ <xsl:template match="name" mode="types">
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="spec0">
+ <xsl:call-template name="find_spec"/>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
+ <xsl:variable name="clause" select="$spec/contract/clause"/>
+
+ <xsl:variable name="type_desc" select="../type_desc"/>
+ <!-- $type is data types to be presented as guards ("local types") -->
+ <xsl:variable name="type"
+ select="../type[string-length(@name) > 0
+ or string-length(@variable) > 0]"/>
+ <xsl:variable name="type_variables"
+ select ="$type[string-length(@variable) > 0]"/>
+ <xsl:variable name="local_types"
+ select ="$type[string-length(@name) > 0]"/>
+ <xsl:variable name="output_subtypes" select="count($type_variables) = 0"/>
+
+ <!-- It is assumed there is no support for overloaded specs
+ (there is no spec with more than one clause) -->
+ <xsl:if test="count($clause/guard) > 0 or count($type) > 0">
+ <xsl:text>&#10;.RS</xsl:text>
+ <xsl:text>&#10;.TP</xsl:text>
+ <xsl:text>&#10;Types</xsl:text>
+
+ <xsl:choose>
+ <xsl:when test="$output_subtypes">
+ <xsl:call-template name="subtype">
+ <xsl:with-param name="subtype" select="$clause/guard/subtype"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ </xsl:call-template>
+ </xsl:when>
+ <xsl:otherwise>
+ <xsl:call-template name="type_variables">
+ <xsl:with-param name="type_variables" select="$type_variables"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="fname" select="$name"/>
+ <xsl:with-param name="arity" select="$arity"/>
+ </xsl:call-template>
+
+ </xsl:otherwise>
+ </xsl:choose>
+
+ <xsl:call-template name="local_type">
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ </xsl:call-template>
+ <xsl:text>&#10;.RE</xsl:text>
+
+ </xsl:if>
+ </xsl:template>
+
+ <!-- Handle <type variable="..." name_i="..."/> -->
+ <xsl:template name="type_variables">
+ <xsl:param name="type_variables"/>
<xsl:param name="type_desc"/>
- <xsl:text>&#10;.RS</xsl:text>
- <xsl:text>&#10;.TP</xsl:text>
- <xsl:text>&#10;Types</xsl:text>
- <xsl:call-template name="subtype">
- <xsl:with-param name="subtype" select="$guard/subtype"/>
- <xsl:with-param name="type_desc" select="$type_desc"/>
- </xsl:call-template>
- <xsl:text>&#10;.RE</xsl:text>
+ <xsl:param name="local_types"/>
+ <xsl:param name="fname"/>
+ <xsl:param name="arity"/>
+
+ <xsl:variable name="names" select="../name[string-length(@arity) > 0]"/>
+ <xsl:for-each select="$type_variables">
+ <xsl:variable name="name_i">
+ <xsl:choose>
+ <xsl:when test="string-length(@name_i) > 0">
+ <xsl:value-of select="@name_i"/>
+ </xsl:when>
+ <xsl:otherwise>
+ <xsl:value-of select="count($names)"/>
+ </xsl:otherwise>
+ </xsl:choose>
+ </xsl:variable>
+ <xsl:variable name="spec0">
+ <xsl:for-each select="$names[position() = $name_i]">
+ <xsl:call-template name="find_spec"/>
+ </xsl:for-each>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
+ <xsl:variable name="clause" select="$spec/contract/clause"/>
+ <xsl:variable name="variable" select="@variable"/>
+ <xsl:variable name="subtype"
+ select="$clause/guard/subtype[typename = $variable]"/>
+
+ <xsl:if test="count($subtype) = 0">
+ <xsl:call-template name="err">
+ <xsl:with-param name="f" select="ancestor::erlref/module"/>
+ <xsl:with-param name="n" select="$fname"/>
+ <xsl:with-param name="a" select="$arity"/>
+ <xsl:with-param name="s">unknown type variable <xsl:value-of select="$variable"/>
+ </xsl:with-param>
+ </xsl:call-template>
+ </xsl:if>
+
+ <xsl:call-template name="subtype">
+ <xsl:with-param name="subtype" select="$subtype"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ </xsl:call-template>
+ </xsl:for-each>
</xsl:template>
<xsl:template name="subtype">
<xsl:param name="subtype"/>
<xsl:param name="type_desc"/>
+
<xsl:for-each select="$subtype">
<xsl:variable name="tname" select="typename"/>
- <xsl:variable name="tdesc" select="$type_desc[@name = $tname]"/>
- <xsl:text>&#10;</xsl:text>
- <xsl:apply-templates select="string"/>
- <xsl:text>&#10;.br</xsl:text>
- <xsl:apply-templates select="$type_desc[@name = $tname]"/>
+ <xsl:text>&#10;</xsl:text>
+ <xsl:apply-templates select="string"/>
+ <xsl:text>&#10;.br</xsl:text>
+ <xsl:apply-templates select="$type_desc[@variable = $tname]"/>
+ </xsl:for-each>
+ </xsl:template>
+
+ <xsl:template name="local_type">
+ <xsl:param name="type_desc"/>
+ <xsl:param name="local_types"/>
+
+ <xsl:for-each select ="$local_types">
+ <xsl:text>&#10;</xsl:text>
+ <xsl:call-template name="type_name">
+ <xsl:with-param name="mode" select="'local_type'"/>
+ </xsl:call-template>
+ <xsl:text>&#10;.br</xsl:text>
+ <xsl:variable name="tname" select="@name"/>
+ <xsl:variable name="tnvars" select="@n_vars"/>
+ <xsl:apply-templates select=
+ "$type_desc[@name = $tname
+ and (@n_vars = $tnvars
+ or string-length(@n_vars) = 0 and
+ string-length($tnvars) = 0)]"/>
</xsl:for-each>
</xsl:template>
@@ -164,59 +269,46 @@
<xsl:apply-templates/>
</xsl:template>
- <xsl:template match="typehead">
- <xsl:text>&#10;.nf&#10;</xsl:text>
- <xsl:text>&#10;.B&#10;</xsl:text>
- <xsl:apply-templates/>
- <xsl:text>&#10;.br</xsl:text>
- <xsl:text>&#10;.fi</xsl:text>
- </xsl:template>
-
- <xsl:template match="local_defs">
- <xsl:text>&#10;.RS</xsl:text>
- <xsl:apply-templates/>
- <xsl:text>&#10;.RE</xsl:text>
- </xsl:template>
-
- <xsl:template match="local_def">
- <xsl:text>&#10;</xsl:text>
- <xsl:apply-templates/>
- <xsl:text>&#10;.br</xsl:text>
- </xsl:template>
-
<xsl:template name="type_name">
+ <xsl:param name="mode"/> <!-- '' if <datatype> -->
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="mod" select="@mod"/>
<xsl:variable name="name" select="@name"/>
- <xsl:variable name="n_vars">
- <xsl:choose>
- <xsl:when test="string-length(@n_vars) > 0">
- <xsl:value-of select="@n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="0"/>
- </xsl:otherwise>
- </xsl:choose>
- </xsl:variable>
+ <xsl:variable name="n_vars" select="@n_vars"/>
<xsl:choose>
<xsl:when test="string-length($name) > 0">
<xsl:variable name="type" select=
"$i/module[@name=$curModule]/type
- [name=$name and n_vars=$n_vars
+ [name=$name
+ and (string-length($n_vars) = 0 or n_vars = $n_vars)
and (string-length($mod) = 0 or module = $mod)]"/>
<xsl:if test="count($type) != 1">
+ <xsl:variable name="why">
+ <xsl:choose>
+ <xsl:when test="count($type) > 1">ambiguous type</xsl:when>
+ <xsl:when test="count($type) = 0">unknown type</xsl:when>
+ </xsl:choose>
+ </xsl:variable>
<xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
<xsl:with-param name="m" select="$mod"/>
<xsl:with-param name="n" select="$name"/>
<xsl:with-param name="a" select="$n_vars"/>
- <xsl:with-param name="s">unknown type</xsl:with-param>
+ <xsl:with-param name="s" select="$why"/>
</xsl:call-template>
</xsl:if>
- <xsl:apply-templates select="$type/typedecl"/>
+ <xsl:choose>
+ <xsl:when test="$mode = ''">
+ <xsl:apply-templates select="$type/typedecl"/>
+ </xsl:when>
+ <xsl:when test="$mode = 'local_type'">
+ <xsl:apply-templates select="$type/typedecl" mode="local_type"/>
+ </xsl:when>
+ </xsl:choose>
</xsl:when>
- <xsl:otherwise>
+ <xsl:otherwise> <!-- <datatype> with <name> -->
<xsl:text>&#10;.nf&#10;</xsl:text>
<xsl:text>&#10;.B&#10;</xsl:text>
<xsl:apply-templates/>
@@ -226,68 +318,109 @@
</xsl:choose>
</xsl:template>
+ <xsl:template match="typehead">
+ <xsl:text>&#10;.nf&#10;</xsl:text>
+ <xsl:text>&#10;.B&#10;</xsl:text>
+ <xsl:apply-templates/>
+ <xsl:text>&#10;.br</xsl:text>
+ <xsl:text>&#10;.fi</xsl:text>
+ </xsl:template>
+
+ <xsl:template match="typehead" mode="local_type">
+ <xsl:text>.nf&#10;</xsl:text>
+ <xsl:apply-templates/>
+ <xsl:text>&#10;.fi</xsl:text>
+ </xsl:template>
+
+ <!-- Not used right now -->
+ <xsl:template match="local_defs">
+ <xsl:text>&#10;.RS</xsl:text>
+ <xsl:apply-templates/>
+ <xsl:text>&#10;.RE</xsl:text>
+ </xsl:template>
+
+ <xsl:template match="local_def">
+ <xsl:text>&#10;</xsl:text>
+ <xsl:apply-templates/>
+ <xsl:text>&#10;.br</xsl:text>
+ </xsl:template>
+
<!-- Used both in <datatype> and in <func>! -->
<xsl:template match="anno">
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="anno" select="normalize-space(text())"/>
<xsl:variable name="namespec"
- select="ancestor::desc/preceding-sibling::name"/>
+ select="ancestor::type_desc/preceding-sibling::name
+ | ancestor::desc/preceding-sibling::name"/>
<xsl:if test="count($namespec) = 0 and string-length($specs_file) > 0">
<xsl:call-template name="err">
- <xsl:with-param name="s">cannot find 'name' (<xsl:value-of select="$anno"/>)
+ <xsl:with-param name="f" select="$curModule"/>
+ <xsl:with-param name="s">cannot find tag 'name' (anno <xsl:value-of select="$anno"/>)
</xsl:with-param>
</xsl:call-template>
</xsl:if>
- <xsl:variable name="mod" select="$namespec/@mod"/>
- <xsl:variable name="name" select="$namespec/@name"/>
- <xsl:variable name="arity" select="$namespec/@arity"/>
- <xsl:variable name="clause" select="$namespec/@clause"/>
- <xsl:variable name="tmp_n_vars" select="$namespec/@n_vars"/>
- <xsl:variable name="n_vars">
- <xsl:choose>
- <xsl:when test="string-length($tmp_n_vars) > 0">
- <xsl:value-of select="$tmp_n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="0"/>
- </xsl:otherwise>
- </xsl:choose>
+ <!-- Search "local types" as well -->
+ <xsl:variable name="local_types"
+ select="ancestor::desc/preceding-sibling::type
+ [string-length(@name) > 0]"/>
+ <xsl:variable name="has_anno_in_local_type">
+ <xsl:for-each select="$local_types">
+ <xsl:call-template name="anno_name">
+ <xsl:with-param name="curModule" select="$curModule"/>
+ <xsl:with-param name="anno" select="$anno"/>
+ </xsl:call-template>
+ </xsl:for-each>
+ </xsl:variable>
+
+ <xsl:variable name="has_anno">
+ <xsl:for-each select="$namespec">
+ <xsl:call-template name="anno_name">
+ <xsl:with-param name="curModule" select="$curModule"/>
+ <xsl:with-param name="anno" select="$anno"/>
+ </xsl:call-template>
+ </xsl:for-each>
</xsl:variable>
+
+ <xsl:if test="$has_anno = '' and $has_anno_in_local_type = ''">
+ <xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
+ <xsl:with-param name="m" select="$namespec/@mod"/>
+ <xsl:with-param name="n" select="$namespec/@name"/>
+ <xsl:with-param name="a" select="'-'"/>
+ <xsl:with-param name="s">unknown annotation <xsl:value-of select="$anno"/>
+ </xsl:with-param>
+ </xsl:call-template>
+ </xsl:if>
+ <xsl:value-of select="$anno"/>
+ </xsl:template>
+
+ <xsl:template name="anno_name">
+ <xsl:param name="curModule"/>
+ <xsl:param name="anno"/>
+ <xsl:variable name="mod" select="@mod"/>
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="n_vars" select="@n_vars"/>
+ <xsl:variable name="clause_i" select="@clause_i"/>
+
<xsl:variable name="spec0" select=
"$i/module[@name=$curModule]/spec
[name=$name and arity=$arity
and (string-length($mod) = 0 or module = $mod)]"/>
<xsl:variable name="spec_annos" select=
- "$spec0[string-length($clause) = 0
- or position() = $clause]/anno[.=$anno]"/>
+ "$spec0[string-length($clause_i) = 0
+ or position() = $clause_i]/anno[.=$anno]"/>
<xsl:variable name="type_annos" select=
"$i/module[@name=$curModule]/type
- [name=$name and n_vars=$n_vars
+ [name=$name
+ and (string-length($n_vars) = 0 or n_vars=$n_vars)
and (string-length($mod) = 0 or module = $mod)]/anno[.=$anno]"/>
-
- <xsl:if test="count($spec_annos) = 0
- and count($type_annos) = 0
- and string-length($specs_file) > 0">
- <xsl:variable name="n">
- <xsl:choose>
- <xsl:when test="string-length($arity) = 0">
- <xsl:value-of select="$n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="$arity"/>
- </xsl:otherwise>
- </xsl:choose>
- </xsl:variable>
- <xsl:call-template name="err">
- <xsl:with-param name="m" select="$mod"/>
- <xsl:with-param name="n" select="$name"/>
- <xsl:with-param name="a" select="$n"/>
- <xsl:with-param name="s">unknown annotation <xsl:value-of select="$anno"/>
- </xsl:with-param>
- </xsl:call-template>
+ <xsl:if test="count($spec_annos) != 0
+ or count($type_annos) != 0
+ or string-length($specs_file) = 0">
+ <xsl:value-of select="true()"/>
</xsl:if>
- <xsl:value-of select="$anno"/>
</xsl:template>
<!-- Used for indentation of formatted types and specs -->
@@ -542,6 +675,9 @@
<xsl:template match="func">
<xsl:text>&#10;.LP</xsl:text>
<xsl:apply-templates select="name"/>
+ <xsl:apply-templates
+ select="name[string-length(@arity) > 0 and position()=last()]"
+ mode="types"/>
<xsl:apply-templates select="fsummary|type|desc"/>
</xsl:template>
@@ -554,6 +690,11 @@
<xsl:when test="ancestor::datatype">
<xsl:call-template name="type_name"/>
</xsl:when>
+ <xsl:when test="string-length(text()) = 0 and ancestor::erlref">
+ <xsl:message terminate="yes">
+ Error <xsl:value-of select="@name"/>: arity is mandatory when referring to specifications!
+ </xsl:message>
+ </xsl:when>
<xsl:otherwise>
<xsl:call-template name="name"/>
</xsl:otherwise>
@@ -569,11 +710,14 @@
<!-- Type -->
<xsl:template match="type">
- <xsl:text>&#10;.RS</xsl:text>
- <xsl:text>&#10;.TP</xsl:text>
- <xsl:text>&#10;Types</xsl:text>
- <xsl:apply-templates/>
- <xsl:text>&#10;.RE</xsl:text>
+ <!-- The case where @name != 0 is taken care of in "type_name" -->
+ <xsl:if test="string-length(@name) = 0 and string-length(@variable) = 0">
+ <xsl:text>&#10;.RS</xsl:text>
+ <xsl:text>&#10;.TP</xsl:text>
+ <xsl:text>&#10;Types</xsl:text>
+ <xsl:apply-templates/>
+ <xsl:text>&#10;.RE</xsl:text>
+ </xsl:if>
</xsl:template>
@@ -622,7 +766,7 @@
<xsl:text>&gt;</xsl:text>
</xsl:template>
- <!-- Do not noramlize any text within pre and code tags. -->
+ <!-- Do not normalize any text within pre and code tags. -->
<xsl:template match="pre/text()">
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="." />
diff --git a/lib/erl_docgen/priv/xsl/db_pdf.xsl b/lib/erl_docgen/priv/xsl/db_pdf.xsl
index f500cd3fee..5119e3e36a 100644
--- a/lib/erl_docgen/priv/xsl/db_pdf.xsl
+++ b/lib/erl_docgen/priv/xsl/db_pdf.xsl
@@ -21,6 +21,8 @@
-->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+ xmlns:exsl="http://exslt.org/common"
+ extension-element-prefixes="exsl"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="xml" indent="yes"/>
@@ -28,45 +30,66 @@
<xsl:include href="db_pdf_params.xsl"/>
<!-- Start of Dialyzer type/spec tags.
- See also the template matching "name" and the template "bookmarks6"
+ See also the templates matching "name" and "seealso" as well as
+ the template "bookmarks6"
-->
<xsl:param name="specs_file" select="''"/>
<xsl:variable name="i" select="document($specs_file)"></xsl:variable>
<xsl:template name="err">
+ <xsl:param name="f"/>
<xsl:param name="m"/>
<xsl:param name="n"/>
<xsl:param name="a"/>
<xsl:param name="s"/>
<xsl:message terminate="yes">
- Error <xsl:if test="$m != ''"><xsl:value-of select ="$m"/>:</xsl:if>
- <xsl:value-of
- select="$n"/>/<xsl:value-of
- select="$a"/>: <xsl:value-of select="$s"/>
+ Error <xsl:if test="$f != ''">in <xsl:value-of select ="$f"/>:</xsl:if>
+ <xsl:if test="$m != ''"><xsl:value-of select ="$m"/>:</xsl:if>
+ <xsl:value-of select="$n"/>
+ <xsl:if test="$a != ''">/<xsl:value-of
+ select ="$a"/></xsl:if>: <xsl:value-of select="$s"/>
</xsl:message>
</xsl:template>
- <xsl:template name="spec_name">
+ <xsl:template name="find_spec">
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="mod" select="@mod"/>
<xsl:variable name="name" select="@name"/>
<xsl:variable name="arity" select="@arity"/>
- <xsl:variable name="clause" select="@clause"/>
+ <xsl:variable name="clause_i" select="@clause_i"/>
<xsl:variable name="spec0" select=
"$i/specs/module[@name=$curModule]/spec
[name=$name and arity=$arity
and (string-length($mod) = 0 or module = $mod)]"/>
- <xsl:variable name="spec" select="$spec0[string-length($clause) = 0
- or position() = $clause]"/>
- <xsl:if test="count($spec) = 0">
+ <xsl:variable name="spec" select="$spec0[string-length($clause_i) = 0
+ or position() = $clause_i]"/>
+
+ <xsl:if test="count($spec) != 1">
+ <xsl:variable name="why">
+ <xsl:choose>
+ <xsl:when test="count($spec) > 1">ambiguous spec</xsl:when>
+ <xsl:when test="count($spec) = 0">unknown spec</xsl:when>
+ </xsl:choose>
+ </xsl:variable>
<xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
<xsl:with-param name="m" select="$mod"/>
<xsl:with-param name="n" select="$name"/>
<xsl:with-param name="a" select="$arity"/>
- <xsl:with-param name="s">unknown spec</xsl:with-param>
+ <xsl:with-param name="s" select="$why"/>
</xsl:call-template>
</xsl:if>
+ <xsl:copy-of select="$spec"/>
+ </xsl:template>
+
+ <xsl:template name="spec_name">
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="spec0">
+ <xsl:call-template name="find_spec"/>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
<xsl:choose>
<xsl:when test="ancestor::cref">
@@ -76,78 +99,175 @@
</xsl:when>
<xsl:when test="ancestor::erlref">
<fo:block id="{generate-id()}">
- <xsl:choose>
- <xsl:when test="string(@with_guards) = 'no'">
- <xsl:apply-templates select="$spec/contract/clause/head"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:call-template name="contract">
- <xsl:with-param name="contract" select="$spec/contract"/>
- </xsl:call-template>
- </xsl:otherwise>
- </xsl:choose>
+ <xsl:apply-templates select="$spec/contract/clause/head"/>
</fo:block>
</xsl:when>
</xsl:choose>
</xsl:template>
- <xsl:template name="contract">
- <xsl:param name="contract"/>
- <xsl:call-template name="clause">
- <xsl:with-param name="clause" select="$contract/clause"/>
- </xsl:call-template>
+ <xsl:template match="head">
+ <fo:block xsl:use-attribute-sets="function-name">
+ <xsl:apply-templates/>
+ </fo:block>
</xsl:template>
- <xsl:template name="clause">
- <xsl:param name="clause"/>
+ <!-- The *last* <name name="..." arity=".."/> -->
+ <xsl:template match="name" mode="types">
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="spec0">
+ <xsl:call-template name="find_spec"/>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
+ <xsl:variable name="clause" select="$spec/contract/clause"/>
+
<xsl:variable name="type_desc" select="../type_desc"/>
- <xsl:for-each select="$clause">
- <xsl:apply-templates select="head"/>
- <xsl:if test="count(guard) > 0">
- <xsl:call-template name="guard">
- <xsl:with-param name="guard" select="guard"/>
+ <!-- $type is data types to be presented as guards ("local types") -->
+ <xsl:variable name="type"
+ select="../type[string-length(@name) > 0
+ or string-length(@variable) > 0]"/>
+ <xsl:variable name="type_variables"
+ select ="$type[string-length(@variable) > 0]"/>
+ <xsl:variable name="local_types"
+ select ="$type[string-length(@name) > 0]"/>
+ <xsl:variable name="output_subtypes" select="count($type_variables) = 0"/>
+
+ <!-- It is assumed there is no support for overloaded specs
+ (there is no spec with more than one clause) -->
+ <xsl:if test="count($clause/guard) > 0 or count($type) > 0">
+ <fo:block>
+ <xsl:text>Types:</xsl:text>
+ </fo:block>
+ <fo:list-block xsl:use-attribute-sets="type-listblock">
+ <xsl:choose>
+ <xsl:when test="$output_subtypes">
+ <xsl:call-template name="subtype">
+ <xsl:with-param name="subtype" select="$clause/guard/subtype"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ </xsl:call-template>
+ </xsl:when>
+ <xsl:otherwise>
+ <xsl:call-template name="type_variables">
+ <xsl:with-param name="type_variables" select="$type_variables"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
+ <xsl:with-param name="fname" select="$name"/>
+ <xsl:with-param name="arity" select="$arity"/>
+ </xsl:call-template>
+
+ </xsl:otherwise>
+ </xsl:choose>
+
+ <xsl:call-template name="local_type">
<xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="local_types" select="$local_types"/>
</xsl:call-template>
- </xsl:if>
- </xsl:for-each>
+ </fo:list-block>
+ </xsl:if>
</xsl:template>
- <xsl:template match="head">
- <fo:block xsl:use-attribute-sets="function-name">
- <xsl:apply-templates/>
- </fo:block>
- </xsl:template>
+ <!-- Handle <type variable="..." name_i="..."/> -->
+ <xsl:template name="type_variables">
+ <xsl:param name="type_variables"/>
+ <xsl:param name="type_desc"/>
+ <xsl:param name="local_types"/>
+ <xsl:param name="fname"/>
+ <xsl:param name="arity"/>
+
+ <xsl:variable name="names" select="../name[string-length(@arity) > 0]"/>
+ <xsl:for-each select="$type_variables">
+ <xsl:variable name="name_i">
+ <xsl:choose>
+ <xsl:when test="string-length(@name_i) > 0">
+ <xsl:value-of select="@name_i"/>
+ </xsl:when>
+ <xsl:otherwise>
+ <xsl:value-of select="count($names)"/>
+ </xsl:otherwise>
+ </xsl:choose>
+ </xsl:variable>
+ <xsl:variable name="spec0">
+ <xsl:for-each select="$names[position() = $name_i]">
+ <xsl:call-template name="find_spec"/>
+ </xsl:for-each>
+ </xsl:variable>
+ <xsl:variable name="spec" select="exsl:node-set($spec0)/spec"/>
+ <xsl:variable name="clause" select="$spec/contract/clause"/>
+ <xsl:variable name="variable" select="@variable"/>
+ <xsl:variable name="subtype"
+ select="$clause/guard/subtype[typename = $variable]"/>
+
+ <xsl:if test="count($subtype) = 0">
+ <xsl:call-template name="err">
+ <xsl:with-param name="f" select="ancestor::erlref/module"/>
+ <xsl:with-param name="n" select="$fname"/>
+ <xsl:with-param name="a" select="$arity"/>
+ <xsl:with-param name="s">unknown type variable <xsl:value-of select="$variable"/>
+ </xsl:with-param>
+ </xsl:call-template>
+ </xsl:if>
- <xsl:template name="guard">
- <fo:block>
- <xsl:text>Types:</xsl:text>
- </fo:block>
- <fo:list-block xsl:use-attribute-sets="type-listblock">
<xsl:call-template name="subtype">
- <xsl:with-param name="subtype" select="$guard/subtype"/>
- <xsl:with-param name="type_desc" select="$type_desc"/>
+ <xsl:with-param name="subtype" select="$subtype"/>
+ <xsl:with-param name="type_desc" select="$type_desc"/>
</xsl:call-template>
- </fo:list-block>
+ </xsl:for-each>
</xsl:template>
+ <!-- Substituted
+ <fo:block xsl:use-attribute-sets="function-name">
+ for
+ <fo:block font-weight="bold">
+ to get proper indentation (a monospace font)
+ -->
<xsl:template name="subtype">
<xsl:param name="subtype"/>
<xsl:param name="type_desc"/>
+
<xsl:for-each select="$subtype">
<xsl:variable name="tname" select="typename"/>
- <xsl:variable name="tdesc" select="$type_desc[@name = $tname]"/>
<fo:list-item xsl:use-attribute-sets="type-listitem">
<fo:list-item-label end-indent="label-end()">
<fo:block>
</fo:block>
</fo:list-item-label>
<fo:list-item-body start-indent="body-start()" format="justify">
- <fo:block font-weight="bold">
- <xsl:apply-templates select="string"/>
+ <fo:block xsl:use-attribute-sets="function-name">
+ <xsl:apply-templates select="string"/>
</fo:block>
</fo:list-item-body>
</fo:list-item>
- <xsl:apply-templates select="$type_desc[@name = $tname]"/>
+ <xsl:apply-templates select="$type_desc[@variable = $tname]"/>
+ </xsl:for-each>
+ </xsl:template>
+
+ <xsl:template name="local_type">
+ <xsl:param name="type_desc"/>
+ <xsl:param name="local_types"/>
+
+ <xsl:for-each select="$local_types">
+ <fo:list-item xsl:use-attribute-sets="type-listitem">
+ <fo:list-item-label end-indent="label-end()">
+ <fo:block>
+ </fo:block>
+ </fo:list-item-label>
+ <fo:list-item-body start-indent="body-start()" format="justify">
+ <!-- <fo:block font-weight="bold">
+ (use function-name in "typehead" instead) -->
+ <xsl:call-template name="type_name">
+ <xsl:with-param name="mode" select="'local_type'"/>
+ </xsl:call-template>
+ <!-- </fo:block> -->
+ </fo:list-item-body>
+ </fo:list-item>
+ <xsl:variable name="tname" select="@name"/>
+ <xsl:variable name="tnvars" select="@n_vars"/>
+ <xsl:apply-templates select=
+ "$type_desc[@name = $tname
+ and (@n_vars = $tnvars
+ or string-length(@n_vars) = 0 and
+ string-length($tnvars) = 0)]"/>
</xsl:for-each>
</xsl:template>
@@ -182,6 +302,53 @@
<xsl:apply-templates select="desc"/>
</xsl:template>
+ <xsl:template name="type_name">
+ <xsl:param name="mode"/> <!-- '' if <datatype> -->
+ <xsl:variable name="curModule" select="ancestor::erlref/module"/>
+ <xsl:variable name="mod" select="@mod"/>
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="n_vars" select="@n_vars"/>
+
+ <xsl:choose>
+ <xsl:when test="string-length($name) > 0">
+ <xsl:variable name="type" select=
+ "$i/specs/module[@name=$curModule]/type
+ [name=$name
+ and (string-length($n_vars) = 0 or n_vars = $n_vars)
+ and (string-length($mod) = 0 or module = $mod)]"/>
+
+ <xsl:if test="count($type) != 1">
+ <xsl:variable name="why">
+ <xsl:choose>
+ <xsl:when test="count($type) > 1">ambiguous type</xsl:when>
+ <xsl:when test="count($type) = 0">unknown type</xsl:when>
+ </xsl:choose>
+ </xsl:variable>
+ <xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
+ <xsl:with-param name="m" select="$mod"/>
+ <xsl:with-param name="n" select="$name"/>
+ <xsl:with-param name="a" select="$n_vars"/>
+ <xsl:with-param name="s" select="$why"/>
+ </xsl:call-template>
+ </xsl:if>
+ <xsl:choose>
+ <xsl:when test="$mode = ''">
+ <xsl:apply-templates select="$type/typedecl"/>
+ </xsl:when>
+ <xsl:when test="$mode = 'local_type'">
+ <xsl:apply-templates select="$type/typedecl" mode="local_type"/>
+ </xsl:when>
+ </xsl:choose>
+ </xsl:when>
+ <xsl:otherwise>
+ <fo:inline font-weight="bold" xsl:use-attribute-sets="type-listitem">
+ <xsl:value-of select="."/>
+ </fo:inline>
+ </xsl:otherwise>
+ </xsl:choose>
+ </xsl:template>
+
<!-- Like <head>... -->
<xsl:template match="typehead">
<fo:block xsl:use-attribute-sets="function-name">
@@ -189,6 +356,20 @@
</fo:block>
</xsl:template>
+ <!-- Substituted
+ <fo:block xsl:use-attribute-sets="function-name">
+ for
+ <fo:block font-weight="bold">
+ to get proper indentation (a monospace font)
+ -->
+
+ <xsl:template match="typehead" mode="local_type">
+ <fo:block xsl:use-attribute-sets="function-name">
+ <xsl:apply-templates/>
+ </fo:block>
+ </xsl:template>
+
+ <!-- Not used right now -->
<!-- Like <guard>, except "Types:"... -->
<xsl:template match="local_defs">
<fo:list-block xsl:use-attribute-sets="type-listblock">
@@ -211,108 +392,82 @@
</fo:list-item>
</xsl:template>
- <xsl:template name="type_name">
- <xsl:variable name="curModule" select="ancestor::erlref/module"/>
- <xsl:variable name="mod" select="@mod"/>
- <xsl:variable name="name" select="@name"/>
- <xsl:variable name="n_vars">
- <xsl:choose>
- <xsl:when test="string-length(@n_vars) > 0">
- <xsl:value-of select="@n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="0"/>
- </xsl:otherwise>
- </xsl:choose>
- </xsl:variable>
-
- <xsl:choose>
- <xsl:when test="string-length($name) > 0">
- <xsl:variable name="type" select=
- "$i/specs/module[@name=$curModule]/type
- [name=$name and n_vars=$n_vars
- and (string-length($mod) = 0 or module = $mod)]"/>
-
- <xsl:if test="count($type) != 1">
- <xsl:call-template name="err">
- <xsl:with-param name="m" select="$mod"/>
- <xsl:with-param name="n" select="$name"/>
- <xsl:with-param name="a" select="$n_vars"/>
- <xsl:with-param name="s">unknown type</xsl:with-param>
- </xsl:call-template>
- </xsl:if>
- <xsl:apply-templates select="$type/typedecl"/>
- </xsl:when>
- <xsl:otherwise>
- <fo:inline font-weight="bold" xsl:use-attribute-sets="type-listitem">
- <xsl:value-of select="."/>
- </fo:inline>
- </xsl:otherwise>
- </xsl:choose>
- </xsl:template>
-
<!-- Used both in <datatype> and in <func>! -->
<xsl:template match="anno">
<xsl:variable name="curModule" select="ancestor::erlref/module"/>
<xsl:variable name="anno" select="normalize-space(text())"/>
<xsl:variable name="namespec"
- select="ancestor::desc/preceding-sibling::name"/>
+ select="ancestor::type_desc/preceding-sibling::name
+ | ancestor::desc/preceding-sibling::name"/>
<xsl:if test="count($namespec) = 0 and string-length($specs_file) > 0">
<xsl:call-template name="err">
- <xsl:with-param name="s">cannot find 'name' (<xsl:value-of select="$anno"/>)
+ <xsl:with-param name="f" select="$curModule"/>
+ <xsl:with-param name="s">cannot find tag 'name' (anno <xsl:value-of select="$anno"/>)
</xsl:with-param>
</xsl:call-template>
</xsl:if>
- <xsl:variable name="mod" select="$namespec/@mod"/>
- <xsl:variable name="name" select="$namespec/@name"/>
- <xsl:variable name="arity" select="$namespec/@arity"/>
- <xsl:variable name="clause" select="$namespec/@clause"/>
- <xsl:variable name="tmp_n_vars" select="$namespec/@n_vars"/>
- <xsl:variable name="n_vars">
- <xsl:choose>
- <xsl:when test="string-length($tmp_n_vars) > 0">
- <xsl:value-of select="$tmp_n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="0"/>
- </xsl:otherwise>
- </xsl:choose>
+ <!-- Search "local types" as well -->
+ <xsl:variable name="local_types"
+ select="ancestor::desc/preceding-sibling::type
+ [string-length(@name) > 0]"/>
+ <xsl:variable name="has_anno_in_local_type">
+ <xsl:for-each select="$local_types">
+ <xsl:call-template name="anno_name">
+ <xsl:with-param name="curModule" select="$curModule"/>
+ <xsl:with-param name="anno" select="$anno"/>
+ </xsl:call-template>
+ </xsl:for-each>
+ </xsl:variable>
+
+ <xsl:variable name="has_anno">
+ <xsl:for-each select="$namespec">
+ <xsl:call-template name="anno_name">
+ <xsl:with-param name="curModule" select="$curModule"/>
+ <xsl:with-param name="anno" select="$anno"/>
+ </xsl:call-template>
+ </xsl:for-each>
</xsl:variable>
+
+ <xsl:if test="$has_anno = '' and $has_anno_in_local_type = ''">
+ <xsl:call-template name="err">
+ <xsl:with-param name="f" select="$curModule"/>
+ <xsl:with-param name="m" select="$namespec/@mod"/>
+ <xsl:with-param name="n" select="$namespec/@name"/>
+ <xsl:with-param name="a" select="'-'"/>
+ <xsl:with-param name="s">unknown annotation <xsl:value-of select="$anno"/>
+ </xsl:with-param>
+ </xsl:call-template>
+ </xsl:if>
+ <xsl:value-of select="$anno"/>
+ </xsl:template>
+
+ <xsl:template name="anno_name">
+ <xsl:param name="curModule"/>
+ <xsl:param name="anno"/>
+ <xsl:variable name="mod" select="@mod"/>
+ <xsl:variable name="name" select="@name"/>
+ <xsl:variable name="arity" select="@arity"/>
+ <xsl:variable name="n_vars" select="@n_vars"/>
+ <xsl:variable name="clause_i" select="@clause_i"/>
+
<xsl:variable name="spec0" select=
"$i/specs/module[@name=$curModule]/spec
[name=$name and arity=$arity
and (string-length($mod) = 0 or module = $mod)]"/>
<xsl:variable name="spec_annos" select=
- "$spec0[string-length($clause) = 0
- or position() = $clause]/anno[.=$anno]"/>
+ "$spec0[string-length($clause_i) = 0
+ or position() = $clause_i]/anno[.=$anno]"/>
<xsl:variable name="type_annos" select=
"$i/specs/module[@name=$curModule]/type
- [name=$name and n_vars=$n_vars
+ [name=$name
+ and (string-length($n_vars) = 0 or n_vars=$n_vars)
and (string-length($mod) = 0 or module = $mod)]/anno[.=$anno]"/>
-
- <xsl:if test="count($spec_annos) = 0
- and count($type_annos) = 0
- and string-length($specs_file) > 0">
- <xsl:variable name="n">
- <xsl:choose>
- <xsl:when test="string-length($arity) = 0">
- <xsl:value-of select="$n_vars"/>
- </xsl:when>
- <xsl:otherwise>
- <xsl:value-of select="$arity"/>
- </xsl:otherwise>
- </xsl:choose>
- </xsl:variable>
- <xsl:call-template name="err">
- <xsl:with-param name="m" select="$mod"/>
- <xsl:with-param name="n" select="$name"/>
- <xsl:with-param name="a" select="$n"/>
- <xsl:with-param name="s">unknown annotation <xsl:value-of select="$anno"/>
- </xsl:with-param>
- </xsl:call-template>
+ <xsl:if test="count($spec_annos) != 0
+ or count($type_annos) != 0
+ or string-length($specs_file) = 0">
+ <xsl:value-of select="true()"/>
</xsl:if>
- <xsl:value-of select="$anno"/>
</xsl:template>
<!-- Used for indentation of formatted types and specs -->
@@ -1227,6 +1382,9 @@
<xsl:param name="partnum"/>
<xsl:apply-templates select="name"/>
+ <xsl:apply-templates
+ select="name[string-length(@arity) > 0 and position()=last()]"
+ mode="types"/>
<xsl:apply-templates select="fsummary|type|desc">
<xsl:with-param name="partnum" select="$partnum"/>
@@ -1245,6 +1403,11 @@
<xsl:when test="ancestor::datatype">
<xsl:call-template name="type_name"/>
</xsl:when>
+ <xsl:when test="string-length(text()) = 0 and ancestor::erlref">
+ <xsl:message terminate="yes">
+ Error <xsl:value-of select="@name"/>: arity is mandatory when referring to specifications!
+ </xsl:message>
+ </xsl:when>
<xsl:otherwise>
<fo:block xsl:use-attribute-sets="function-name">
<xsl:call-template name="name">
@@ -1276,15 +1439,20 @@
<xsl:template match="type">
<xsl:param name="partnum"/>
- <fo:block>
- <xsl:text>Types:</xsl:text>
- </fo:block>
+ <!-- The case where @name != 0 is taken care of in "type_name" -->
+ <xsl:if test="string-length(@name) = 0 and string-length(@variable) = 0">
- <fo:list-block xsl:use-attribute-sets="type-listblock">
- <xsl:apply-templates>
- <xsl:with-param name="partnum" select="$partnum"/>
- </xsl:apply-templates>
- </fo:list-block>
+ <fo:block>
+ <xsl:text>Types:</xsl:text>
+ </fo:block>
+
+ <fo:list-block xsl:use-attribute-sets="type-listblock">
+ <xsl:apply-templates>
+ <xsl:with-param name="partnum" select="$partnum"/>
+ </xsl:apply-templates>
+ </fo:list-block>
+
+ </xsl:if>
</xsl:template>
@@ -1431,6 +1599,7 @@
</xsl:template>
+ <!-- Does not look at @n_vars -->
<xsl:template match="seealso">
<fo:inline font-style="italic">
<xsl:apply-templates/>
diff --git a/lib/erl_docgen/src/otp_specs.erl b/lib/erl_docgen/src/otp_specs.erl
index 728ddb2e6e..edb437a942 100644
--- a/lib/erl_docgen/src/otp_specs.erl
+++ b/lib/erl_docgen/src/otp_specs.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -380,6 +380,8 @@ t_type([E=#xmlElement{name = float}]) ->
t_float(E);
t_type([#xmlElement{name = nil}]) ->
t_nil();
+t_type([#xmlElement{name = paren, content = Es}]) ->
+ t_paren(Es);
t_type([#xmlElement{name = list, content = Es}]) ->
t_list(Es);
t_type([#xmlElement{name = nonempty_list, content = Es}]) ->
@@ -416,6 +418,9 @@ t_float(E) ->
t_nil() ->
["[]"].
+t_paren(Es) ->
+ ["("] ++ t_utype(get_elem(type, Es)) ++ [")"].
+
t_list(Es) ->
["["] ++ t_utype(get_elem(type, Es)) ++ ["]"].
@@ -532,6 +537,8 @@ ot_type([E=#xmlElement{name = float}]) ->
ot_float(E);
ot_type([#xmlElement{name = nil}]) ->
ot_nil();
+ot_type([#xmlElement{name = paren, content = Es}]) ->
+ ot_paren(Es);
ot_type([#xmlElement{name = list, content = Es}]) ->
ot_list(Es);
ot_type([#xmlElement{name = nonempty_list, content = Es}]) ->
@@ -582,6 +589,9 @@ ot_float(E) ->
ot_nil() ->
{nil,0}.
+ot_paren(Es) ->
+ {paren_type,0,[ot_utype(get_elem(type, Es))]}.
+
ot_list(Es) ->
{type,0,list,[ot_utype(get_elem(type, Es))]}.
@@ -697,5 +707,7 @@ annos_type([#xmlElement{name = union, content = Es}]) ->
lists:flatmap(fun annos_elem/1, Es);
annos_type([E=#xmlElement{name = typevar}]) ->
annos_elem(E);
+annos_type([#xmlElement{name = paren, content = Es}]) ->
+ annos(get_elem(type, Es));
annos_type(_) ->
[].
diff --git a/lib/erl_interface/doc/src/notes.xml b/lib/erl_interface/doc/src/notes.xml
index 784ba78d3e..d83a8307e4 100644
--- a/lib/erl_interface/doc/src/notes.xml
+++ b/lib/erl_interface/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/erl_interface/src/epmd/epmd_port.c b/lib/erl_interface/src/epmd/epmd_port.c
index 698c75c217..6450f285cc 100644
--- a/lib/erl_interface/src/epmd/epmd_port.c
+++ b/lib/erl_interface/src/epmd/epmd_port.c
@@ -228,11 +228,8 @@ int ei_epmd_port (struct in_addr *addr, const char *alive, int *dist)
return ei_epmd_port_tmo (addr, alive, dist, 0);
}
-int ei_epmd_port_tmo (struct in_addr *addr, const char *alive, int *dist,
- unsigned ms)
+int ei_epmd_port_tmo (struct in_addr *addr, const char *alive, int *dist, unsigned ms)
{
- int i;
-
- return ei_epmd_r4_port(addr,alive,dist,ms);
+ return ei_epmd_r4_port(addr,alive,dist,ms);
}
diff --git a/lib/hipe/doc/src/notes.xml b/lib/hipe/doc/src/notes.xml
index 434bfac64c..5c06e5e558 100644
--- a/lib/hipe/doc/src/notes.xml
+++ b/lib/hipe/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2006</year><year>2010</year>
+ <year>2006</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/inets/doc/src/httpc.xml b/lib/inets/doc/src/httpc.xml
index 8f68087871..f6b6827e93 100644
--- a/lib/inets/doc/src/httpc.xml
+++ b/lib/inets/doc/src/httpc.xml
@@ -76,38 +76,37 @@ socket_opt() = See the Options used by gen_tcp(3) and
<p>For more information about HTTP see rfc 2616</p>
<code type="none"><![CDATA[
-method() = head | get | put | post | trace | options | delete
-request() = {url(), headers()} |
- {url(), headers(), content_type(), body()}
-url() = string() - Syntax according to the URI definition in rfc 2396, ex: "http://www.erlang.org"
-status_line() = {http_version(), status_code(), reason_phrase()}
-http_version() = string() ex: "HTTP/1.1"
-status_code() = integer()
-reason_phrase() = string()
-content_type() = string()
-headers() = [header()]
-header() = {field(), value()}
-field() = string()
-value() = string()
-body() = string() | binary()
-filename() = string()
+method() = head | get | put | post | trace | options | delete
+request() = {url(), headers()} |
+ {url(), headers(), content_type(), body()}
+url() = string() - Syntax according to the URI definition in rfc 2396, ex: "http://www.erlang.org"
+status_line() = {http_version(), status_code(), reason_phrase()}
+http_version() = string() ex: "HTTP/1.1"
+status_code() = integer()
+reason_phrase() = string()
+content_type() = string()
+headers() = [header()]
+header() = {field(), value()}
+field() = string()
+value() = string()
+body() = string() |
+ binary() |
+ {fun(accumulator()) -> body_processing_result(),
+ accumulator()} |
+ {chunkify,
+ fun(accumulator()) -> body_processing_result(),
+ accumulator()}
+body_processing_result() = eof | {ok, iolist(), accumulator()}
+accumulator() = term()
+filename() = string()
]]></code>
</section>
<section>
<title>SSL DATA TYPES </title>
- <p>Some type definitions relevant when using https,
- for details <seealso marker="ssl:ssl">ssl(3)</seealso>: </p>
- <code type="none"><![CDATA[
-ssl_options() = {verify, code()} |
- {depth, depth()} |
- {certfile, path()} |
- {keyfile, path()} |
- {password, string()} |
- {cacertfile, path()} |
- {ciphers, string()}
- ]]></code>
+ <p>See <seealso marker="ssl:ssl">ssl(3)</seealso> for information
+ about ssl options (<c>ssloptions()</c>). </p>
</section>
<section>
@@ -142,8 +141,9 @@ ssl_options() = {verify, code()} |
<fsummary>Sends a get HTTP-request</fsummary>
<type>
<v>Url = url() </v>
- <v>Result = {status_line(), headers(), body()} |
- {status_code(), body()} | request_id() </v>
+ <v>Result = {status_line(), headers(), Body} |
+ {status_code(), Body} | request_id() </v>
+ <v>Body = string() | binary()</v>
<v>Profile = profile()</v>
<v>Reason = term() </v>
</type>
@@ -166,9 +166,9 @@ ssl_options() = {verify, code()} |
<v>http_options() = [http_option()]</v>
<v>http_option() = {timeout, timeout()} |
{connect_timeout, timeout()} |
- {ssl, ssl_options()} |
- {ossl, ssl_options()} |
- {essl, ssl_options()} |
+ {ssl, ssloptions()} |
+ {ossl, ssloptions()} |
+ {essl, ssloptions()} |
{autoredirect, boolean()} |
{proxy_auth, {userstring(), passwordstring()}} |
{version, http_version()} |
@@ -191,8 +191,9 @@ ssl_options() = {verify, code()} |
<v>Function = atom() </v>
<v>Args = list() </v>
<v>body_format() = string | binary </v>
- <v>Result = {status_line(), headers(), body()} |
- {status_code(), body()} | request_id() </v>
+ <v>Result = {status_line(), headers(), Body} |
+ {status_code(), Body} | request_id() </v>
+ <v>Body = string() | binary()</v>
<v>Profile = profile() </v>
<v>Reason = {connect_failed, term()} |
{send_failed, term()} | term() </v>
@@ -226,7 +227,7 @@ ssl_options() = {verify, code()} |
<tag><c><![CDATA[ssl]]></c></tag>
<item>
<p>This is the default ssl config option, currently defaults to
- <c>ossl</c>, see below. </p>
+ <c>essl</c>, see below. </p>
<p>Defaults to <c>[]</c>. </p>
</item>
diff --git a/lib/inets/doc/src/httpd.xml b/lib/inets/doc/src/httpd.xml
index 6470b6fac7..edacb73b65 100644
--- a/lib/inets/doc/src/httpd.xml
+++ b/lib/inets/doc/src/httpd.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2010</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -154,7 +154,7 @@
<c>ossl</c> specifically uses the OpenSSL based (old) SSL.
<c>essl</c> specifically uses the Erlang based (new) SSL.
When using <c>ssl</c> it <em>currently</em> defaults to
- <c>ossl</c>. </p>
+ <c>essl</c>. </p>
<p>Defaults to <c>ip_comm</c>. </p>
</item>
@@ -794,14 +794,14 @@ bytes
<marker id="sdir_prop"></marker>
<p> Here follows the valid properties for security directories</p>
<taglist>
- <tag>{security_data_file, path()}</tag>
+ <tag>{data_file, path()}</tag>
<item>
Name of the security data file. The filename can either
absolute or relative to the server_root. This file is used to
store persistent data for the mod_security module. </item>
- <tag>{security_max_retries, integer()}</tag>
+ <tag>{max_retries, integer()}</tag>
<item> Specifies the maximum number of tries to authenticate a
user has before the user is blocked out. If a user
@@ -811,13 +811,13 @@ bytes
server will return 401 (Unauthorized), for security
reasons. Defaults to 3 may also be set to infinity.</item>
- <tag>{security_block_time, integer()}</tag>
+ <tag>{block_time, integer()}</tag>
<item> Specifies the number of minutes a user is blocked. After
this amount of time, he automatically regains access.
Defaults to 60</item>
- <tag>{security_fail_expire_time, integer()}</tag>
+ <tag>{fail_expire_time, integer()}</tag>
<item>
Specifies the number of minutes a failed user authentication
@@ -825,7 +825,7 @@ bytes
time, his previous failed authentications are
forgotten. Defaults to 30</item>
- <tag>{security_auth_timeout, integer()}</tag>
+ <tag>{auth_timeout, integer()}</tag>
<item>
Specifies the number of seconds a successful user
diff --git a/lib/inets/doc/src/inets.xml b/lib/inets/doc/src/inets.xml
index c367d7fa77..a2bf42320f 100644
--- a/lib/inets/doc/src/inets.xml
+++ b/lib/inets/doc/src/inets.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
@@ -32,8 +32,10 @@
<modulesummary>The inets services API</modulesummary>
<description>
<p>This module provides the most basic API to the
- clients and servers, that are part of the Inets application,
- such as start and stop. </p>
+ clients and servers, that are part of the Inets application,
+ such as start and stop. </p>
+
+ <marker id="common_data_types"></marker>
</description>
<section>
@@ -42,7 +44,10 @@
this module: </p>
<p><c> service() = ftpc | tftp | httpc | httpd</c></p>
<p><c> property() = atom() </c></p>
+ <marker id="functions"></marker>
+ <marker id="services"></marker>
</section>
+
<funcs>
<func>
<name>services() -> [{Service, Pid}]</name>
@@ -54,11 +59,13 @@
<desc>
<p>Returns a list of currently running services.</p>
<note>
- <p>Services started as <c>stand_alone</c> will not
- be listed.</p>
+ <p>Services started as <c>stand_alone</c> will not be listed.</p>
</note>
+
+ <marker id="services_info"></marker>
</desc>
</func>
+
<func>
<name>services_info() -> [{Service, Pid, Info}]</name>
<fsummary>Returns a list of currently running services where
@@ -73,11 +80,13 @@
</type>
<desc>
<p>Returns a list of currently running services where each
- service is described by a [{Option, Value}] list. The
- information given in the list is specific for each service
- and it is probable that each service will have its own info
- function that gives you even more details about the
- service.</p>
+ service is described by a [{Option, Value}] list. The
+ information given in the list is specific for each service
+ and it is probable that each service will have its own info
+ function that gives you even more details about the
+ service.</p>
+
+ <marker id="service_names"></marker>
</desc>
</func>
@@ -89,6 +98,8 @@
</type>
<desc>
<p>Returns a list of available service names.</p>
+
+ <marker id="start"></marker>
</desc>
</func>
@@ -101,18 +112,24 @@
</type>
<desc>
<p>Starts the Inets application. Default type
- is temporary. See also
- <seealso marker="kernel:application">application(3)</seealso></p>
+ is temporary. See also
+ <seealso marker="kernel:application">application(3)</seealso>. </p>
+
+ <marker id="stop"></marker>
</desc>
</func>
+
<func>
<name>stop() -> ok </name>
<fsummary>Stops the inets application.</fsummary>
<desc>
<p>Stops the inets application. See also
- <seealso marker="kernel:application">application(3)</seealso></p>
+ <seealso marker="kernel:application">application(3)</seealso>. </p>
+
+ <marker id="start2"></marker>
</desc>
</func>
+
<func>
<name>start(Service, ServiceConfig) -> {ok, Pid} | {error, Reason}</name>
<name>start(Service, ServiceConfig, How) -> {ok, Pid} | {error, Reason}</name>
@@ -144,8 +161,11 @@
some sense the calling process has now become the top
supervisor.</p>
</note>
+
+ <marker id="stop2"></marker>
</desc>
</func>
+
<func>
<name>stop(Service, Reference) -> ok | {error, Reason} </name>
<fsummary>Stops a started service of the inets application or takes
@@ -157,9 +177,11 @@
</type>
<desc>
<p>Stops a started service of the inets application or takes
- down a "stand_alone-service" gracefully. When the
- <c>stand_alone</c> option is used in start,
- only the pid is a valid argument to stop.</p>
+ down a "stand_alone-service" gracefully. When the
+ <c>stand_alone</c> option is used in start,
+ only the pid is a valid argument to stop.</p>
+
+ <marker id="see_also"></marker>
</desc>
</func>
</funcs>
diff --git a/lib/inets/doc/src/mod_esi.xml b/lib/inets/doc/src/mod_esi.xml
index e81308a502..9674cd9a88 100644
--- a/lib/inets/doc/src/mod_esi.xml
+++ b/lib/inets/doc/src/mod_esi.xml
@@ -1,10 +1,10 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
<header>
<copyright>
- <year>1997</year><year>2010</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -32,16 +32,19 @@
<modulesummary>Erlang Server Interface </modulesummary>
<description>
<p>This module defines the API - Erlang Server Interface (ESI).
- Which is a more efficient way of writing erlang scripts
- for your Inets web server than writing them as common CGI scripts.</p>
+ Which is a more efficient way of writing erlang scripts
+ for your Inets web server than writing them as common CGI scripts.</p>
+
+ <marker id="deliver"></marker>
</description>
+
<funcs>
<func>
<name>deliver(SessionID, Data) -> ok | {error, Reason}</name>
<fsummary>Sends Data back to client.</fsummary>
<type>
<v>SessionID = term()</v>
- <v>Data = string() | io_list()</v>
+ <v>Data = string() | io_list() | binary()</v>
<v>Reason = term()</v>
</type>
<desc>
@@ -51,13 +54,15 @@
parts of the content to the user.</p>
<p>Sends data from a Erl Scheme script back to the client.</p>
- <note><p>Note
- that if any HTTP-header fields should be added by the
- script they must be in the first call to deliver/2 and the
- data in the call must be a string. Do not
- assume anything about the data type of SessionID, the
- SessionID must be the value given as input to the esi
- call back function that you implemented.</p></note>
+ <note>
+ <p>Note that if any HTTP-header fields should be added by the
+ script they must be in the first call to deliver/2 and the
+ data in the call must be a string. Calls after the headers
+ are complete may contain binary data to reduce copying
+ overhead. Do not assume anything about the data type of
+ SessionID, the SessionID must be the value given as input to
+ the esi call back function that you implemented.</p>
+ </note>
</desc>
</func>
</funcs>
diff --git a/lib/inets/doc/src/mod_security.xml b/lib/inets/doc/src/mod_security.xml
index 2a871d29d8..a3c91dca5b 100644
--- a/lib/inets/doc/src/mod_security.xml
+++ b/lib/inets/doc/src/mod_security.xml
@@ -1,10 +1,10 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
<header>
<copyright>
- <year>1998</year><year>2010</year>
+ <year>1998</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/inets/doc/src/notes.xml b/lib/inets/doc/src/notes.xml
index 5da9d98002..0926df8581 100644
--- a/lib/inets/doc/src/notes.xml
+++ b/lib/inets/doc/src/notes.xml
@@ -32,6 +32,140 @@
<file>notes.xml</file>
</header>
+ <section><title>Inets 5.6</title>
+
+ <section><title>Improvements and New Features</title>
+<!--
+ <p>-</p>
+-->
+ <list>
+ <item>
+ <p>[httpc] Add support for upload body streaming (PUT and POST).</p>
+ <p>For more info,
+ see the definition of the <c>Body</c> argument of the
+ <seealso marker="httpc#request2">request/4,5</seealso>
+ function. </p>
+ <p>Filipe David Manana</p>
+ <p>Own Id: OTP-9094</p>
+ </item>
+
+ <item>
+ <p>[ftp] Added (type) spec for all exported functions.</p>
+ <p>Own Id: OTP-9114 Aux Id: seq11799</p>
+ </item>
+
+ <item>
+ <p>[httpd]
+ <seealso marker="mod_esi#deliver">mod_esi:deliver/2</seealso>
+ made to accept binary data. </p>
+ <p>Bernard Duggan</p>
+ <p>Own Id: OTP-9123</p>
+ </item>
+
+ <item>
+ <p>[httpd] Prevent XSS in error pages.
+ Prevent user controlled input from being interpreted
+ as HTML in error pages by encoding the reserved HTML
+ characters. </p>
+ <p>Michael Santos</p>
+ <p>Own Id: OTP-9124</p>
+ </item>
+
+ <item>
+ <p>[httpd] Improved error messages. </p>
+ <p>Ricardo Catalinas Jim�nez</p>
+ <p>Own Id: OTP-9157</p>
+ </item>
+
+ <item>
+ <p>[httpd] Extended support for file descriptors.
+ In order to be able to bind to a privileged port
+ without running the erlang VM as root, the support
+ for using file descriptors has been improved.
+ It is now possible to add the file descriptor to the config
+ (option fd) when calling the
+ <seealso marker="inets#start2">inets:start(httpd, ...)</seealso>
+ function. </p>
+ <p>Attila Rajmund Nohl</p>
+ <p>Own Id: OTP-9202</p>
+ <p>Aux Id: seq11819</p>
+ </item>
+
+ <item>
+ <p>The default ssl kind has now been changed to <c>essl</c>. </p>
+ <p><c>ossl</c> will work for as long as the ssl application
+ supports it. </p>
+ <p>See the httpd
+ <seealso marker="httpd#comm_prop">socket_type</seealso>
+ communication property or the httpc
+ <seealso marker="httpc#request2">request/4,5</seealso> function
+ for more info. </p>
+ <p>Own Id: OTP-9230</p>
+ <p>*** POTENTIAL INCOMPATIBILITY ***</p>
+ </item>
+
+ </list>
+ </section>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+<!--
+ <p>-</p>
+-->
+
+ <list>
+ <item>
+ <p>[httpd] Wrong
+ <seealso marker="httpd#sec_prop">security property</seealso>
+ names used in documentation. </p>
+ <p><c>security_data_file</c> used instead of <c>data_file</c>. </p>
+ <p><c>security_max_retries</c> used instead of <c>max_retries</c>. </p>
+ <p><c>security_block_time</c> used instead of <c>block_time</c>. </p>
+ <p><c>security_fail_expire_time</c> used instead of <c>fail_expire_time</c>. </p>
+ <p><c>security_auth_timeout</c> used instead of <c>auth_timeout</c>. </p>
+ <p>Garrett Smith</p>
+ <p>Own Id: OTP-9131</p>
+ </item>
+
+ <item>
+ <p>[httpd] Fix timeout message generated by mod_esi.
+ When a mod_esi request times out, the code to send a
+ timeout response was incorrect and generated an
+ internal server error as well as an invalid response
+ line. </p>
+ <p>Bernard Duggan</p>
+ <p>Own Id: OTP-9158</p>
+ </item>
+
+ <item>
+ <p>[httpc] httpc manager crashes.
+ When a request results in a retry, the request id will be "reused"
+ in the previous implementation a race condition could occur causing
+ the manager to crash. </p>
+ <p>This is now avoided by using proc_lib:init_ack and
+ gen_server:enter_loop to allow mor advanced initialization of
+ httpc_handlers without blocking the httpc_manger and eliminating
+ extra processes that can cause race conditions. </p>
+ <p>Own Id: OTP-9246</p>
+ </item>
+
+ <item>
+ <p>[httpc] Issuing a request (<c>httpc:request</c>) to an
+ host with the ssl option
+ <c>{ip, {127,0,0,1}}</c> results in an handler crash.
+ The reason was that the connect call resulted in an exit with
+ reason <c>badarg</c>
+ (this was the same for both <c>ssl</c> and <c>gen_tcp</c>). </p>
+ <p>Exits was not catched. This has now been improved. </p>
+ <p>Own Id: OTP-9289</p>
+ <p>Aux Id: seq11845</p>
+ </item>
+
+ </list>
+ </section>
+
+ </section> <!-- 5.6 -->
+
+
<section><title>Inets 5.5.2</title>
<section><title>Improvements and New Features</title>
@@ -80,7 +214,8 @@
are URL-encoded. Added support in http-client to use
URL-encoding. Also added the missing include directory
for the inets application.</p>
- <p>Own Id: OTP-8940 Aux Id: seq11735 </p>
+ <p>Own Id: OTP-8940</p>
+ <p>Aux Id: seq11735</p>
</item>
</list>
</section>
diff --git a/lib/inets/src/ftp/ftp.erl b/lib/inets/src/ftp/ftp.erl
index 5ad74851c8..fe6cb0c191 100644
--- a/lib/inets/src/ftp/ftp.erl
+++ b/lib/inets/src/ftp/ftp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -92,6 +92,12 @@
}).
+-type shortage_reason() :: 'etnospc' | 'epnospc'.
+-type restriction_reason() :: 'epath' | 'efnamena' | 'elogin' | 'enotbinary'.
+-type common_reason() :: 'econn' | 'eclosed' | term().
+-type file_write_error_reason() :: term(). % See file:write for more info
+
+
%%%=========================================================================
%%% API - CLIENT FUNCTIONS
%%%=========================================================================
@@ -106,6 +112,9 @@
%% Description: Start an ftp client and connect to a host.
%%--------------------------------------------------------------------------
+-spec open(Host :: string() | inet:ip_address()) ->
+ {'ok', Pid :: pid()} | {'error', Reason :: 'ehost' | term()}.
+
%% <BACKWARD-COMPATIBILLITY>
open({option_list, Options}) when is_list(Options) ->
try
@@ -126,6 +135,9 @@ open({option_list, Options}) when is_list(Options) ->
open(Host) ->
open(Host, []).
+-spec open(Host :: string() | inet:ip_address(), Opts :: list()) ->
+ {'ok', Pid :: pid()} | {'error', Reason :: 'ehost' | term()}.
+
%% <BACKWARD-COMPATIBILLITY>
open(Host, Port) when is_integer(Port) ->
open(Host, [{port, Port}]);
@@ -161,12 +173,24 @@ open(Host, Opts) when is_list(Opts) ->
%%
%% Description: Login with or without a supplied account name.
%%--------------------------------------------------------------------------
+-spec user(Pid :: pid(),
+ User :: string(),
+ Pass :: string()) ->
+ 'ok' | {'error', Reason :: 'euser' | common_reason()}.
+
user(Pid, User, Pass) ->
call(Pid, {user, User, Pass}, atom).
+-spec user(Pid :: pid(),
+ User :: string(),
+ Pass :: string(),
+ Acc :: string()) ->
+ 'ok' | {'error', Reason :: 'euser' | common_reason()}.
+
user(Pid, User, Pass, Acc) ->
call(Pid, {user, User, Pass, Acc}, atom).
+
%%--------------------------------------------------------------------------
%% account(Pid, Acc) -> ok | {error, eacct}
%% Pid = pid()
@@ -174,9 +198,14 @@ user(Pid, User, Pass, Acc) ->
%%
%% Description: Set a user Account.
%%--------------------------------------------------------------------------
+
+-spec account(Pid :: pid(), Acc :: string()) ->
+ 'ok' | {'error', Reason :: 'eacct' | common_reason()}.
+
account(Pid, Acc) ->
call(Pid, {account, Acc}, atom).
+
%%--------------------------------------------------------------------------
%% pwd(Pid) -> {ok, Dir} | {error, elogin} | {error, econn}
%% Pid = pid()
@@ -184,19 +213,30 @@ account(Pid, Acc) ->
%%
%% Description: Get the current working directory at remote server.
%%--------------------------------------------------------------------------
+
+-spec pwd(Pid :: pid()) ->
+ {'ok', Dir :: string()} |
+ {'error', Reason :: restriction_reason() | common_reason()}.
+
pwd(Pid) ->
call(Pid, pwd, ctrl).
+
%%--------------------------------------------------------------------------
-%% lpwd(Pid) -> {ok, Dir} | {error, elogin}
+%% lpwd(Pid) -> {ok, Dir}
%% Pid = pid()
%% Dir = string()
%%
%% Description: Get the current working directory at local server.
%%--------------------------------------------------------------------------
+
+-spec lpwd(Pid :: pid()) ->
+ {'ok', Dir :: string()}.
+
lpwd(Pid) ->
call(Pid, lpwd, string).
+
%%--------------------------------------------------------------------------
%% cd(Pid, Dir) -> ok | {error, epath} | {error, elogin} | {error, econn}
%% Pid = pid()
@@ -204,9 +244,14 @@ lpwd(Pid) ->
%%
%% Description: Change current working directory at remote server.
%%--------------------------------------------------------------------------
+
+-spec cd(Pid :: pid(), Dir :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() | common_reason()}.
+
cd(Pid, Dir) ->
call(Pid, {cd, Dir}, atom).
+
%%--------------------------------------------------------------------------
%% lcd(Pid, Dir) -> ok | {error, epath}
%% Pid = pid()
@@ -214,9 +259,14 @@ cd(Pid, Dir) ->
%%
%% Description: Change current working directory for the local client.
%%--------------------------------------------------------------------------
+
+-spec lcd(Pid :: pid(), Dir :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason()}.
+
lcd(Pid, Dir) ->
call(Pid, {lcd, Dir}, string).
+
%%--------------------------------------------------------------------------
%% ls(Pid) -> Result
%% ls(Pid, <Dir>) -> Result
@@ -229,11 +279,22 @@ lcd(Pid, Dir) ->
%%
%% Description: Returns a list of files in long format.
%%--------------------------------------------------------------------------
+
+-spec ls(Pid :: pid()) ->
+ {'ok', Listing :: string()} |
+ {'error', Reason :: restriction_reason() | common_reason()}.
+
ls(Pid) ->
ls(Pid, "").
+
+-spec ls(Pid :: pid(), Dir :: string()) ->
+ {'ok', Listing :: string()} |
+ {'error', Reason :: restriction_reason() | common_reason()}.
+
ls(Pid, Dir) ->
call(Pid, {dir, long, Dir}, string).
+
%%--------------------------------------------------------------------------
%% nlist(Pid) -> Result
%% nlist(Pid, Pathname) -> Result
@@ -246,21 +307,37 @@ ls(Pid, Dir) ->
%%
%% Description: Returns a list of files in short format
%%--------------------------------------------------------------------------
+
+-spec nlist(Pid :: pid()) ->
+ {'ok', Listing :: string()} |
+ {'error', Reason :: restriction_reason() | common_reason()}.
+
nlist(Pid) ->
nlist(Pid, "").
+
+-spec nlist(Pid :: pid(), Pathname :: string()) ->
+ {'ok', Listing :: string()} |
+ {'error', Reason :: restriction_reason() | common_reason()}.
+
nlist(Pid, Dir) ->
call(Pid, {dir, short, Dir}, string).
+
%%--------------------------------------------------------------------------
-%% rename(Pid, CurrFile, NewFile) -> ok | {error, epath} | {error, elogin}
-%% | {error, econn}
+%% rename(Pid, Old, New) -> ok | {error, epath} | {error, elogin}
+%% | {error, econn}
%% Pid = pid()
%% CurrFile = NewFile = string()
%%
%% Description: Rename a file at remote server.
%%--------------------------------------------------------------------------
-rename(Pid, CurrFile, NewFile) ->
- call(Pid, {rename, CurrFile, NewFile}, string).
+
+-spec rename(Pid :: pid(), Old :: string(), New :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() | common_reason()}.
+
+rename(Pid, Old, New) ->
+ call(Pid, {rename, Old, New}, string).
+
%%--------------------------------------------------------------------------
%% delete(Pid, File) -> ok | {error, epath} | {error, elogin} |
@@ -270,9 +347,14 @@ rename(Pid, CurrFile, NewFile) ->
%%
%% Description: Remove file at remote server.
%%--------------------------------------------------------------------------
+
+-spec delete(Pid :: pid(), File :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() | common_reason()}.
+
delete(Pid, File) ->
call(Pid, {delete, File}, string).
+
%%--------------------------------------------------------------------------
%% mkdir(Pid, Dir) -> ok | {error, epath} | {error, elogin} | {error, econn}
%% Pid = pid(),
@@ -280,9 +362,14 @@ delete(Pid, File) ->
%%
%% Description: Make directory at remote server.
%%--------------------------------------------------------------------------
+
+-spec mkdir(Pid :: pid(), Dir :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() | common_reason()}.
+
mkdir(Pid, Dir) ->
call(Pid, {mkdir, Dir}, atom).
+
%%--------------------------------------------------------------------------
%% rmdir(Pid, Dir) -> ok | {error, epath} | {error, elogin} | {error, econn}
%% Pid = pid(),
@@ -290,9 +377,14 @@ mkdir(Pid, Dir) ->
%%
%% Description: Remove directory at remote server.
%%--------------------------------------------------------------------------
+
+-spec rmdir(Pid :: pid(), Dir :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() | common_reason()}.
+
rmdir(Pid, Dir) ->
call(Pid, {rmdir, Dir}, atom).
+
%%--------------------------------------------------------------------------
%% type(Pid, Type) -> ok | {error, etype} | {error, elogin} | {error, econn}
%% Pid = pid()
@@ -300,23 +392,41 @@ rmdir(Pid, Dir) ->
%%
%% Description: Set transfer type.
%%--------------------------------------------------------------------------
+
+-spec type(Pid :: pid(), Type :: ascii | binary) ->
+ 'ok' |
+ {'error', Reason :: 'etype' | restriction_reason() | common_reason()}.
+
type(Pid, Type) ->
call(Pid, {type, Type}, atom).
+
%%--------------------------------------------------------------------------
-%% recv(Pid, RemoteFileName <LocalFileName>) -> ok | {error, epath} |
+%% recv(Pid, RemoteFileName [, LocalFileName]) -> ok | {error, epath} |
%% {error, elogin} | {error, econn}
%% Pid = pid()
%% RemoteFileName = LocalFileName = string()
%%
%% Description: Transfer file from remote server.
%%--------------------------------------------------------------------------
+
+-spec recv(Pid :: pid(), RemoteFileName :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() |
+ common_reason() |
+ file_write_error_reason()}.
+
recv(Pid, RemotFileName) ->
recv(Pid, RemotFileName, RemotFileName).
+-spec recv(Pid :: pid(),
+ RemoteFileName :: string(),
+ LocalFileName :: string()) ->
+ 'ok' | {'error', Reason :: term()}.
+
recv(Pid, RemotFileName, LocalFileName) ->
call(Pid, {recv, RemotFileName, LocalFileName}, atom).
+
%%--------------------------------------------------------------------------
%% recv_bin(Pid, RemoteFile) -> {ok, Bin} | {error, epath} | {error, elogin}
%% | {error, econn}
@@ -326,9 +436,16 @@ recv(Pid, RemotFileName, LocalFileName) ->
%%
%% Description: Transfer file from remote server into binary.
%%--------------------------------------------------------------------------
+
+-spec recv_bin(Pid :: pid(),
+ RemoteFile :: string()) ->
+ {'ok', Bin :: binary()} |
+ {'error', Reason :: restriction_reason() | common_reason()}.
+
recv_bin(Pid, RemoteFile) ->
call(Pid, {recv_bin, RemoteFile}, bin).
+
%%--------------------------------------------------------------------------
%% recv_chunk_start(Pid, RemoteFile) -> ok | {error, elogin} | {error, epath}
%% | {error, econn}
@@ -337,9 +454,15 @@ recv_bin(Pid, RemoteFile) ->
%%
%% Description: Start receive of chunks of remote file.
%%--------------------------------------------------------------------------
+
+-spec recv_chunk_start(Pid :: pid(),
+ RemoteFile :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() | common_reason()}.
+
recv_chunk_start(Pid, RemoteFile) ->
call(Pid, {recv_chunk_start, RemoteFile}, atom).
+
%%--------------------------------------------------------------------------
%% recv_chunk(Pid, RemoteFile) -> ok | {ok, Bin} | {error, Reason}
%% Pid = pid()
@@ -347,24 +470,47 @@ recv_chunk_start(Pid, RemoteFile) ->
%%
%% Description: Transfer file from remote server into binary in chunks
%%--------------------------------------------------------------------------
+
+-spec recv_chunk(Pid :: pid()) ->
+ 'ok' |
+ {'ok', Bin :: binary()} |
+ {'error', Reason :: restriction_reason() | common_reason()}.
+
recv_chunk(Pid) ->
call(Pid, recv_chunk, atom).
+
%%--------------------------------------------------------------------------
-%% send(Pid, LocalFileName <RemotFileName>) -> ok | {error, epath}
-%% | {error, elogin}
-%% | {error, econn}
+%% send(Pid, LocalFileName [, RemotFileName]) -> ok | {error, epath}
+%% | {error, elogin}
+%% | {error, econn}
%% Pid = pid()
%% LocalFileName = RemotFileName = string()
%%
%% Description: Transfer file to remote server.
%%--------------------------------------------------------------------------
+
+-spec send(Pid :: pid(), LocalFileName :: string()) ->
+ 'ok' |
+ {'error', Reason :: restriction_reason() |
+ common_reason() |
+ shortage_reason()}.
+
send(Pid, LocalFileName) ->
send(Pid, LocalFileName, LocalFileName).
+-spec send(Pid :: pid(),
+ LocalFileName :: string(),
+ RemoteFileName :: string()) ->
+ 'ok' |
+ {'error', Reason :: restriction_reason() |
+ common_reason() |
+ shortage_reason()}.
+
send(Pid, LocalFileName, RemotFileName) ->
call(Pid, {send, LocalFileName, RemotFileName}, atom).
+
%%--------------------------------------------------------------------------
%% send_bin(Pid, Bin, RemoteFile) -> ok | {error, epath} | {error, elogin}
%% | {error, enotbinary} | {error, econn}
@@ -374,11 +520,19 @@ send(Pid, LocalFileName, RemotFileName) ->
%%
%% Description: Transfer a binary to a remote file.
%%--------------------------------------------------------------------------
+
+-spec send_bin(Pid :: pid(), Bin :: binary(), RemoteFile :: string()) ->
+ 'ok' |
+ {'error', Reason :: restriction_reason() |
+ common_reason() |
+ shortage_reason()}.
+
send_bin(Pid, Bin, RemoteFile) when is_binary(Bin) ->
call(Pid, {send_bin, Bin, RemoteFile}, atom);
send_bin(_Pid, _Bin, _RemoteFile) ->
{error, enotbinary}.
+
%%--------------------------------------------------------------------------
%% send_chunk_start(Pid, RemoteFile) -> ok | {error, elogin} | {error, epath}
%% | {error, econn}
@@ -387,9 +541,14 @@ send_bin(_Pid, _Bin, _RemoteFile) ->
%%
%% Description: Start transfer of chunks to remote file.
%%--------------------------------------------------------------------------
+
+-spec send_chunk_start(Pid :: pid(), RemoteFile :: string()) ->
+ 'ok' | {'error', Reason :: restriction_reason() | common_reason()}.
+
send_chunk_start(Pid, RemoteFile) ->
call(Pid, {send_chunk_start, RemoteFile}, atom).
+
%%--------------------------------------------------------------------------
%% append_chunk_start(Pid, RemoteFile) -> ok | {error, elogin} |
%% {error, epath} | {error, econn}
@@ -398,9 +557,14 @@ send_chunk_start(Pid, RemoteFile) ->
%%
%% Description: Start append chunks of data to remote file.
%%--------------------------------------------------------------------------
+
+-spec append_chunk_start(Pid :: pid(), RemoteFile :: string()) ->
+ 'ok' | {'error', Reason :: term()}.
+
append_chunk_start(Pid, RemoteFile) ->
call(Pid, {append_chunk_start, RemoteFile}, atom).
+
%%--------------------------------------------------------------------------
%% send_chunk(Pid, Bin) -> ok | {error, elogin} | {error, enotbinary}
%% | {error, echunk} | {error, econn}
@@ -409,11 +573,19 @@ append_chunk_start(Pid, RemoteFile) ->
%%
%% Purpose: Send chunk to remote file.
%%--------------------------------------------------------------------------
+
+-spec send_chunk(Pid :: pid(), Bin :: binary()) ->
+ 'ok' |
+ {'error', Reason :: 'echunk' |
+ restriction_reason() |
+ common_reason()}.
+
send_chunk(Pid, Bin) when is_binary(Bin) ->
call(Pid, {transfer_chunk, Bin}, atom);
send_chunk(_Pid, _Bin) ->
{error, enotbinary}.
+
%%--------------------------------------------------------------------------
%% append_chunk(Pid, Bin) -> ok | {error, elogin} | {error, enotbinary}
%% | {error, echunk} | {error, econn}
@@ -422,11 +594,19 @@ send_chunk(_Pid, _Bin) ->
%%
%% Description: Append chunk to remote file.
%%--------------------------------------------------------------------------
+
+-spec append_chunk(Pid :: pid(), Bin :: binary()) ->
+ 'ok' |
+ {'error', Reason :: 'echunk' |
+ restriction_reason() |
+ common_reason()}.
+
append_chunk(Pid, Bin) when is_binary(Bin) ->
call(Pid, {transfer_chunk, Bin}, atom);
append_chunk(_Pid, _Bin) ->
{error, enotbinary}.
+
%%--------------------------------------------------------------------------
%% send_chunk_end(Pid) -> ok | {error, elogin} | {error, echunk}
%% | {error, econn}
@@ -434,9 +614,17 @@ append_chunk(_Pid, _Bin) ->
%%
%% Description: End sending of chunks to remote file.
%%--------------------------------------------------------------------------
+
+-spec send_chunk_end(Pid :: pid()) ->
+ 'ok' |
+ {'error', Reason :: restriction_reason() |
+ common_reason() |
+ shortage_reason()}.
+
send_chunk_end(Pid) ->
call(Pid, chunk_end, atom).
+
%%--------------------------------------------------------------------------
%% append_chunk_end(Pid) -> ok | {error, elogin} | {error, echunk}
%% | {error, econn}
@@ -444,23 +632,47 @@ send_chunk_end(Pid) ->
%%
%% Description: End appending of chunks to remote file.
%%--------------------------------------------------------------------------
+
+-spec append_chunk_end(Pid :: pid()) ->
+ 'ok' |
+ {'error', Reason :: restriction_reason() |
+ common_reason() |
+ shortage_reason()}.
+
append_chunk_end(Pid) ->
call(Pid, chunk_end, atom).
+
%%--------------------------------------------------------------------------
-%% append(Pid, LocalFileName, RemotFileName) -> ok | {error, epath}
-%% | {error, elogin} | {error, econn}
+%% append(Pid, LocalFileName [, RemotFileName]) -> ok | {error, epath}
+%% | {error, elogin}
+%% | {error, econn}
%% Pid = pid()
%% LocalFileName = RemotFileName = string()
%%
%% Description: Append the local file to the remote file
%%--------------------------------------------------------------------------
+
+-spec append(Pid :: pid(), LocalFileName :: string()) ->
+ 'ok' |
+ {'error', Reason :: 'epath' |
+ 'elogin' |
+ 'etnospc' |
+ 'epnospc' |
+ 'efnamena' | common_reason()}.
+
append(Pid, LocalFileName) ->
append(Pid, LocalFileName, LocalFileName).
+-spec append(Pid :: pid(),
+ LocalFileName :: string(),
+ RemoteFileName :: string()) ->
+ 'ok' | {'error', Reason :: term()}.
+
append(Pid, LocalFileName, RemotFileName) ->
call(Pid, {append, LocalFileName, RemotFileName}, atom).
+
%%--------------------------------------------------------------------------
%% append_bin(Pid, Bin, RemoteFile) -> ok | {error, epath} | {error, elogin}
%% | {error, enotbinary} | {error, econn}
@@ -470,27 +682,44 @@ append(Pid, LocalFileName, RemotFileName) ->
%%
%% Purpose: Append a binary to a remote file.
%%--------------------------------------------------------------------------
+
+-spec append_bin(Pid :: pid(),
+ Bin :: binary(),
+ RemoteFile :: string()) ->
+ 'ok' |
+ {'error', Reason :: restriction_reason() |
+ common_reason() |
+ shortage_reason()}.
+
append_bin(Pid, Bin, RemoteFile) when is_binary(Bin) ->
call(Pid, {append_bin, Bin, RemoteFile}, atom);
append_bin(_Pid, _Bin, _RemoteFile) ->
{error, enotbinary}.
+
%%--------------------------------------------------------------------------
-%% quote(Pid, Cmd) -> ok
+%% quote(Pid, Cmd) -> list()
%% Pid = pid()
%% Cmd = string()
%%
%% Description: Send arbitrary ftp command.
%%--------------------------------------------------------------------------
+
+-spec quote(Pid :: pid(), Cmd :: string()) -> list().
+
quote(Pid, Cmd) when is_list(Cmd) ->
call(Pid, {quote, Cmd}, atom).
+
%%--------------------------------------------------------------------------
%% close(Pid) -> ok
%% Pid = pid()
%%
%% Description: End the ftp session.
%%--------------------------------------------------------------------------
+
+-spec close(Pid :: pid()) -> 'ok'.
+
close(Pid) ->
cast(Pid, close),
ok.
@@ -502,9 +731,13 @@ close(Pid) ->
%%
%% Description: Return diagnostics.
%%--------------------------------------------------------------------------
+
+-spec formaterror(Tag :: term()) -> string().
+
formaterror(Tag) ->
ftp_response:error_string(Tag).
+
info(Pid) ->
call(Pid, info, list).
diff --git a/lib/inets/src/http_client/httpc.erl b/lib/inets/src/http_client/httpc.erl
index 04fae13b20..b70b16f57f 100644
--- a/lib/inets/src/http_client/httpc.erl
+++ b/lib/inets/src/http_client/httpc.erl
@@ -126,7 +126,10 @@ request(Url, Profile) ->
%% Header = {Field, Value}
%% Field = string()
%% Value = string()
-%% Body = string() | binary() - HTLM-code
+%% Body = string() | binary() | {fun(SendAcc) -> SendFunResult, SendAcc} |
+%% {chunkify, fun(SendAcc) -> SendFunResult, SendAcc} - HTLM-code
+%% SendFunResult = eof | {ok, iolist(), NewSendAcc}
+%% SendAcc = NewSendAcc = term()
%%
%% Description: Sends a HTTP-request. The function can be both
%% syncronus and asynchronous in the later case the function will
@@ -426,26 +429,44 @@ service_info(Pid) ->
handle_request(Method, Url,
{Scheme, UserInfo, Host, Port, Path, Query},
- Headers, ContentType, Body,
+ Headers0, ContentType, Body0,
HTTPOptions0, Options0, Profile) ->
- Started = http_util:timestamp(),
- NewHeaders = [{http_util:to_lower(Key), Val} || {Key, Val} <- Headers],
+ Started = http_util:timestamp(),
+ NewHeaders0 = [{http_util:to_lower(Key), Val} || {Key, Val} <- Headers0],
try
begin
+ ?hcrt("begin processing", [{started, Started},
+ {new_headers, NewHeaders0}]),
+
+ {NewHeaders, Body} =
+ case Body0 of
+ {chunkify, ProcessBody, Acc}
+ when is_function(ProcessBody, 1) ->
+ NewHeaders1 = ensure_chunked_encoding(NewHeaders0),
+ Body1 = {mk_chunkify_fun(ProcessBody), Acc},
+ {NewHeaders1, Body1};
+ {ProcessBody, _}
+ when is_function(ProcessBody, 1) ->
+ {NewHeaders0, Body0};
+ _ when is_list(Body0) orelse is_binary(Body0) ->
+ {NewHeaders0, Body0};
+ _ ->
+ throw({error, {bad_body, Body0}})
+ end,
+
HTTPOptions = http_options(HTTPOptions0),
Options = request_options(Options0),
Sync = proplists:get_value(sync, Options),
Stream = proplists:get_value(stream, Options),
Host2 = header_host(Scheme, Host, Port),
HeadersRecord = header_record(NewHeaders, Host2, HTTPOptions),
- Receiver = proplists:get_value(receiver, Options),
- SocketOpts = proplists:get_value(socket_opts, Options),
- UrlEncodeBool = HTTPOptions#http_options.url_encode,
- MaybeEscPath = url_encode(Path, UrlEncodeBool),
- MaybeEscQuery = url_encode(Query, UrlEncodeBool),
- AbsUri = url_encode(Url, UrlEncodeBool),
+ Receiver = proplists:get_value(receiver, Options),
+ SocketOpts = proplists:get_value(socket_opts, Options),
+ MaybeEscPath = maybe_encode_uri(HTTPOptions, Path),
+ MaybeEscQuery = maybe_encode_uri(HTTPOptions, Query),
+ AbsUri = maybe_encode_uri(HTTPOptions, Url),
Request = #request{from = Receiver,
scheme = Scheme,
@@ -458,38 +479,71 @@ handle_request(Method, Url,
settings = HTTPOptions,
abs_uri = AbsUri,
userinfo = UserInfo,
- stream = Stream,
- headers_as_is = headers_as_is(Headers, Options),
+ stream = Stream,
+ headers_as_is = headers_as_is(Headers0, Options),
socket_opts = SocketOpts,
started = Started},
+
case httpc_manager:request(Request, profile_name(Profile)) of
{ok, RequestId} ->
handle_answer(RequestId, Sync, Options);
{error, Reason} ->
+ ?hcrd("request failed", [{reason, Reason}]),
{error, Reason}
end
end
catch
error:{noproc, _} ->
+ ?hcrv("noproc", [{profile, Profile}]),
{error, {not_started, Profile}};
throw:Error ->
+ ?hcrv("throw", [{error, Error}]),
Error
end.
-url_encode(URI, true) ->
+ensure_chunked_encoding(Hdrs) ->
+ Key = "transfer-encoding",
+ lists:keystore(Key, 1, Hdrs, {Key, "chunked"}).
+
+maybe_encode_uri(#http_options{url_encode = true}, URI) ->
http_uri:encode(URI);
-url_encode(URI, false) ->
+maybe_encode_uri(_, URI) ->
URI.
+mk_chunkify_fun(ProcessBody) ->
+ fun(eof_body) ->
+ eof;
+ (Acc) ->
+ case ProcessBody(Acc) of
+ eof ->
+ {ok, <<"0\r\n\r\n">>, eof_body};
+ {ok, Data, NewAcc} ->
+ {ok, mk_chunk_bin(Data), NewAcc}
+ end
+ end.
+
+mk_chunk_bin(Data) ->
+ Bin = iolist_to_binary(Data),
+ iolist_to_binary([hex_size(Bin), "\r\n", Bin, "\r\n"]).
+
+hex_size(Bin) ->
+ hd(io_lib:format("~.16B", [size(Bin)])).
+
+
handle_answer(RequestId, false, _) ->
{ok, RequestId};
handle_answer(RequestId, true, Options) ->
receive
{http, {RequestId, saved_to_file}} ->
+ ?hcrt("received saved-to-file", [{request_id, RequestId}]),
{ok, saved_to_file};
{http, {RequestId, {_,_,_} = Result}} ->
+ ?hcrt("received answer", [{request_id, RequestId},
+ {result, Result}]),
return_answer(Options, Result);
{http, {RequestId, {error, Reason}}} ->
+ ?hcrt("received error", [{request_id, RequestId},
+ {reason, Reason}]),
{error, Reason}
end.
diff --git a/lib/inets/src/http_client/httpc_handler.erl b/lib/inets/src/http_client/httpc_handler.erl
index cb6f3e2841..1f0e012e7e 100644
--- a/lib/inets/src/http_client/httpc_handler.erl
+++ b/lib/inets/src/http_client/httpc_handler.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2002-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2002-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
@@ -29,10 +29,10 @@
%%--------------------------------------------------------------------
%% Internal Application API
-export([
- start_link/2,
- connect_and_send/2,
+ start_link/4,
+ %% connect_and_send/2,
send/2,
- cancel/2,
+ cancel/3,
stream/3,
stream_next/1,
info/1
@@ -51,7 +51,7 @@
-record(state,
{
request, % #request{}
- session, % #tcp_session{}
+ session, % #session{}
status_line, % {Version, StatusCode, ReasonPharse}
headers, % #http_response_h{}
body, % binary()
@@ -94,13 +94,9 @@
%%--------------------------------------------------------------------
%%--------------------------------------------------------------------
-start_link(Options, ProfileName) ->
- Args = [Options, ProfileName],
- gen_server:start_link(?MODULE, Args, []).
-
-connect_and_send(Request, HandlerPid) ->
- call({connect_and_send, Request}, HandlerPid).
-
+start_link(Parent, Request, Options, ProfileName) ->
+ {ok, proc_lib:start_link(?MODULE, init, [[Parent, Request, Options,
+ ProfileName]])}.
%%--------------------------------------------------------------------
%% Function: send(Request, Pid) -> ok
@@ -122,8 +118,8 @@ send(Request, Pid) ->
%% Description: Cancels a request. Intended to be called by the httpc
%% manager process.
%%--------------------------------------------------------------------
-cancel(RequestId, Pid) ->
- cast({cancel, RequestId}, Pid).
+cancel(RequestId, Pid, From) ->
+ cast({cancel, RequestId, From}, Pid).
%%--------------------------------------------------------------------
@@ -229,16 +225,27 @@ stream(BodyPart, Request,_) -> % only 200 and 206 responses can be streamed
%% but we do not want that so errors will be handled by the process
%% sending an init_error message to itself.
%%--------------------------------------------------------------------
-init([Options, ProfileName]) ->
- ?hcrv("init - starting", [{options, Options}, {profile, ProfileName}]),
+init([Parent, Request, Options, ProfileName]) ->
process_flag(trap_exit, true),
- handle_verbose(Options#options.verbose),
- State = #state{status = undefined,
- options = Options,
- profile_name = ProfileName},
- ?hcrd("init - started", []),
- {ok, State}.
+ %% Do not let initial tcp-connection block the manager-process
+ proc_lib:init_ack(Parent, self()),
+ handle_verbose(Options#options.verbose),
+ Address = handle_proxy(Request#request.address, Options#options.proxy),
+ {ok, State} =
+ case {Address /= Request#request.address, Request#request.scheme} of
+ {true, https} ->
+ Error = https_through_proxy_is_not_currently_supported,
+ self() ! {init_error,
+ Error, httpc_response:error(Request, Error)},
+ {ok, #state{request = Request, options = Options,
+ status = ssl_tunnel}};
+ {_, _} ->
+ connect_and_send_first_request(Address, Request,
+ #state{options = Options,
+ profile_name = ProfileName})
+ end,
+ gen_server:enter_loop(?MODULE, [], State).
%%--------------------------------------------------------------------
%% Function: handle_call(Request, From, State) -> {reply, Reply, State} |
@@ -249,41 +256,6 @@ init([Options, ProfileName]) ->
%% {stop, Reason, State} (terminate/2 is called)
%% Description: Handling call messages
%%--------------------------------------------------------------------
-
-
-%% This is the first request, the reason the proc was started
-handle_call({connect_and_send, #request{address = Address0,
- scheme = Scheme} = Request},
- _From,
- #state{options = #options{proxy = Proxy},
- status = undefined,
- session = undefined} = State) ->
- ?hcrv("connect and send", [{address0, Address0}, {proxy, Proxy}]),
- Address = handle_proxy(Address0, Proxy),
- if
- ((Address =/= Address0) andalso (Scheme =:= https)) ->
- %% This is what we should do if and when ssl supports
- %% "socket upgrading"
- %%send_ssl_tunnel_request(Address, Request,
- %% #state{options = Options,
- %% status = ssl_tunnel});
- Reason = {failed_connecting,
- https_through_proxy_is_not_currently_supported},
- %% Send a reply to the original caller
- ErrorResponse = httpc_response:error(Request, Reason),
- httpc_response:send(Request#request.from, ErrorResponse),
- %% Reply to the manager
- ErrorReply = {error, Reason},
- {stop, normal, ErrorReply, State};
- true ->
- case connect_and_send_first_request(Address, Request, State) of
- {ok, NewState} ->
- {reply, ok, NewState};
- {stop, Error, NewState} ->
- {stop, normal, Error, NewState}
- end
- end;
-
handle_call(#request{address = Addr} = Request, _,
#state{status = Status,
session = #session{type = pipeline} = Session,
@@ -445,25 +417,27 @@ handle_call(info, _, State) ->
%% handle_keep_alive_queue/2 on the other hand will just skip the
%% request as if it was never issued as in this case the request will
%% not have been sent.
-handle_cast({cancel, RequestId},
+handle_cast({cancel, RequestId, From},
#state{request = #request{id = RequestId} = Request,
profile_name = ProfileName,
canceled = Canceled} = State) ->
?hcrv("cancel current request", [{request_id, RequestId},
{profile, ProfileName},
{canceled, Canceled}]),
- httpc_manager:request_canceled(RequestId, ProfileName),
+ httpc_manager:request_canceled(RequestId, ProfileName, From),
?hcrv("canceled", []),
{stop, normal,
State#state{canceled = [RequestId | Canceled],
request = Request#request{from = answer_sent}}};
-handle_cast({cancel, RequestId},
+handle_cast({cancel, RequestId, From},
#state{profile_name = ProfileName,
+ request = #request{id = CurrId},
canceled = Canceled} = State) ->
- ?hcrv("cancel", [{request_id, RequestId},
+ ?hcrv("cancel", [{request_id, RequestId},
+ {curr_req_id, CurrId},
{profile, ProfileName},
{canceled, Canceled}]),
- httpc_manager:request_canceled(RequestId, ProfileName),
+ httpc_manager:request_canceled(RequestId, ProfileName, From),
?hcrv("canceled", []),
{noreply, State#state{canceled = [RequestId | Canceled]}};
@@ -872,62 +846,55 @@ connect(SocketType, ToAddress,
Opts3 = [IpFamily | Opts2],
http_transport:connect(SocketType, ToAddress, Opts3, Timeout)
end.
-
-connect_and_send_first_request(Address,
- #request{settings = Settings,
- headers = Headers,
- address = OrigAddress,
- scheme = Scheme} = Request,
- #state{options = Options} = State) ->
-
- ?hcrd("connect",
- [{address, Address}, {request, Request}, {options, Options}]),
+connect_and_send_first_request(Address, Request, #state{options = Options} = State) ->
SocketType = socket_type(Request),
- ConnTimeout = Settings#http_options.connect_timeout,
+ ConnTimeout = (Request#request.settings)#http_options.connect_timeout,
+ ?hcri("connect",
+ [{address, Address}, {request, Request}, {options, Options}]),
case connect(SocketType, Address, Options, ConnTimeout) of
{ok, Socket} ->
- Session = #session{id = {OrigAddress, self()},
- scheme = Scheme,
- socket = Socket,
- socket_type = SocketType},
- ?hcrd("connected - now send first request", [{socket, Socket}]),
+ ClientClose =
+ httpc_request:is_client_closing(
+ Request#request.headers),
+ SessionType = httpc_manager:session_type(Options),
+ SocketType = socket_type(Request),
+ Session = #session{id = {Request#request.address, self()},
+ scheme = Request#request.scheme,
+ socket = Socket,
+ socket_type = SocketType,
+ client_close = ClientClose,
+ type = SessionType},
+ ?hcri("connected - now send first request", [{socket, Socket}]),
+
case httpc_request:send(Address, Session, Request) of
ok ->
- ?hcrd("first request sent", []),
- ClientClose =
- httpc_request:is_client_closing(Headers),
- SessionType = httpc_manager:session_type(Options),
- Session2 =
- Session#session{client_close = ClientClose,
- type = SessionType},
- TmpState =
- State#state{request = Request,
- session = Session2,
- mfa = init_mfa(Request, State),
- status_line = init_status_line(Request),
- headers = undefined,
- body = undefined,
- status = new},
- ?hcrt("activate socket", []),
- activate_once(Session),
+ ?hcri("first request sent", []),
+ TmpState = State#state{request = Request,
+ session = Session,
+ mfa = init_mfa(Request, State),
+ status_line =
+ init_status_line(Request),
+ headers = undefined,
+ body = undefined,
+ status = new},
+ http_transport:setopts(SocketType,
+ Socket, [{active, once}]),
NewState = activate_request_timeout(TmpState),
{ok, NewState};
-
- {error, Reason} = Error ->
- ?hcrv("failed sending request", [{reason, Reason}]),
- {stop, Error,
- State#state{session = {send_failed, Reason},
- request = Request}}
+ {error, Reason} ->
+ self() ! {init_error, error_sending,
+ httpc_response:error(Request, Reason)},
+ {ok, State#state{request = Request,
+ session =
+ #session{socket = Socket}}}
end;
-
- {error, Reason} = Error ->
- ?hcri("connect failed", [{reason, Reason}]),
- {stop, Error, State#state{session = {connect_failed, Reason},
- request = Request}}
+ {error, Reason} ->
+ self() ! {init_error, error_connecting,
+ httpc_response:error(Request, Reason)},
+ {ok, State#state{request = Request}}
end.
-
handler_info(#state{request = Request,
session = Session,
status_line = _StatusLine,
@@ -1167,12 +1134,12 @@ handle_response(#state{request = Request,
{ok, Msg, Data} ->
?hcrd("handle response - ok", []),
end_stream(StatusLine, Request),
- NewState = answer_request(Request, Msg, State),
+ NewState = maybe_send_answer(Request, Msg, State),
handle_queue(NewState, Data);
{stop, Msg} ->
?hcrd("handle response - stop", [{msg, Msg}]),
end_stream(StatusLine, Request),
- NewState = answer_request(Request, Msg, State),
+ NewState = maybe_send_answer(Request, Msg, State),
{stop, normal, NewState}
end.
@@ -1242,7 +1209,8 @@ handle_pipeline(#state{status = pipeline,
%% See comment for handle_cast({cancel, RequestId})
{stop, normal,
State#state{request =
- NextRequest#request{from = answer_sent}}};
+ NextRequest#request{from = answer_sent},
+ pipeline = Pipeline}};
false ->
?hcrv("next request", [{request, NextRequest}]),
NewSession =
@@ -1443,6 +1411,7 @@ answer_request(#request{id = RequestId, from = From} = Request, Msg,
Timer = {RequestId, TimerRef},
cancel_timer(TimerRef, {timeout, Request#request.id}),
httpc_manager:request_done(RequestId, ProfileName),
+
State#state{request = Request#request{from = answer_sent},
timers =
Timers#timers{request_timers =
@@ -1662,71 +1631,28 @@ handle_verbose(_) ->
ok.
-%%% Normaly I do not comment out code, I throw it away. But this might
-%%% actually be used one day if ssl is improved.
-%% send_ssl_tunnel_request(Address, Request = #request{address = {Host, Port}},
-%% State) ->
-%% %% A ssl tunnel request is a special http request that looks like
-%% %% CONNECT host:port HTTP/1.1
-%% SslTunnelRequest = #request{method = connect, scheme = http,
-%% headers =
-%% #http_request_h{
-%% host = Host,
-%% address = Address,
-%% path = Host ++ ":",
-%% pquery = integer_to_list(Port),
-%% other = [{ "Proxy-Connection", "keep-alive"}]},
-%% Ipv6 = (State#state.options)#options.ipv6,
-%% SocketType = socket_type(SslTunnelRequest),
-%% case http_transport:connect(SocketType,
-%% SslTunnelRequest#request.address, Ipv6) of
-%% {ok, Socket} ->
-%% case httpc_request:send(Address, SslTunnelRequest, Socket) of
-%% ok ->
-%% Session = #tcp_session{id =
-%% {SslTunnelRequest#request.address,
-%% self()},
-%% scheme =
-%% SslTunnelRequest#request.scheme,
-%% socket = Socket},
-%% NewState = State#state{mfa =
-%% {httpc_response, parse,
-%% [State#state.max_header_size]},
-%% request = Request,
-%% session = Session},
-%% http_transport:setopts(socket_type(
-%% SslTunnelRequest#request.scheme),
-%% Socket,
-%% [{active, once}]),
-%% {ok, NewState};
-%% {error, Reason} ->
-%% self() ! {init_error, error_sending,
-%% httpc_response:error(Request, Reason)},
-%% {ok, State#state{request = Request,
-%% session = #tcp_session{socket =
-%% Socket}}}
-%% end;
-%% {error, Reason} ->
-%% self() ! {init_error, error_connecting,
-%% httpc_response:error(Request, Reason)},
-%% {ok, State#state{request = Request}}
-%% end.
-
-%% d(F) ->
-%% d(F, []).
-
-%% d(F, A) ->
-%% d(get(dbg), F, A).
-
-%% d(true, F, A) ->
-%% io:format(user, "~w:~w:" ++ F ++ "~n", [self(), ?MODULE | A]);
-%% d(_, _, _) ->
-%% ok.
-
+send_raw(#session{socket = Socket, socket_type = SocketType},
+ {ProcessBody, Acc}) when is_function(ProcessBody, 1) ->
+ ?hcrt("send raw", [{acc, Acc}]),
+ send_raw(SocketType, Socket, ProcessBody, Acc);
send_raw(#session{socket = Socket, socket_type = SocketType}, Body) ->
http_transport:send(SocketType, Socket, Body).
+send_raw(SocketType, Socket, ProcessBody, Acc) ->
+ case ProcessBody(Acc) of
+ eof ->
+ ok;
+ {ok, Data, NewAcc} ->
+ DataBin = iolist_to_binary(Data),
+ ?hcrd("send", [{data, DataBin}]),
+ case http_transport:send(SocketType, Socket, DataBin) of
+ ok ->
+ send_raw(SocketType, Socket, ProcessBody, NewAcc);
+ Error ->
+ Error
+ end
+ end.
call(Msg, Pid) ->
@@ -1738,11 +1664,5 @@ call(Msg, Pid, Timeout) ->
cast(Msg, Pid) ->
gen_server:cast(Pid, Msg).
-
-%% to(To, Start) when is_integer(Start) andalso (Start >= 0) ->
-%% http_util:timeout(To, Start);
-%% to(To, _Start) ->
-%% http_util:timeout(To, t()).
-
t() ->
http_util:timestamp().
diff --git a/lib/inets/src/http_client/httpc_handler_sup.erl b/lib/inets/src/http_client/httpc_handler_sup.erl
index 2a69fd15d0..f7a0b014b3 100644
--- a/lib/inets/src/http_client/httpc_handler_sup.erl
+++ b/lib/inets/src/http_client/httpc_handler_sup.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2007-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2007-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
@@ -23,7 +23,7 @@
%% API
-export([start_link/0]).
--export([start_child/2]).
+-export([start_child/1]).
%% Supervisor callback
-export([init/1]).
@@ -34,11 +34,9 @@
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
-start_child(Options, Profile) ->
- Args = [Options, Profile],
+start_child(Args) ->
supervisor:start_child(?MODULE, Args).
-
%%%=========================================================================
%%% Supervisor callback
%%%=========================================================================
diff --git a/lib/inets/src/http_client/httpc_manager.erl b/lib/inets/src/http_client/httpc_manager.erl
index 591cb78c29..7f66b477eb 100644
--- a/lib/inets/src/http_client/httpc_manager.erl
+++ b/lib/inets/src/http_client/httpc_manager.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2002-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2002-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
@@ -29,7 +29,7 @@
start_link/3,
request/2,
cancel_request/2,
- request_canceled/2,
+ request_canceled/3,
request_done/2,
retry_request/2,
redirect_request/2,
@@ -66,6 +66,7 @@
state % State of the handler: initiating | started | operational | canceled
}).
+-define(DELAY, 500).
%%====================================================================
%% Internal Application API
@@ -158,7 +159,8 @@ cancel_request(RequestId, ProfileName) ->
%% be called by the httpc handler process.
%%--------------------------------------------------------------------
-request_canceled(RequestId, ProfileName) ->
+request_canceled(RequestId, ProfileName, From) ->
+ gen_server:reply(From, ok),
cast(ProfileName, {request_canceled, RequestId}).
@@ -355,44 +357,32 @@ do_init(ProfileName, CookiesDir) ->
%% {stop, Reason, State} (terminate/2 is called)
%% Description: Handling call messages
%%--------------------------------------------------------------------
-handle_call({request, Request}, _From, State) ->
- ?hcrv("request", [{request, Request}]),
+handle_call({request, Request}, _, State) ->
+ ?hcri("request", [{request, Request}]),
case (catch handle_request(Request, State)) of
- {ok, ReqId, NewState} ->
- {reply, {ok, ReqId}, NewState};
-
+ {reply, Msg, NewState} ->
+ {reply, Msg, NewState};
Error ->
- NewError = {error, {failed_process_request, Error}},
- {reply, NewError, State}
+ {stop, Error, httpc_response:error(Request, Error), State}
end;
-
-handle_call({cancel_request, RequestId}, From,
- #state{handler_db = HandlerDb} = State) ->
- ?hcrv("cancel_request", [{request_id, RequestId}]),
+
+handle_call({cancel_request, RequestId}, From, State) ->
+ ?hcri("cancel_request", [{request_id, RequestId}]),
case ets:lookup(State#state.handler_db, RequestId) of
[] ->
- ?hcrd("nothing to cancel", []),
- Reply = ok, %% Nothing to cancel
- {reply, Reply, State};
-
- [#handler_info{handler = Pid}] when is_pid(Pid) ->
- ?hcrd("found operational handler for this request",
- [{handler, Pid}]),
- httpc_handler:cancel(RequestId, Pid),
- {noreply, State#state{cancel =
- [{RequestId, Pid, From} |
- State#state.cancel]}};
-
- [#handler_info{starter = Pid, state = HandlerState}]
- when is_pid(Pid) ->
- ?hcri("found *initiating* handler for this request",
- [{starter, Pid}, {state, HandlerState}]),
- ets:update_element(HandlerDb, RequestId,
- {#handler_info.state, canceled}),
+ %% The request has allready compleated make sure
+ %% it is deliverd to the client process queue so
+ %% it can be thrown away by httpc:cancel_request
+ %% This delay is hopfully a temporary workaround.
+ %% Note that it will not not delay the manager,
+ %% only the client that called httpc:cancel_request
+ timer:apply_after(?DELAY, gen_server, reply, [From, ok]),
+ {noreply, State};
+ [{_, Pid, _}] ->
+ httpc_handler:cancel(RequestId, Pid, From),
{noreply, State#state{cancel =
- [{RequestId, Pid, From} |
+ [{RequestId, Pid, From} |
State#state.cancel]}}
-
end;
handle_call(reset_cookies, _, #state{cookie_db = CookieDb} = State) ->
@@ -437,43 +427,16 @@ handle_call(Req, From, #state{profile_name = ProfileName} = State) ->
%%--------------------------------------------------------------------
handle_cast({retry_or_redirect_request, {Time, Request}},
#state{profile_name = ProfileName} = State) ->
- ?hcrv("retry or redirect request", [{time, Time}, {request, Request}]),
- case timer:apply_after(Time, ?MODULE, retry_request,
- [Request, ProfileName]) of
- {ok, _} ->
- {noreply, State};
- {error, Reason} ->
- error_report(ProfileName,
- "failed scheduling retry/redirect request"
- "~n Time: ~p"
- "~n Request: ~p"
- "~n Reason: ~p", [Time, Request, Reason]),
- {noreply, State}
- end;
+ {ok, _} = timer:apply_after(Time, ?MODULE, retry_request, [Request, ProfileName]),
+ {noreply, State};
-handle_cast({retry_or_redirect_request, Request},
- #state{profile_name = Profile,
- handler_db = HandlerDb} = State) ->
- ?hcrv("retry or redirect request", [{request, Request}]),
+handle_cast({retry_or_redirect_request, Request}, State) ->
case (catch handle_request(Request, State)) of
- {ok, _, NewState} ->
+ {reply, {ok, _}, NewState} ->
{noreply, NewState};
-
Error ->
- ReqId = Request#request.id,
- error_report(Profile,
- "failed to retry or redirect request ~p"
- "~n Error: ~p", [ReqId, Error]),
- case ets:lookup(HandlerDb, ReqId) of
- [#handler_info{from = From}] ->
- Error2 = httpc_response:error(Request, Error),
- httpc_response:send(From, Error2),
- ok;
-
- _ ->
- ok
- end,
- {noreply, State}
+ httpc_response:error(Request, Error),
+ {stop, Error, State}
end;
handle_cast({request_canceled, RequestId}, State) ->
@@ -482,7 +445,6 @@ handle_cast({request_canceled, RequestId}, State) ->
case lists:keysearch(RequestId, 1, State#state.cancel) of
{value, Entry = {RequestId, _, From}} ->
?hcrt("found in cancel", [{from, From}]),
- gen_server:reply(From, ok),
{noreply,
State#state{cancel = lists:delete(Entry, State#state.cancel)}};
Else ->
@@ -539,8 +501,6 @@ handle_cast(Msg, #state{profile_name = ProfileName} = State) ->
"recived unknown message"
"~n Msg: ~p", [Msg]),
{noreply, State}.
-
-
%%--------------------------------------------------------------------
%% Function: handle_info(Info, State) -> {noreply, State} |
@@ -548,39 +508,17 @@ handle_cast(Msg, #state{profile_name = ProfileName} = State) ->
%% {stop, Reason, State} (terminate/2 is called)
%% Description: Handling all non call/cast messages
%%---------------------------------------------------------
-
-handle_info({started, StarterPid, ReqId, HandlerPid}, State) ->
- handle_started(StarterPid, ReqId, HandlerPid, State),
- {noreply, State};
-
-handle_info({connect_and_send, StarterPid, ReqId, HandlerPid, Res}, State) ->
- handle_connect_and_send(StarterPid, ReqId, HandlerPid, Res, State),
- {noreply, State};
-
-handle_info({failed_starting_handler, StarterPid, ReqId, Res}, State) ->
- handle_failed_starting_handler(StarterPid, ReqId, Res, State),
- {noreply, State};
-
-handle_info({'EXIT', Pid, Reason}, #state{handler_db = HandlerDb} = State) ->
- maybe_handle_terminating_starter(Pid, Reason, HandlerDb),
+handle_info({'EXIT', _, _}, State) ->
+ %% Handled in DOWN
{noreply, State};
-
handle_info({'DOWN', _, _, Pid, _}, State) ->
-
- %%
- %% Normally this should have been cleaned up already
- %% (when receiving {request_done, PequestId}), but
- %% just in case there is a glitch, cleanup anyway.
- %%
-
- Pattern = #handler_info{handler = Pid, _ = '_'},
- ets:match_delete(State#state.handler_db, Pattern),
+ ets:match_delete(State#state.handler_db, {'_', Pid, '_'}),
%% If there where any canceled request, handled by the
%% the process that now has terminated, the
%% cancelation can be viewed as sucessfull!
- NewCanceledList =
- lists:foldl(fun({_, HandlerPid, From} = Entry, Acc) ->
+ NewCanceldList =
+ lists:foldl(fun(Entry = {_, HandlerPid, From}, Acc) ->
case HandlerPid of
Pid ->
gen_server:reply(From, ok),
@@ -589,15 +527,13 @@ handle_info({'DOWN', _, _, Pid, _}, State) ->
Acc
end
end, State#state.cancel, State#state.cancel),
- {noreply, State#state{cancel = NewCanceledList}};
-
-handle_info(Info, #state{profile_name = ProfileName} = State) ->
- error_report(ProfileName,
- "received unknown info"
- "~n Info: ~p", [Info]),
+ {noreply, State#state{cancel = NewCanceldList}};
+handle_info(Info, State) ->
+ Report = io_lib:format("Unknown message in "
+ "httpc_manager:handle_info ~p~n", [Info]),
+ error_logger:error_report(Report),
{noreply, State}.
-
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> _ (ignored by gen_server)
%% Description: Shutdown the httpc_handler
@@ -655,224 +591,79 @@ get_handler_info(Tab) ->
{Pid, State} <- Handlers2],
Handlers3.
-
-%%
-%% The request handler process is started asynchronously by a
-%% "starter process". When the handler has sucessfully been started,
-%% this message (started) is sent.
-%%
-
-handle_started(StarterPid, ReqId, HandlerPid,
- #state{profile_name = Profile,
- handler_db = HandlerDb}) ->
- case ets:lookup(HandlerDb, ReqId) of
- [#handler_info{state = initiating} = HandlerInfo] ->
- ?hcri("received started ack for initiating handler", []),
- %% As a last resort, make sure we know when it exits,
- %% in case it forgets to notify us.
- %% We dont need to know the ref id?
- erlang:monitor(process, HandlerPid),
- HandlerInfo2 = HandlerInfo#handler_info{handler = HandlerPid,
- state = started},
- ets:insert(HandlerDb, HandlerInfo2),
- ok;
-
- [#handler_info{state = State}] ->
- error_report(Profile,
- "unexpected (started) message for handler (~p) in state "
- "~p regarding request ~p - ignoring", [HandlerPid, State, ReqId]),
- ?hcri("received unexpected started message", [{state, State}]),
- ok;
-
- [] ->
- error_report(Profile,
- "unknown handler ~p (~p) started for request ~w - canceling",
- [HandlerPid, StarterPid, ReqId]),
- httpc_handler:cancel(ReqId, HandlerPid)
- end.
-
-
-%%
-%% The request handler process is started asynchronously by a
-%% "starter process". When that process terminates it sends
-%% one of two messages. These ara handled by the two functions
-%% below.
-%%
-
-handle_connect_and_send(_StarterPid, ReqId, HandlerPid, Result,
- #state{profile_name = Profile,
- handler_db = HandlerDb}) ->
- case ets:lookup(HandlerDb, ReqId) of
- [#handler_info{state = started} = HandlerInfo] when Result =:= ok ->
- ?hcri("received connect-and-send ack for started handler", []),
- HandlerInfo2 = HandlerInfo#handler_info{starter = undefined,
- handler = HandlerPid,
- state = operational},
- ets:insert(HandlerDb, HandlerInfo2),
- ok;
-
- [#handler_info{state = canceled} = HandlerInfo] when Result =:= ok ->
- ?hcri("received connect-and-send ack for canceled handler", []),
- httpc_handler:cancel(ReqId, HandlerPid),
- HandlerInfo2 = HandlerInfo#handler_info{starter = undefined,
- handler = HandlerPid},
- ets:insert(HandlerDb, HandlerInfo2),
- ok;
-
- [#handler_info{state = State}] when Result =/= ok ->
- error_report(Profile,
- "handler (~p, ~w) failed to connect and/or "
- "send request ~p"
- "~n Result: ~p",
- [HandlerPid, State, ReqId, Result]),
- ?hcri("received connect-and-send error",
- [{result, Result}, {state, State}]),
- %% We don't need to send a response to the original caller
- %% because the handler already sent one in its terminate
- %% function.
- ets:delete(HandlerDb, ReqId),
- ok;
-
- [] ->
- ?hcri("handler successfully started "
- "for unknown request => canceling",
- [{profile, Profile},
- {handler, HandlerPid},
- {request, ReqId}]),
- httpc_handler:cancel(ReqId, HandlerPid)
- end.
-
-
-handle_failed_starting_handler(_StarterPid, ReqId, Error,
- #state{profile_name = Profile,
- handler_db = HandlerDb}) ->
- case ets:lookup(HandlerDb, ReqId) of
- [#handler_info{state = canceled}] ->
- error_report(Profile,
- "failed starting handler for request ~p"
- "~n Error: ~p", [ReqId, Error]),
- request_canceled(Profile, ReqId), % Fake signal from handler
- ets:delete(HandlerDb, ReqId),
- ok;
-
- [#handler_info{from = From}] ->
- error_report(Profile,
- "failed starting handler for request ~p"
- "~n Error: ~p", [ReqId, Error]),
- Reason2 =
- case Error of
- {error, Reason} ->
- {failed_connecting, Reason};
- _ ->
- {failed_connecting, Error}
- end,
- DummyReq = #request{id = ReqId},
- httpc_response:send(From, httpc_response:error(DummyReq, Reason2)),
- ets:delete(HandlerDb, ReqId),
- ok;
-
- [] ->
- error_report(Profile,
- "failed starting handler for unknown request ~p"
- "~n Error: ~p", [ReqId, Error]),
- ok
- end.
-
-
-maybe_handle_terminating_starter(MeybeStarterPid, Reason, HandlerDb) ->
- Pattern = #handler_info{starter = MeybeStarterPid, _ = '_'},
- case ets:match_object(HandlerDb, Pattern) of
- [#handler_info{id = ReqId, from = From, state = initiating}] ->
- %% The starter process crashed before it could start the
- %% the handler process, therefor we need to answer the
- %% original caller.
- ?hcri("starter process crashed bfore starting handler",
- [{starter, MeybeStarterPid}, {reason, Reason}]),
- Reason2 =
- case Reason of
- {error, Error} ->
- {failed_connecting, Error};
- _ ->
- {failed_connecting, Reason}
- end,
- DummyReq = #request{id = ReqId},
- httpc_response:send(From, httpc_response:error(DummyReq, Reason2)),
- ets:delete(HandlerDb, ReqId),
- ok;
-
- [#handler_info{state = State} = HandlerInfo] ->
- %% The starter process crashed after the handler was started.
- %% The handler will answer to the original caller.
- ?hcri("starter process crashed after starting handler",
- [{starter, MeybeStarterPid}, {reason, Reason}, {state, State}]),
- HandlerInfo2 = HandlerInfo#handler_info{starter = undefined},
- ets:insert(HandlerDb, HandlerInfo2),
- ok;
-
- _ ->
- ok
- end.
-
-
-%% -----
-%% Act as an HTTP/0.9 client that does not know anything
-%% about persistent connections
handle_request(#request{settings =
- #http_options{version = "HTTP/0.9"}} = Request0,
+ #http_options{version = "HTTP/0.9"}} = Request,
State) ->
- Request1 = handle_cookies(generate_request_id(Request0), State),
- Hdrs0 = Request1#request.headers,
- Hdrs1 = Hdrs0#http_request_h{connection = undefined},
- Request2 = Request1#request{headers = Hdrs1},
- create_handler_starter(Request2, State),
- {ok, Request2#request.id, State};
-
-%% -----
-%% Act as an HTTP/1.0 client that does not
-%% use persistent connections
+ %% Act as an HTTP/0.9 client that does not know anything
+ %% about persistent connections
+
+ NewRequest = handle_cookies(generate_request_id(Request), State),
+ NewHeaders =
+ (NewRequest#request.headers)#http_request_h{connection
+ = undefined},
+ start_handler(NewRequest#request{headers = NewHeaders}, State),
+ {reply, {ok, NewRequest#request.id}, State};
+
handle_request(#request{settings =
- #http_options{version = "HTTP/1.0"}} = Request0,
+ #http_options{version = "HTTP/1.0"}} = Request,
State) ->
- Request1 = handle_cookies(generate_request_id(Request0), State),
- Hdrs0 = Request1#request.headers,
- Hdrs1 = Hdrs0#http_request_h{connection = "close"},
- Request2 = Request1#request{headers = Hdrs1},
- create_handler_starter(Request2, State),
- {ok, Request2#request.id, State};
-
-
-%% -----
-handle_request(#request{method = Method,
- address = Address,
- scheme = Scheme} = Request0,
- #state{options = Opts} = State) ->
- Request1 = handle_cookies(generate_request_id(Request0), State),
- SessionType = session_type(Opts),
- case select_session(Method, Address, Scheme, SessionType, State) of
+ %% Act as an HTTP/1.0 client that does not
+ %% use persistent connections
+
+ NewRequest = handle_cookies(generate_request_id(Request), State),
+ NewHeaders =
+ (NewRequest#request.headers)#http_request_h{connection
+ = "close"},
+ start_handler(NewRequest#request{headers = NewHeaders}, State),
+ {reply, {ok, NewRequest#request.id}, State};
+
+handle_request(Request, State = #state{options = Options}) ->
+
+ NewRequest = handle_cookies(generate_request_id(Request), State),
+ SessionType = session_type(Options),
+ case select_session(Request#request.method,
+ Request#request.address,
+ Request#request.scheme, SessionType, State) of
{ok, HandlerPid} ->
- pipeline_or_keep_alive(Request1, HandlerPid, State);
+ pipeline_or_keep_alive(NewRequest, HandlerPid, State);
no_connection ->
- create_handler_starter(Request1, State);
- {no_session, OpenSessions}
- when OpenSessions < Opts#options.max_sessions ->
- create_handler_starter(Request1, State);
+ start_handler(NewRequest, State);
+ {no_session, OpenSessions} when OpenSessions
+ < Options#options.max_sessions ->
+ start_handler(NewRequest, State);
{no_session, _} ->
%% Do not start any more persistent connections
%% towards this server.
- Hdrs0 = Request1#request.headers,
- Hdrs1 = Hdrs0#http_request_h{connection = "close"},
- Request2 = Request1#request{headers = Hdrs1},
- create_handler_starter(Request2, State)
+ NewHeaders =
+ (NewRequest#request.headers)#http_request_h{connection
+ = "close"},
+ start_handler(NewRequest#request{headers = NewHeaders}, State)
end,
- {ok, Request1#request.id, State}.
+ {reply, {ok, NewRequest#request.id}, State}.
+
+
+start_handler(Request, State) ->
+ {ok, Pid} =
+ case is_inets_manager() of
+ true ->
+ httpc_handler_sup:start_child([whereis(httpc_handler_sup),
+ Request, State#state.options,
+ State#state.profile_name]);
+ false ->
+ httpc_handler:start_link(self(), Request, State#state.options,
+ State#state.profile_name)
+ end,
+ ets:insert(State#state.handler_db, {Request#request.id,
+ Pid, Request#request.from}),
+ erlang:monitor(process, Pid).
select_session(Method, HostPort, Scheme, SessionType,
#state{options = #options{max_pipeline_length = MaxPipe,
max_keep_alive_length = MaxKeepAlive},
session_db = SessionDb}) ->
- ?hcrd("select session", [{session_type, SessionType},
- {max_pipeline_length, MaxPipe},
+ ?hcrd("select session", [{session_type, SessionType},
+ {max_pipeline_length, MaxPipe},
{max_keep_alive_length, MaxKeepAlive}]),
case httpc_request:is_idempotent(Method) orelse
(SessionType =:= keep_alive) of
@@ -918,92 +709,17 @@ select_session(Candidates, Max) ->
?hcrd("select session - found one", [{handler, HandlerPid}]),
{ok, HandlerPid}
end.
-
-pipeline_or_keep_alive(#request{id = Id} = Request, HandlerPid, State) ->
- ?hcrd("pipeline of keep-alive", [{id, Id}, {handler, HandlerPid}]),
+
+pipeline_or_keep_alive(Request, HandlerPid, State) ->
case (catch httpc_handler:send(Request, HandlerPid)) of
ok ->
- ?hcrd("pipeline or keep-alive - successfully sent", []),
- Entry = #handler_info{id = Id,
- handler = HandlerPid,
- state = operational},
- ets:insert(State#state.handler_db, Entry);
-
- _ -> %% timeout pipelining failed
- ?hcrd("pipeline or keep-alive - failed sending -> "
- "start a new handler", []),
- create_handler_starter(Request, State)
+ ets:insert(State#state.handler_db, {Request#request.id,
+ HandlerPid,
+ Request#request.from});
+ _ -> %timeout pipelining failed
+ start_handler(Request, State)
end.
-
-create_handler_starter(#request{socket_opts = SocketOpts} = Request,
- #state{options = Options} = State)
- when is_list(SocketOpts) ->
- %% The user provided us with (override) socket options
- ?hcrt("create handler starter", [{socket_opts, SocketOpts}, {options, Options}]),
- Options2 = Options#options{socket_opts = SocketOpts},
- create_handler_starter(Request#request{socket_opts = undefined},
- State#state{options = Options2});
-
-create_handler_starter(#request{id = Id,
- from = From} = Request,
- #state{profile_name = ProfileName,
- options = Options,
- handler_db = HandlerDb} = _State) ->
- ?hcrv("create handler starter", [{id, Id}, {profile, ProfileName}]),
- IsInetsManager = is_inets_manager(),
- ManagerPid = self(),
- StarterFun =
- fun() ->
- ?hcrd("handler starter - start",
- [{id, Id},
- {profile, ProfileName},
- {inets_manager, IsInetsManager}]),
- Result1 =
- case IsInetsManager of
- true ->
- httpc_handler_sup:start_child(Options,
- ProfileName);
- false ->
- httpc_handler:start_link(Options,
- ProfileName)
- end,
- ?hcrd("handler starter - maybe connect and send",
- [{id, Id}, {profile, ProfileName}, {result, Result1}]),
- case Result1 of
- {ok, HandlerPid} ->
- StartedMessage =
- {started, self(), Id, HandlerPid},
- ManagerPid ! StartedMessage,
- Result2 = httpc_handler:connect_and_send(Request,
- HandlerPid),
- ?hcrd("handler starter - connected and sent",
- [{id, Id}, {profile, ProfileName},
- {handler, HandlerPid}, {result, Result2}]),
- ConnAndSendMessage =
- {connect_and_send,
- self(), Id, HandlerPid, Result2},
- ManagerPid ! ConnAndSendMessage;
- {error, Reason} ->
- StartFailureMessage =
- {failed_starting_handler, self(), Id, Reason},
- ManagerPid ! StartFailureMessage;
- _ ->
- StartFailureMessage =
- {failed_starting_handler, self(), Id, Result1},
- ManagerPid ! StartFailureMessage
- end
- end,
- Starter = erlang:spawn_link(StarterFun),
- ?hcrd("create handler starter - started", [{id, Id}, {starter, Starter}]),
- Entry = #handler_info{id = Id,
- starter = Starter,
- from = From,
- state = initiating},
- ets:insert(HandlerDb, Entry),
- ok.
-
-
is_inets_manager() ->
case get('$ancestors') of
[httpc_profile_sup | _] ->
@@ -1045,8 +761,6 @@ do_store_cookies([Cookie | Cookies], #state{cookie_db = CookieDb} = State) ->
ok = httpc_cookie:insert(CookieDb, Cookie),
do_store_cookies(Cookies, State).
-
-
session_db_name(ProfileName) ->
make_db_name(ProfileName, "__session_db").
@@ -1074,7 +788,6 @@ cast(ProfileName, Msg) ->
gen_server:cast(ProfileName, Msg).
-
get_proxy(Opts, #options{proxy = Default}) ->
proplists:get_value(proxy, Opts, Default).
@@ -1133,20 +846,6 @@ handle_verbose(trace) ->
handle_verbose(_) ->
ok.
-
error_report(Profile, F, A) ->
Report = io_lib:format("HTTPC-MANAGER<~p> " ++ F ++ "~n", [Profile | A]),
error_logger:error_report(Report).
-
-
-%% d(F) ->
-%% d(F, []).
-
-%% d(F, A) ->
-%% d(get(dbg), F, A).
-
-%% d(true, F, A) ->
-%% io:format(user, "~w:~w:" ++ F ++ "~n", [self(), ?MODULE | A]);
-%% d(_, _, _) ->
-%% ok.
-
diff --git a/lib/inets/src/http_client/httpc_request.erl b/lib/inets/src/http_client/httpc_request.erl
index d4df97ad40..879053f0f2 100644
--- a/lib/inets/src/http_client/httpc_request.erl
+++ b/lib/inets/src/http_client/httpc_request.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2004-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2004-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
@@ -79,36 +79,62 @@ send(SendAddr, Socket, SocketType,
{settings, HttpOptions},
{userinfo, UserInfo}]),
- TmpHeaders = handle_user_info(UserInfo, Headers),
+ TmpHdrs = handle_user_info(UserInfo, Headers),
- {TmpHeaders2, Body} =
- post_data(Method, TmpHeaders, Content, HeadersAsIs),
+ {TmpHdrs2, Body} = post_data(Method, TmpHdrs, Content, HeadersAsIs),
- {NewHeaders, Uri} = case Address of
- SendAddr ->
- {TmpHeaders2, Path ++ Query};
- _Proxy ->
- TmpHeaders3 =
- handle_proxy(HttpOptions, TmpHeaders2),
- {TmpHeaders3, AbsUri}
- end,
-
- FinalHeaders = case NewHeaders of
- HeaderList when is_list(HeaderList) ->
- http_headers(HeaderList, []);
- _ ->
- http_request:http_headers(NewHeaders)
- end,
+ {NewHeaders, Uri} =
+ case Address of
+ SendAddr ->
+ {TmpHdrs2, Path ++ Query};
+ _Proxy ->
+ TmpHdrs3 = handle_proxy(HttpOptions, TmpHdrs2),
+ {TmpHdrs3, AbsUri}
+ end,
+
+ FinalHeaders =
+ case NewHeaders of
+ HeaderList when is_list(HeaderList) ->
+ http_headers(HeaderList, []);
+ _ ->
+ http_request:http_headers(NewHeaders)
+ end,
Version = HttpOptions#http_options.version,
- Message = [method(Method), " ", Uri, " ",
- version(Version), ?CRLF,
- headers(FinalHeaders, Version), ?CRLF, Body],
+ do_send_body(SocketType, Socket, Method, Uri, Version, FinalHeaders, Body).
+
+
+do_send_body(SocketType, Socket, Method, Uri, Version, Headers,
+ {ProcessBody, Acc}) when is_function(ProcessBody, 1) ->
+ ?hcrt("send", [{acc, Acc}]),
+ case do_send_body(SocketType, Socket, Method, Uri, Version, Headers, []) of
+ ok ->
+ do_send_body(SocketType, Socket, ProcessBody, Acc);
+ Error ->
+ Error
+ end;
+do_send_body(SocketType, Socket, Method, Uri, Version, Headers, Body) ->
+ ?hcrt("create message", [{body, Body}]),
+ Message = [method(Method), " ", Uri, " ",
+ version(Version), ?CRLF,
+ headers(Headers, Version), ?CRLF, Body],
?hcrd("send", [{message, Message}]),
-
- http_transport:send(SocketType, Socket, lists:append(Message)).
+ http_transport:send(SocketType, Socket, Message).
+
+do_send_body(SocketType, Socket, ProcessBody, Acc) ->
+ case ProcessBody(Acc) of
+ eof ->
+ ok;
+ {ok, Data, NewAcc} ->
+ case http_transport:send(SocketType, Socket, Data) of
+ ok ->
+ do_send_body(SocketType, Socket, ProcessBody, NewAcc);
+ Error ->
+ Error
+ end
+ end.
%%-------------------------------------------------------------------------
@@ -161,7 +187,6 @@ is_client_closing(Headers) ->
%%%========================================================================
post_data(Method, Headers, {ContentType, Body}, HeadersAsIs)
when (Method =:= post) orelse (Method =:= put) ->
- ContentLength = body_length(Body),
NewBody = case Headers#http_request_h.expect of
"100-continue" ->
"";
@@ -170,14 +195,22 @@ post_data(Method, Headers, {ContentType, Body}, HeadersAsIs)
end,
NewHeaders = case HeadersAsIs of
- [] ->
- Headers#http_request_h{'content-type' =
- ContentType,
- 'content-length' =
- ContentLength};
- _ ->
- HeadersAsIs
- end,
+ [] ->
+ Headers#http_request_h{
+ 'content-type' = ContentType,
+ 'content-length' = case body_length(Body) of
+ undefined ->
+ % on upload streaming the caller must give a
+ % value to the Content-Length header
+ % (or use chunked Transfer-Encoding)
+ Headers#http_request_h.'content-length';
+ Len when is_list(Len) ->
+ Len
+ end
+ };
+ _ ->
+ HeadersAsIs
+ end,
{NewHeaders, NewBody};
@@ -190,7 +223,10 @@ body_length(Body) when is_binary(Body) ->
integer_to_list(size(Body));
body_length(Body) when is_list(Body) ->
- integer_to_list(length(Body)).
+ integer_to_list(length(Body));
+
+body_length({DataFun, _Acc}) when is_function(DataFun, 1) ->
+ undefined.
method(Method) ->
http_util:to_upper(atom_to_list(Method)).
diff --git a/lib/inets/src/http_lib/http_internal.hrl b/lib/inets/src/http_lib/http_internal.hrl
index 5440f214b5..2e924667c6 100644
--- a/lib/inets/src/http_lib/http_internal.hrl
+++ b/lib/inets/src/http_lib/http_internal.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2002-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2002-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
@@ -28,8 +28,8 @@
-define(HTTP_MAX_URI_SIZE, nolimit).
-ifndef(HTTP_DEFAULT_SSL_KIND).
--define(HTTP_DEFAULT_SSL_KIND, ossl).
-%% -define(HTTP_DEFAULT_SSL_KIND, essl).
+%% -define(HTTP_DEFAULT_SSL_KIND, ossl).
+-define(HTTP_DEFAULT_SSL_KIND, essl).
-endif. % -ifdef(HTTP_DEFAULT_SSL_KIND).
diff --git a/lib/inets/src/http_lib/http_transport.erl b/lib/inets/src/http_lib/http_transport.erl
index 0024d19fc1..8cabfe3c71 100644
--- a/lib/inets/src/http_lib/http_transport.erl
+++ b/lib/inets/src/http_lib/http_transport.erl
@@ -23,7 +23,7 @@
-export([
start/1,
connect/3, connect/4,
- listen/2, listen/3,
+ listen/2, listen/3, listen/4,
accept/2, accept/3,
close/2,
send/3,
@@ -110,7 +110,17 @@ connect(ip_comm = _SocketType, {Host, Port}, Opts0, Timeout)
Opts = [binary, {packet, 0}, {active, false}, {reuseaddr, true} | Opts0],
?hlrt("connect using gen_tcp",
[{host, Host}, {port, Port}, {opts, Opts}, {timeout, Timeout}]),
- gen_tcp:connect(Host, Port, Opts, Timeout);
+ try gen_tcp:connect(Host, Port, Opts, Timeout) of
+ {ok, _} = OK ->
+ OK;
+ {error, _} = ERROR ->
+ ERROR
+ catch
+ exit:{badarg, _} ->
+ {error, {eoptions, Opts}};
+ exit:badarg ->
+ {error, {eoptions, Opts}}
+ end;
%% Wrapper for backaward compatibillity
connect({ssl, SslConfig}, Address, Opts, Timeout) ->
@@ -123,7 +133,14 @@ connect({ossl, SslConfig}, {Host, Port}, _, Timeout) ->
{port, Port},
{ssl_config, SslConfig},
{timeout, Timeout}]),
- ssl:connect(Host, Port, Opts, Timeout);
+ case (catch ssl:connect(Host, Port, Opts, Timeout)) of
+ {'EXIT', Reason} ->
+ {error, {eoptions, Reason}};
+ {ok, _} = OK ->
+ OK;
+ {error, _} = ERROR ->
+ ERROR
+ end;
connect({essl, SslConfig}, {Host, Port}, _, Timeout) ->
Opts = [binary, {active, false}, {ssl_imp, new}] ++ SslConfig,
@@ -132,14 +149,22 @@ connect({essl, SslConfig}, {Host, Port}, _, Timeout) ->
{port, Port},
{ssl_config, SslConfig},
{timeout, Timeout}]),
- ssl:connect(Host, Port, Opts, Timeout).
+ case (catch ssl:connect(Host, Port, Opts, Timeout)) of
+ {'EXIT', Reason} ->
+ {error, {eoptions, Reason}};
+ {ok, _} = OK ->
+ OK;
+ {error, _} = ERROR ->
+ ERROR
+ end.
%%-------------------------------------------------------------------------
-%% listen(SocketType, Port) -> {ok, Socket} | {error, Reason}
+%% listen(SocketType, Addr, Port, Fd) -> {ok, Socket} | {error, Reason}
%% SocketType = ip_comm | {ssl, SSLConfig}
%% Port = integer()
-%% Socket = socket()
+%% Socket = socket()
+%% Fd = undefined | fd()
%%
%% Description: Sets up socket to listen on the port Port on the local
%% host using either gen_tcp or ssl. In the gen_tcp case the port
@@ -151,13 +176,8 @@ connect({essl, SslConfig}, {Host, Port}, _, Timeout) ->
listen(SocketType, Port) ->
listen(SocketType, undefined, Port).
-listen(ip_comm, Addr, Port) ->
- case (catch listen_ip_comm(Addr, Port)) of
- {'EXIT', Reason} ->
- {error, {exit, Reason}};
- Else ->
- Else
- end;
+listen(ip_comm = SocketType, Addr, Port) ->
+ listen(SocketType, Addr, Port, undefined);
%% Wrapper for backaward compatibillity
listen({ssl, SSLConfig}, Addr, Port) ->
@@ -186,9 +206,17 @@ listen({essl, SSLConfig} = Ssl, Addr, Port) ->
Opt2 = [{ssl_imp, new}, {reuseaddr, true} | Opt],
ssl:listen(Port, Opt2).
+listen(ip_comm, Addr, Port, Fd) ->
+ case (catch listen_ip_comm(Addr, Port, Fd)) of
+ {'EXIT', Reason} ->
+ {error, {exit, Reason}};
+ Else ->
+ Else
+ end.
+
-listen_ip_comm(Addr, Port) ->
- {NewPort, Opts, IpFamily} = get_socket_info(Addr, Port),
+listen_ip_comm(Addr, Port, Fd) ->
+ {NewPort, Opts, IpFamily} = get_socket_info(Addr, Port, Fd),
case IpFamily of
inet6fb4 ->
Opts2 = [inet6 | Opts],
@@ -223,29 +251,36 @@ listen_ip_comm(Addr, Port) ->
ipfamily_default(Addr, Port) ->
httpd_conf:lookup(Addr, Port, ipfamily, inet6fb4).
-get_socket_info(Addr, Port) ->
- Key = list_to_atom("httpd_" ++ integer_to_list(Port)),
- BaseOpts = [{backlog, 128}, {reuseaddr, true}],
+get_socket_info(Addr, Port, Fd0) ->
+ BaseOpts = [{backlog, 128}, {reuseaddr, true}],
IpFamilyDefault = ipfamily_default(Addr, Port),
- case init:get_argument(Key) of
- {ok, [[Value]]} ->
- {Fd, IpFamily} =
- case string:tokens(Value, [$|]) of
- [FdStr, IpFamilyStr] ->
- Fd0 = fd_of(FdStr),
- IpFamily0 = ip_family_of(IpFamilyStr),
- {Fd0, IpFamily0};
- [FdStr] ->
- {fd_of(FdStr), IpFamilyDefault};
- _ ->
- throw({error, {bad_descriptor, Value}})
- end,
+ %% The presence of a file descriptor takes precedence
+ case get_fd(Port, Fd0, IpFamilyDefault) of
+ {Fd, IpFamily} ->
{0, sock_opt(ip_comm, Addr, [{fd, Fd} | BaseOpts]), IpFamily};
- error ->
+ undefined ->
{Port, sock_opt(ip_comm, Addr, BaseOpts), IpFamilyDefault}
end.
+get_fd(Port, undefined = _Fd, IpFamilyDefault) ->
+ FdKey = list_to_atom("httpd_" ++ integer_to_list(Port)),
+ case init:get_argument(FdKey) of
+ {ok, [[Value]]} ->
+ case string:tokens(Value, [$|]) of
+ [FdStr, IpFamilyStr] ->
+ {fd_of(FdStr), ip_family_of(IpFamilyStr)};
+ [FdStr] ->
+ {fd_of(FdStr), IpFamilyDefault};
+ _ ->
+ throw({error, {bad_descriptor, Value}})
+ end;
+ error ->
+ undefined
+ end;
+get_fd(_Port, Fd, IpFamilyDefault) ->
+ {Fd, IpFamilyDefault}.
+
fd_of(FdStr) ->
case (catch list_to_integer(FdStr)) of
Fd when is_integer(Fd) ->
diff --git a/lib/inets/src/http_lib/http_util.erl b/lib/inets/src/http_lib/http_util.erl
index 4f1147176c..5e6b69ac5e 100644
--- a/lib/inets/src/http_lib/http_util.erl
+++ b/lib/inets/src/http_lib/http_util.erl
@@ -25,7 +25,8 @@
hexlist_to_integer/1, integer_to_hexlist/1,
convert_month/1,
is_hostname/1,
- timestamp/0, timeout/2
+ timestamp/0, timeout/2,
+ html_encode/1
]).
@@ -187,6 +188,13 @@ timeout(Timeout, Started) ->
end.
+html_encode(Chars) ->
+ Reserved = sets:from_list([$&, $<, $>, $\", $', $/]),
+ lists:append(lists:map(fun(Char) ->
+ char_to_html_entity(Char, Reserved)
+ end, Chars)).
+
+
%%%========================================================================
%%% Internal functions
%%%========================================================================
@@ -235,3 +243,11 @@ convert_to_ascii([Num | Reversed], Number)
convert_to_ascii([Num | Reversed], Number)
when (Num > 9) andalso (Num < 16) ->
convert_to_ascii(Reversed, [Num + 55 | Number]).
+
+char_to_html_entity(Char, Reserved) ->
+ case sets:is_element(Char, Reserved) of
+ true ->
+ "&#" ++ integer_to_list(Char) ++ ";";
+ false ->
+ [Char]
+ end.
diff --git a/lib/inets/src/http_server/httpd_file.erl b/lib/inets/src/http_server/httpd_file.erl
index 7e21d9e158..ccc1f7874a 100644
--- a/lib/inets/src/http_server/httpd_file.erl
+++ b/lib/inets/src/http_server/httpd_file.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2006-2010. All Rights Reserved.
+%% 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
@@ -26,22 +26,21 @@
handle_error(eacces, Op, ModData, Path) ->
- handle_error(403, Op, ModData, Path,"Forbidden");
+ handle_error(403, Op, ModData, Path, ": Forbidden");
handle_error(enoent, Op, ModData, Path) ->
- handle_error(404, Op, ModData, Path,"File not found");
+ handle_error(404, Op, ModData, Path, ": File not found");
handle_error(enotdir, Op, ModData, Path) ->
handle_error(404, Op, ModData, Path,
- ": A component of the file name is not a directory");
+ ": A component of the file name is not a directory");
handle_error(emfile, Op, _ModData, Path) ->
handle_error(500, Op, none, Path, ": To many open files");
handle_error({enfile,_}, Op, _ModData, Path) ->
handle_error(500, Op, none, Path, ": File table overflow");
handle_error(_Reason, Op, ModData, Path) ->
- handle_error(404, Op, ModData, Path, "File not found").
-
-handle_error(StatusCode, Op, none, Path, Reason) ->
- {StatusCode, none, ?NICE("Can't " ++ Op ++ Path ++ Reason)};
+ handle_error(404, Op, ModData, Path, ": File not found").
+handle_error(StatusCode, Op, none, Path, Reason) ->
+ {StatusCode, none, ?NICE("Can't " ++ Op ++ " " ++ Path ++ Reason)};
handle_error(StatusCode, Op, ModData, Path, Reason) ->
{StatusCode, ModData#mod.request_uri,
- ?NICE("Can't " ++ Op ++ Path ++ Reason)}.
+ ?NICE("Can't " ++ Op ++ " " ++ Path ++ Reason)}.
diff --git a/lib/inets/src/http_server/httpd_log.erl b/lib/inets/src/http_server/httpd_log.erl
index f3ea3aa0e2..db1e2c627a 100644
--- a/lib/inets/src/http_server/httpd_log.erl
+++ b/lib/inets/src/http_server/httpd_log.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
+%% 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
@@ -113,7 +113,7 @@ do_error_entry(ConfigDB, RemoteHost, undefined, Date, Reason) ->
do_error_entry(ConfigDB, RemoteHost, URI, Date, Reason) ->
case httpd_util:lookup(ConfigDB, error_log_format, pretty) of
pretty ->
- io_lib:format("[~s] access to ~s failed for ~s reason: ~n~p~n",
+ io_lib:format("[~s] access to ~s failed for ~s, reason: ~n~p~n",
[Date, URI, RemoteHost, Reason]);
compact ->
io_lib:format( "[~s] access to ~s failed for ~s, reason: ~w~n",
diff --git a/lib/inets/src/http_server/httpd_request_handler.erl b/lib/inets/src/http_server/httpd_request_handler.erl
index a9db6e2058..c3b47ce390 100644
--- a/lib/inets/src/http_server/httpd_request_handler.erl
+++ b/lib/inets/src/http_server/httpd_request_handler.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -240,13 +240,13 @@ handle_info({ssl_error, _, _} = Reason, State) ->
%% Timeouts
handle_info(timeout, #state{mod = ModData, mfa = {_, parse, _}} = State) ->
- error_log("No request received on keep-alive connection"
+ error_log("No request received on keep-alive connection "
"before server side timeout", ModData),
%% No response should be sent!
{stop, normal, State#state{response_sent = true}};
handle_info(timeout, #state{mod = ModData} = State) ->
httpd_response:send_status(ModData, 408, "Request timeout"),
- error_log("The client did not send the whole request before the"
+ error_log("The client did not send the whole request before the "
"server side timeout", ModData),
{stop, normal, State#state{response_sent = true}};
diff --git a/lib/inets/src/http_server/httpd_sup.erl b/lib/inets/src/http_server/httpd_sup.erl
index f94e5459c1..d028a19bf0 100644
--- a/lib/inets/src/http_server/httpd_sup.erl
+++ b/lib/inets/src/http_server/httpd_sup.erl
@@ -90,7 +90,7 @@ id(Address, Port) ->
%%% Supervisor callback
%%%=========================================================================
init([HttpdServices]) ->
- ?hdrd("starting", []),
+ ?hdrd("starting", [{httpd_service, HttpdServices}]),
RestartStrategy = one_for_one,
MaxR = 10,
MaxT = 3600,
@@ -182,24 +182,32 @@ httpd_child_spec(ConfigFile, AcceptTimeout, Debug) ->
Error
end.
-httpd_child_spec(Config, AcceptTimeout, Debug, Addr, 0) ->
- case start_listen(Addr, 0, Config) of
- {Pid, {NewPort, NewConfig, ListenSocket}} ->
- Name = {httpd_instance_sup, Addr, NewPort},
- StartFunc = {httpd_instance_sup, start_link,
- [NewConfig, AcceptTimeout,
- {Pid, ListenSocket}, Debug]},
- Restart = permanent,
- Shutdown = infinity,
- Modules = [httpd_instance_sup],
- Type = supervisor,
- {Name, StartFunc, Restart, Shutdown, Type, Modules};
- {Pid, {error, Reason}} ->
- exit(Pid, normal),
- {error, Reason}
- end;
-
httpd_child_spec(Config, AcceptTimeout, Debug, Addr, Port) ->
+ case Port == 0 orelse proplists:is_defined(fd, Config) of
+ true ->
+ httpd_child_spec_listen(Config, AcceptTimeout, Debug, Addr, Port);
+ false ->
+ httpd_child_spec_nolisten(Config, AcceptTimeout, Debug, Addr, Port)
+ end.
+
+httpd_child_spec_listen(Config, AcceptTimeout, Debug, Addr, Port) ->
+ case start_listen(Addr, Port, Config) of
+ {Pid, {NewPort, NewConfig, ListenSocket}} ->
+ Name = {httpd_instance_sup, Addr, NewPort},
+ StartFunc = {httpd_instance_sup, start_link,
+ [NewConfig, AcceptTimeout,
+ {Pid, ListenSocket}, Debug]},
+ Restart = permanent,
+ Shutdown = infinity,
+ Modules = [httpd_instance_sup],
+ Type = supervisor,
+ {Name, StartFunc, Restart, Shutdown, Type, Modules};
+ {Pid, {error, Reason}} ->
+ exit(Pid, normal),
+ {error, Reason}
+ end.
+
+httpd_child_spec_nolisten(Config, AcceptTimeout, Debug, Addr, Port) ->
Name = {httpd_instance_sup, Addr, Port},
StartFunc = {httpd_instance_sup, start_link,
[Config, AcceptTimeout, Debug]},
@@ -224,7 +232,8 @@ listen(Address, Port, Config) ->
SocketType = proplists:get_value(socket_type, Config, ip_comm),
case http_transport:start(SocketType) of
ok ->
- case http_transport:listen(SocketType, Address, Port) of
+ Fd = proplists:get_value(fd, Config),
+ case http_transport:listen(SocketType, Address, Port, Fd) of
{ok, ListenSocket} ->
NewConfig = proplists:delete(port, Config),
{ok, NewPort} = inet:port(ListenSocket),
diff --git a/lib/inets/src/http_server/httpd_util.erl b/lib/inets/src/http_server/httpd_util.erl
index 789f12652b..c1aff65d5e 100644
--- a/lib/inets/src/http_server/httpd_util.erl
+++ b/lib/inets/src/http_server/httpd_util.erl
@@ -181,7 +181,7 @@ message(304, _URL,_) ->
message(400,none,_) ->
"Your browser sent a query that this server could not understand.";
message(400,Msg,_) ->
- "Your browser sent a query that this server could not understand. "++ maybe_encode(Msg);
+ "Your browser sent a query that this server could not understand. "++ http_util:html_encode(Msg);
message(401,none,_) ->
"This server could not verify that you
are authorized to access the document you
@@ -190,48 +190,48 @@ credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.";
message(403,RequestURI,_) ->
- "You don't have permission to access "++ maybe_encode(RequestURI) ++" on this server.";
+ "You don't have permission to access "++ http_util:html_encode(RequestURI) ++" on this server.";
message(404,RequestURI,_) ->
- "The requested URL " ++ maybe_encode(RequestURI) ++ " was not found on this server.";
+ "The requested URL " ++ http_util:html_encode(RequestURI) ++ " was not found on this server.";
message(408, Timeout, _) ->
Timeout;
message(412,none,_) ->
- "The requested preconditions where false";
+ "The requested preconditions were false";
message(413, Reason,_) ->
- "Entity: " ++ Reason;
+ "Entity: " ++ http_util:html_encode(Reason);
message(414,ReasonPhrase,_) ->
- "Message "++ ReasonPhrase ++".";
+ "Message "++ http_util:html_encode(ReasonPhrase) ++".";
message(416,ReasonPhrase,_) ->
- ReasonPhrase;
+ http_util:html_encode(ReasonPhrase);
message(500,_,ConfigDB) ->
ServerAdmin=lookup(ConfigDB,server_admin,"unknown@unknown"),
"The server encountered an internal error or "
"misconfiguration and was unable to complete "
"your request.<P>Please contact the server administrator "
- ++ ServerAdmin ++ ", and inform them of the time the error occurred "
+ ++ http_util:html_encode(ServerAdmin) ++ ", and inform them of the time the error occurred "
"and anything you might have done that may have caused the error.";
message(501,{Method, RequestURI, HTTPVersion}, _ConfigDB) ->
if
is_atom(Method) ->
- atom_to_list(Method)++
- " to "++ maybe_encode(RequestURI)++" ("++HTTPVersion++") not supported.";
+ http_util:html_encode(atom_to_list(Method))++
+ " to "++ http_util:html_encode(RequestURI)++" ("++ http_util:html_encode(HTTPVersion)++") not supported.";
is_list(Method) ->
- Method++
- " to "++ maybe_encode(RequestURI)++" ("++HTTPVersion++") not supported."
+ http_util:html_encode(Method)++
+ " to "++ http_util:html_encode(RequestURI)++" ("++ http_util:html_encode(HTTPVersion)++") not supported."
end;
message(503, String, _ConfigDB) ->
- "This service in unavailable due to: "++String.
+ "This service in unavailable due to: "++ http_util:html_encode(String).
maybe_encode(URI) ->
- case lists:member($%, URI) of
- true ->
- URI;
- false ->
- http_uri:encode(URI)
- end.
+ Decoded = try http_uri:decode(URI) of
+ N -> N
+ catch
+ error:_ -> URI
+ end,
+ http_uri:encode(Decoded).
%%convert_rfc_date(Date)->{{YYYY,MM,DD},{HH,MIN,SEC}}
diff --git a/lib/inets/src/http_server/mod_esi.erl b/lib/inets/src/http_server/mod_esi.erl
index 929185a67a..e36c33b282 100644
--- a/lib/inets/src/http_server/mod_esi.erl
+++ b/lib/inets/src/http_server/mod_esi.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -415,7 +415,7 @@ deliver_webpage_chunk(#mod{config_db = Db} = ModData, Pid, Timeout) ->
end;
timeout ->
?hdrv("deliver_webpage_chunk - timeout", []),
- send_headers(ModData, {504, "Timeout"},[{"connection", "close"}]),
+ send_headers(ModData, 504, [{"connection", "close"}]),
httpd_socket:close(ModData#mod.socket_type, ModData#mod.socket),
process_flag(trap_exit,false),
{proceed,[{response, {already_sent, 200, 0}} | ModData#mod.data]}
@@ -452,6 +452,10 @@ handle_body(Pid, ModData, Body, Timeout, Size, IsDisableChunkedSend) ->
?hdrt("handle_body - send chunk", [{timeout, Timeout}, {size, Size}]),
httpd_response:send_chunk(ModData, Body, IsDisableChunkedSend),
receive
+ {esi_data, Data} when is_binary(Data) ->
+ ?hdrt("handle_body - received binary data (esi)", []),
+ handle_body(Pid, ModData, Data, Timeout, Size + byte_size(Data),
+ IsDisableChunkedSend);
{esi_data, Data} ->
?hdrt("handle_body - received data (esi)", []),
handle_body(Pid, ModData, Data, Timeout, Size + length(Data),
diff --git a/lib/inets/src/inets_app/inets.appup.src b/lib/inets/src/inets_app/inets.appup.src
index 07da8ca961..47f3fbba58 100644
--- a/lib/inets/src/inets_app/inets.appup.src
+++ b/lib/inets/src/inets_app/inets.appup.src
@@ -18,9 +18,14 @@
{"%VSN%",
[
+ {"5.5.2",
+ [
+ {restart_application, inets}
+ ]
+ },
{"5.5.1",
[
- {load_module, http_chunk, soft_purge, soft_purge, []}
+ {restart_application, inets}
]
},
{"5.5",
@@ -34,10 +39,15 @@
]
}
],
- [
+ [
+ {"5.5.2",
+ [
+ {restart_application, inets}
+ ]
+ },
{"5.5.1",
[
- {load_module, http_chunk, soft_purge, soft_purge, []}
+ {restart_application, inets}
]
},
{"5.5",
diff --git a/lib/inets/test/ftp_SUITE.erl b/lib/inets/test/ftp_SUITE.erl
index 4bafdbfef8..17e5f6777e 100644
--- a/lib/inets/test/ftp_SUITE.erl
+++ b/lib/inets/test/ftp_SUITE.erl
@@ -57,35 +57,42 @@
%% Description: Returns documentation/test cases in this test suite
%% or a skip tuple if the platform is not supported.
%%--------------------------------------------------------------------
-suite() -> [{ct_hooks,[ts_install_cth]}].
+suite() -> [{ct_hooks, [ts_install_cth]}].
all() ->
- [{group, solaris8_test}, {group, solaris9_test},
- {group, solaris10_test}, {group, linux_x86_test},
- {group, linux_ppc_test}, {group, macosx_x86_test},
- {group, macosx_ppc_test}, {group, openbsd_test},
- {group, freebsd_test}, {group, netbsd_test},
+ [
+ {group, solaris8_test},
+ {group, solaris9_test},
+ {group, solaris10_test},
+ {group, linux_x86_test},
+ {group, linux_ppc_test},
+ {group, macosx_x86_test},
+ {group, macosx_ppc_test},
+ {group, openbsd_test},
+ {group, freebsd_test},
+ {group, netbsd_test},
{group, windows_xp_test},
{group, windows_2003_server_test},
- {group, ticket_tests}].
+ {group, ticket_tests}
+ ].
groups() ->
- [{solaris8_test, [], [{ftp_solaris8_sparc_test, all}]},
- {solaris9_test, [], [{ftp_solaris9_sparc_test, all}]},
- {solaris10_test, [],
- [{ftp_solaris10_sparc_test, all},
- {ftp_solaris10_x86_test, all}]},
- {linux_x86_test, [], [{ftp_linux_x86_test, all}]},
- {linux_ppc_test, [], [{ftp_linux_ppc_test, all}]},
- {macosx_x86_test, [], [{ftp_macosx_x86_test, all}]},
- {macosx_ppc_test, [], [{ftp_macosx_ppc_test, all}]},
- {openbsd_test, [], [{ftp_openbsd_x86_test, all}]},
- {freebsd_test, [], [{ftp_freebsd_x86_test, all}]},
- {netbsd_test, [], [{ftp_netbsd_x86_test, all}]},
- {windows_xp_test, [], [{ftp_windows_xp_test, all}]},
- {windows_2003_server_test, [],
- [{ftp_windows_2003_server_test, all}]},
- {ticket_tests, [], [{ftp_ticket_test, all}]}].
+ [
+ {solaris8_test, [], [{ftp_solaris8_sparc_test, all}]},
+ {solaris9_test, [], [{ftp_solaris9_sparc_test, all}]},
+ {solaris10_test, [], [{ftp_solaris10_sparc_test, all},
+ {ftp_solaris10_x86_test, all}]},
+ {linux_x86_test, [], [{ftp_linux_x86_test, all}]},
+ {linux_ppc_test, [], [{ftp_linux_ppc_test, all}]},
+ {macosx_x86_test, [], [{ftp_macosx_x86_test, all}]},
+ {macosx_ppc_test, [], [{ftp_macosx_ppc_test, all}]},
+ {openbsd_test, [], [{ftp_openbsd_x86_test, all}]},
+ {freebsd_test, [], [{ftp_freebsd_x86_test, all}]},
+ {netbsd_test, [], [{ftp_netbsd_x86_test, all}]},
+ {windows_xp_test, [], [{ftp_windows_xp_test, all}]},
+ {windows_2003_server_test, [], [{ftp_windows_2003_server_test, all}]},
+ {ticket_tests, [], [{ftp_ticket_test, all}]}
+ ].
init_per_group(_GroupName, Config) ->
Config.
diff --git a/lib/inets/test/httpc_SUITE.erl b/lib/inets/test/httpc_SUITE.erl
index 2c8febf5ed..1998bd3950 100644
--- a/lib/inets/test/httpc_SUITE.erl
+++ b/lib/inets/test/httpc_SUITE.erl
@@ -28,6 +28,7 @@
-include("test_server_line.hrl").
-include_lib("kernel/include/file.hrl").
+-include("inets_test_lib.hrl").
%% Note: This directive should only be used in test suites.
-compile(export_all).
@@ -62,36 +63,84 @@
suite() -> [{ct_hooks,[ts_install_cth]}].
all() ->
- [proxy_options, proxy_head, proxy_get, proxy_trace,
- proxy_post, proxy_put, proxy_delete, proxy_auth,
- proxy_headers, proxy_emulate_lower_versions,
- http_options, http_head, http_get, http_post,
- http_dummy_pipe, http_inets_pipe, http_trace,
- http_async, http_save_to_file, http_save_to_file_async,
- http_headers, http_headers_dummy, http_bad_response,
- ssl_head, ossl_head, essl_head, ssl_get, ossl_get,
- essl_get, ssl_trace, ossl_trace, essl_trace,
- http_redirect, http_redirect_loop,
- http_internal_server_error, http_userinfo, http_cookie,
- http_server_does_not_exist, http_invalid_http,
- http_emulate_lower_versions, http_relaxed,
- page_does_not_exist, proxy_page_does_not_exist,
- proxy_https_not_supported, http_stream,
- http_stream_once, proxy_stream, parse_url, options,
- ipv6, headers_as_is, {group, tickets}].
+ [
+ proxy_options,
+ proxy_head,
+ proxy_get,
+ proxy_trace,
+ proxy_post,
+ proxy_put,
+ proxy_delete,
+ proxy_auth,
+ proxy_headers,
+ proxy_emulate_lower_versions,
+ http_options,
+ http_head,
+ http_get,
+ http_post,
+ http_post_streaming,
+ http_dummy_pipe,
+ http_inets_pipe,
+ http_trace,
+ http_async,
+ http_save_to_file,
+ http_save_to_file_async,
+ http_headers,
+ http_headers_dummy,
+ http_bad_response,
+ ssl_head,
+ ossl_head,
+ essl_head,
+ ssl_get,
+ ossl_get,
+ essl_get,
+ ssl_trace,
+ ossl_trace,
+ essl_trace,
+ http_redirect,
+ http_redirect_loop,
+ http_internal_server_error,
+ http_userinfo, http_cookie,
+ http_server_does_not_exist,
+ http_invalid_http,
+ http_emulate_lower_versions,
+ http_relaxed,
+ page_does_not_exist,
+ proxy_page_does_not_exist,
+ proxy_https_not_supported,
+ http_stream,
+ http_stream_once,
+ proxy_stream,
+ parse_url,
+ options,
+ ipv6,
+ headers_as_is,
+ {group, tickets},
+ initial_server_connect
+ ].
groups() ->
- [{tickets, [],
- [hexed_query_otp_6191, empty_body_otp_6243,
- empty_response_header_otp_6830,
- transfer_encoding_otp_6807, proxy_not_modified_otp_6821,
- no_content_204_otp_6982, missing_CR_otp_7304,
- {group, otp_7883}, {group, otp_8154}, {group, otp_8106},
- otp_8056, otp_8352, otp_8371, otp_8739]},
- {otp_7883, [], [otp_7883_1, otp_7883_2]},
+ [{tickets, [], [hexed_query_otp_6191,
+ empty_body_otp_6243,
+ empty_response_header_otp_6830,
+ transfer_encoding_otp_6807,
+ proxy_not_modified_otp_6821,
+ no_content_204_otp_6982,
+ missing_CR_otp_7304,
+ {group, otp_7883},
+ {group, otp_8154},
+ {group, otp_8106},
+ otp_8056,
+ otp_8352,
+ otp_8371,
+ otp_8739]},
+ {otp_7883, [], [otp_7883_1,
+ otp_7883_2]},
{otp_8154, [], [otp_8154_1]},
- {otp_8106, [],
- [otp_8106_pid, otp_8106_fun, otp_8106_mfa]}].
+ {otp_8106, [], [otp_8106_pid,
+ otp_8106_fun,
+ otp_8106_mfa]}].
+
init_per_group(_GroupName, Config) ->
Config.
@@ -138,6 +187,7 @@ init_per_suite(Config) ->
{local_port, ?IP_PORT},
{local_ssl_port, ?SSL_PORT} | Config].
+
%%--------------------------------------------------------------------
%% Function: end_per_suite(Config) -> _
%% Config - [tuple()]
@@ -165,6 +215,20 @@ end_per_suite(Config) ->
%%--------------------------------------------------------------------
init_per_testcase(otp_8154_1 = Case, Config) ->
init_per_testcase(Case, 5, Config);
+
+init_per_testcase(initial_server_connect, Config) ->
+ %% Try to check if crypto actually exist or not,
+ %% this test case does not work unless it does
+ case (catch crypto:start()) of
+ ok ->
+ application:start(public_key),
+ application:start(ssl),
+ inets:start(),
+ Config;
+ _ ->
+ {skip,"Could not start crypto"}
+ end;
+
init_per_testcase(Case, Config) ->
init_per_testcase(Case, 2, Config).
@@ -180,8 +244,8 @@ init_per_testcase_ssl(Tag, PrivDir, SslConfFile, Config) ->
[{local_ssl_server, Server} | Config2].
init_per_testcase(Case, Timeout, Config) ->
- io:format(user, "~n~n*** INIT ~w:[~w][~w] ***~n~n",
- [?MODULE, Timeout, Case]),
+ io:format(user, "~n~n*** INIT ~w:~w[~w] ***~n~n",
+ [?MODULE, Case, Timeout]),
PrivDir = ?config(priv_dir, Config),
tsp("init_per_testcase -> stop inets"),
application:stop(inets),
@@ -205,9 +269,10 @@ init_per_testcase(Case, Timeout, Config) ->
[$e, $s, $s, $l | _] ->
init_per_testcase_ssl(essl, PrivDir, SslConfFile, [{watchdog, Dog} | TmpConfig]);
- "proxy" ++ Rest ->
+ "proxy_" ++ Rest ->
+ io:format("init_per_testcase -> Rest: ~p~n", [Rest]),
case Rest of
- "_https_not_supported" ->
+ "https_not_supported" ->
tsp("init_per_testcase -> [proxy case] start inets"),
inets:start(),
tsp("init_per_testcase -> [proxy case] start ssl"),
@@ -221,13 +286,39 @@ init_per_testcase(Case, Timeout, Config) ->
| TmpConfig]
end;
_ ->
+ %% We use erlang.org for the proxy tests
+ %% and after the switch to erlang-web, many
+ %% of the test cases no longer work (erlang.org
+ %% previously run on Apache).
+ %% Until we have had time to update inets
+ %% (and updated erlang.org to use that inets)
+ %% and the test cases, we simply skip the
+ %% problematic test cases.
+ %% This is not ideal, but I am busy....
case is_proxy_available(?PROXY, ?PROXY_PORT) of
true ->
- inets:start(),
- [{watchdog, Dog} | TmpConfig];
+ BadCases =
+ [
+ "delete",
+ "get",
+ "head",
+ "not_modified_otp_6821",
+ "options",
+ "page_does_not_exist",
+ "post",
+ "put",
+ "stream"
+ ],
+ case lists:member(Rest, BadCases) of
+ true ->
+ [{skip, "TC and server not compatible"}|
+ TmpConfig];
+ false ->
+ inets:start(),
+ [{watchdog, Dog} | TmpConfig]
+ end;
false ->
- [{skip, "Failed to contact proxy"} |
- TmpConfig]
+ [{skip, "proxy not responding"} | TmpConfig]
end
end;
_ ->
@@ -395,6 +486,53 @@ http_post(Config) when is_list(Config) ->
end.
%%-------------------------------------------------------------------------
+http_post_streaming(doc) ->
+ ["Test streaming http post request against local server. "
+ "We only care about the client side of the the post. "
+ "The server script will not actually use the post data."];
+http_post_streaming(suite) ->
+ [];
+http_post_streaming(Config) when is_list(Config) ->
+ case ?config(local_server, Config) of
+ ok ->
+ Port = ?config(local_port, Config),
+ URL = case test_server:os_type() of
+ {win32, _} ->
+ ?URL_START ++ integer_to_list(Port) ++
+ "/cgi-bin/cgi_echo.exe";
+ _ ->
+ ?URL_START ++ integer_to_list(Port) ++
+ "/cgi-bin/cgi_echo"
+ end,
+ %% Cgi-script expects the body length to be 100
+ BodyFun = fun(0) ->
+ io:format("~w:http_post_streaming_fun -> "
+ "zero~n", [?MODULE]),
+ eof;
+ (LenLeft) ->
+ io:format("~w:http_post_streaming_fun -> "
+ "LenLeft: ~p~n", [?MODULE, LenLeft]),
+ {ok, lists:duplicate(10, "1"), LenLeft - 10}
+ end,
+
+ {ok, {{_,200,_}, [_ | _], [_ | _]}} =
+ httpc:request(post, {URL,
+ [{"expect", "100-continue"},
+ {"content-length", "100"}],
+ "text/plain", {BodyFun, 100}}, [], []),
+
+ {ok, {{_,504,_}, [_ | _], []}} =
+ httpc:request(post, {URL,
+ [{"expect", "100-continue"},
+ {"content-length", "10"}],
+ "text/plain", {BodyFun, 10}}, [], []);
+
+ _ ->
+ {skip, "Failed to start local http-server"}
+ end.
+
+
+%%-------------------------------------------------------------------------
http_emulate_lower_versions(doc) ->
["Perform request as 0.9 and 1.0 clients."];
http_emulate_lower_versions(suite) ->
@@ -478,34 +616,35 @@ http_inets_pipe(Config) when is_list(Config) ->
{skip, "Failed to start local http-server"}
end.
+
test_pipeline(URL) ->
- p("test_pipeline -> entry with"
- "~n URL: ~p", [URL]),
+ p("test_pipeline -> entry with"
+ "~n URL: ~p", [URL]),
- httpc:set_options([{pipeline_timeout, 50000}]),
-
- p("test_pipeline -> issue (async) request 1"),
- {ok, RequestId1} =
+ httpc:set_options([{pipeline_timeout, 50000}]),
+
+ p("test_pipeline -> issue (async) request 1"),
+ {ok, RequestId1} =
httpc:request(get, {URL, []}, [], [{sync, false}]),
- test_server:format("RequestId1: ~p~n", [RequestId1]),
- p("test_pipeline -> RequestId1: ~p", [RequestId1]),
+ test_server:format("RequestId1: ~p~n", [RequestId1]),
+ p("test_pipeline -> RequestId1: ~p", [RequestId1]),
- %% Make sure pipeline is initiated
- p("test_pipeline -> sleep some", []),
- test_server:sleep(4000),
+ %% Make sure pipeline is initiated
+ p("test_pipeline -> sleep some", []),
+ test_server:sleep(4000),
- p("test_pipeline -> issue (async) request 2"),
- {ok, RequestId2} =
+ p("test_pipeline -> issue (async) request 2"),
+ {ok, RequestId2} =
httpc:request(get, {URL, []}, [], [{sync, false}]),
- tsp("RequestId2: ~p", [RequestId2]),
- p("test_pipeline -> RequestId2: ~p", [RequestId2]),
+ tsp("RequestId2: ~p", [RequestId2]),
+ p("test_pipeline -> RequestId2: ~p", [RequestId2]),
- p("test_pipeline -> issue (sync) request 3"),
- {ok, {{_,200,_}, [_ | _], [_ | _]}} =
+ p("test_pipeline -> issue (sync) request 3"),
+ {ok, {{_,200,_}, [_ | _], [_ | _]}} =
httpc:request(get, {URL, []}, [], []),
p("test_pipeline -> expect reply for (async) request 1 or 2"),
- receive
+ receive
{http, {RequestId1, {{_, 200, _}, _, _}}} ->
p("test_pipeline -> received reply for (async) request 1 - now wait for 2"),
receive
@@ -523,46 +662,46 @@ test_pipeline(URL) ->
ok;
{http, Msg2} ->
test_server:fail(Msg2)
- end;
+ end;
{http, Msg3} ->
test_server:fail(Msg3)
- after 60000 ->
- receive Any1 ->
- tsp("received crap after timeout: ~n ~p", [Any1]),
- test_server:fail({error, {timeout, Any1}})
- end
+ after 60000 ->
+ receive Any1 ->
+ tsp("received crap after timeout: ~n ~p", [Any1]),
+ test_server:fail({error, {timeout, Any1}})
+ end
end,
-
- p("test_pipeline -> sleep some"),
- test_server:sleep(4000),
- p("test_pipeline -> issue (async) request 4"),
- {ok, RequestId3} =
- httpc:request(get, {URL, []}, [], [{sync, false}]),
- tsp("RequestId3: ~p", [RequestId3]),
- p("test_pipeline -> RequestId3: ~p", [RequestId3]),
+ p("test_pipeline -> sleep some"),
+ test_server:sleep(4000),
- p("test_pipeline -> issue (async) request 5"),
- {ok, RequestId4} =
+ p("test_pipeline -> issue (async) request 4"),
+ {ok, RequestId3} =
httpc:request(get, {URL, []}, [], [{sync, false}]),
- tsp("RequestId4: ~p~n", [RequestId4]),
- p("test_pipeline -> RequestId4: ~p", [RequestId4]),
-
- p("test_pipeline -> cancel (async) request 4"),
- ok = httpc:cancel_request(RequestId3),
-
- p("test_pipeline -> expect *no* reply for cancelled (async) request 4 (for 3 secs)"),
- receive
- {http, {RequestId3, _}} ->
- test_server:fail(http_cancel_request_failed)
- after 3000 ->
- ok
- end,
+ tsp("RequestId3: ~p", [RequestId3]),
+ p("test_pipeline -> RequestId3: ~p", [RequestId3]),
- p("test_pipeline -> expect reply for (async) request 4"),
- Body =
- receive
- {http, {RequestId4, {{_, 200, _}, _, BinBody4}}} = Res ->
+ p("test_pipeline -> issue (async) request 5"),
+ {ok, RequestId4} =
+ httpc:request(get, {URL, []}, [], [{sync, false}]),
+ tsp("RequestId4: ~p~n", [RequestId4]),
+ p("test_pipeline -> RequestId4: ~p", [RequestId4]),
+
+ p("test_pipeline -> cancel (async) request 4"),
+ ok = httpc:cancel_request(RequestId3),
+
+ p("test_pipeline -> expect *no* reply for cancelled (async) request 4 (for 3 secs)"),
+ receive
+ {http, {RequestId3, _}} ->
+ test_server:fail(http_cancel_request_failed)
+ after 3000 ->
+ ok
+ end,
+
+ p("test_pipeline -> expect reply for (async) request 4"),
+ Body =
+ receive
+ {http, {RequestId4, {{_, 200, _}, _, BinBody4}}} = Res ->
p("test_pipeline -> received reply for (async) request 5"),
tsp("Receive : ~p", [Res]),
BinBody4;
@@ -577,9 +716,9 @@ test_pipeline(URL) ->
p("test_pipeline -> check reply for (async) request 5"),
inets_test_lib:check_body(binary_to_list(Body)),
-
+
p("test_pipeline -> ensure no unexpected incomming"),
- receive
+ receive
{http, Any} ->
test_server:fail({unexpected_message, Any})
after 500 ->
@@ -589,8 +728,6 @@ test_pipeline(URL) ->
p("test_pipeline -> done"),
ok.
-
-
%%-------------------------------------------------------------------------
http_trace(doc) ->
["Perform a TRACE request that goes through a proxy."];
@@ -1253,6 +1390,9 @@ proxy_options(doc) ->
proxy_options(suite) ->
[];
proxy_options(Config) when is_list(Config) ->
+ %% As of 2011-03-24, erlang.org (which is used as server)
+ %% does no longer run Apache, but instead runs inets, which
+ %% do not implement "options".
case ?config(skip, Config) of
undefined ->
case httpc:request(options, {?PROXY_URL, []}, [], []) of
@@ -1277,6 +1417,8 @@ proxy_head(doc) ->
proxy_head(suite) ->
[];
proxy_head(Config) when is_list(Config) ->
+ %% As of 2011-03-24, erlang.org (which is used as server)
+ %% does no longer run Apache, but instead runs inets.
case ?config(skip, Config) of
undefined ->
case httpc:request(head, {?PROXY_URL, []}, [], []) of
@@ -1372,6 +1514,8 @@ proxy_post(doc) ->
proxy_post(suite) ->
[];
proxy_post(Config) when is_list(Config) ->
+ %% As of 2011-03-24, erlang.org (which is used as server)
+ %% does no longer run Apache, but instead runs inets.
case ?config(skip, Config) of
undefined ->
case httpc:request(post, {?PROXY_URL, [],
@@ -1394,6 +1538,8 @@ proxy_put(doc) ->
proxy_put(suite) ->
[];
proxy_put(Config) when is_list(Config) ->
+ %% As of 2011-03-24, erlang.org (which is used as server)
+ %% does no longer run Apache, but instead runs inets.
case ?config(skip, Config) of
undefined ->
case httpc:request(put, {"http://www.erlang.org/foobar.html", [],
@@ -1418,6 +1564,8 @@ proxy_delete(doc) ->
proxy_delete(suite) ->
[];
proxy_delete(Config) when is_list(Config) ->
+ %% As of 2011-03-24, erlang.org (which is used as server)
+ %% does no longer run Apache, but instead runs inets.
case ?config(skip, Config) of
undefined ->
URL = ?PROXY_URL ++ "/foobar.html",
@@ -1541,25 +1689,11 @@ proxy_https_not_supported(suite) ->
proxy_https_not_supported(Config) when is_list(Config) ->
Result = httpc:request(get, {"https://login.yahoo.com", []}, [], []),
case Result of
- {error, Reason} ->
- %% ok so far
- case Reason of
- {failed_connecting, Why} ->
- %% ok, now check why
- case Why of
- https_through_proxy_is_not_currently_supported ->
- ok;
- _ ->
- tsf({unexpected_why, Why})
- end;
- _ ->
- tsf({unexpected_reason, Reason})
- end;
+ {error, https_through_proxy_is_not_currently_supported} ->
+ ok;
_ ->
- tsf({unexpected_result, Result})
- end,
- ok.
-
+ tsf({unexpected_reason, Result})
+ end.
%%-------------------------------------------------------------------------
@@ -2312,7 +2446,7 @@ otp_8106_fun(Config) when is_list(Config) ->
ok;
_ ->
{skip, "Failed to start local http-server"}
- end.
+ end.
otp_8106_mfa(doc) ->
@@ -2538,7 +2672,7 @@ otp_8739(Config) when is_list(Config) ->
Request = {URL, []},
HttpOptions = [{connect_timeout, 500}, {timeout, 1}],
Options = [{sync, true}],
- case http:request(Method, Request, HttpOptions, Options) of
+ case httpc:request(Method, Request, HttpOptions, Options) of
{error, timeout} ->
%% And now we check the size of the handler db
Info = httpc:info(),
@@ -2573,7 +2707,7 @@ otp_8739_dummy_server_init(Parent) ->
Parent ! {port, Port},
otp_8739_dummy_server_main(Parent, ListenSocket).
-otp_8739_dummy_server_main(Parent, ListenSocket) ->
+otp_8739_dummy_server_main(_Parent, ListenSocket) ->
case gen_tcp:accept(ListenSocket) of
{ok, Sock} ->
%% Ignore the request, and simply wait for the socket to close
@@ -2595,7 +2729,31 @@ otp_8739_dummy_server_main(Parent, ListenSocket) ->
exit(Error)
end.
-
+%%-------------------------------------------------------------------------
+
+initial_server_connect(doc) ->
+ ["If this test cases times out the init of httpc_handler process is"
+ "blocking the manager/client process (implementation dependent which) but nither"
+ "should be blocked."];
+initial_server_connect(suite) ->
+ [];
+initial_server_connect(Config) when is_list(Config) ->
+ DataDir = ?config(data_dir, Config),
+ ok = httpc:set_options([{ipfamily, inet}]),
+
+ CertFile = filename:join(DataDir, "ssl_server_cert.pem"),
+ SSLOptions = [{certfile, CertFile}, {keyfile, CertFile}],
+
+ {DummyServerPid, Port} = dummy_ssl_server_hang(self(), ipv4, SSLOptions),
+
+ URL = ?SSL_URL_START ++ integer_to_list(Port) ++ "/index.html",
+
+ httpc:request(get, {URL, []}, [{ssl,{essl,[]}}], [{sync, false}]),
+
+ [{session_cookies,[]}] = httpc:which_cookies(),
+
+ DummyServerPid ! stop,
+ ok = httpc:set_options([{ipfamily, inet6fb4}]).
%%--------------------------------------------------------------------
%% Internal functions
@@ -3108,11 +3266,9 @@ pick_header(Headers, Name) ->
Val
end.
-
not_implemented_yet() ->
exit(not_implemented_yet).
-
p(F) ->
p(F, []).
@@ -3126,3 +3282,37 @@ tsp(F, A) ->
tsf(Reason) ->
test_server:fail(Reason).
+
+
+dummy_ssl_server_hang(Caller, IpV, SslOpt) ->
+ Pid = spawn(httpc_SUITE, dummy_ssl_server_hang_init, [Caller, IpV, SslOpt]),
+ receive
+ {port, Port} ->
+ {Pid, Port}
+ end.
+
+dummy_ssl_server_hang_init(Caller, IpV, SslOpt) ->
+ {ok, ListenSocket} =
+ case IpV of
+ ipv4 ->
+ ssl:listen(0, [binary, inet, {packet, 0},
+ {reuseaddr,true},
+ {active, false}] ++ SslOpt);
+ ipv6 ->
+ ssl:listen(0, [binary, inet6, {packet, 0},
+ {reuseaddr,true},
+ {active, false}] ++ SslOpt)
+ end,
+ {ok, {_,Port}} = ssl:sockname(ListenSocket),
+ tsp("dummy_ssl_server_hang_init -> Port: ~p", [Port]),
+ Caller ! {port, Port},
+ {ok, AcceptSocket} = ssl:transport_accept(ListenSocket),
+ dummy_ssl_server_hang_loop(AcceptSocket).
+
+dummy_ssl_server_hang_loop(_) ->
+ %% Do not do ssl:ssl_accept as we
+ %% want to time out the underlying gen_tcp:connect
+ receive
+ stop ->
+ ok
+ end.
diff --git a/lib/inets/test/httpd_basic_SUITE.erl b/lib/inets/test/httpd_basic_SUITE.erl
index 3e29b68283..f23d0b4765 100644
--- a/lib/inets/test/httpd_basic_SUITE.erl
+++ b/lib/inets/test/httpd_basic_SUITE.erl
@@ -29,7 +29,11 @@
suite() -> [{ct_hooks,[ts_install_cth]}].
all() ->
- [uri_too_long_414, header_too_long_413, escaped_url_in_error_body].
+ [
+ uri_too_long_414,
+ header_too_long_413,
+ escaped_url_in_error_body
+ ].
groups() ->
[].
@@ -40,6 +44,7 @@ init_per_group(_GroupName, Config) ->
end_per_group(_GroupName, Config) ->
Config.
+
%%--------------------------------------------------------------------
%% Function: init_per_suite(Config) -> Config
%% Config - [tuple()]
@@ -50,6 +55,8 @@ end_per_group(_GroupName, Config) ->
%% variable, but should NOT alter/remove any existing entries.
%%--------------------------------------------------------------------
init_per_suite(Config) ->
+ tsp("init_per_suite -> entry with"
+ "~n Config: ~p", [Config]),
ok = inets:start(),
PrivDir = ?config(priv_dir, Config),
HttpdConf = [{port, 0}, {ipfamily, inet},
@@ -64,6 +71,8 @@ init_per_suite(Config) ->
%% Description: Cleanup after the whole suite
%%--------------------------------------------------------------------
end_per_suite(_Config) ->
+ tsp("end_per_suite -> entry with"
+ "~n Config: ~p", [_Config]),
inets:stop(),
ok.
@@ -79,9 +88,12 @@ end_per_suite(_Config) ->
%% Note: This function is free to add any key/value pairs to the Config
%% variable, but should NOT alter/remove any existing entries.
%%--------------------------------------------------------------------
-init_per_testcase(_Case, Config) ->
+init_per_testcase(Case, Config) ->
+ tsp("init_per_testcase(~w) -> entry with"
+ "~n Config: ~p", [Case, Config]),
Config.
+
%%--------------------------------------------------------------------
%% Function: end_per_testcase(Case, Config) -> _
%% Case - atom()
@@ -90,9 +102,12 @@ init_per_testcase(_Case, Config) ->
%% A list of key/value pairs, holding the test case configuration.
%% Description: Cleanup after each test case
%%--------------------------------------------------------------------
-end_per_testcase(_, Config) ->
+end_per_testcase(Case, Config) ->
+ tsp("end_per_testcase(~w) -> entry with"
+ "~n Config: ~p", [Case, Config]),
Config.
+
%%-------------------------------------------------------------------------
%% Test cases starts here.
%%-------------------------------------------------------------------------
@@ -142,22 +157,30 @@ escaped_url_in_error_body(doc) ->
escaped_url_in_error_body(suite) ->
[];
escaped_url_in_error_body(Config) when is_list(Config) ->
- HttpdConf = ?config(httpd_conf, Config),
+ tsp("escaped_url_in_error_body -> entry with"
+ "~n Config: ~p", [Config]),
+ HttpdConf = ?config(httpd_conf, Config),
{ok, Pid} = inets:start(httpd, [{port, 0} | HttpdConf]),
Info = httpd:info(Pid),
Port = proplists:get_value(port, Info),
- Address = proplists:get_value(bind_address, Info),
- Path = "/<b>this_is_bold<b>",
+ _Address = proplists:get_value(bind_address, Info),
+ Path = "/<b>this_is_bold</b>",
URL = ?URL_START ++ integer_to_list(Port) ++ Path,
EscapedPath = http_uri:encode(Path),
- {ok, {404, Body}} = httpc:request(get, {URL, []},
- [{url_encode, true}],
- [{version, "HTTP/1.0"}, {full_result, false}]),
- EscapedPath = find_URL_path(string:tokens(Body, " ")),
- {ok, {404, Body1}} = httpc:request(get, {URL, []}, [],
- [{version, "HTTP/1.0"}, {full_result, false}]),
+ {ok, {404, Body1}} = httpc:request(get, {URL, []},
+ [{url_encode, true},
+ {version, "HTTP/1.0"}],
+ [{full_result, false}]),
EscapedPath = find_URL_path(string:tokens(Body1, " ")),
- inets:stop(httpd, Pid).
+ {ok, {404, Body2}} = httpc:request(get, {URL, []},
+ [{url_encode, false},
+ {version, "HTTP/1.0"}],
+ [{full_result, false}]),
+ HTMLEncodedPath = http_util:html_encode(Path),
+ HTMLEncodedPath = find_URL_path(string:tokens(Body2, " ")),
+ inets:stop(httpd, Pid),
+ tsp("escaped_url_in_error_body -> done"),
+ ok.
find_URL_path([]) ->
"";
@@ -165,3 +188,10 @@ find_URL_path(["URL", URL | _]) ->
URL;
find_URL_path([_ | Rest]) ->
find_URL_path(Rest).
+
+
+tsp(F) ->
+ tsp(F, []).
+tsp(F, A) ->
+ test_server:format("~p ~p:" ++ F ++ "~n", [self(), ?MODULE | A]).
+
diff --git a/lib/inets/test/httpd_mod.erl b/lib/inets/test/httpd_mod.erl
index f2c1fd6a65..1754cec7bc 100644
--- a/lib/inets/test/httpd_mod.erl
+++ b/lib/inets/test/httpd_mod.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2005-2010. All Rights Reserved.
+%% 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
@@ -19,7 +19,6 @@
%%
-module(httpd_mod).
--author('[email protected]').
-include("test_server.hrl").
-include("test_server_line.hrl").
@@ -815,6 +814,8 @@ esi(Type, Port, Host, Node) ->
[{statuscode, 302},
{version, "HTTP/1.0"}]),
ok.
+
+
%%--------------------------------------------------------------------
get(Type, Port, Host, Node) ->
ok = httpd_test_lib:verify_request(Type, Host, Port, Node,
diff --git a/lib/inets/test/inets_app_test.erl b/lib/inets/test/inets_app_test.erl
index 11b507fa26..49ea18501f 100644
--- a/lib/inets/test/inets_app_test.erl
+++ b/lib/inets/test/inets_app_test.erl
@@ -241,6 +241,20 @@ undef_funcs(suite) ->
undef_funcs(doc) ->
[];
undef_funcs(Config) when is_list(Config) ->
+ %% We need to check if there is a point to run this test.
+ %% On some platforms, crypto will not build, which in turn
+ %% causes ssl to not to not build (at this time, this will
+ %% change in the future).
+ %% So, we first check if we can start crypto, and if not,
+ %% we skip this test case!
+ case (catch crypto:start()) of
+ ok ->
+ ok;
+ {error, {already_started, crypto}} ->
+ ok;
+ _ ->
+ ?SKIP(crypto_start_check_failed)
+ end,
App = inets,
AppFile = key1search(app_file, Config),
Mods = key1search(modules, AppFile),
diff --git a/lib/inets/test/inets_test_lib.erl b/lib/inets/test/inets_test_lib.erl
index c56a714f5a..c837326bb5 100644
--- a/lib/inets/test/inets_test_lib.erl
+++ b/lib/inets/test/inets_test_lib.erl
@@ -32,7 +32,7 @@
-export([check_body/1]).
-export([millis/0, millis_diff/2, hours/1, minutes/1, seconds/1, sleep/1]).
-export([oscmd/1]).
--export([non_pc_tc_maybe_skip/4, os_based_skip/1]).
+-export([non_pc_tc_maybe_skip/4, os_based_skip/1, skip/3, fail/3]).
-export([flush/0]).
-export([start_node/1, stop_node/1]).
@@ -395,6 +395,13 @@ sleep(MSecs) ->
skip(Reason, File, Line) ->
exit({skipped, {Reason, File, Line}}).
+fail(Reason, File, Line) ->
+ String = lists:flatten(io_lib:format("Failure ~p(~p): ~p~n",
+ [File, Line, Reason])),
+ tsf(String).
+
+
+
flush() ->
receive
Msg ->
@@ -407,7 +414,7 @@ flush() ->
tsp(F) ->
tsp(F, []).
tsp(F, A) ->
- test_server:format("~p ~p:" ++ F ++ "~n", [self(), ?MODULE | A]).
+ test_server:format("~p ~p ~p:" ++ F ++ "~n", [node(), self(), ?MODULE | A]).
tsf(Reason) ->
test_server:fail(Reason).
diff --git a/lib/inets/test/inets_test_lib.hrl b/lib/inets/test/inets_test_lib.hrl
index 0cdb04139c..cc83a309b5 100644
--- a/lib/inets/test/inets_test_lib.hrl
+++ b/lib/inets/test/inets_test_lib.hrl
@@ -72,7 +72,7 @@
%% - Test case macros -
--define(SKIP(Reason), inets_test_lib:skip(Reason)).
+-define(SKIP(Reason), inets_test_lib:skip(Reason, ?MODULE, ?LINE)).
-define(FAIL(Reason), inets_test_lib:fail(Reason, ?MODULE, ?LINE)).
diff --git a/lib/inets/vsn.mk b/lib/inets/vsn.mk
index b1de3fef43..c0e25a30e3 100644
--- a/lib/inets/vsn.mk
+++ b/lib/inets/vsn.mk
@@ -18,7 +18,7 @@
# %CopyrightEnd%
APPLICATION = inets
-INETS_VSN = 5.5.2
+INETS_VSN = 5.6
PRE_VSN =
APP_VSN = "$(APPLICATION)-$(INETS_VSN)$(PRE_VSN)"
diff --git a/lib/jinterface/doc/src/notes.xml b/lib/jinterface/doc/src/notes.xml
index 962be63968..11fcc5f387 100644
--- a/lib/jinterface/doc/src/notes.xml
+++ b/lib/jinterface/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2000</year><year>2010</year>
+ <year>2000</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/kernel/doc/specs/.gitignore b/lib/kernel/doc/specs/.gitignore
new file mode 100644
index 0000000000..322eebcb06
--- /dev/null
+++ b/lib/kernel/doc/specs/.gitignore
@@ -0,0 +1 @@
+specs_*.xml
diff --git a/lib/kernel/doc/src/Makefile b/lib/kernel/doc/src/Makefile
index f8c1cac8b3..de10e31d36 100644
--- a/lib/kernel/doc/src/Makefile
+++ b/lib/kernel/doc/src/Makefile
@@ -1,19 +1,20 @@
-# ``The contents of this file are subject to the Erlang Public License,
+#
+# %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 via the world wide web at http://www.erlang.org/.
-#
+# 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.
-#
-# The Initial Developer of the Original Code is Ericsson Utvecklings AB.
-# Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
-# AB. All Rights Reserved.''
-#
-# $Id$
+#
+# %CopyrightEnd%
#
include $(ERL_TOP)/make/target.mk
include $(ERL_TOP)/make/$(TARGET)/otp.mk
@@ -94,19 +95,24 @@ HTML_REF_MAN_FILE = $(HTMLDIR)/index.html
TOP_PDF_FILE = $(PDFDIR)/$(APPLICATION)-$(VSN).pdf
+SPECS_FILES = $(XML_REF3_FILES:%.xml=$(SPECDIR)/specs_%.xml)
+
+TOP_SPECS_FILE = specs.xml
# ----------------------------------------------------
# FLAGS
# ----------------------------------------------------
XML_FLAGS +=
+SPECS_FLAGS = -I../../include
+
# ----------------------------------------------------
# Targets
# ----------------------------------------------------
$(HTMLDIR)/%.gif: %.gif
$(INSTALL_DATA) $< $@
-docs: pdf html man
+docs: man pdf html
$(TOP_PDF_FILE): $(XML_FILES)
@@ -125,8 +131,22 @@ clean clean_docs:
rm -f $(MAN4DIR)/*
rm -f $(MAN6DIR)/*
rm -f $(TOP_PDF_FILE) $(TOP_PDF_FILE:%.pdf=%.fo)
+ rm -f $(SPECDIR)/*
rm -f errs core *~
+$(SPECDIR)/specs_erl_prim_loader_stub.xml:
+ escript $(SPECS_EXTRACTOR) $(SPECS_FLAGS) \
+ -o$(dir $@) -module erl_prim_loader_stub
+$(SPECDIR)/specs_erlang_stub.xml:
+ escript $(SPECS_EXTRACTOR) $(SPECS_FLAGS) \
+ -o$(dir $@) -module erlang_stub
+$(SPECDIR)/specs_init_stub.xml:
+ escript $(SPECS_EXTRACTOR) $(SPECS_FLAGS) \
+ -o$(dir $@) -module init_stub
+$(SPECDIR)/specs_zlib_stub.xml:
+ escript $(SPECS_EXTRACTOR) $(SPECS_FLAGS) \
+ -o$(dir $@) -module zlib_stub
+
# ----------------------------------------------------
# Release Target
# ----------------------------------------------------
diff --git a/lib/kernel/doc/src/application.xml b/lib/kernel/doc/src/application.xml
index 47d578a339..51a3311ec2 100644
--- a/lib/kernel/doc/src/application.xml
+++ b/lib/kernel/doc/src/application.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -50,20 +50,27 @@
<p>Refer to <seealso marker="doc/design_principles:des_princ">OTP Design Principles</seealso> for more information about
applications and behaviours.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="start_type"/>
+ </datatype>
+ <datatype>
+ <name name="restart_type"/>
+ </datatype>
+ <datatype>
+ <!-- Parameterized opaque types are NYI: -->
+ <name><marker id="type-tuple_of">tuple_of(T)</marker></name>
+ <desc><p>A tuple where the elements are of type <c>T</c>.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>get_all_env() -> Env</name>
- <name>get_all_env(Application) -> Env</name>
+ <name name="get_all_env" arity="0"/>
+ <name name="get_all_env" arity="1"/>
<fsummary>Get the configuration parameters for an application</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Env = [{Par,Val}]</v>
- <v>&nbsp;Par = atom()</v>
- <v>&nbsp;Val = term()</v>
- </type>
<desc>
<p>Returns the configuration parameters and their values for
- <c>Application</c>. If the argument is omitted, it defaults to
+ <c><anno>Application</anno></c>. If the argument is omitted, it defaults to
the application of the calling process.</p>
<p>If the specified application is not loaded, or if the process
executing the call does not belong to any application,
@@ -71,18 +78,12 @@
</desc>
</func>
<func>
- <name>get_all_key() -> {ok, Keys} | []</name>
- <name>get_all_key(Application) -> {ok, Keys} | undefined </name>
+ <name name="get_all_key" arity="0"/>
+ <name name="get_all_key" arity="1"/>
<fsummary>Get the application specification keys</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Keys = [{Key,Val}]</v>
- <v>&nbsp;Key = atom()</v>
- <v>&nbsp;Val = term()</v>
- </type>
<desc>
<p>Returns the application specification keys and their values
- for <c>Application</c>. If the argument is omitted, it
+ for <c><anno>Application</anno></c>. If the argument is omitted, it
defaults to the application of the calling process.</p>
<p>If the specified application is not loaded, the function
returns <c>undefined</c>. If the process executing the call
@@ -91,17 +92,12 @@
</desc>
</func>
<func>
- <name>get_application() -> {ok, Application} | undefined</name>
- <name>get_application(Pid | Module) -> {ok, Application} | undefined</name>
+ <name name="get_application" arity="0"/>
+ <name name="get_application" arity="1"/>
<fsummary>Get the name of an application containing a certain process or module</fsummary>
- <type>
- <v>Pid = pid()</v>
- <v>Module = atom()</v>
- <v>Application = atom()</v>
- </type>
<desc>
<p>Returns the name of the application to which the process
- <c>Pid</c> or the module <c>Module</c> belongs. Providing no
+ <c><anno>Pid</anno></c> or the module <c><anno>Module</anno></c> belongs. Providing no
argument is the same as calling
<c>get_application(self())</c>.</p>
<p>If the specified process does not belong to any application,
@@ -110,17 +106,12 @@
</desc>
</func>
<func>
- <name>get_env(Par) -> {ok, Val} | undefined</name>
- <name>get_env(Application, Par) -> {ok, Val} | undefined</name>
+ <name name="get_env" arity="1"/>
+ <name name="get_env" arity="2"/>
<fsummary>Get the value of a configuration parameter</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Par = atom()</v>
- <v>Val = term()</v>
- </type>
<desc>
- <p>Returns the value of the configuration parameter <c>Par</c>
- for <c>Application</c>. If the application argument is
+ <p>Returns the value of the configuration parameter <c><anno>Par</anno></c>
+ for <c><anno>Application</anno></c>. If the application argument is
omitted, it defaults to the application of the calling
process.</p>
<p>If the specified application is not loaded, or
@@ -130,17 +121,12 @@
</desc>
</func>
<func>
- <name>get_key(Key) -> {ok, Val} | undefined</name>
- <name>get_key(Application, Key) -> {ok, Val} | undefined</name>
+ <name name="get_key" arity="1"/>
+ <name name="get_key" arity="2"/>
<fsummary>Get the value of an application specification key</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Key = atom()</v>
- <v>Val = term()</v>
- </type>
<desc>
<p>Returns the value of the application specification key
- <c>Key</c> for <c>Application</c>. If the application
+ <c><anno>Key</anno></c> for <c><anno>Application</anno></c>. If the application
argument is omitted, it defaults to the application of
the calling process.</p>
<p>If the specified application is not loaded, or
@@ -150,45 +136,35 @@
</desc>
</func>
<func>
- <name>load(AppDescr) -> ok | {error, Reason}</name>
- <name>load(AppDescr, Distributed) -> ok | {error, Reason}</name>
+ <name name="load" arity="1"/>
+ <name name="load" arity="2"/>
<fsummary>Load an application</fsummary>
- <type>
- <v>AppDescr = Application | AppSpec</v>
- <v>&nbsp;Application = atom()</v>
- <v>&nbsp;AppSpec = {application,Application,AppSpecKeys}</v>
- <v>&nbsp;&nbsp;AppSpec = [{Key,Val}]</v>
- <v>&nbsp;&nbsp;&nbsp;Key = atom()</v>
- <v>&nbsp;&nbsp;&nbsp;Val = term()</v>
- <v>Distributed = {Application,Nodes} | {Application,Time,Nodes} | default</v>
- <v>&nbsp;Nodes = [node() | {node(),..,node()}]</v>
- <v>&nbsp;Time = integer() > 0</v>
- <v>Reason = term()</v>
- </type>
+ <type name="application_spec"/>
+ <type name="application_opt"/>
<desc>
<p>Loads the application specification for an application into
the application controller. It will also load the application
specifications for any included applications. Note that
the function does not load the actual Erlang object code.</p>
- <p>The application can be given by its name <c>Application</c>.
+ <p>The application can be given by its name <c><anno>Application</anno></c>.
In this case the application controller will search the code
- path for the application resource file <c>Application.app</c>
+ path for the application resource file <c><anno>Application</anno>.app</c>
and load the specification it contains.</p>
<p>The application specification can also be given directly as a
- tuple <c>AppSpec</c>. This tuple should have the format and
+ tuple <c><anno>AppSpec</anno></c>. This tuple should have the format and
contents as described in <c>app(4)</c>.</p>
- <p>If <c>Distributed == {Application,[Time,]Nodes}</c>,
+ <p>If <c><anno>Distributed</anno> == {<anno>Application</anno>,[<anno>Time</anno>,]<anno>Nodes</anno>}</c>,
the application will be distributed. The argument overrides
the value for the application in the Kernel configuration
- parameter <c>distributed</c>. <c>Application</c> must be
+ parameter <c>distributed</c>. <c><anno>Application</anno></c> must be
the name of the application (same as in the first argument).
- If a node crashes and <c>Time</c> has been specified, then
- the application controller will wait for <c>Time</c>
+ If a node crashes and <c><anno>Time</anno></c> has been specified, then
+ the application controller will wait for <c><anno>Time</anno></c>
milliseconds before attempting to restart the application on
- another node. If <c>Time</c> is not specified, it will
+ another node. If <c><anno>Time</anno></c> is not specified, it will
default to 0 and the application will be restarted
immediately.</p>
- <p><c>Nodes</c> is a list of node names where the application
+ <p><c><anno>Nodes</anno></c> is a list of node names where the application
may run, in priority from left to right. Node names can be
grouped using tuples to indicate that they have the same
priority. Example:</p>
@@ -204,32 +180,22 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>loaded_applications() -> [{Application, Description, Vsn}]</name>
+ <name name="loaded_applications" arity="0"/>
<fsummary>Get the currently loaded applications</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Description = string()</v>
- <v>Vsn = string()</v>
- </type>
<desc>
<p>Returns a list with information about the applications which
have been loaded using <c>load/1,2</c>, also included
- applications. <c>Application</c> is the application name.
- <c>Description</c> and <c>Vsn</c> are the values of its
+ applications. <c><anno>Application</anno></c> is the application name.
+ <c><anno>Description</anno></c> and <c><anno>Vsn</anno></c> are the values of its
<c>description</c> and <c>vsn</c> application specification
keys, respectively.</p>
</desc>
</func>
<func>
- <name>permit(Application, Bool) -> ok | {error, Reason}</name>
+ <name name="permit" arity="2"/>
<fsummary>Change an application's permission to run on a node.</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Bool = bool()</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Changes the permission for <c>Application</c> to run at
+ <p>Changes the permission for <c><anno>Application</anno></c> to run at
the current node. The application must have been loaded using
<c>load/1,2</c> for the function to have effect.</p>
<p>If the permission of a loaded, but not started, application
@@ -258,20 +224,14 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>set_env(Application, Par, Val) -> ok</name>
- <name>set_env(Application, Par, Val, Timeout) -> ok</name>
+ <name name="set_env" arity="3"/>
+ <name name="set_env" arity="4"/>
<fsummary>Set the value of a configuration parameter</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Par = atom()</v>
- <v>Val = term()</v>
- <v>Timeout = int() | infinity</v>
- </type>
<desc>
- <p>Sets the value of the configuration parameter <c>Par</c> for
- <c>Application</c>.</p>
+ <p>Sets the value of the configuration parameter <c><anno>Par</anno></c> for
+ <c><anno>Application</anno></c>.</p>
<p><c>set_env/3</c> uses the standard <c>gen_server</c> timeout
- value (5000 ms). A <c>Timeout</c> argument can be provided
+ value (5000 ms). A <c><anno>Timeout</anno></c> argument can be provided
if another timeout value is useful, for example, in situations
where the application controller is heavily loaded.</p>
<warning>
@@ -285,20 +245,15 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>start(Application) -> ok | {error, Reason}</name>
- <name>start(Application, Type) -> ok | {error, Reason}</name>
+ <name name="start" arity="1"/>
+ <name name="start" arity="2"/>
<fsummary>Load and start an application</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Type = permanent | transient | temporary</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Starts <c>Application</c>. If it is not loaded,
+ <p>Starts <c><anno>Application</anno></c>. If it is not loaded,
the application controller will first load it using
<c>load/1</c>. It will make sure any included applications
are loaded, but will not start them. That is assumed to be
- taken care of in the code for <c>Application</c>.</p>
+ taken care of in the code for <c><anno>Application</anno></c>.</p>
<p>The application controller checks the value of
the application specification key <c>applications</c>, to
ensure that all applications that should be started before
@@ -310,7 +265,7 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
The application master starts the application by calling
the application callback function <c>Module:start/2</c> as
defined by the application specification key <c>mod</c>.</p>
- <p>The <c>Type</c> argument specifies the type of
+ <p>The <c><anno>Type</anno></c> argument specifies the type of
the application. If omitted, it defaults to <c>temporary</c>.</p>
<list type="bulleted">
<item>If a permanent application terminates, all other
@@ -331,19 +286,15 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>start_type() -> StartType | local | undefined</name>
+ <name name="start_type" arity="0"/>
<fsummary>Get the start type of an ongoing application startup.</fsummary>
- <type>
- <v>StartType = normal | {takeover,Node} | {failover,Node}</v>
- <v>&nbsp;Node = node()</v>
- </type>
<desc>
<p>This function is intended to be called by a process belonging
to an application, when the application is being started, to
- determine the start type which is either <c>StartType</c> or
+ determine the start type which is either <c><anno>StartType</anno></c> or
<c>local</c>.</p>
- <p>See <c>Module:start/2</c> for a description of
- <c>StartType</c>.</p>
+ <p>See <seealso marker="#start_type"><c>Module:start/2</c></seealso> for a description of
+ <c><anno>StartType</anno></c>.</p>
<p><c>local</c> is returned if only parts of the application is
being restarted (by a supervisor), or if the function is
called outside a startup.</p>
@@ -352,14 +303,10 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>stop(Application) -> ok | {error, Reason}</name>
+ <name name="stop" arity="1"/>
<fsummary>Stop an application</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Stops <c>Application</c>. The application master calls
+ <p>Stops <c><anno>Application</anno></c>. The application master calls
<c>Module:prep_stop/1</c>, if such a function is defined, and
then tells the top supervisor of the application to shutdown
(see <c>supervisor(3)</c>). This means that the entire
@@ -384,16 +331,11 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>takeover(Application, Type) -> ok | {error, Reason}</name>
+ <name name="takeover" arity="2"/>
<fsummary>Take over a distributed application</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Type = permanent | transient | temporary</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Performs a takeover of the distributed application
- <c>Application</c>, which executes at another node
+ <c><anno>Application</anno></c>, which executes at another node
<c>Node</c>. At the current node, the application is
restarted by calling
<c>Module:start({takeover,Node},StartArgs)</c>. <c>Module</c>
@@ -413,14 +355,10 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>unload(Application) -> ok | {error, Reason}</name>
+ <name name="unload" arity="1"/>
<fsummary>Unload an application</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Unloads the application specification for <c>Application</c>
+ <p>Unloads the application specification for <c><anno>Application</anno></c>
from the application controller. It will also unload
the application specifications for any included applications.
Note that the function does not purge the actual Erlang
@@ -428,19 +366,14 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>unset_env(Application, Par) -> ok</name>
- <name>unset_env(Application, Par, Timeout) -> ok</name>
+ <name name="unset_env" arity="2"/>
+ <name name="unset_env" arity="3"/>
<fsummary>Unset the value of a configuration parameter</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Par = atom()</v>
- <v>Timeout = int() | infinity</v>
- </type>
<desc>
- <p>Removes the configuration parameter <c>Par</c> and its value
- for <c>Application</c>.</p>
+ <p>Removes the configuration parameter <c><anno>Par</anno></c> and its value
+ for <c><anno>Application</anno></c>.</p>
<p><c>unset_env/2</c> uses the standard <c>gen_server</c>
- timeout value (5000 ms). A <c>Timeout</c> argument can be
+ timeout value (5000 ms). A <c><anno>Timeout</anno></c> argument can be
provided if another timeout value is useful, for example, in
situations where the application controller is heavily loaded.</p>
<warning>
@@ -454,23 +387,17 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
</desc>
</func>
<func>
- <name>which_applications() -> [{Application, Description, Vsn}]</name>
- <name>which_applications(Timeout) -> [{Application, Description, Vsn}]</name>
+ <name name="which_applications" arity="0"/>
+ <name name="which_applications" arity="1"/>
<fsummary>Get the currently running applications</fsummary>
- <type>
- <v>Application = atom()</v>
- <v>Description = string()</v>
- <v>Vsn = string()</v>
- <v>Timeout = int() | infinity</v>
- </type>
<desc>
<p>Returns a list with information about the applications which
- are currently running. <c>Application</c> is the application
- name. <c>Description</c> and <c>Vsn</c> are the values of its
+ are currently running. <c><anno>Application</anno></c> is the application
+ name. <c><anno>Description</anno></c> and <c><anno>Vsn</anno></c> are the values of its
<c>description</c> and <c>vsn</c> application specification
keys, respectively.</p>
<p><c>which_applications/0</c> uses the standard
- <c>gen_server</c> timeout value (5000 ms). A <c>Timeout</c>
+ <c>gen_server</c> timeout value (5000 ms). A <c><anno>Timeout</anno></c>
argument can be provided if another timeout value is useful,
for example, in situations where the application controller
is heavily loaded.</p>
@@ -501,7 +428,7 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
structured according to the OTP design principles as a
supervision tree, this means starting the top supervisor of
the tree.</p>
- <p><c>StartType</c> defines the type of start:</p>
+ <p><marker id="start_type"/><c>StartType</c> defines the type of start:</p>
<list type="bulleted">
<item><c>normal</c> if it's a normal startup.</item>
<item><c>normal</c> also if the application is distributed and
@@ -532,8 +459,7 @@ Nodes = [cp1@cave, {cp2@cave, cp3@cave}]</code>
<fsummary>Extended start of an application</fsummary>
<type>
<v>Phase = atom()</v>
- <v>StartType = normal | {takeover,Node} | {failover,Node}</v>
- <v>&nbsp;Node = node()</v>
+ <v>StartType = <seealso marker="#type-start_type">start_type()</seealso></v>
<v>PhaseArgs = term()</v>
<v>Pid = pid()</v>
<v>State = state()</v>
diff --git a/lib/kernel/doc/src/auth.xml b/lib/kernel/doc/src/auth.xml
index f53fc8b29a..15d9ef0fe4 100644
--- a/lib/kernel/doc/src/auth.xml
+++ b/lib/kernel/doc/src/auth.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -34,29 +34,28 @@
Cookie system, refer to
<seealso marker="doc/reference_manual:distributed">Distributed Erlang</seealso> in the Erlang Reference Manual.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="cookie"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>is_auth(Node) -> yes | no</name>
+ <name name="is_auth" arity="1"/>
<fsummary>Status of communication authorization (deprecated)</fsummary>
- <type>
- <v>Node = node()</v>
- </type>
<desc>
- <p>Returns <c>yes</c> if communication with <c>Node</c> is
- authorized. Note that a connection to <c>Node</c> will
- be established in this case. Returns <c>no</c> if <c>Node</c>
+ <p>Returns <c>yes</c> if communication with <c><anno>Node</anno></c> is
+ authorized. Note that a connection to <c><anno>Node</anno></c> will
+ be established in this case. Returns <c>no</c> if <c><anno>Node</anno></c>
does not exist or communication is not authorized (it has
another cookie than <c>auth</c> thinks it has).</p>
- <p>Use <seealso marker="net_adm#ping/1">net_adm:ping(Node)</seealso>
+ <p>Use <seealso marker="net_adm#ping/1">net_adm:ping(<anno>Node</anno>)</seealso>
instead.</p>
</desc>
</func>
<func>
- <name>cookie() -> Cookie</name>
+ <name name="cookie" arity="0"/>
<fsummary>Magic cookie for local node (deprecated)</fsummary>
- <type>
- <v>Cookie = atom()</v>
- </type>
<desc>
<p>Use
<seealso marker="erts:erlang#erlang:get_cookie/0">erlang:get_cookie()</seealso>
@@ -64,16 +63,14 @@
</desc>
</func>
<func>
- <name>cookie(TheCookie) -> true</name>
+ <name name="cookie" arity="1"/>
<fsummary>Set the magic for the local node (deprecated)</fsummary>
- <type>
- <v>TheCookie = Cookie | [Cookie]</v>
- <d>The cookie may also be given as a list with a single atom element</d>
- <v>&nbsp;Cookie = atom()</v>
- </type>
+ <type_desc variable="TheCookie">
+ The cookie may also be given as a list with a single atom element.
+ </type_desc>
<desc>
<p>Use
- <seealso marker="erts:erlang#erlang:set_cookie/2">erlang:set_cookie(node(), Cookie)</seealso>
+ <seealso marker="erts:erlang#erlang:set_cookie/2">erlang:set_cookie(node(), <anno>Cookie</anno>)</seealso>
instead.</p>
</desc>
</func>
@@ -82,7 +79,7 @@
<fsummary>Set the magic cookie for a node and verify authorization (deprecated)</fsummary>
<type>
<v>Node = node()</v>
- <v>Cookie = atom()</v>
+ <v>Cookie = <seealso marker="#type-cookie">cookie()</seealso></v>
</type>
<desc>
<p>Equivalent to
@@ -90,18 +87,14 @@
</desc>
</func>
<func>
- <name>node_cookie(Node, Cookie) -> yes | no</name>
+ <name name="node_cookie" arity="2"/>
<fsummary>Set the magic cookie for a node and verify authorization (deprecated)</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Cookie = atom()</v>
- </type>
<desc>
- <p>Sets the magic cookie of <c>Node</c> to <c>Cookie</c>, and
+ <p>Sets the magic cookie of <c><anno>Node</anno></c> to <c><anno>Cookie</anno></c>, and
verifies the status of the authorization.
Equivalent to calling
- <seealso marker="erts:erlang#erlang:set_cookie/2">erlang:set_cookie(Node, Cookie)</seealso>, followed by
- <seealso marker="#is_auth/1">auth:is_auth(Node)</seealso>.</p>
+ <seealso marker="erts:erlang#erlang:set_cookie/2">erlang:set_cookie(<anno>Node</anno>, <anno>Cookie</anno>)</seealso>, followed by
+ <seealso marker="#is_auth/1">auth:is_auth(<anno>Node</anno>)</seealso>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/kernel/doc/src/code.xml b/lib/kernel/doc/src/code.xml
index 4b8f934df1..6f85388c22 100644
--- a/lib/kernel/doc/src/code.xml
+++ b/lib/kernel/doc/src/code.xml
@@ -286,6 +286,12 @@
given to <c>set_path/1</c>.</p>
</section>
+ <datatypes>
+ <datatype>
+ <name name="load_error_rsn"/>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
<name>set_path(Path) -> true | {error, What}</name>
diff --git a/lib/kernel/doc/src/disk_log.xml b/lib/kernel/doc/src/disk_log.xml
index 324d4264cf..9721907162 100644
--- a/lib/kernel/doc/src/disk_log.xml
+++ b/lib/kernel/doc/src/disk_log.xml
@@ -179,13 +179,48 @@
reopen the log simultaneously.</p>
</note>
</description>
+ <datatypes>
+ <datatype>
+ <name name="log"/>
+ </datatype>
+ <datatype>
+ <name name="dlog_size"/>
+ </datatype>
+ <datatype>
+ <name name="dlog_format"/>
+ </datatype>
+ <datatype>
+ <name name="dlog_head_opt"/>
+ </datatype>
+ <datatype>
+ <name name="dlog_byte"/>
+ </datatype>
+ <datatype>
+ <name name="dlog_mode"/>
+ </datatype>
+ <datatype>
+ <name name="dlog_type"/>
+ </datatype>
+ <datatype>
+ <name name="continuation"/>
+ <desc><p>Chunk continuation returned by
+ <c>chunk/2,3</c>, <c>bchunk/2,3</c>, or <c>chunk_step/3</c>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="bytes"/>
+ </datatype>
+ <datatype>
+ <name name="invalid_header"/>
+ </datatype>
+ <datatype>
+ <name name="file_error"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>accessible_logs() -> {[LocalLog], [DistributedLog]}</name>
+ <name name="accessible_logs" arity="0"/>
<fsummary>Return the accessible disk logs on the current node.</fsummary>
- <type>
- <v>LocalLog = DistributedLog = term()</v>
- </type>
<desc>
<p>The <c>accessible_logs/0</c> function returns
the names of the disk logs accessible on the current node.
@@ -195,16 +230,13 @@
</desc>
</func>
<func>
- <name>alog(Log, Term)</name>
- <name>balog(Log, Bytes) -> ok | {error, Reason}</name>
+ <name name="alog" arity="2"/>
+ <name name="balog" arity="2"/>
+ <type variable="Log"/>
+ <type variable="Term" name_i="1"/>
+ <type variable="Bytes"/>
+ <type name="notify_ret"/>
<fsummary>Asynchronously log an item onto a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Term = term()</v>
- <v>Bytes = binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Reason = no_such_log</v>
- </type>
<desc>
<p>The <c>alog/2</c> and <c>balog/2</c> functions asynchronously
append an item to a disk log. The function <c>alog/2</c> is
@@ -225,17 +257,13 @@
</desc>
</func>
<func>
- <name>alog_terms(Log, TermList)</name>
- <name>balog_terms(Log, BytesList) -> ok | {error, Reason}</name>
+ <name name="alog_terms" arity="2"/>
+ <name name="balog_terms" arity="2"/>
<fsummary>Asynchronously log several items onto a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>TermList = [term()]</v>
- <v>BytesList = [Bytes]</v>
- <v>Bytes = binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Reason = no_such_log</v>
- </type>
+ <type variable="Log"/>
+ <type variable="TermList" name_i="1"/>
+ <type variable="ByteList"/>
+ <type name="notify_ret"/>
<desc>
<p>The <c>alog_terms/2</c> and <c>balog_terms/2</c> functions
asynchronously append a list of items to a disk log.
@@ -257,14 +285,10 @@
</desc>
</func>
<func>
- <name>block(Log)</name>
- <name>block(Log, QueueLogRecords) -> ok | {error, Reason}</name>
+ <name name="block" arity="1"/>
+ <name name="block" arity="2"/>
+ <type name="block_error_rsn"/>
<fsummary>Block a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>QueueLogRecords = bool()</v>
- <v>Reason = no_such_log | nonode | {blocked_log, Log}</v>
- </type>
<desc>
<p>With a call to <c>block/1,2</c> a process can block a log.
If the blocking process is not an owner of the log, a temporary
@@ -280,52 +304,32 @@
affected by the block. Any other attempt than those hitherto
mentioned to update or read a blocked log suspends the
calling process until the log is unblocked or returns an
- error message <c>{blocked_log, Log}</c>, depending on
- whether the value of <c>QueueLogRecords</c> is <c>true</c>
- or <c>false</c>. The default value of <c>QueueLogRecords</c>
+ error message <c>{blocked_log, <anno>Log</anno>}</c>, depending on
+ whether the value of <c><anno>QueueLogRecords</anno></c> is <c>true</c>
+ or <c>false</c>. The default value of <c><anno>QueueLogRecords</anno></c>
is <c>true</c>, which is used by <c>block/1</c>.
</p>
</desc>
</func>
<func>
- <name>change_header(Log, Header) -> ok | {error, Reason}</name>
+ <name name="change_header" arity="2"/>
<fsummary>Change the head or head_func option for an owner of a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Header = {head, Head} | {head_func, {M,F,A}}</v>
- <v>Head = none | term() | binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {blocked_log, Log} | {badarg, head}</v>
- </type>
<desc>
<p>The <c>change_header/2</c> function changes the value of
the <c>head</c> or <c>head_func</c> option of a disk log.</p>
</desc>
</func>
<func>
- <name>change_notify(Log, Owner, Notify) -> ok | {error, Reason}</name>
+ <name name="change_notify" arity="3"/>
<fsummary>Change the notify option for an owner of a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Owner = pid()</v>
- <v>Notify = bool()</v>
- <v>Reason = no_such_log | nonode | {blocked_log, Log} | {badarg, notify} | {not_owner, Owner}</v>
- </type>
<desc>
<p>The <c>change_notify/3</c> function changes the value of the
<c>notify</c> option for an owner of a disk log. </p>
</desc>
</func>
<func>
- <name>change_size(Log, Size) -> ok | {error, Reason}</name>
+ <name name="change_size" arity="2"/>
<fsummary>Change the size of an open disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Size = integer() > 0 | infinity | {MaxNoBytes, MaxNoFiles}</v>
- <v>MaxNoBytes = integer() > 0</v>
- <v>MaxNoFiles = integer() > 0</v>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {blocked_log, Log} | {new_size_too_small, CurrentSize} | {badarg, size} | {file_error, FileName, FileError}</v>
- </type>
<desc>
<p>The <c>change_size/2</c> function changes the size of an open log.
For a halt log it is always possible to increase the size,
@@ -363,21 +367,17 @@
</desc>
</func>
<func>
- <name>chunk(Log, Continuation)</name>
- <name>chunk(Log, Continuation, N) -> {Continuation2, Terms} | {Continuation2, Terms, Badbytes} | eof | {error, Reason}</name>
- <name>bchunk(Log, Continuation)</name>
- <name>bchunk(Log, Continuation, N) -> {Continuation2, Binaries} | {Continuation2, Binaries, Badbytes} | eof | {error, Reason}</name>
+ <name name="chunk" arity="2"/>
+ <name name="chunk" arity="3"/>
+ <name name="bchunk" arity="2"/>
+ <name name="bchunk" arity="3"/>
<fsummary>Read a chunk of items written to a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Continuation = start | cont()</v>
- <v>N = integer() > 0 | infinity</v>
- <v>Continuation2 = cont()</v>
- <v>Terms = [term()]</v>
- <v>Badbytes = integer()</v>
- <v>Reason = no_such_log | {format_external, Log} | {blocked_log, Log} | {badarg, continuation} | {not_internal_wrap, Log} | {corrupt_log_file, FileName} | {file_error, FileName, FileError}</v>
- <v>Binaries = [binary()]</v>
- </type>
+ <type variable="Log"/>
+ <type variable="Continuation"/>
+ <type variable="N"/>
+ <type name="chunk_ret"/>
+ <type name="bchunk_ret"/>
+ <type name="chunk_error_rsn"/>
<desc>
<p>The <c>chunk/2,3</c> and <c>bchunk/2,3</c> functions make
it possible to efficiently read the terms which have been
@@ -394,31 +394,31 @@
individual distributed log on some other node is chosen, if
such a log exists.
</p>
- <p>When <c>chunk/3</c> is called, <c>N</c> controls the
+ <p>When <c>chunk/3</c> is called, <c><anno>N</anno></c> controls the
maximum number of terms that are read from the log in each
chunk. Default is <c>infinity</c>, which means that all the
terms contained in the 64 kilobyte chunk are read. If less than
- <c>N</c> terms are returned, this does not necessarily mean
+ <c><anno>N</anno></c> terms are returned, this does not necessarily mean
that the end of the file has been reached.
</p>
<p>The <c>chunk</c> function returns a tuple
- <c>{Continuation2, Terms}</c>, where <c>Terms</c> is a list
- of terms found in the log. <c>Continuation2</c> is yet
+ <c>{<anno>Continuation2</anno>, <anno>Terms</anno>}</c>, where <c><anno>Terms</anno></c> is a list
+ of terms found in the log. <c><anno>Continuation2</anno></c> is yet
another continuation which must be passed on to any
subsequent calls to <c>chunk</c>. With a series of calls to
<c>chunk</c> it is possible to extract all terms from a log.
</p>
<p>The <c>chunk</c> function returns a tuple
- <c>{Continuation2, Terms, Badbytes}</c> if the log is opened
- in read-only mode and the read chunk is corrupt. <c>Badbytes</c>
+ <c>{<anno>Continuation2</anno>, <anno>Terms</anno>, <anno>Badbytes</anno>}</c> if the log is opened
+ in read-only mode and the read chunk is corrupt. <c><anno>Badbytes</anno></c>
is the number of bytes in the file which were found not to be
Erlang terms in the chunk. Note also that the log is not repaired.
When trying to read chunks from a log opened in read-write mode,
- the tuple <c>{corrupt_log_file, FileName}</c> is returned if the
+ the tuple <c>{corrupt_log_file, <anno>FileName</anno>}</c> is returned if the
read chunk is corrupt.
</p>
<p><c>chunk</c> returns <c>eof</c> when the end of the log is
- reached, or <c>{error, Reason}</c> if an error occurs. Should
+ reached, or <c>{error, <anno>Reason</anno>}</c> if an error occurs. Should
a wrap log file be missing, a message is output on the error log.
</p>
<p>When <c>chunk/2,3</c> is used with wrap logs, the returned
@@ -431,12 +431,8 @@
</desc>
</func>
<func>
- <name>chunk_info(Continuation) -> InfoList | {error, Reason}</name>
+ <name name="chunk_info" arity="1"/>
<fsummary>Return information about a chunk continuation of a disk log.</fsummary>
- <type>
- <v>Continuation = cont()</v>
- <v>Reason = {no_continuation, Continuation}</v>
- </type>
<desc>
<p>The <c>chunk_info/1</c> function returns the following pair
describing the chunk continuation returned by
@@ -444,29 +440,22 @@
</p>
<list type="bulleted">
<item>
- <p><c>{node, Node}</c>. Terms are read from
- the disk log running on <c>Node</c>.</p>
+ <p><c>{node, <anno>Node</anno>}</c>. Terms are read from
+ the disk log running on <c><anno>Node</anno></c>.</p>
</item>
</list>
</desc>
</func>
<func>
- <name>chunk_step(Log, Continuation, Step) -> {ok, Continuation2} | {error, Reason}</name>
+ <name name="chunk_step" arity="3"/>
<fsummary>Step forward or backward among the wrap log files of a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Continuation = start | cont()</v>
- <v>Step = integer()</v>
- <v>Continuation2 = cont()</v>
- <v>Reason = no_such_log | end_of_log | {format_external, Log} | {blocked_log, Log} | {badarg, continuation} | {file_error, FileName, FileError}</v>
- </type>
<desc>
<p>The function <c>chunk_step</c> can be used in conjunction
with <c>chunk/2,3</c> and <c>bchunk/2,3</c> to search
through an internally formatted wrap log. It takes as
argument a continuation as returned by <c>chunk/2,3</c>,
<c>bchunk/2,3</c>, or <c>chunk_step/3</c>, and steps forward
- (or backward) <c>Step</c> files in the wrap log. The
+ (or backward) <c><anno>Step</anno></c> files in the wrap log. The
continuation returned points to the first log item in the
new current file.
</p>
@@ -482,11 +471,9 @@
</desc>
</func>
<func>
- <name>close(Log) -> ok | {error, Reason}</name>
+ <name name="close" arity="1"/>
<fsummary>Close a disk log.</fsummary>
- <type>
- <v>Reason = no_such_log | nonode | {file_error, FileName, FileError}</v>
- </type>
+ <type name="close_error_rsn"/>
<desc>
<p> <marker id="close_1"></marker>
The function <c>close/1</c> closes a
@@ -511,11 +498,8 @@ The function <c>close/1</c> closes a
</desc>
</func>
<func>
- <name>format_error(Error) -> Chars</name>
+ <name name="format_error" arity="1"/>
<fsummary>Return an English description of a disk log error reply.</fsummary>
- <type>
- <v>Chars = [char() | Chars]</v>
- </type>
<desc>
<p>Given the error returned by any function in this module,
the function <c>format_error</c> returns a descriptive string
@@ -524,11 +508,10 @@ The function <c>close/1</c> closes a
</desc>
</func>
<func>
- <name>inc_wrap_file(Log) -> ok | {error, Reason}</name>
+ <name name="inc_wrap_file" arity="1"/>
<fsummary>Change to the next wrap log file of a disk log.</fsummary>
- <type>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {blocked_log, Log} | {halt_log, Log} | {invalid_header, InvalidHeader} | {file_error, FileName, FileError}</v>
- </type>
+ <type name="inc_wrap_error_rsn"/>
+ <type name="invalid_header"/>
<desc>
<p>The <c>inc_wrap_file/1</c> function forces the internally formatted
disk log to start logging to the
@@ -543,8 +526,9 @@ The function <c>close/1</c> closes a
</desc>
</func>
<func>
- <name>info(Log) -> InfoList | {error, no_such_log}</name>
+ <name name="info" arity="1"/>
<fsummary>Return information about a disk log.</fsummary>
+ <type name="dlog_info"/>
<desc>
<p>The <c>info/1</c> function returns a list of <c>{Tag, Value}</c>
pairs describing the log. If there is a disk log process running
@@ -556,55 +540,55 @@ The function <c>close/1</c> closes a
</p>
<list type="bulleted">
<item>
- <p><c>{name, Log}</c>, where <c>Log</c> is the name of
+ <p><c>{name, <anno>Log</anno>}</c>, where <c><anno>Log</anno></c> is the name of
the log as given by the <c>open/1</c> option <c>name</c>.</p>
</item>
<item>
- <p><c>{file, File}</c>. For halt logs <c>File</c> is the
- filename, and for wrap logs <c>File</c> is the base name.</p>
+ <p><c>{file, <anno>File</anno>}</c>. For halt logs <c><anno>File</anno></c> is the
+ filename, and for wrap logs <c><anno>File</anno></c> is the base name.</p>
</item>
<item>
- <p><c>{type, Type}</c>, where <c>Type</c> is the type of
+ <p><c>{type, <anno>Type</anno>}</c>, where <c><anno>Type</anno></c> is the type of
the log as given by the <c>open/1</c> option <c>type</c>.</p>
</item>
<item>
- <p><c>{format, Format}</c>, where <c>Format</c> is the format
+ <p><c>{format, <anno>Format</anno>}</c>, where <c><anno>Format</anno></c> is the format
of the log as given by the <c>open/1</c> option <c>format</c>.</p>
</item>
<item>
- <p><c>{size, Size}</c>, where <c>Size</c> is the size
+ <p><c>{size, <anno>Size</anno>}</c>, where <c><anno>Size</anno></c> is the size
of the log as given by the <c>open/1</c> option <c>size</c>,
or the size set by <c>change_size/2</c>. The value set by
<c>change_size/2</c> is reflected immediately.</p>
</item>
<item>
- <p><c>{mode, Mode}</c>, where <c>Mode</c> is the mode
+ <p><c>{mode, <anno>Mode</anno>}</c>, where <c><anno>Mode</anno></c> is the mode
of the log as given by the <c>open/1</c> option <c>mode</c>.</p>
</item>
<item>
- <p><c>{owners, [{pid(), Notify}]}</c> where <c>Notify</c>
+ <p><c>{owners, [{pid(), <anno>Notify</anno>}]}</c> where <c><anno>Notify</anno></c>
is the value set by the <c>open/1</c> option <c>notify</c>
or the function <c>change_notify/3</c> for the owners of
the log.</p>
</item>
<item>
- <p><c>{users, Users}</c> where <c>Users</c> is the number
+ <p><c>{users, <anno>Users</anno>}</c> where <c><anno>Users</anno></c> is the number
of anonymous users of the log, see the <c>open/1</c> option
<seealso marker="#linkto">linkto</seealso>.</p>
</item>
<item>
- <p><c>{status, Status}</c>, where <c>Status</c> is <c>ok</c>
- or <c>{blocked, QueueLogRecords}</c> as set by the functions
+ <p><c>{status, <anno>Status</anno>}</c>, where <c><anno>Status</anno></c> is <c>ok</c>
+ or <c>{blocked, <anno>QueueLogRecords</anno>}</c> as set by the functions
<c>block/1,2</c> and <c>unblock/1</c>.</p>
</item>
<item>
- <p><c>{node, Node}</c>. The information returned by the
+ <p><c>{node, <anno>Node</anno>}</c>. The information returned by the
current invocation of the <c>info/1</c> function has been
- gathered from the disk log process running on <c>Node</c>.</p>
+ gathered from the disk log process running on <c><anno>Node</anno></c>.</p>
</item>
<item>
- <p><c>{distributed, Dist}</c>. If the log is local on
- the current node, then <c>Dist</c> has the value <c>local</c>,
+ <p><c>{distributed, <anno>Dist</anno>}</c>. If the log is local on
+ the current node, then <c><anno>Dist</anno></c> has the value <c>local</c>,
otherwise all nodes where the log is distributed
are returned as a list.</p>
</item>
@@ -614,16 +598,16 @@ The function <c>close/1</c> closes a
</p>
<list type="bulleted">
<item>
- <p><c>{head, Head}</c>. Depending of the value of
+ <p><c>{head, <anno>Head</anno>}</c>. Depending of the value of
the <c>open/1</c> options <c>head</c> and <c>head_func</c>
or set by the function <c>change_header/2</c>, the value
- of <c>Head</c> is <c>none</c> (default),
+ of <c><anno>Head</anno></c> is <c>none</c> (default),
<c>{head, H}</c> (<c>head</c> option) or <c>{M,F,A}</c>
(<c>head_func</c> option).</p>
</item>
<item>
- <p><c>{no_written_items, NoWrittenItems}</c>, where
- <c>NoWrittenItems</c> is the number of items
+ <p><c>{no_written_items, <anno>NoWrittenItems</anno>}</c>, where
+ <c><anno>NoWrittenItems</anno></c> is the number of items
written to the log since the disk log process was created.</p>
</item>
</list>
@@ -632,7 +616,7 @@ The function <c>close/1</c> closes a
</p>
<list type="bulleted">
<item>
- <p><c>{full, Full}</c>, where <c>Full</c> is <c>true</c> or
+ <p><c>{full, <anno>Full</anno>}</c>, where <c><anno>Full</anno></c> is <c>true</c> or
<c>false</c> depending on whether the halt log is full or not.</p>
</item>
</list>
@@ -660,8 +644,8 @@ The function <c>close/1</c> closes a
<c>size</c> or set by <c>change_size/2</c>.</p>
</item>
<item>
- <p><c>{no_overflows, {SinceLogWasOpened, SinceLastInfo}}</c>,
- where <c>SinceLogWasOpened</c> (<c>SinceLastInfo</c>) is
+ <p><c>{no_overflows, {<anno>SinceLogWasOpened</anno>, <anno>SinceLastInfo</anno>}}</c>,
+ where <c><anno>SinceLogWasOpened</anno></c> (<c><anno>SinceLastInfo</anno></c>) is
the number of times a wrap log file has been filled up and a
new one opened or <c>inc_wrap_file/1</c> has been called since
the disk log was last opened (<c>info/1</c>
@@ -677,21 +661,18 @@ The function <c>close/1</c> closes a
</desc>
</func>
<func>
- <name>lclose(Log)</name>
- <name>lclose(Log, Node) -> ok | {error, Reason}</name>
+ <name name="lclose" arity="1"/>
+ <name name="lclose" arity="2"/>
+ <type name="lclose_error_rsn"/>
<fsummary>Close a disk log on one node.</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Reason = no_such_log | {file_error, FileName, FileError}</v>
- </type>
<desc>
<p>The function <c>lclose/1</c> closes a local log or an
individual distributed log on the current node.
The function <c>lclose/2</c> closes an individual
distributed log on the specified node if the node
is not the current one.
- <c>lclose(Log)</c> is equivalent to
- <c>lclose(Log,&nbsp;node())</c>.
+ <c>lclose(<anno>Log</anno>)</c> is equivalent to
+ <c>lclose(<anno>Log</anno>,&nbsp;node())</c>.
See also <seealso marker="#close_1">close/1</seealso>.
</p>
<p>If there is no log with the given name
@@ -700,20 +681,17 @@ The function <c>close/1</c> closes a
</desc>
</func>
<func>
- <name>log(Log, Term)</name>
- <name>blog(Log, Bytes) -> ok | {error, Reason}</name>
+ <name name="log" arity="2"/>
+ <name name="blog" arity="2"/>
<fsummary>Log an item onto a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Term = term()</v>
- <v>Bytes = binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {format_external, Log} | {blocked_log, Log} | {full, Log} | {invalid_header, InvalidHeader} | {file_error, FileName, FileError}</v>
- </type>
+ <type variable="Log"/>
+ <type variable="Term" name_i="1"/>
+ <type variable="Bytes"/>
+ <type name="log_error_rsn"/>
<desc>
<p>The <c>log/2</c> and <c>blog/2</c> functions synchronously
append a term to a disk log. They return <c>ok</c> or
- <c>{error, Reason}</c> when the term has been written to
+ <c>{error, <anno>Reason</anno>}</c> when the term has been written to
disk. If the log is distributed, <c>ok</c> is always
returned, unless all nodes are down. Terms are written by
means of the ordinary <c>write()</c> function of the
@@ -736,17 +714,13 @@ The function <c>close/1</c> closes a
</desc>
</func>
<func>
- <name>log_terms(Log, TermList)</name>
- <name>blog_terms(Log, BytesList) -> ok | {error, Reason}</name>
+ <name name="log_terms" arity="2"/>
+ <name name="blog_terms" arity="2"/>
<fsummary>Log several items onto a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>TermList = [term()]</v>
- <v>BytesList = [Bytes]</v>
- <v>Bytes = binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {format_external, Log} | {blocked_log, Log} | {full, Log} | {invalid_header, InvalidHeader} | {file_error, FileName, FileError}</v>
- </type>
+ <type variable="Log"/>
+ <type variable="TermList" name_i="1"/>
+ <type variable="BytesList"/>
+ <type name="log_error_rsn"/>
<desc>
<p>The <c>log_terms/2</c> and <c>blog_terms/2</c> functions
synchronously append a list of items to the log. The benefit
@@ -769,47 +743,33 @@ The function <c>close/1</c> closes a
</desc>
</func>
<func>
- <name>open(ArgL) -> OpenRet | DistOpenRet</name>
+ <name name="open" arity="1"/>
+ <type name="dlog_options"/>
+ <type name="dlog_option"/>
+ <type name="open_ret"/>
+ <type name="ret"/>
+ <type name="dist_open_ret"/>
+ <type name="dist_error_rsn"/>
+ <type name="open_error_rsn"/>
+ <type name="dlog_optattr"/>
+ <type name="dlog_size"/>
<fsummary>Open a disk log file.</fsummary>
- <type>
- <v>ArgL = [Opt]</v>
- <v>Opt = {name, term()} | {file, FileName}, {linkto, LinkTo} | {repair, Repair} | {type, Type} | {format, Format} | {size, Size} | {distributed, [Node]} | {notify, bool()} | {head, Head} | {head_func, {M,F,A}} | {mode, Mode}</v>
- <v>FileName = string() | atom()</v>
- <v>LinkTo = pid() | none</v>
- <v>Repair = true | false | truncate</v>
- <v>Type = halt | wrap</v>
- <v>Format = internal | external</v>
- <v>Size = integer() > 0 | infinity | {MaxNoBytes, MaxNoFiles}</v>
- <v>MaxNoBytes = integer() > 0</v>
- <v>MaxNoFiles = 0 &lt; integer() &lt; 65000</v>
- <v>Rec = integer()</v>
- <v>Bad = integer()</v>
- <v>Head = none | term() | binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Mode = read_write | read_only</v>
- <v>OpenRet = Ret | {error, Reason}</v>
- <v>DistOpenRet = {[{Node, Ret}], [{BadNode, {error, DistReason}}]}</v>
- <v>Node = BadNode = atom()</v>
- <v>Ret = {ok, Log} | {repaired, Log, {recovered, Rec}, {badbytes, Bad}}</v>
- <v>DistReason = nodedown | Reason</v>
- <v>Reason = no_such_log | {badarg, Arg} | {size_mismatch, CurrentSize, NewSize} | {arg_mismatch, OptionName, CurrentValue, Value} | {name_already_open, Log} | {open_read_write, Log} | {open_read_only, Log} | {need_repair, Log} | {not_a_log_file, FileName} | {invalid_index_file, FileName} | {invalid_header, InvalidHeader} | {file_error, FileName, FileError} | {node_already_open, Log}</v>
- </type>
<desc>
- <p>The <c>ArgL</c> parameter is a list of options which have
+ <p>The <c><anno>ArgL</anno></c> parameter is a list of options which have
the following meanings:</p>
<list type="bulleted">
<item>
- <p><c>{name, Log}</c> specifies the name of the log.
+ <p><c>{name, <anno>Log</anno>}</c> specifies the name of the log.
This is the name which must be passed on as a parameter in
all subsequent logging operations. A name must always
be supplied.
</p>
</item>
<item>
- <p><c>{file, FileName}</c> specifies the name of the
+ <p><c>{file, <anno>FileName</anno>}</c> specifies the name of the
file which will be used for logged terms. If this value is
omitted and the name of the log is either an atom or a string,
- the file name will default to <c>lists:concat([Log, ".LOG"])</c> for halt logs. For wrap logs, this will be
+ the file name will default to <c>lists:concat([<anno>Log</anno>, ".LOG"])</c> for halt logs. For wrap logs, this will be
the base name of the files. Each file in a wrap log
will be called <c><![CDATA[<base_name>.N]]></c>, where <c>N</c> is an
integer. Each wrap log will also have two files called
@@ -817,22 +777,22 @@ The function <c>close/1</c> closes a
</p>
</item>
<item>
- <p><c>{linkto, LinkTo}</c>. <marker id="linkto"></marker>
+ <p><c>{linkto, <anno>LinkTo</anno>}</c>. <marker id="linkto"></marker>
If
- <c>LinkTo</c> is a pid, that pid becomes an owner of the
- log. If <c>LinkTo</c> is <c>none</c> the log records
+ <c><anno>LinkTo</anno></c> is a pid, that pid becomes an owner of the
+ log. If <c><anno>LinkTo</anno></c> is <c>none</c> the log records
that it is used anonymously by some process by
incrementing the <c>users</c> counter. By default, the
process which calls <c>open/1</c> owns the log.
</p>
</item>
<item>
- <p><c>{repair, Repair}</c>. If <c>Repair</c> is <c>true</c>,
+ <p><c>{repair, <anno>Repair</anno>}</c>. If <c><anno>Repair</anno></c> is <c>true</c>,
the current log file will be repaired, if needed. As the
restoration is initiated, a message is output on the error log.
If <c>false</c> is given,
no automatic repair will be attempted. Instead, the
- tuple <c>{error, {need_repair, Log}}</c> is returned if an
+ tuple <c>{error, {need_repair, <anno>Log</anno>}}</c> is returned if an
attempt is made to open a corrupt log file.
If <c>truncate</c> is given, the log file will
be truncated, creating an empty log. Default is
@@ -841,41 +801,41 @@ If
</p>
</item>
<item>
- <p><c>{type, Type}</c> is the type of the log. Default
+ <p><c>{type, <anno>Type</anno>}</c> is the type of the log. Default
is <c>halt</c>.
</p>
</item>
<item>
- <p><c>{format, Format}</c> specifies the format of the
+ <p><c>{format, <anno>Format</anno>}</c> specifies the format of the
disk log. Default is <c>internal</c>.
</p>
</item>
<item>
- <p><c>{size, Size}</c> specifies the size of the log.
+ <p><c>{size, <anno>Size</anno>}</c> specifies the size of the log.
When a halt log has reached its maximum size, all attempts to
log more items are rejected. The default size is
<c>infinity</c>, which for halt implies that there is no
- maximum size. For wrap logs, the <c>Size</c> parameter
+ maximum size. For wrap logs, the <c><anno>Size</anno></c> parameter
may be either a pair
- <c>{MaxNoBytes, MaxNoFiles}</c> or <c>infinity</c>. In the
+ <c>{<anno>MaxNoBytes</anno>, <anno>MaxNoFiles</anno>}</c> or <c>infinity</c>. In the
latter case, if the files of an already existing wrap log
with the same name can be found, the size is read
from the existing wrap log, otherwise an error is returned.
- Wrap logs write at most <c>MaxNoBytes</c> bytes on each file
- and use <c>MaxNoFiles</c> files before starting all over with
- the first wrap log file. Regardless of <c>MaxNoBytes</c>,
+ Wrap logs write at most <c><anno>MaxNoBytes</anno></c> bytes on each file
+ and use <c><anno>MaxNoFiles</anno></c> files before starting all over with
+ the first wrap log file. Regardless of <c><anno>MaxNoBytes</anno></c>,
at least the header (if there is one) and one
item is written on each wrap log file before
wrapping to the next file.
When opening an existing wrap log, it is not
necessary to supply a value for the option <c>Size</c>, but any
supplied value must equal the current size of the log, otherwise
- the tuple <c>{error, {size_mismatch, CurrentSize, NewSize}}</c>
+ the tuple <c>{error, {size_mismatch, <anno>CurrentSize</anno>, <anno>NewSize</anno>}}</c>
is returned.
</p>
</item>
<item>
- <p><c>{distributed, Nodes}</c>. This option can be used for
+ <p><c>{distributed, <anno>Nodes</anno>}</c>. This option can be used for
adding members to a distributed disk log. The
default value is <c>[]</c>, which means that
the log is local on the current node.
@@ -946,10 +906,10 @@ If
</list>
</item>
<item>
- <p><c>{head, Head}</c> specifies a header to be
+ <p><c>{head, <anno>Head</anno>}</c> specifies a header to be
written first on the log file. If the log is a wrap
- log, the item <c>Head</c> is written first in each new file.
- <c>Head</c> should be a term if the format is
+ log, the item <c><anno>Head</anno></c> is written first in each new file.
+ <c><anno>Head</anno></c> should be a term if the format is
<c>internal</c>, and a deep list of bytes (or a binary)
otherwise. Default is <c>none</c>, which means that
no header is written first on the file.
@@ -966,17 +926,17 @@ If
</p>
</item>
<item>
- <p><c>{mode, Mode}</c> specifies if the log is to be
+ <p><c>{mode, <anno>Mode</anno>}</c> specifies if the log is to be
opened in read-only or read-write mode. It defaults to
<c>read_write</c>.
</p>
</item>
</list>
- <p>The <c>open/1</c> function returns <c>{ok, Log}</c> if the
+ <p>The <c>open/1</c> function returns <c>{ok, <anno>Log</anno>}</c> if the
log file was successfully opened. If the file was
- successfully repaired, the tuple <c>{repaired, Log, {recovered, Rec}, {badbytes, Bad}}</c> is returned, where
- <c>Rec</c> is the number of whole Erlang terms found in the
- file and <c>Bad</c> is the number of bytes in the file which
+ successfully repaired, the tuple <c>{repaired, <anno>Log</anno>, {recovered, <anno>Rec</anno>}, {badbytes, <anno>Bad</anno>}}</c> is returned, where
+ <c><anno>Rec</anno></c> is the number of whole Erlang terms found in the
+ file and <c><anno>Bad</anno></c> is the number of bytes in the file which
were non-Erlang terms. If the <c>distributed</c> parameter
was given, <c>open/1</c> returns a list of
successful replies and a list of erroneous replies. Each
@@ -988,7 +948,7 @@ If
position after the last logged item, and the logging of items
will commence from there. If the format is <c>internal</c>
and the existing file is not recognized as an internally
- formatted log, a tuple <c>{error, {not_a_log_file, FileName}}</c>
+ formatted log, a tuple <c>{error, {not_a_log_file, <anno>FileName</anno>}}</c>
is returned.
</p>
<p>The <c>open/1</c> function cannot be used for changing the
@@ -1000,15 +960,15 @@ If
or <c>change_size/2</c>. As a consequence,
none of the options except <c>name</c> is mandatory. If some
given value differs from the current value, a tuple
- <c>{error, {arg_mismatch, OptionName, CurrentValue, Value}}</c>
+ <c>{error, {arg_mismatch, <anno>OptionName</anno>, <anno>CurrentValue</anno>, <anno>Value</anno>}}</c>
is returned. Caution: an owner's attempt to open a log
as owner once again is acknowledged with the return value
- <c>{ok, Log}</c>, but the state of the disk log is not
+ <c>{ok, <anno>Log</anno>}</c>, but the state of the disk log is not
affected in any way.
</p>
<p>If a log with a given name is local on some node,
and one tries to open the log distributed on the same node,
- then the tuple <c>{error, {node_already_open, Name}}</c> is
+ then the tuple <c>{error, {node_already_open, <anno>Log</anno>}}</c> is
returned. The same tuple is returned if the log is distributed on
some node, and one tries to open the log locally on the same node.
Opening individual distributed disk logs for the first time
@@ -1036,12 +996,8 @@ If
</desc>
</func>
<func>
- <name>pid2name(Pid) -> {ok, Log} | undefined</name>
+ <name name="pid2name" arity="1"/>
<fsummary>Return the name of the disk log handled by a pid.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Pid = pid()</v>
- </type>
<desc>
<p>The <c>pid2name/1</c> function returns the name of the log
given the pid of a disk log process on the current node, or
@@ -1052,26 +1008,23 @@ If
</desc>
</func>
<func>
- <name>reopen(Log, File)</name>
- <name>reopen(Log, File, Head)</name>
- <name>breopen(Log, File, BHead) -> ok | {error, Reason}</name>
+ <name name="reopen" arity="2"/>
+ <name name="reopen" arity="3"/>
+ <name name="breopen" arity="3"/>
<fsummary>Reopen a disk log and save the old log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>File = string()</v>
- <v>Head = term()</v>
- <v>BHead = binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {blocked_log, Log} | {same_file_name, Log} | {invalid_index_file, FileName} | {invalid_header, InvalidHeader} | {file_error, FileName, FileError}</v>
- </type>
+ <type variable="Log"/>
+ <type variable="File" name_i="1"/>
+ <type variable="Head" name_i="2"/>
+ <type variable="BHead"/>
+ <type name="reopen_error_rsn"/>
<desc>
<p>The <c>reopen</c> functions first rename the log file
- to <c>File</c> and then re-create a new log file.
- In case of a wrap log, <c>File</c> is used as the base name
+ to <c><anno>File</anno></c> and then re-create a new log file.
+ In case of a wrap log, <c><anno>File</anno></c> is used as the base name
of the renamed files.
By default the header given to <c>open/1</c> is written first in
- the newly opened log file, but if the <c>Head</c> or the
- <c>BHead</c> argument is given, this item is used instead.
+ the newly opened log file, but if the <c><anno>Head</anno></c> or the
+ <c><anno>BHead</anno></c> argument is given, this item is used instead.
The header argument is used once only; next time a wrap log file
is opened, the header given to <c>open/1</c> is used.
</p>
@@ -1089,12 +1042,9 @@ If
</desc>
</func>
<func>
- <name>sync(Log) -> ok | {error, Reason}</name>
+ <name name="sync" arity="1"/>
+ <type name="sync_error_rsn"/>
<fsummary>Flush the contents of a disk log to the disk.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {blocked_log, Log} | {file_error, FileName, FileError}</v>
- </type>
<desc>
<p>The <c>sync/1</c> function ensures that the contents of the
log are actually written to the disk.
@@ -1103,20 +1053,17 @@ If
</desc>
</func>
<func>
- <name>truncate(Log)</name>
- <name>truncate(Log, Head)</name>
- <name>btruncate(Log, BHead) -> ok | {error, Reason}</name>
+ <name name="truncate" arity="1"/>
+ <name name="truncate" arity="2"/>
+ <name name="btruncate" arity="2"/>
<fsummary>Truncate a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Head = term()</v>
- <v>BHead = binary() | [Byte]</v>
- <v>Byte = [Byte] | 0 =&lt; integer() =&lt; 255</v>
- <v>Reason = no_such_log | nonode | {read_only_mode, Log} | {blocked_log, Log} | {invalid_header, InvalidHeader} | {file_error, FileName, FileError}</v>
- </type>
+ <type variable="Log"/>
+ <type variable="Head" name_i="2"/>
+ <type variable="BHead"/>
+ <type name="trunc_error_rsn"/>
<desc>
<p>The <c>truncate</c> functions remove all items from a disk log.
- If the <c>Head</c> or the <c>BHead</c> argument is
+ If the <c><anno>Head</anno></c> or the <c><anno>BHead</anno></c> argument is
given, this item is written first in the newly truncated
log, otherwise the header given to <c>open/1</c> is used.
The header argument is only used once; next time a wrap log file
@@ -1138,12 +1085,9 @@ If
</desc>
</func>
<func>
- <name>unblock(Log) -> ok | {error, Reason}</name>
+ <name name="unblock" arity="1"/>
+ <type name="unblock_error_rsn"/>
<fsummary>Unblock a disk log.</fsummary>
- <type>
- <v>Log = term()</v>
- <v>Reason = no_such_log | nonode | {not_blocked, Log} | {not_blocked_by_pid, Log}</v>
- </type>
<desc>
<p>The <c>unblock/1</c> function unblocks a log.
A log can only be unblocked by the blocking process.
@@ -1159,4 +1103,3 @@ If
<seealso marker="wrap_log_reader">wrap_log_reader(3)</seealso></p>
</section>
</erlref>
-
diff --git a/lib/kernel/doc/src/erl_boot_server.xml b/lib/kernel/doc/src/erl_boot_server.xml
index 4e7533810e..472671a80e 100644
--- a/lib/kernel/doc/src/erl_boot_server.xml
+++ b/lib/kernel/doc/src/erl_boot_server.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -49,29 +49,17 @@
</description>
<funcs>
<func>
- <name>start(Slaves) -> {ok, Pid} | {error, What}</name>
+ <name name="start" arity="1"/>
<fsummary>Start the boot server</fsummary>
- <type>
- <v>Slaves = [Host]</v>
- <v>Host = atom()</v>
- <v>Pid = pid()</v>
- <v>What = term()</v>
- </type>
<desc>
- <p>Starts the boot server. <c>Slaves</c> is a list of IP
+ <p>Starts the boot server. <c><anno>Slaves</anno></c> is a list of IP
addresses for hosts which are allowed to use this server as a
boot server.</p>
</desc>
</func>
<func>
- <name>start_link(Slaves) -> {ok, Pid} | {error, What}</name>
+ <name name="start_link" arity="1"/>
<fsummary>Start the boot server and links the caller</fsummary>
- <type>
- <v>Slaves = [Host]</v>
- <v>Host = atom()</v>
- <v>Pid = pid()</v>
- <v>What = term()()</v>
- </type>
<desc>
<p>Starts the boot server and links to the caller. This function
is used to start the server if it is included in a supervision
@@ -79,37 +67,23 @@
</desc>
</func>
<func>
- <name>add_slave(Slave) -> ok | {error, What}</name>
+ <name name="add_slave" arity="1"/>
<fsummary>Add a slave to the list of allowed slaves</fsummary>
- <type>
- <v>Slave = Host</v>
- <v>Host = atom()</v>
- <v>What = term()</v>
- </type>
<desc>
- <p>Adds a <c>Slave</c> node to the list of allowed slave hosts.</p>
+ <p>Adds a <c><anno>Slave</anno></c> node to the list of allowed slave hosts.</p>
</desc>
</func>
<func>
- <name>delete_slave(Slave) -> ok | {error, What}</name>
+ <name name="delete_slave" arity="1"/>
<fsummary>Delete a slave from the list of allowed slaves</fsummary>
- <type>
- <v>Slave = Host</v>
- <v>Host = atom()</v>
- <v>What = void()</v>
- </type>
<desc>
- <p>Deletes a <c>Slave</c> node from the list of allowed slave
+ <p>Deletes a <c><anno>Slave</anno></c> node from the list of allowed slave
hosts.</p>
</desc>
</func>
<func>
- <name>which_slaves() -> Slaves</name>
+ <name name="which_slaves" arity="0"/>
<fsummary>Return the current list of allowed slave hosts</fsummary>
- <type>
- <v>Slaves = [Host]</v>
- <v>Host = atom()</v>
- </type>
<desc>
<p>Returns the current list of allowed slave hosts.</p>
</desc>
diff --git a/lib/kernel/doc/src/erl_ddll.xml b/lib/kernel/doc/src/erl_ddll.xml
index 9a62b45d63..f9514dda2f 100644
--- a/lib/kernel/doc/src/erl_ddll.xml
+++ b/lib/kernel/doc/src/erl_ddll.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2010</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -172,6 +172,14 @@
</item>
</taglist>
</description>
+ <datatypes>
+ <datatype>
+ <name name="driver"/>
+ </datatype>
+ <datatype>
+ <name name="path"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
<name>demonitor(MonitorRef) -> ok</name>
@@ -189,37 +197,21 @@
</desc>
</func>
<func>
- <name>info() -> AllInfoList</name>
+ <name name="info" arity="0"/>
<fsummary>Retrieve information about all drivers</fsummary>
- <type>
- <v>AllInfoList = [ DriverInfo ]</v>
- <v>DriverInfo = {DriverName, InfoList}</v>
- <v>DriverName = string()</v>
- <v>InfoList = [ InfoItem ]</v>
- <v>InfoItem = {Tag, Value}</v>
- <v>Tag = atom()</v>
- <v>Value = term()</v>
- </type>
<desc>
- <p>Returns a list of tuples <c>{DriverName, InfoList}</c>, where
- <c>InfoList</c> is the result of calling <seealso marker="#info/1">info/1</seealso> for that
- <c>DriverName</c>. Only dynamically linked in drivers are
+ <p>Returns a list of tuples <c>{<anno>DriverName</anno>, <anno>InfoList</anno>}</c>, where
+ <c><anno>InfoList</anno></c> is the result of calling <seealso marker="#info/1">info/1</seealso> for that
+ <c><anno>DriverName</anno></c>. Only dynamically linked in drivers are
included in the list.</p>
</desc>
</func>
<func>
- <name>info(Name) -> InfoList</name>
+ <name name="info" arity="1"/>
<fsummary>Retrieve information about one driver</fsummary>
- <type>
- <v>Name = string() | atom()</v>
- <v>InfoList = [ InfoItem ]</v>
- <v>InfoItem = {Tag, Value}</v>
- <v>Tag = atom()</v>
- <v>Value = term()</v>
- </type>
<desc>
- <p>Returns a list of tuples <c>{Tag, Value}</c>, where
- <c>Tag</c> is the information item and <c>Value</c> is the result
+ <p>Returns a list of tuples <c>{<anno>Tag</anno>, <anno>Value</anno>}</c>, where
+ <c><anno>Tag</anno></c> is the information item and <c><anno>Value</anno></c> is the result
of calling <seealso marker="#info/2">info/2</seealso> with this driver name and
this tag. The result being a tuple list containing all
information available about a driver. </p>
@@ -305,22 +297,18 @@
</desc>
</func>
<func>
- <name>load(Path, Name) -> ok | {error, ErrorDesc}</name>
+ <name name="load" arity="2"/>
<fsummary>Load a driver</fsummary>
- <type>
- <v>Path = Name = string() | atom()</v>
- <v>ErrorDesc = term()</v>
- </type>
<desc>
- <p>Loads and links the dynamic driver <c>Name</c>. <c>Path</c>
+ <p>Loads and links the dynamic driver <c><anno>Name</anno></c>. <c><anno>Path</anno></c>
is a file path to the directory containing the driver.
- <c>Name</c> must be a sharable object/dynamic library. Two
- drivers with different <c>Path</c> parameters cannot be
- loaded under the same name. The <c>Name</c> is a string or
+ <c><anno>Name</anno></c> must be a sharable object/dynamic library. Two
+ drivers with different <c><anno>Path</anno></c> parameters cannot be
+ loaded under the same name. The <c><anno>Name</anno></c> is a string or
atom containing at least one character.</p>
- <p>The <c>Name</c> given should correspond to the filename
+ <p>The <c><anno>Name</anno></c> given should correspond to the filename
of the actual dynamically loadable object file residing in
- the directory given as <c>Path</c>, but <em>without</em> the
+ the directory given as <c><anno>Path</anno></c>, but <em>without</em> the
extension (i.e. <c>.so</c>). The driver name provided in
the driver initialization routine must correspond with the
filename, in much the same way as erlang module names
@@ -328,14 +316,14 @@
<p>If the driver has been previously unloaded, but is still
present due to open ports against it, a call to
<c>load/2</c> will stop the unloading and keep the driver
- (as long as the <c>Path</c> is the same) and <c>ok</c> is
+ (as long as the <c><anno>Path</anno></c> is the same) and <c>ok</c> is
returned. If one actually wants the object code to be
reloaded, one uses <seealso marker="#reload/2">reload/2</seealso> or the low-level
interface <seealso marker="#try_load/3">try_load/3</seealso>
instead. Please refer to the description of <seealso marker="#scenarios">different scenarios</seealso> for
loading/unloading in the introduction.</p>
<p>If more than one process tries to load an already loaded
- driver withe the same <c>Path</c>, or if the same process
+ driver withe the same <c><anno>Path</anno></c>, or if the same process
tries to load it several times, the function will return
<c>ok</c>. The emulator will keep track of the
<c>load/2</c> calls, so that a corresponding number of
@@ -349,16 +337,16 @@
several drivers with the same name but with different
<c>Path</c> parameters.</p>
<note>
- <p>Note especially that the <c>Path</c> is interpreted
+ <p>Note especially that the <c><anno>Path</anno></c> is interpreted
literally, so that all loaders of the same driver needs to
- give the same <em>literal</em><c>Path</c> string, even
+ give the same <em>literal</em><c><anno>Path</anno></c> string, even
though different paths might point out the same directory
in the filesystem (due to use of relative paths and
links).</p>
</note>
<p>On success, the function returns <c>ok</c>. On
- failure, the return value is <c>{error,ErrorDesc}</c>,
- where <c>ErrorDesc</c> is an opaque term to be
+ failure, the return value is <c>{error,<anno>ErrorDesc</anno>}</c>,
+ where <c><anno>ErrorDesc</anno></c> is an opaque term to be
translated into human readable form by the <seealso marker="#format_error/1">format_error/1</seealso>
function.</p>
<p>For more control over the error handling, again use the
@@ -369,20 +357,16 @@
</desc>
</func>
<func>
- <name>load_driver(Path, Name) -> ok | {error, ErrorDesc}</name>
+ <name name="load_driver" arity="2"/>
<fsummary>Load a driver</fsummary>
- <type>
- <v>Path = Name = string() | atom()</v>
- <v>ErrorDesc = term()</v>
- </type>
<desc>
<p>Works essentially as <c>load/2</c>, but will load the driver
- with options other options. All ports that are using the
+ with other options. All ports that are using the
driver will get killed with the reason
<c>driver_unloaded</c> when the driver is to be unloaded.</p>
<p>The number of loads and unloads by different <seealso marker="#users">users</seealso> influence the actual loading
and unloading of a driver file. The port killing will
- therefore only happen when the <em>last</em><seealso marker="#users">user</seealso> unloads the driver, or the
+ therefore only happen when the <em>last</em> <seealso marker="#users">user</seealso> unloads the driver, or the
last process having loaded the driver exits.</p>
<p>This interface (or at least the name of the functions) is
kept for backward compatibility. Using <seealso marker="#try_load/3">try_load/3</seealso> with
@@ -551,16 +535,11 @@
</desc>
</func>
<func>
- <name>reload(Path, Name) -> ok | {error, ErrorDesc}</name>
+ <name name="reload" arity="2"/>
<fsummary>Replace a driver</fsummary>
- <type>
- <v>Path = Name = string() | atom()</v>
- <v>ErrorDesc = pending_process | OpaqueError</v>
- <v>OpaqueError = term()</v>
- </type>
<desc>
- <p>Reloads the driver named <c>Name</c> from a possibly
- different <c>Path</c> than was previously used. This
+ <p>Reloads the driver named <c><anno>Name</anno></c> from a possibly
+ different <c><anno>Path</anno></c> than was previously used. This
function is used in the code change <seealso marker="#scenarios">scenario</seealso> described in the
introduction.</p>
<p>If there are other <seealso marker="#users">users</seealso>
@@ -574,7 +553,7 @@
<p>If one wants to avoid hanging on open ports, one should use
the <seealso marker="#try_load/3">try_load/3</seealso>
function instead.</p>
- <p>The <c>Name</c> and <c>Path</c> parameters have exactly the
+ <p>The <c><anno>Name</anno></c> and <c><anno>Path</anno></c> parameters have exactly the
same meaning as when calling the plain <seealso marker="#load/2">load/2</seealso> function.</p>
<note>
<p>Avoid mixing
@@ -594,13 +573,8 @@
</desc>
</func>
<func>
- <name>reload_driver(Path, Name) -> ok | {error, ErrorDesc}</name>
+ <name name="reload_driver" arity="2"/>
<fsummary>Replace a driver</fsummary>
- <type>
- <v>Path = Name = string() | atom()</v>
- <v>ErrorDesc = pending_process | OpaqueError</v>
- <v>OpaqueError = term()</v>
- </type>
<desc>
<p>Works exactly as <seealso marker="#reload/2">reload/2</seealso>, but for drivers
loaded with the <seealso marker="#load_driver/2">load_driver/2</seealso> interface. </p>
@@ -1066,15 +1040,11 @@
</desc>
</func>
<func>
- <name>unload(Name) -> ok | {error, ErrorDesc}</name>
+ <name name="unload" arity="1"/>
<fsummary>Unload a driver</fsummary>
- <type>
- <v>Name = string() | atom()</v>
- <v>ErrorDesc = term()</v>
- </type>
<desc>
<p>Unloads, or at least dereferences the driver named
- <c>Name</c>. If the caller is the last <seealso marker="#users">user</seealso> of the driver, and there
+ <c><anno>Name</anno></c>. If the caller is the last <seealso marker="#users">user</seealso> of the driver, and there
are no more open ports using the driver, the driver will
actually get unloaded. In all other cases, actual unloading
will be delayed until all ports are closed and there are no
@@ -1084,7 +1054,7 @@
is no longer considered a user of the driver. For usage
scenarios, see the <seealso marker="#scenarios">description</seealso> in the beginning
of this document. </p>
- <p>The <c>ErrorDesc</c> returned is an opaque value to be
+ <p>The <c><anno>ErrorDesc</anno></c> returned is an opaque value to be
passed further on to the <seealso marker="#format_error/1">format_error/1</seealso>
function. For more control over the operation, use the
<seealso marker="#try_unload/2">try_unload/2</seealso>
@@ -1094,15 +1064,11 @@
</desc>
</func>
<func>
- <name>unload_driver(Name) -> ok | {error, ErrorDesc}</name>
+ <name name="unload_driver" arity="1"/>
<fsummary>Unload a driver</fsummary>
- <type>
- <v>Name = string() | atom()</v>
- <v>ErrorDesc = term()</v>
- </type>
<desc>
<p>Unloads, or at least dereferences the driver named
- <c>Name</c>. If the caller is the last <seealso marker="#users">user</seealso> of the driver, all
+ <c><anno>Name</anno></c>. If the caller is the last <seealso marker="#users">user</seealso> of the driver, all
remaining open ports using the driver will get killed with
the reason <c>driver_unloaded</c> and the driver will
eventually get unloaded.</p>
@@ -1112,7 +1078,7 @@
<seealso marker="#users">user</seealso>. For
usage scenarios, see the <seealso marker="#scenarios">description</seealso> in the beginning
of this document.</p>
- <p>The <c>ErrorDesc</c> returned is an opaque value to be
+ <p>The <c><anno>ErrorDesc</anno></c> returned is an opaque value to be
passed further on to the <seealso marker="#format_error/1">format_error/1</seealso>
function. For more control over the operation, use the
<seealso marker="#try_unload/2">try_unload/2</seealso>
@@ -1125,7 +1091,7 @@
<name>loaded_drivers() -> {ok, Drivers}</name>
<fsummary>List loaded drivers</fsummary>
<type>
- <v>Drivers = [Driver()]</v>
+ <v>Drivers = [Driver]</v>
<v>Driver = string()</v>
</type>
<desc>
@@ -1138,13 +1104,10 @@
</desc>
</func>
<func>
- <name>format_error(ErrorDesc) -> string()</name>
+ <name name="format_error" arity="1"/>
<fsummary>Format an error descriptor</fsummary>
- <type>
- <v>ErrorDesc -- see below</v>
- </type>
<desc>
- <p>Takes an <c>ErrorDesc</c> returned by load, unload or
+ <p>Takes an <c><anno>ErrorDesc</anno></c> returned by load, unload or
reload functions and returns a string which
describes the error or warning.</p>
<note>
diff --git a/lib/kernel/doc/src/error_handler.xml b/lib/kernel/doc/src/error_handler.xml
index 7f78322472..acbf9a2c6e 100644
--- a/lib/kernel/doc/src/error_handler.xml
+++ b/lib/kernel/doc/src/error_handler.xml
@@ -37,48 +37,44 @@
</description>
<funcs>
<func>
- <name>undefined_function(Module, Function, Args) -> term()</name>
+ <name name="undefined_function" arity="3"/>
<fsummary>Called when an undefined function is encountered</fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <d>A (possibly empty) list of arguments <c>Arg1,..,ArgN</c></d>
- </type>
+ <type_desc variable="Args">
+ A (possibly empty) list of arguments <c>Arg1,..,ArgN</c>
+ </type_desc>
<desc>
<p>This function is evaluated if a call is made to
- <c>Module:Function(Arg1,.., ArgN)</c> and
- <c>Module:Function/N</c> is undefined. Note that
+ <c><anno>Module</anno>:<anno>Function</anno>(Arg1,.., ArgN)</c> and
+ <c><anno>Module</anno>:<anno>Function</anno>/N</c> is undefined. Note that
<c>undefined_function/3</c> is evaluated inside the process
making the original call.</p>
- <p>If <c>Module</c> is interpreted, the interpreter is invoked
+ <p>If <c><anno>Module</anno></c> is interpreted, the interpreter is invoked
and the return value of the interpreted
- <c>Function(Arg1,.., ArgN)</c> call is returned.</p>
+ <c><anno>Function</anno>(Arg1,.., ArgN)</c> call is returned.</p>
<p>Otherwise, it returns, if possible, the value of
- <c>apply(Module, Function, Args)</c> after an attempt has been
- made to autoload <c>Module</c>. If this is not possible, the
- call to <c>Module:Function(Arg1,.., ArgN)</c> fails with
+ <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c> after an attempt has been
+ made to autoload <c><anno>Module</anno></c>. If this is not possible, the
+ call to <c><anno>Module</anno>:<anno>Function</anno>(Arg1,.., ArgN)</c> fails with
exit reason <c>undef</c>.</p>
</desc>
</func>
<func>
- <name>undefined_lambda(Module, Fun, Args) -> term()</name>
+ <name name="undefined_lambda" arity="3"/>
<fsummary>Called when an undefined lambda (fun) is encountered</fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <d>A (possibly empty) list of arguments <c>Arg1,..,ArgN</c></d>
- </type>
+ <type_desc variable="Args">
+ A (possibly empty) list of arguments <c>Arg1,..,ArgN</c>
+ </type_desc>
<desc>
<p>This function is evaluated if a call is made to
- <c>Fun(Arg1,.., ArgN)</c> when the module defining the fun is
+ <c><anno>Fun</anno>(Arg1,.., ArgN)</c> when the module defining the fun is
not loaded. The function is evaluated inside the process
making the original call.</p>
- <p>If <c>Module</c> is interpreted, the interpreter is invoked
+ <p>If <c><anno>Module</anno></c> is interpreted, the interpreter is invoked
and the return value of the interpreted
- <c>Fun(Arg1,.., ArgN)</c> call is returned.</p>
+ <c><anno>Fun</anno>(Arg1,.., ArgN)</c> call is returned.</p>
<p>Otherwise, it returns, if possible, the value of
- <c>apply(Fun, Args)</c> after an attempt has been made to
- autoload <c>Module</c>. If this is not possible, the call
+ <c>apply(<anno>Fun</anno>, <anno>Args</anno>)</c> after an attempt has been made to
+ autoload <c><anno>Module</anno></c>. If this is not possible, the call
fails with exit reason <c>undef</c>.</p>
</desc>
</func>
diff --git a/lib/kernel/doc/src/error_logger.xml b/lib/kernel/doc/src/error_logger.xml
index e107d9b746..2d95f96ac7 100644
--- a/lib/kernel/doc/src/error_logger.xml
+++ b/lib/kernel/doc/src/error_logger.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -65,19 +65,20 @@
be tagged as warnings or info. Tagging them as warnings may
require rewriting existing user defined event handlers.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="report"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>error_msg(Format) -> ok</name>
- <name>error_msg(Format, Data) -> ok</name>
- <name>format(Format, Data) -> ok</name>
+ <name name="error_msg" arity="1"/>
+ <name name="error_msg" arity="2"/>
+ <name name="format" arity="2"/>
<fsummary>Send an standard error event to the error logger</fsummary>
- <type>
- <v>Format = string()</v>
- <v>Data = [term()]</v>
- </type>
<desc>
<p>Sends a standard error event to the error logger.
- The <c>Format</c> and <c>Data</c> arguments are the same as
+ The <c><anno>Format</anno></c> and <c><anno>Data</anno></c> arguments are the same as
the arguments of <c>io:format/2</c>. The event is handled by
the standard event handler.</p>
<pre>
@@ -94,12 +95,8 @@ ok</pre>
</desc>
</func>
<func>
- <name>error_report(Report) -> ok</name>
+ <name name="error_report" arity="1"/>
<fsummary>Send a standard error report event to the error logger</fsummary>
- <type>
- <v>Report = [{Tag, Data} | term()] | string() | term()</v>
- <v>&nbsp;Tag = Data = term()</v>
- </type>
<desc>
<p>Sends a standard error report event to the error logger.
The event is handled by the standard event handler.</p>
@@ -119,18 +116,13 @@ ok</pre>
</desc>
</func>
<func>
- <name>error_report(Type, Report) -> ok</name>
+ <name name="error_report" arity="2"/>
<fsummary>Send a user defined error report event to the error logger</fsummary>
- <type>
- <v>Type = term()</v>
- <v>Report = [{Tag, Data} | term()] | string() | term()</v>
- <v>&nbsp;Tag = Data = term()</v>
- </type>
<desc>
<p>Sends a user defined error report event to the error logger.
An event handler to handle the event is supposed to have been
added. The event is ignored by the standard event handler.</p>
- <p>It is recommended that <c>Report</c> follows the same
+ <p>It is recommended that <c><anno>Report</anno></c> follows the same
structure as for <c>error_report/1</c>.</p>
</desc>
</func>
@@ -174,16 +166,12 @@ ok</pre>
</desc>
</func>
<func>
- <name>warning_msg(Format) -> ok</name>
- <name>warning_msg(Format, Data) -> ok</name>
+ <name name="warning_msg" arity="1"/>
+ <name name="warning_msg" arity="2"/>
<fsummary>Send a standard warning event to the error logger</fsummary>
- <type>
- <v>Format = string()</v>
- <v>Data = [term()]</v>
- </type>
<desc>
<p>Sends a standard warning event to the error logger.
- The <c>Format</c> and <c>Data</c> arguments are the same as
+ The <c><anno>Format</anno></c> and <c><anno>Data</anno></c> arguments are the same as
the arguments of <c>io:format/2</c>. The event is handled by
the standard event handler. It is tagged either as an error,
warning or info, see
@@ -196,12 +184,8 @@ ok</pre>
</desc>
</func>
<func>
- <name>warning_report(Report) -> ok</name>
+ <name name="warning_report" arity="1"/>
<fsummary>Send a standard warning report event to the error logger</fsummary>
- <type>
- <v>Report = [{Tag, Data} | term()] | string() | term()</v>
- <v>&nbsp;Tag = Data = term()</v>
- </type>
<desc>
<p>Sends a standard warning report event to the error logger.
The event is handled by the standard event handler. It is
@@ -210,13 +194,8 @@ ok</pre>
</desc>
</func>
<func>
- <name>warning_report(Type, Report) -> ok</name>
+ <name name="warning_report" arity="2"/>
<fsummary>Send a user defined warning report event to the error logger</fsummary>
- <type>
- <v>Type = term()</v>
- <v>Report = [{Tag, Data} | term()] | string() | term()</v>
- <v>&nbsp;Tag = Data = term()</v>
- </type>
<desc>
<p>Sends a user defined warning report event to the error
logger. An event handler to handle the event is supposed to
@@ -227,16 +206,12 @@ ok</pre>
</desc>
</func>
<func>
- <name>info_msg(Format) -> ok</name>
- <name>info_msg(Format, Data) -> ok</name>
+ <name name="info_msg" arity="1"/>
+ <name name="info_msg" arity="2"/>
<fsummary>Send a standard information event to the error logger</fsummary>
- <type>
- <v>Format = string()</v>
- <v>Data = [term()]</v>
- </type>
<desc>
<p>Sends a standard information event to the error logger.
- The <c>Format</c> and <c>Data</c> arguments are the same as
+ The <c><anno>Format</anno></c> and <c><anno>Data</anno></c> arguments are the same as
the arguments of <c>io:format/2</c>. The event is handled by
the standard event handler.</p>
<pre>
@@ -253,12 +228,8 @@ ok</pre>
</desc>
</func>
<func>
- <name>info_report(Report) -> ok</name>
+ <name name="info_report" arity="1"/>
<fsummary>Send a standard information report event to the error logger</fsummary>
- <type>
- <v>Report = [{Tag, Data} | term()] | string() | term()</v>
- <v>&nbsp;Tag = Data = term()</v>
- </type>
<desc>
<p>Sends a standard information report event to the error
logger. The event is handled by the standard event handler.</p>
@@ -278,63 +249,49 @@ ok</pre>
</desc>
</func>
<func>
- <name>info_report(Type, Report) -> ok</name>
+ <name name="info_report" arity="2"/>
<fsummary>Send a user defined information report event to the error logger</fsummary>
- <type>
- <v>Type = term()</v>
- <v>Report = [{Tag, Data} | term()] | string() | term()</v>
- <v>&nbsp;Tag = Data = term()</v>
- </type>
<desc>
<p>Sends a user defined information report event to the error
logger. An event handler to handle the event is supposed to
have been added. The event is ignored by the standard event
handler.</p>
- <p>It is recommended that <c>Report</c> follows the same
+ <p>It is recommended that <c><anno>Report</anno></c> follows the same
structure as for <c>info_report/1</c>.</p>
</desc>
</func>
<func>
- <name>add_report_handler(Handler) -> Result</name>
- <name>add_report_handler(Handler, Args) -> Result</name>
+ <name name="add_report_handler" arity="1"/>
+ <name name="add_report_handler" arity="2"/>
<fsummary>Add an event handler to the error logger</fsummary>
- <type>
- <v>Handler, Args, Result -- see gen_event:add_handler/3</v>
- </type>
<desc>
<p>Adds a new event handler to the error logger. The event
handler must be implemented as a <c>gen_event</c> callback
module, see
<seealso marker="stdlib:gen_event">gen_event(3)</seealso>.</p>
- <p><c>Handler</c> is typically the name of the callback module
- and <c>Args</c> is an optional term (defaults to []) passed
- to the initialization callback function <c>Module:init/1</c>.
+ <p><c><anno>Handler</anno></c> is typically the name of the callback module
+ and <c><anno>Args</anno></c> is an optional term (defaults to []) passed
+ to the initialization callback function <c><anno>Handler</anno>:init/1</c>.
The function returns <c>ok</c> if successful.</p>
<p>The event handler must be able to handle the
<seealso marker="#events">events</seealso> described below.</p>
</desc>
</func>
<func>
- <name>delete_report_handler(Handler) -> Result</name>
+ <name name="delete_report_handler" arity="1"/>
<fsummary>Delete an event handler from the error logger</fsummary>
- <type>
- <v>Handler, Result -- see gen_event:delete_handler/3</v>
- </type>
<desc>
<p>Deletes an event handler from the error logger by calling
- <c>gen_event:delete_handler(error_logger, Handler, [])</c>,
+ <c>gen_event:delete_handler(error_logger, <anno>Handler</anno>, [])</c>,
see <seealso marker="stdlib:gen_event">gen_event(3)</seealso>.</p>
</desc>
</func>
<func>
- <name>tty(Flag) -> ok</name>
+ <name name="tty" arity="1"/>
<fsummary>Enable or disable printouts to the tty</fsummary>
- <type>
- <v>Flag = bool()</v>
- </type>
<desc>
- <p>Enables (<c>Flag == true</c>) or disables
- (<c>Flag == false</c>) printout of standard events to the tty.</p>
+ <p>Enables (<c><anno>Flag</anno> == true</c>) or disables
+ (<c><anno>Flag</anno> == false</c>) printout of standard events to the tty.</p>
<p>This is done by adding or deleting the standard event handler
for output to tty, thus calling this function overrides
the value of the Kernel <c>error_logger</c> configuration
@@ -342,13 +299,15 @@ ok</pre>
</desc>
</func>
<func>
- <name>logfile(Request) -> ok | Filename | {error, What}</name>
+ <name name="logfile" arity="1" clause_i="1"/>
+ <name name="logfile" arity="1" clause_i="2"/>
+ <name name="logfile" arity="1" clause_i="3"/>
+ <type variable="Filename"/>
+ <type variable="OpenReason" name_i="1"/>
+ <type variable="CloseReason" name_i="2"/>
+ <type variable="FilenameReason" name_i="3"/>
+ <type name="open_error"/>
<fsummary>Enable or disable error printouts to a file</fsummary>
- <type>
- <v>Request = {open, Filename} | close | filename</v>
- <v>&nbsp;Filename = atom() | string()</v>
- <v>What = allready_have_logfile | no_log_file | term()</v>
- </type>
<desc>
<p>Enables or disables printout of standard events to a file.</p>
<p>This is done by adding or deleting the standard event handler
@@ -361,22 +320,22 @@ ok</pre>
There can only be one active log file at a time.</p>
<p><c>Request</c> is one of:</p>
<taglist>
- <tag><c>{open, Filename}</c></tag>
+ <tag><c>{open, <anno>Filename</anno>}</c></tag>
<item>
- <p>Opens the log file <c>Filename</c>. Returns <c>ok</c> if
+ <p>Opens the log file <c><anno>Filename</anno></c>. Returns <c>ok</c> if
successful, or <c>{error, allready_have_logfile}</c> if
logging to file is already enabled, or an error tuple if
- another error occurred. For example, if <c>Filename</c>
+ another error occurred. For example, if <c><anno>Filename</anno></c>
could not be opened.</p>
</item>
<tag><c>close</c></tag>
<item>
<p>Closes the current log file. Returns <c>ok</c>, or
- <c>{error, What}</c>.</p>
+ <c>{error, module_not_found}</c>.</p>
</item>
<tag><c>filename</c></tag>
<item>
- <p>Returns the name of the log file <c>Filename</c>, or
+ <p>Returns the name of the log file <c><anno>Filename</anno></c>, or
<c>{error, no_log_file}</c> if logging to file is not
enabled.</p>
</item>
diff --git a/lib/kernel/doc/src/file.xml b/lib/kernel/doc/src/file.xml
index 36fce464c5..e0feaf6ee7 100644
--- a/lib/kernel/doc/src/file.xml
+++ b/lib/kernel/doc/src/file.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -93,47 +93,76 @@
is UTF-8...</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-iodata() = iolist() | binary()
- iolist() = [char() | binary() | iolist()]
-
-io_device()
- as returned by file:open/2, a process handling IO protocols
-
-name() = string() | atom() | DeepList | RawFilename
- DeepList = [char() | atom() | DeepList]
- RawFilename = binary()
- If VM is in unicode filename mode, string() and char() are allowed to be > 255.
- RawFilename is a filename not subject to Unicode translation, meaning that it
- can contain characters not conforming to the Unicode encoding expected from the
- filesystem (i.e. non-UTF-8 characters although the VM is started in Unicode
- filename mode).
-
-posix()
- an atom which is named from the POSIX error codes used in
- Unix, and in the runtime libraries of most C compilers
-
-ext_posix() = posix() | badarg
+ <datatypes>
+ <datatype>
+ <name name="bindings"/>
+ </datatype>
+ <datatype>
+ <name name="deep_list"/>
+ </datatype>
+ <datatype>
+ <name name="fd"/>
+ </datatype>
+ <datatype>
+ <name name="filename"/>
+ </datatype>
+ <datatype>
+ <name name="io_device"/>
+ <desc>
+ <p>As returned by
+ <seealso marker="#open/2">file:open/2</seealso>,
+ a process handling IO protocols.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="name"/>
+ <desc>
+ <p>If VM is in Unicode filename mode, <c>string()</c> and <c>char()</c>
+ are allowed to be > 255.
+ <c><anno>RawFilename</anno></c> is a filename not subject to
+ Unicode translation,
+ meaning that it can contain characters not conforming to
+ the Unicode encoding expected from the filesystem
+ (i.e. non-UTF-8 characters although the VM is started
+ in Unicode filename mode).
+ </p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="posix"/>
+ <desc>
+ <p>An atom which is named from the POSIX error codes used in
+ Unix, and in the runtime libraries of most C compilers.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="date"/>
+ </datatype>
+ <datatype>
+ <name name="time"/>
+ </datatype>
+ <datatype>
+ <name name="date_time"/>
+ <desc>
+ <p>Must denote a valid date and time.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="file_info"/>
+ </datatype>
+ <datatype>
+ <name name="location"/>
+ </datatype>
+ <datatype>
+ <name name="mode"/>
+ </datatype>
+ </datatypes>
-time() = {{Year, Month, Day}, {Hour, Minute, Second}}
- Year = Month = Day = Hour = Minute = Second = int()
- Must denote a valid date and time</code>
- </section>
<funcs>
<func>
- <name>advise(IoDevice, Offset, Length, Advise) -> ok | {error, Reason}</name>
+ <name name="advise" arity="4"/>
<fsummary>Predeclare an access pattern for file data</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Offset = int()</v>
- <v>Length = int()</v>
- <v>Advise = posix_file_advise()</v>
- <v>posix_file_advise() = normal | sequential | random | no_reuse
- | will_need | dont_need</v>
- <v>Reason = ext_posix()</v>
- </type>
+ <type name="posix_file_advise"/>
<desc>
<p><c>advise/4</c> can be used to announce an intention to access file
data in a specific pattern in the future, thus allowing the
@@ -142,93 +171,58 @@ time() = {{Year, Month, Day}, {Hour, Minute, Second}}
</desc>
</func>
<func>
- <name>change_group(Filename, Gid) -> ok | {error, Reason}</name>
+ <name name="change_group" arity="2"/>
<fsummary>Change group of a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Gid = int()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Changes group of a file. See
<seealso marker="#write_file_info/2">write_file_info/2</seealso>.</p>
</desc>
</func>
<func>
- <name>change_mode(Filename, Mode) -> ok | {error, Reason}</name>
+ <name name="change_mode" arity="2"/>
<fsummary>Change permissions of a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Mode = int()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Changes permissions of a file. See
<seealso marker="#write_file_info/2">write_file_info/2</seealso>.</p>
</desc>
</func>
<func>
- <name>change_owner(Filename, Uid) -> ok | {error, Reason}</name>
+ <name name="change_owner" arity="2"/>
<fsummary>Change owner of a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Uid = int()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Changes owner of a file. See
<seealso marker="#write_file_info/2">write_file_info/2</seealso>.</p>
</desc>
</func>
<func>
- <name>change_owner(Filename, Uid, Gid) -> ok | {error, Reason}</name>
+ <name name="change_owner" arity="3"/>
<fsummary>Change owner and group of a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Uid = int()</v>
- <v>Gid = int()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Changes owner and group of a file. See
<seealso marker="#write_file_info/2">write_file_info/2</seealso>.</p>
</desc>
</func>
<func>
- <name>change_time(Filename, Mtime) -> ok | {error, Reason}</name>
+ <name name="change_time" arity="2"/>
<fsummary>Change the modification time of a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Mtime = time()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Changes the modification and access times of a file. See
<seealso marker="#write_file_info/2">write_file_info/2</seealso>.</p>
</desc>
</func>
<func>
- <name>change_time(Filename, Mtime, Atime) -> ok | {error, Reason}</name>
+ <name name="change_time" arity="3"/>
<fsummary>Change the modification and last access time of a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Mtime = Atime = time()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Changes the modification and last access times of a file. See
<seealso marker="#write_file_info/2">write_file_info/2</seealso>.</p>
</desc>
</func>
<func>
- <name>close(IoDevice) -> ok | {error, Reason}</name>
+ <name name="close" arity="1"/>
<fsummary>Close a file</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
- <p>Closes the file referenced by <c>IoDevice</c>. It mostly
+ <p>Closes the file referenced by <c><anno>IoDevice</anno></c>. It mostly
returns <c>ok</c>, expect for some severe errors such as out
of memory.</p>
<p>Note that if the option <c>delayed_write</c> was
@@ -238,20 +232,13 @@ time() = {{Year, Month, Day}, {Hour, Minute, Second}}
</desc>
</func>
<func>
- <name>consult(Filename) -> {ok, Terms} | {error, Reason}</name>
+ <name name="consult" arity="1"/>
<fsummary>Read Erlang terms from a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Terms = [term()]</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see below</v>
- </type>
<desc>
- <p>Reads Erlang terms, separated by '.', from <c>Filename</c>.
- Returns one of the following:</p>
+ <p>Reads Erlang terms, separated by '.', from
+ <c><anno>Filename</anno></c>. Returns one of the following:</p>
<taglist>
- <tag><c>{ok, Terms}</c></tag>
+ <tag><c>{ok, <anno>Terms</anno>}</c></tag>
<item>
<p>The file was successfully read.</p>
</item>
@@ -261,7 +248,8 @@ time() = {{Year, Month, Day}, {Hour, Minute, Second}}
See <seealso marker="#open/2">open/2</seealso> for a list
of typical error codes.</p>
</item>
- <tag><c>{error, {Line, Mod, Term}}</c></tag>
+ <tag><c>{error, {<anno>Line</anno>, <anno>Mod</anno>,
+ <anno>Term</anno>}}</c></tag>
<item>
<p>An error occurred when interpreting the Erlang terms in
the file. Use <c>format_error/1</c> to convert
@@ -279,53 +267,46 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>copy(Source, Destination) -></name>
- <name>copy(Source, Destination, ByteCount) -> {ok, BytesCopied} | {error, Reason}</name>
+ <name name="copy" arity="2"/>
+ <name name="copy" arity="3"/>
<fsummary>Copy file contents</fsummary>
- <type>
- <v>Source = Destination = io_device() | Filename | {Filename, Modes}</v>
- <v>&nbsp;Filename = name()</v>
- <v>&nbsp;Modes = [Mode] -- see open/2</v>
- <v>ByteCount = int() >= 0 | infinity</v>
- <v>BytesCopied = int()</v>
- </type>
<desc>
- <p>Copies <c>ByteCount</c> bytes from <c>Source</c> to
- <c>Destination</c>. <c>Source</c> and <c>Destination</c> refer
+ <p>Copies <c><anno>ByteCount</anno></c> bytes from
+ <c><anno>Source</anno></c> to <c><anno>Destination</anno></c>.
+ <c><anno>Source</anno></c> and <c><anno>Destination</anno></c> refer
to either filenames or IO devices from e.g. <c>open/2</c>.
- <c>ByteCount</c> defaults <c>infinity</c>, denoting an
+ <c><anno>ByteCount</anno></c> defaults to <c>infinity</c>, denoting an
infinite number of bytes.</p>
- <p>The argument <c>Modes</c> is a list of possible modes, see
- <seealso marker="#open/2">open/2</seealso>, and defaults to
+ <p>The argument <c><anno>Modes</anno></c> is a list of possible modes,
+ see <seealso marker="#open/2">open/2</seealso>, and defaults to
[].</p>
- <p>If both <c>Source</c> and <c>Destination</c> refer to
+ <p>If both <c><anno>Source</anno></c> and
+ <c><anno>Destination</anno></c> refer to
filenames, the files are opened with <c>[read, binary]</c>
and <c>[write, binary]</c> prepended to their mode lists,
respectively, to optimize the copy.</p>
- <p>If <c>Source</c> refers to a filename, it is opened with
+ <p>If <c><anno>Source</anno></c> refers to a filename, it is opened with
<c>read</c> mode prepended to the mode list before the copy,
and closed when done.</p>
- <p>If <c>Destination</c> refers to a filename, it is opened
+ <p>If <c><anno>Destination</anno></c> refers to a filename, it is opened
with <c>write</c> mode prepended to the mode list before
the copy, and closed when done.</p>
- <p>Returns <c>{ok, BytesCopied}</c> where <c>BytesCopied</c> is
+ <p>Returns <c>{ok, <anno>BytesCopied</anno>}</c> where
+ <c><anno>BytesCopied</anno></c> is
the number of bytes that actually was copied, which may be
- less than <c>ByteCount</c> if end of file was encountered on
- the source. If the operation fails, <c>{error, Reason}</c> is
- returned.</p>
+ less than <c><anno>ByteCount</anno></c> if end of file was
+ encountered on the source. If the operation fails,
+ <c>{error, <anno>Reason</anno>}</c> is returned.</p>
<p>Typical error reasons: As for <c>open/2</c> if a file had to
be opened, and as for <c>read/2</c> and <c>write/2</c>.</p>
</desc>
</func>
<func>
- <name>del_dir(Dir) -> ok | {error, Reason}</name>
+ <name name="del_dir" arity="1"/>
<fsummary>Delete a directory</fsummary>
- <type>
- <v>Dir = name()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p>Tries to delete the directory <c>Dir</c>. The directory must
+ <p>Tries to delete the directory <c><anno>Dir</anno></c>.
+ The directory must
be empty before it can be deleted. Returns <c>ok</c> if
successful.</p>
<p>Typical error reasons are:</p>
@@ -333,7 +314,7 @@ f.txt: {person, "kalle", 25}.
<tag><c>eacces</c></tag>
<item>
<p>Missing search or write permissions for the parent
- directories of <c>Dir</c>.</p>
+ directories of <c><anno>Dir</anno></c>.</p>
</item>
<tag><c>eexist</c></tag>
<item>
@@ -345,8 +326,8 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>enotdir</c></tag>
<item>
- <p>A component of <c>Dir</c> is not a directory. On some
- platforms, <c>enoent</c> is returned instead.</p>
+ <p>A component of <c><anno>Dir</anno></c> is not a directory.
+ On some platforms, <c>enoent</c> is returned instead.</p>
</item>
<tag><c>einval</c></tag>
<item>
@@ -357,15 +338,11 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>delete(Filename) -> ok | {error, Reason}</name>
+ <name name="delete" arity="1"/>
<fsummary>Delete a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p>Tries to delete the file <c>Filename</c>. Returns <c>ok</c>
- if successful.</p>
+ <p>Tries to delete the file <c><anno>Filename</anno></c>.
+ Returns <c>ok</c> if successful.</p>
<p>Typical error reasons are:</p>
<taglist>
<tag><c>enoent</c></tag>
@@ -387,30 +364,25 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>einval</c></tag>
<item>
- <p><c>Filename</c> had an improper type, such as tuple.</p>
+ <p><c><anno>Filename</anno></c> had an improper type, such as tuple.</p>
</item>
</taglist>
<warning>
- <p>In a future release, a bad type for the <c>Filename</c>
- argument will probably generate an exception.</p>
+ <p>In a future release, a bad type for the
+ <c><anno>Filename</anno></c> argument will probably generate
+ an exception.</p>
<p></p>
</warning>
</desc>
</func>
<func>
- <name>eval(Filename) -> ok | {error, Reason}</name>
+ <name name="eval" arity="1"/>
<fsummary>Evaluate Erlang expressions in a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see below</v>
- </type>
<desc>
<p>Reads and evaluates Erlang expressions, separated by '.' (or
',', a sequence of expressions is also an expression), from
- <c>Filename</c>. The actual result of the evaluation is not
- returned; any expression sequence in the file must be there
+ <c><anno>Filename</anno></c>. The actual result of the evaluation
+ is not returned; any expression sequence in the file must be there
for its side effect. Returns one of the following:</p>
<taglist>
<tag><c>ok</c></tag>
@@ -422,7 +394,8 @@ f.txt: {person, "kalle", 25}.
<p>An error occurred when opening the file or reading it.
See <c>open/2</c> for a list of typical error codes.</p>
</item>
- <tag><c>{error, {Line, Mod, Term}}</c></tag>
+ <tag><c>{error, {<anno>Line</anno>, <anno>Mod</anno>,
+ <anno>Term</anno>}}</c></tag>
<item>
<p>An error occurred when interpreting the Erlang
expressions in the file. Use <c>format_error/1</c> to
@@ -433,18 +406,11 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>eval(Filename, Bindings) -> ok | {error, Reason}</name>
+ <name name="eval" arity="2"/>
<fsummary>Evaluate Erlang expressions in a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Bindings -- see erl_eval(3)</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see eval/1</v>
- </type>
<desc>
<p>The same as <c>eval/1</c> but the variable bindings
- <c>Bindings</c> are used in the evaluation. See
+ <c><anno>Bindings</anno></c> are used in the evaluation. See
<seealso marker="stdlib:erl_eval">erl_eval(3)</seealso> about
variable bindings.</p>
</desc>
@@ -458,27 +424,19 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>format_error(Reason) -> Chars</name>
+ <name name="format_error" arity="1"/>
<fsummary>Return a descriptive string for an error reason</fsummary>
- <type>
- <v>Reason = atom() | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see eval/1</v>
- <v>Chars = [char() | Chars]</v>
- </type>
<desc>
<p>Given the error reason returned by any function in this
module, returns a descriptive string of the error in English.</p>
</desc>
</func>
<func>
- <name>get_cwd() -> {ok, Dir} | {error, Reason}</name>
+ <name name="get_cwd" arity="0"/>
<fsummary>Get the current working directory</fsummary>
- <type>
- <v>Dir = string()</v>
- <v>Reason = posix()</v>
- </type>
<desc>
- <p>Returns <c>{ok, Dir}</c>, where <c>Dir</c> is the current
+ <p>Returns <c>{ok, <anno>Dir</anno>}</c>, where <c><anno>Dir</anno></c>
+ is the current
working directory of the file server.</p>
<note>
<p>In rare circumstances, this function can fail on Unix.
@@ -496,17 +454,14 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>get_cwd(Drive) -> {ok, Dir} | {error, Reason}</name>
+ <name name="get_cwd" arity="1"/>
<fsummary>Get the current working directory for the drive specified</fsummary>
- <type>
- <v>Drive = string() -- see below</v>
- <v>Dir = string()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p><c>Drive</c> should be of the form "<c>Letter</c><c>:</c>",
- for example "c:". Returns <c>{ok, Dir}</c> or
- <c>{error, Reason}</c>, where <c>Dir</c> is the current
+ <p><c><anno>Drive</anno></c> should be of the form
+ "<c>Letter</c><c>:</c>",
+ for example "c:". Returns <c>{ok, <anno>Dir</anno>}</c> or
+ <c>{error, <anno>Reason</anno>}</c>, where <c><anno>Dir</anno></c>
+ is the current
working directory of the drive specified.</p>
<p>This function returns <c>{error, enotsup}</c> on platforms
which have no concept of current drive (Unix, for example).</p>
@@ -514,7 +469,7 @@ f.txt: {person, "kalle", 25}.
<taglist>
<tag><c>enotsup</c></tag>
<item>
- <p>The operating system have no concept of drives.</p>
+ <p>The operating system has no concept of drives.</p>
</item>
<tag><c>eacces</c></tag>
<item>
@@ -522,32 +477,27 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>einval</c></tag>
<item>
- <p>The format of <c>Drive</c> is invalid.</p>
+ <p>The format of <c><anno>Drive</anno></c> is invalid.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>list_dir(Dir) -> {ok, Filenames} | {error, Reason}</name>
+ <name name="list_dir" arity="1"/>
<fsummary>List files in a directory</fsummary>
- <type>
- <v>Dir = name()</v>
- <v>Filenames = [Filename]</v>
- <v>&nbsp;Filename = string()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Lists all the files in a directory. Returns
- <c>{ok, Filenames}</c> if successful. Otherwise, it returns
- <c>{error, Reason}</c>. <c>Filenames</c> is a list of
+ <c>{ok, <anno>Filenames</anno>}</c> if successful.
+ Otherwise, it returns <c>{error, <anno>Reason</anno>}</c>.
+ <c><anno>Filenames</anno></c> is a list of
the names of all the files in the directory. The names are
not sorted.</p>
<p>Typical error reasons are:</p>
<taglist>
<tag><c>eacces</c></tag>
<item>
- <p>Missing search or write permissions for <c>Dir</c> or
- one of its parent directories.</p>
+ <p>Missing search or write permissions for <c><anno>Dir</anno></c>
+ or one of its parent directories.</p>
</item>
<tag><c>enoent</c></tag>
<item>
@@ -557,14 +507,10 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>make_dir(Dir) -> ok | {error, Reason}</name>
+ <name name="make_dir" arity="1"/>
<fsummary>Make a directory</fsummary>
- <type>
- <v>Dir = name()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p>Tries to create the directory <c>Dir</c>. Missing parent
+ <p>Tries to create the directory <c><anno>Dir</anno></c>. Missing parent
directories are <em>not</em> created. Returns <c>ok</c> if
successful.</p>
<p>Typical error reasons are:</p>
@@ -572,15 +518,15 @@ f.txt: {person, "kalle", 25}.
<tag><c>eacces</c></tag>
<item>
<p>Missing search or write permissions for the parent
- directories of <c>Dir</c>.</p>
+ directories of <c><anno>Dir</anno></c>.</p>
</item>
<tag><c>eexist</c></tag>
<item>
- <p>There is already a file or directory named <c>Dir</c>.</p>
+ <p>There is already a file or directory named <c><anno>Dir</anno></c>.</p>
</item>
<tag><c>enoent</c></tag>
<item>
- <p>A component of <c>Dir</c> does not exist.</p>
+ <p>A component of <c><anno>Dir</anno></c> does not exist.</p>
</item>
<tag><c>enospc</c></tag>
<item>
@@ -588,35 +534,33 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>enotdir</c></tag>
<item>
- <p>A component of <c>Dir</c> is not a directory. On some
- platforms, <c>enoent</c> is returned instead.</p>
+ <p>A component of <c><anno>Dir</anno></c> is not a directory.
+ On some platforms, <c>enoent</c> is returned instead.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>make_link(Existing, New) -> ok | {error, Reason}</name>
+ <name name="make_link" arity="2"/>
<fsummary>Make a hard link to a file</fsummary>
- <type>
- <v>Existing = New = name()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p>Makes a hard link from <c>Existing</c> to <c>New</c>, on
+ <p>Makes a hard link from <c><anno>Existing</anno></c> to
+ <c><anno>New</anno></c>, on
platforms that support links (Unix). This function returns
<c>ok</c> if the link was successfully created, or
- <c>{error, Reason}</c>. On platforms that do not support
+ <c>{error, <anno>Reason</anno>}</c>. On platforms that do not support
links, <c>{error,enotsup}</c> is returned.</p>
<p>Typical error reasons:</p>
<taglist>
<tag><c>eacces</c></tag>
<item>
<p>Missing read or write permissions for the parent
- directories of <c>Existing</c> or <c>New</c>.</p>
+ directories of <c><anno>Existing</anno></c> or
+ <c><anno>New</anno></c>.</p>
</item>
<tag><c>eexist</c></tag>
<item>
- <p><c>New</c> already exists.</p>
+ <p><c><anno>New</anno></c> already exists.</p>
</item>
<tag><c>enotsup</c></tag>
<item>
@@ -626,30 +570,28 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>make_symlink(Name1, Name2) -> ok | {error, Reason}</name>
+ <name name="make_symlink" arity="2"/>
<fsummary>Make a symbolic link to a file or directory</fsummary>
- <type>
- <v>Name1 = Name2 = name()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p>This function creates a symbolic link <c>Name2</c> to
- the file or directory <c>Name1</c>, on platforms that support
- symbolic links (most Unix systems). <c>Name1</c> need not
+ <p>This function creates a symbolic link <c><anno>Name2</anno></c> to
+ the file or directory <c><anno>Name1</anno></c>, on platforms that
+ support
+ symbolic links (most Unix systems). <c><anno>Name1</anno></c> need not
exist. This function returns <c>ok</c> if the link was
- successfully created, or <c>{error, Reason}</c>. On platforms
+ successfully created, or <c>{error, <anno>Reason</anno>}</c>.
+ On platforms
that do not support symbolic links, <c>{error, enotsup}</c>
is returned.</p>
<p>Typical error reasons:</p>
<taglist>
<tag><c>eacces</c></tag>
<item>
- <p>Missing read or write permissions for the parent
- directories of <c>Name1</c> or <c>Name2</c>.</p>
+ <p>Missing read or write permissions for the parent directories
+ of <c><anno>Name1</anno></c> or <c><anno>Name2</anno></c>.</p>
</item>
<tag><c>eexist</c></tag>
<item>
- <p><c>Name2</c> already exists.</p>
+ <p><c><anno>Name2</anno></c> already exists.</p>
</item>
<tag><c>enotsup</c></tag>
<item>
@@ -668,22 +610,12 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>open(Filename, Modes) -> {ok, IoDevice} | {error, Reason}</name>
+ <name name="open" arity="2"/>
<fsummary>Open a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Modes = [Mode]</v>
- <v>&nbsp;Mode = read | write | append | exclusive | raw | binary | {delayed_write, Size, Delay} | delayed_write | {read_ahead, Size} | read_ahead | compressed | {encoding, Encoding}</v>
- <v>&nbsp;&nbsp;Size = Delay = int()</v>
- <v>&nbsp;&nbsp;Encoding = latin1 | unicode | utf8 | utf16 | {utf16, Endian} | utf32 | {utf32, Endian}</v>
- <v>&nbsp;&nbsp;&nbsp;&nbsp;Endian = big | little</v>
- <v>IoDevice = io_device()</v>
- <v>Reason = ext_posix() | system_limit</v>
- </type>
<desc>
- <p>Opens the file <c>Filename</c> in the mode determined by
- <c>Modes</c>, which may contain one or more of the following
- items:</p>
+ <p>Opens the file <c><anno>Filename</anno></c> in the mode determined
+ by <c><anno>Modes</anno></c>, which may contain one or more of the
+ following items:</p>
<taglist>
<tag><c>read</c></tag>
<item>
@@ -841,23 +773,23 @@ f.txt: {person, "kalle", 25}.
</taglist>
<p>Returns:</p>
<taglist>
- <tag><c>{ok, IoDevice}</c></tag>
+ <tag><c>{ok, <anno>IoDevice</anno>}</c></tag>
<item>
<p>The file has been opened in the requested mode.
- <c>IoDevice</c> is a reference to the file.</p>
+ <c><anno>IoDevice</anno></c> is a reference to the file.</p>
</item>
- <tag><c>{error, Reason}</c></tag>
+ <tag><c>{error, <anno>Reason</anno>}</c></tag>
<item>
<p>The file could not be opened.</p>
</item>
</taglist>
- <p><c>IoDevice</c> is really the pid of the process which
+ <p><c><anno>IoDevice</anno></c> is really the pid of the process which
handles the file. This process is linked to the process
which originally opened the file. If any process to which
- the <c>IoDevice</c> is linked terminates, the file will be
- closed and the process itself will be terminated.
- An <c>IoDevice</c> returned from this call can be used as an
- argument to the IO functions (see
+ the <c><anno>IoDevice</anno></c> is linked terminates, the file will
+ be closed and the process itself will be terminated.
+ An <c><anno>IoDevice</anno></c> returned from this call can be used
+ as an argument to the IO functions (see
<seealso marker="stdlib:io">io(3)</seealso>).</p>
<note>
<p>In previous versions of <c>file</c>, modes were given
@@ -897,34 +829,25 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>path_consult(Path, Filename) -> {ok, Terms, FullName} | {error, Reason}</name>
+ <name name="path_consult" arity="2"/>
<fsummary>Read Erlang terms from a file</fsummary>
- <type>
- <v>Path = [Dir]</v>
- <v>&nbsp;Dir = name()</v>
- <v>Filename = name()</v>
- <v>Terms = [term()]</v>
- <v>FullName = string()</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see below</v>
- </type>
<desc>
- <p>Searches the path <c>Path</c> (a list of directory names)
- until the file <c>Filename</c> is found. If <c>Filename</c>
- is an absolute filename, <c>Path</c> is ignored.
+ <p>Searches the path <c><anno>Path</anno></c> (a list of directory
+ names) until the file <c><anno>Filename</anno></c> is found.
+ If <c><anno>Filename</anno></c>
+ is an absolute filename, <c><anno>Path</anno></c> is ignored.
Then reads Erlang terms, separated by '.', from the file.
Returns one of the following:</p>
<taglist>
- <tag><c>{ok, Terms, FullName}</c></tag>
+ <tag><c>{ok, <anno>Terms</anno>, <anno>FullName</anno>}</c></tag>
<item>
- <p>The file was successfully read. <c>FullName</c> is
+ <p>The file was successfully read. <c><anno>FullName</anno></c> is
the full name of the file.</p>
</item>
<tag><c>{error, enoent}</c></tag>
<item>
<p>The file could not be found in any of the directories in
- <c>Path</c>.</p>
+ <c><anno>Path</anno></c>.</p>
</item>
<tag><c>{error, atom()}</c></tag>
<item>
@@ -932,7 +855,8 @@ f.txt: {person, "kalle", 25}.
See <seealso marker="#open/2">open/2</seealso> for a list
of typical error codes.</p>
</item>
- <tag><c>{error, {Line, Mod, Term}}</c></tag>
+ <tag><c>{error, {<anno>Line</anno>, <anno>Mod</anno>,
+ <anno>Term</anno>}}</c></tag>
<item>
<p>An error occurred when interpreting the Erlang terms in
the file. Use <c>format_error/1</c> to convert
@@ -943,36 +867,28 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>path_eval(Path, Filename) -> {ok, FullName} | {error, Reason}</name>
+ <name name="path_eval" arity="2"/>
<fsummary>Evaluate Erlang expressions in a file</fsummary>
- <type>
- <v>Path = [Dir]</v>
- <v>&nbsp;Dir = name()</v>
- <v>Filename = name()</v>
- <v>FullName = string()</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see below</v>
- </type>
<desc>
- <p>Searches the path <c>Path</c> (a list of directory names)
- until the file <c>Filename</c> is found. If <c>Filename</c>
- is an absolute file name, <c>Path</c> is ignored. Then reads
+ <p>Searches the path <c><anno>Path</anno></c> (a list of directory
+ names) until the file <c><anno>Filename</anno></c> is found.
+ If <c><anno>Filename</anno></c> is an absolute file name,
+ <c><anno>Path</anno></c> is ignored. Then reads
and evaluates Erlang expressions, separated by '.' (or ',', a
sequence of expressions is also an expression), from the file.
The actual result of evaluation is not returned; any
expression sequence in the file must be there for its side
effect. Returns one of the following:</p>
<taglist>
- <tag><c>{ok, FullName}</c></tag>
+ <tag><c>{ok, <anno>FullName</anno>}</c></tag>
<item>
- <p>The file was read and evaluated. <c>FullName</c> is
+ <p>The file was read and evaluated. <c><anno>FullName</anno></c> is
the full name of the file.</p>
</item>
<tag><c>{error, enoent}</c></tag>
<item>
<p>The file could not be found in any of the directories in
- <c>Path</c>.</p>
+ <c><anno>Path</anno></c>.</p>
</item>
<tag><c>{error, atom()}</c></tag>
<item>
@@ -980,7 +896,8 @@ f.txt: {person, "kalle", 25}.
See <seealso marker="#open/2">open/2</seealso> for a list
of typical error codes.</p>
</item>
- <tag><c>{error, {Line, Mod, Term}}</c></tag>
+ <tag><c>{error, {<anno>Line</anno>, <anno>Mod</anno>,
+ <anno>Term</anno>}}</c></tag>
<item>
<p>An error occurred when interpreting the Erlang
expressions in the file. Use <c>format_error/1</c> to
@@ -991,34 +908,26 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>path_open(Path, Filename, Modes) -> {ok, IoDevice, FullName} | {error, Reason}</name>
+ <name name="path_open" arity="3"/>
<fsummary>Open a file</fsummary>
- <type>
- <v>Path = [Dir]</v>
- <v>&nbsp;Dir = name()</v>
- <v>Filename = name()</v>
- <v>Modes = [Mode] -- see open/2</v>
- <v>IoDevice = io_device()</v>
- <v>FullName = string()</v>
- <v>Reason = ext_posix() | system_limit</v>
- </type>
<desc>
- <p>Searches the path <c>Path</c> (a list of directory names)
- until the file <c>Filename</c> is found. If <c>Filename</c>
- is an absolute file name, <c>Path</c> is ignored.
- Then opens the file in the mode determined by <c>Modes</c>.
+ <p>Searches the path <c><anno>Path</anno></c> (a list of directory
+ names) until the file <c><anno>Filename</anno></c> is found.
+ If <c><anno>Filename</anno></c>
+ is an absolute file name, <c><anno>Path</anno></c> is ignored.
+ Then opens the file in the mode determined by <c><anno>Modes</anno></c>.
Returns one of the following:</p>
<taglist>
- <tag><c>{ok, IoDevice, FullName}</c></tag>
+ <tag><c>{ok, <anno>IoDevice</anno>, <anno>FullName</anno>}</c></tag>
<item>
<p>The file has been opened in the requested mode.
- <c>IoDevice</c> is a reference to the file and
- <c>FullName</c> is the full name of the file.</p>
+ <c><anno>IoDevice</anno></c> is a reference to the file and
+ <c><anno>FullName</anno></c> is the full name of the file.</p>
</item>
<tag><c>{error, enoent}</c></tag>
<item>
<p>The file could not be found in any of the directories in
- <c>Path</c>.</p>
+ <c><anno>Path</anno></c>.</p>
</item>
<tag><c>{error, atom()}</c></tag>
<item>
@@ -1028,36 +937,27 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>path_script(Path, Filename) -> {ok, Value, FullName} | {error, Reason}</name>
+ <name name="path_script" arity="2"/>
<fsummary>Evaluate and return the value of Erlang expressions in a file</fsummary>
- <type>
- <v>Path = [Dir]</v>
- <v>&nbsp;Dir = name()</v>
- <v>Filename = name()</v>
- <v>Value = term()</v>
- <v>FullName = string()</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see below</v>
- </type>
<desc>
- <p>Searches the path <c>Path</c> (a list of directory names)
- until the file <c>Filename</c> is found. If <c>Filename</c>
- is an absolute file name, <c>Path</c> is ignored. Then reads
+ <p>Searches the path <c><anno>Path</anno></c> (a list of directory
+ names) until the file <c><anno>Filename</anno></c> is found.
+ If <c><anno>Filename</anno></c> is an absolute file name,
+ <c><anno>Path</anno></c> is ignored. Then reads
and evaluates Erlang expressions, separated by '.' (or ',', a
sequence of expressions is also an expression), from the file.
Returns one of the following:</p>
<taglist>
- <tag><c>{ok, Value, FullName}</c></tag>
+ <tag><c>{ok, <anno>Value</anno>, <anno>FullName</anno>}</c></tag>
<item>
- <p>The file was read and evaluated. <c>FullName</c> is
- the full name of the file and <c>Value</c> the value of
+ <p>The file was read and evaluated. <c><anno>FullName</anno></c> is
+ the full name of the file and <c><anno>Value</anno></c> the value of
the last expression.</p>
</item>
<tag><c>{error, enoent}</c></tag>
<item>
<p>The file could not be found in any of the directories in
- <c>Path</c>.</p>
+ <c><anno>Path</anno></c>.</p>
</item>
<tag><c>{error, atom()}</c></tag>
<item>
@@ -1065,7 +965,8 @@ f.txt: {person, "kalle", 25}.
See <seealso marker="#open/2">open/2</seealso> for a list
of typical error codes.</p>
</item>
- <tag><c>{error, {Line, Mod, Term}}</c></tag>
+ <tag><c>{error, {<anno>Line</anno>, <anno>Mod</anno>,
+ <anno>Term</anno>}}</c></tag>
<item>
<p>An error occurred when interpreting the Erlang
expressions in the file. Use <c>format_error/1</c> to
@@ -1076,42 +977,28 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>path_script(Path, Filename, Bindings) -> {ok, Value, FullName} | {error, Reason}</name>
+ <name name="path_script" arity="3"/>
<fsummary>Evaluate and return the value of Erlang expressions in a file</fsummary>
- <type>
- <v>Path = [Dir]</v>
- <v>&nbsp;Dir = name()</v>
- <v>Filename = name()</v>
- <v>Bindings -- see erl_eval(3)</v>
- <v>Value = term()</v>
- <v>FullName = string()</v>
- <v>Reason = posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see path_script/2</v>
- </type>
<desc>
<p>The same as <c>path_script/2</c> but the variable bindings
- <c>Bindings</c> are used in the evaluation. See
+ <c><anno>Bindings</anno></c> are used in the evaluation. See
<seealso marker="stdlib:erl_eval">erl_eval(3)</seealso> about
variable bindings.</p>
</desc>
</func>
<func>
- <name>pid2name(Pid) -> string() | undefined</name>
+ <name name="pid2name" arity="1"/>
<fsummary>Return the name of the file handled by a pid</fsummary>
- <type>
- <v>Pid = pid()</v>
- </type>
<desc>
- <p>If <c>Pid</c> is an IO device, that is, a pid returned from
+ <p>If <c><anno>Pid</anno></c> is an IO device, that is, a pid returned from
<c>open/2</c>, this function returns the filename, or rather:</p>
<taglist>
- <tag><c>{ok, Filename}</c></tag>
+ <tag><c>{ok, <anno>Filename</anno>}</c></tag>
<item>
<p>If this node's file server is not a slave, the file was
opened by this node's file server, (this implies that
- <c>Pid</c> must be a local pid) and the file is not
- closed. <c>Filename</c> is the filename in flat string
+ <c><anno>Pid</anno></c> must be a local pid) and the file is not
+ closed. <c><anno>Filename</anno></c> is the filename in flat string
format.</p>
</item>
<tag><c>undefined</c></tag>
@@ -1125,21 +1012,15 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>position(IoDevice, Location) -> {ok, NewPosition} | {error, Reason}</name>
+ <name name="position" arity="2"/>
<fsummary>Set position in a file</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Location = Offset | {bof, Offset} | {cur, Offset} | {eof, Offset} | bof | cur | eof</v>
- <v>&nbsp;Offset = int()</v>
- <v>NewPosition = int()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
- <p>Sets the position of the file referenced by <c>IoDevice</c>
- to <c>Location</c>. Returns <c>{ok, NewPosition}</c> (as
+ <p>Sets the position of the file referenced by <c><anno>IoDevice</anno></c>
+ to <c><anno>Location</anno></c>. Returns
+ <c>{ok, <anno>NewPosition</anno>}</c> (as
absolute offset) if successful, otherwise
- <c>{error, Reason}</c>. <c>Location</c> is one of
- the following:</p>
+ <c>{error, <anno>Reason</anno>}</c>. <c><anno>Location</anno></c> is
+ one of the following:</p>
<taglist>
<tag><c>Offset</c></tag>
<item>
@@ -1167,7 +1048,8 @@ f.txt: {person, "kalle", 25}.
<taglist>
<tag><c>einval</c></tag>
<item>
- <p>Either <c>Location</c> was illegal, or it evaluated to a
+ <p>Either <c><anno>Location</anno></c> was illegal, or it
+ evaluated to a
negative offset in the file. Note that if the resulting
position is a negative value, the result is an error, and
after the call the file position is undefined.</p>
@@ -1176,22 +1058,14 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>pread(IoDevice, LocNums) -> {ok, DataL} | eof | {error, Reason}</name>
+ <name name="pread" arity="2"/>
<fsummary>Read from a file at certain positions</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>LocNums = [{Location, Number}]</v>
- <v>&nbsp;Location -- see position/2</v>
- <v>&nbsp;Number = int()</v>
- <v>DataL = [Data]</v>
- <v>&nbsp;Data = [char()] | binary()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
<p>Performs a sequence of <c>pread/3</c> in one operation,
which is more efficient than calling them one at a time.
- Returns <c>{ok, [Data, ...]}</c> or <c>{error, Reason}</c>,
- where each <c>Data</c>, the result of the corresponding
+ Returns <c>{ok, [<anno>Data</anno>, ...]}</c> or
+ <c>{error, <anno>Reason</anno>}</c>,
+ where each <c><anno>Data</anno></c>, the result of the corresponding
<c>pread</c>, is either a list or a binary depending on
the mode of the file, or <c>eof</c> if the requested position
was beyond end of file.</p>
@@ -1199,76 +1073,53 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>pread(IoDevice, Location, Number) -> {ok, Data} | eof | {error, Reason}</name>
+ <name name="pread" arity="3"/>
<fsummary>Read from a file at a certain position</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Location -- see position/2</v>
- <v>Number = int()</v>
- <v>Data = [char()] | binary()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
<p>Combines <c>position/2</c> and <c>read/2</c> in one
operation, which is more efficient than calling them one at a
- time. If <c>IoDevice</c> has been opened in raw mode, some
- restrictions apply: <c>Location</c> is only allowed to be an
+ time. If <c><anno>IoDevice</anno></c> has been opened in raw mode,
+ some restrictions apply: <c><anno>Location</anno></c> is only allowed
+ to be an
integer; and the current position of the file is undefined
after the operation.</p>
<p>As the position is given as a byte-offset, special caution has to be taken when working with files where <c>encoding</c> is set to something else than <c>latin1</c>, as not every byte position will be a valid character boundary on such a file.</p>
</desc>
</func>
<func>
- <name>pwrite(IoDevice, LocBytes) -> ok | {error, {N, Reason}}</name>
+ <name name="pwrite" arity="2"/>
<fsummary>Write to a file at certain positions</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>LocBytes = [{Location, Bytes}]</v>
- <v>&nbsp;Location -- see position/2</v>
- <v>&nbsp;Bytes = iodata()</v>
- <v>N = int()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
<p>Performs a sequence of <c>pwrite/3</c> in one operation,
which is more efficient than calling them one at a time.
- Returns <c>ok</c> or <c>{error, {N, Reason}}</c>, where
- <c>N</c> is the number of successful writes that was done
+ Returns <c>ok</c> or <c>{error, {<anno>N</anno>,
+ <anno>Reason</anno>}}</c>, where
+ <c><anno>N</anno></c> is the number of successful writes that was done
before the failure.</p>
<p>When positioning in a file with other <c>encoding</c> than <c>latin1</c>, caution must be taken to set the position on a correct character boundary, see <seealso marker="#position/2">position/2</seealso> for details.</p>
</desc>
</func>
<func>
- <name>pwrite(IoDevice, Location, Bytes) -> ok | {error, Reason}</name>
+ <name name="pwrite" arity="3"/>
<fsummary>Write to a file at a certain position</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Location -- see position/2</v>
- <v>Bytes = iodata()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
<p>Combines <c>position/2</c> and <c>write/2</c> in one
operation, which is more efficient than calling them one at a
- time. If <c>IoDevice</c> has been opened in raw mode, some
- restrictions apply: <c>Location</c> is only allowed to be an
+ time. If <c><anno>IoDevice</anno></c> has been opened in raw mode,
+ some restrictions apply: <c><anno>Location</anno></c> is only allowed
+ to be an
integer; and the current position of the file is undefined
after the operation.</p>
<p>When positioning in a file with other <c>encoding</c> than <c>latin1</c>, caution must be taken to set the position on a correct character boundary, see <seealso marker="#position/2">position/2</seealso> for details.</p>
</desc>
</func>
<func>
- <name>read(IoDevice, Number) -> {ok, Data} | eof | {error, Reason}</name>
+ <name name="read" arity="2"/>
<fsummary>Read from a file</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Number = int()</v>
- <v>Data = [char()] | binary()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
- <p>Reads <c>Number</c> bytes/characters from the file referenced by
- <c>IoDevice</c>. The functions <c>read/2</c>, <c>pread/3</c>
+ <p>Reads <c><anno>Number</anno></c> bytes/characters from the file
+ referenced by <c><anno>IoDevice</anno></c>. The functions
+ <c>read/2</c>, <c>pread/3</c>
and <c>read_line/1</c> are the only ways to read from a file
opened in raw mode (although they work for normally opened
files, too).</p>
@@ -1276,7 +1127,7 @@ f.txt: {person, "kalle", 25}.
<p>Also if <c>encoding</c> is set to something else than <c>latin1</c>, the <c>read/3</c> call will fail if the data contains characters larger than 255, why the <seealso marker="stdlib:io">io(3)</seealso> module is to be preferred when reading such a file.</p>
<p>The function returns:</p>
<taglist>
- <tag><c>{ok, Data}</c></tag>
+ <tag><c>{ok, <anno>Data</anno>}</c></tag>
<item>
<p>If the file was opened in binary mode, the read bytes are
returned in a binary, otherwise in a list. The list or
@@ -1285,10 +1136,10 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>eof</c></tag>
<item>
- <p>Returned if <c>Number>0</c> and end of file was reached
- before anything at all could be read.</p>
+ <p>Returned if <c><anno>Number</anno>>0</c> and end of file was
+ reached before anything at all could be read.</p>
</item>
- <tag><c>{error, Reason}</c></tag>
+ <tag><c>{error, <anno>Reason</anno>}</c></tag>
<item>
<p>An error occurred.</p>
</item>
@@ -1307,17 +1158,14 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>read_file(Filename) -> {ok, Binary} | {error, Reason}</name>
+ <name name="read_file" arity="1"/>
<fsummary>Read a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Binary = binary()</v>
- <v>Reason = ext_posix() | terminated | system_limit</v>
- </type>
<desc>
- <p>Returns <c>{ok, Binary}</c>, where <c>Binary</c> is a binary
- data object that contains the contents of <c>Filename</c>, or
- <c>{error, Reason}</c> if an error occurs.</p>
+ <p>Returns <c>{ok, <anno>Binary</anno>}</c>, where
+ <c><anno>Binary</anno></c> is a binary
+ data object that contains the contents of
+ <c><anno>Filename</anno></c>, or
+ <c>{error, <anno>Reason</anno>}</c> if an error occurs.</p>
<p>Typical error reasons:</p>
<taglist>
<tag><c>enoent</c></tag>
@@ -1346,17 +1194,13 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>read_file_info(Filename) -> {ok, FileInfo} | {error, Reason}</name>
+ <name name="read_file_info" arity="1"/>
<fsummary>Get information about a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>FileInfo = #file_info{}</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Retrieves information about a file. Returns
- <c>{ok, FileInfo}</c> if successful, otherwise
- <c>{error, Reason}</c>. <c>FileInfo</c> is a record
+ <c>{ok, <anno>FileInfo</anno>}</c> if successful, otherwise
+ <c>{error, <anno>Reason</anno>}</c>. <c><anno>FileInfo</anno></c>
+ is a record
<c>file_info</c>, defined in the Kernel include file
<c>file.hrl</c>. Include the following directive in the module
from which the function is called:</p>
@@ -1364,7 +1208,7 @@ f.txt: {person, "kalle", 25}.
-include_lib("kernel/include/file.hrl").</code>
<p>The record <c>file_info</c> contains the following fields.</p>
<taglist>
- <tag><c>size = int()</c></tag>
+ <tag><c>size = integer()</c></tag>
<item>
<p>Size of file in bytes.</p>
</item>
@@ -1391,7 +1235,7 @@ f.txt: {person, "kalle", 25}.
the file or the inode was changed. In Windows, it is
the create time.</p>
</item>
- <tag><c>mode = int()</c></tag>
+ <tag><c>mode = integer()</c></tag>
<item>
<p>The file permissions as the sum of the following bit
values:</p>
@@ -1422,33 +1266,33 @@ f.txt: {person, "kalle", 25}.
<p>On Unix platforms, other bits than those listed above
may be set.</p>
</item>
- <tag><c>links = int()</c></tag>
+ <tag><c>links = integer()</c></tag>
<item>
<p>Number of links to the file (this will always be 1 for
file systems which have no concept of links).</p>
</item>
- <tag><c>major_device = int()</c></tag>
+ <tag><c>major_device = integer()</c></tag>
<item>
<p>Identifies the file system where the file is located.
In Windows, the number indicates a drive as follows:
0 means A:, 1 means B:, and so on.</p>
</item>
- <tag><c>minor_device = int()</c></tag>
+ <tag><c>minor_device = integer()</c></tag>
<item>
<p>Only valid for character devices on Unix. In all other
cases, this field is zero.</p>
</item>
- <tag><c>inode = int()</c></tag>
+ <tag><c>inode = integer()</c></tag>
<item>
<p>Gives the <c>inode</c> number. On non-Unix file systems,
this field will be zero.</p>
</item>
- <tag><c>uid = int()</c></tag>
+ <tag><c>uid = integer()</c></tag>
<item>
<p>Indicates the owner of the file. Will be zero for
non-Unix file systems.</p>
</item>
- <tag><c>gid = int()</c></tag>
+ <tag><c>gid = integer()</c></tag>
<item>
<p>Gives the group that the owner of the file belongs to.
Will be zero for non-Unix file systems.</p>
@@ -1474,21 +1318,16 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>read_line(IoDevice) -> {ok, Data} | eof | {error, Reason}</name>
+ <name name="read_line" arity="1"/>
<fsummary>Read a line from a file</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Data = [char()] | binary()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
<p>Reads a line of bytes/characters from the file referenced by
- <c>IoDevice</c>. Lines are defined to be delimited by the linefeed (LF, <c>\n</c>) character, but any carriage return (CR, <c>\r</c>) followed by a newline is also treated as a single LF character (the carriage return is silently ignored). The line is returned <em>including</em> the LF, but excluding any CR immediately followed by a LF. This behaviour is consistent with the behaviour of <seealso marker="stdlib:io#get_line/2">io:get_line/2</seealso>. If end of file is reached without any LF ending the last line, a line with no trailing LF is returned.</p>
+ <c><anno>IoDevice</anno></c>. Lines are defined to be delimited by the linefeed (LF, <c>\n</c>) character, but any carriage return (CR, <c>\r</c>) followed by a newline is also treated as a single LF character (the carriage return is silently ignored). The line is returned <em>including</em> the LF, but excluding any CR immediately followed by a LF. This behaviour is consistent with the behaviour of <seealso marker="stdlib:io#get_line/2">io:get_line/2</seealso>. If end of file is reached without any LF ending the last line, a line with no trailing LF is returned.</p>
<p>The function can be used on files opened in <c>raw</c> mode. It is however inefficient to use it on <c>raw</c> files if the file is not opened with the option <c>{read_ahead, Size}</c> specified, why combining <c>raw</c> and <c>{read_ahead, Size}</c> is highly recommended when opening a text file for raw line oriented reading.</p>
<p>If <c>encoding</c> is set to something else than <c>latin1</c>, the <c>read_line/1</c> call will fail if the data contains characters larger than 255, why the <seealso marker="stdlib:io">io(3)</seealso> module is to be preferred when reading such a file.</p>
<p>The function returns:</p>
<taglist>
- <tag><c>{ok, Data}</c></tag>
+ <tag><c>{ok, <anno>Data</anno>}</c></tag>
<item>
<p>One line from the file is returned, including the trailing LF, but with CRLF sequences replaced by a single LF (see above).</p>
<p>If the file was opened in binary mode, the read bytes are
@@ -1499,7 +1338,7 @@ f.txt: {person, "kalle", 25}.
<p>Returned if end of file was reached
before anything at all could be read.</p>
</item>
- <tag><c>{error, Reason}</c></tag>
+ <tag><c>{error, <anno>Reason</anno>}</c></tag>
<item>
<p>An error occurred.</p>
</item>
@@ -1518,23 +1357,19 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>read_link(Name) -> {ok, Filename} | {error, Reason}</name>
+ <name name="read_link" arity="1"/>
<fsummary>See what a link is pointing to</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Filename = string()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p>This function returns <c>{ok, Filename}</c> if <c>Name</c>
- refers to a symbolic link or <c>{error, Reason}</c> otherwise.
+ <p>This function returns <c>{ok, <anno>Filename</anno>}</c> if
+ <c><anno>Name</anno></c> refers to a symbolic link or
+ <c>{error, <anno>Reason</anno>}</c> otherwise.
On platforms that do not support symbolic links, the return
value will be <c>{error,enotsup}</c>.</p>
<p>Typical error reasons:</p>
<taglist>
<tag><c>einval</c></tag>
<item>
- <p><c>Linkname</c> does not refer to a symbolic link.</p>
+ <p><c><anno>Name</anno></c> does not refer to a symbolic link.</p>
</item>
<tag><c>enoent</c></tag>
<item>
@@ -1548,34 +1383,26 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>read_link_info(Name) -> {ok, FileInfo} | {error, Reason}</name>
+ <name name="read_link_info" arity="1"/>
<fsummary>Get information about a link or file</fsummary>
- <type>
- <v>Name = name()</v>
- <v>FileInfo = #file_info{}, see read_file_info/1</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>This function works like <c>read_file_info/1</c>, except that
- if <c>Name</c> is a symbolic link, information about the link
- will be returned in the <c>file_info</c> record and
+ if <c><anno>Name</anno></c> is a symbolic link, information about
+ the link will be returned in the <c>file_info</c> record and
the <c>type</c> field of the record will be set to
<c>symlink</c>.</p>
- <p>If <c>Name</c> is not a symbolic link, this function returns
+ <p>If <c><anno>Name</anno></c> is not a symbolic link, this function returns
exactly the same result as <c>read_file_info/1</c>.
On platforms that do not support symbolic links, this function
is always equivalent to <c>read_file_info/1</c>.</p>
</desc>
</func>
<func>
- <name>rename(Source, Destination) -> ok | {error, Reason}</name>
+ <name name="rename" arity="2"/>
<fsummary>Rename a file</fsummary>
- <type>
- <v>Source = Destination = name()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
- <p>Tries to rename the file <c>Source</c> to <c>Destination</c>.
+ <p>Tries to rename the file <c><anno>Source</anno></c> to
+ <c><anno>Destination</anno></c>.
It can be used to move files (and directories) between
directories, but it is not sufficient to specify
the destination only. The destination file name must also be
@@ -1593,25 +1420,28 @@ f.txt: {person, "kalle", 25}.
<tag><c>eacces</c></tag>
<item>
<p>Missing read or write permissions for the parent
- directories of <c>Source</c> or <c>Destination</c>. On
+ directories of <c><anno>Source</anno></c> or
+ <c><anno>Destination</anno></c>. On
some platforms, this error is given if either
- <c>Source</c> or <c>Destination</c> is open.</p>
+ <c><anno>Source</anno></c> or <c><anno>Destination</anno></c>
+ is open.</p>
</item>
<tag><c>eexist</c></tag>
<item>
- <p><c>Destination</c> is not an empty directory. On some
- platforms, also given when <c>Source</c> and
- <c>Destination</c> are not of the same type.</p>
+ <p><c><anno>Destination</anno></c> is not an empty directory.
+ On some platforms, also given when <c><anno>Source</anno></c> and
+ <c><anno>Destination</anno></c> are not of the same type.</p>
</item>
<tag><c>einval</c></tag>
<item>
- <p><c>Source</c> is a root directory, or <c>Destination</c>
- is a sub-directory of <c>Source</c>.</p>
+ <p><c><anno>Source</anno></c> is a root directory, or
+ <c><anno>Destination</anno></c>
+ is a sub-directory of <c><anno>Source</anno></c>.</p>
</item>
<tag><c>eisdir</c></tag>
<item>
- <p><c>Destination</c> is a directory, but <c>Source</c> is
- not.</p>
+ <p><c><anno>Destination</anno></c> is a directory, but
+ <c><anno>Source</anno></c> is not.</p>
</item>
<tag><c>enoent</c></tag>
<item>
@@ -1619,35 +1449,28 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>enotdir</c></tag>
<item>
- <p><c>Source</c> is a directory, but <c>Destination</c> is
- not.</p>
+ <p><c><anno>Source</anno></c> is a directory, but
+ <c><anno>Destination</anno></c> is not.</p>
</item>
<tag><c>exdev</c></tag>
<item>
- <p><c>Source</c> and <c>Destination</c> are on different
- file systems.</p>
+ <p><c><anno>Source</anno></c> and <c><anno>Destination</anno></c>
+ are on different file systems.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>script(Filename) -> {ok, Value} | {error, Reason}</name>
+ <name name="script" arity="1"/>
<fsummary>Evaluate and return the value of Erlang expressions in a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Value = term()</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see below</v>
- </type>
<desc>
<p>Reads and evaluates Erlang expressions, separated by '.' (or
',', a sequence of expressions is also an expression), from
the file. Returns one of the following:</p>
<taglist>
- <tag><c>{ok, Value}</c></tag>
+ <tag><c>{ok, <anno>Value</anno>}</c></tag>
<item>
- <p>The file was read and evaluated. <c>Value</c> is
+ <p>The file was read and evaluated. <c><anno>Value</anno></c> is
the value of the last expression.</p>
</item>
<tag><c>{error, atom()}</c></tag>
@@ -1656,7 +1479,8 @@ f.txt: {person, "kalle", 25}.
See <seealso marker="#open/2">open/2</seealso> for a list
of typical error codes.</p>
</item>
- <tag><c>{error, {Line, Mod, Term}}</c></tag>
+ <tag><c>{error, {<anno>Line</anno>, <anno>Mod</anno>,
+ <anno>Term</anno>}}</c></tag>
<item>
<p>An error occurred when interpreting the Erlang
expressions in the file. Use <c>format_error/1</c> to
@@ -1667,33 +1491,21 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>script(Filename, Bindings) -> {ok, Value} | {error, Reason}</name>
+ <name name="script" arity="2"/>
<fsummary>Evaluate and return the value of Erlang expressions in a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Bindings -- see erl_eval(3)</v>
- <v>Value = term()</v>
- <v>Reason = ext_posix() | terminated | system_limit
- | {Line, Mod, Term}</v>
- <v>&nbsp;Line, Mod, Term -- see below</v>
- </type>
<desc>
<p>The same as <c>script/1</c> but the variable bindings
- <c>Bindings</c> are used in the evaluation. See
+ <c><anno>Bindings</anno></c> are used in the evaluation. See
<seealso marker="stdlib:erl_eval">erl_eval(3)</seealso> about
variable bindings.</p>
</desc>
</func>
<func>
- <name>set_cwd(Dir) -> ok | {error,Reason}</name>
+ <name name="set_cwd" arity="1"/>
<fsummary>Set the current working directory</fsummary>
- <type>
- <v>Dir = name()</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Sets the current working directory of the file server to
- <c>Dir</c>. Returns <c>ok</c> if successful.</p>
+ <c><anno>Dir</anno></c>. Returns <c>ok</c> if successful.</p>
<p>Typical error reasons are:</p>
<taglist>
<tag><c>enoent</c></tag>
@@ -1702,8 +1514,8 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>enotdir</c></tag>
<item>
- <p>A component of <c>Dir</c> is not a directory. On some
- platforms, <c>enoent</c> is returned.</p>
+ <p>A component of <c><anno>Dir</anno></c> is not a directory.
+ On some platforms, <c>enoent</c> is returned.</p>
</item>
<tag><c>eacces</c></tag>
<item>
@@ -1712,23 +1524,21 @@ f.txt: {person, "kalle", 25}.
</item>
<tag><c>badarg</c></tag>
<item>
- <p><c>Filename</c> had an improper type, such as tuple.</p>
+ <p><c><anno>Dir</anno></c> had an improper type,
+ such as tuple.</p>
</item>
</taglist>
<warning>
- <p>In a future release, a bad type for the <c>Filename</c>
+ <p>In a future release, a bad type for the
+ <c><anno>Dir</anno></c>
argument will probably generate an exception.</p>
<p></p>
</warning>
</desc>
</func>
<func>
- <name>sync(IoDevice) -> ok | {error, Reason}</name>
+ <name name="sync" arity="1"/>
<fsummary>Synchronizes the in-memory state of a file with that on the physical medium</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
<p>Makes sure that any buffers kept by the operating system
(not by the Erlang runtime system) are written to disk. On
@@ -1743,12 +1553,8 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>datasync(IoDevice) -> ok | {error, Reason}</name>
+ <name name="datasync" arity="1"/>
<fsummary>Synchronizes the in-memory data of a file, ignoring most of its metadata, with that on the physical medium</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
<p>Makes sure that any buffers kept by the operating system
(not by the Erlang runtime system) are written to disk. In
@@ -1770,32 +1576,23 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>truncate(IoDevice) -> ok | {error, Reason}</name>
+ <name name="truncate" arity="1"/>
<fsummary>Truncate a file</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
- <p>Truncates the file referenced by <c>IoDevice</c> at
+ <p>Truncates the file referenced by <c><anno>IoDevice</anno></c> at
the current position. Returns <c>ok</c> if successful,
- otherwise <c>{error, Reason}</c>.</p>
+ otherwise <c>{error, <anno>Reason</anno>}</c>.</p>
</desc>
</func>
<func>
- <name>write(IoDevice, Bytes) -> ok | {error, Reason}</name>
+ <name name="write" arity="2"/>
<fsummary>Write to a file</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Bytes = iodata()</v>
- <v>Reason = ext_posix() | terminated</v>
- </type>
<desc>
- <p>Writes <c>Bytes</c> to the file referenced by
- <c>IoDevice</c>. This function is the only way to write to a
+ <p>Writes <c><anno>Bytes</anno></c> to the file referenced by
+ <c><anno>IoDevice</anno></c>. This function is the only way to write to a
file opened in raw mode (although it works for normally
opened files, too). Returns <c>ok</c> if successful, and
- <c>{error, Reason}</c> otherwise.</p>
+ <c>{error, <anno>Reason</anno>}</c> otherwise.</p>
<p>If the file is opened with <c>encoding</c> set to something else than <c>latin1</c>, each byte written might result in several bytes actually being written to the file, as the byte range 0..255 might represent anything between one and four bytes depending on value and UTF encoding type.</p>
<p>Typical error reasons are:</p>
<taglist>
@@ -1811,18 +1608,14 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>write_file(Filename, Bytes) -> ok | {error, Reason}</name>
+ <name name="write_file" arity="2"/>
<fsummary>Write a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Bytes = iodata()</v>
- <v>Reason = ext_posix() | terminated | system_limit</v>
- </type>
<desc>
- <p>Writes the contents of the iodata term <c>Bytes</c> to the
- file <c>Filename</c>. The file is created if it does not
+ <p>Writes the contents of the iodata term <c><anno>Bytes</anno></c>
+ to the file <c><anno>Filename</anno></c>.
+ The file is created if it does not
exist. If it exists, the previous contents are
- overwritten. Returns <c>ok</c>, or <c>{error, Reason}</c>.</p>
+ overwritten. Returns <c>ok</c>, or <c>{error, <anno>Reason</anno>}</c>.</p>
<p>Typical error reasons are:</p>
<taglist>
<tag><c>enoent</c></tag>
@@ -1851,33 +1644,23 @@ f.txt: {person, "kalle", 25}.
</desc>
</func>
<func>
- <name>write_file(Filename, Bytes, Modes) -> ok | {error, Reason}</name>
+ <name name="write_file" arity="3"/>
<fsummary>Write a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Bytes = iodata()</v>
- <v>Modes = [Mode] -- see open/2</v>
- <v>Reason = ext_posix() | terminated | system_limit</v>
- </type>
<desc>
<p>Same as <c>write_file/2</c>, but takes a third argument
- <c>Modes</c>, a list of possible modes, see
+ <c><anno>Modes</anno></c>, a list of possible modes, see
<seealso marker="#open/2">open/2</seealso>. The mode flags
<c>binary</c> and <c>write</c> are implicit, so they should
not be used.</p>
</desc>
</func>
<func>
- <name>write_file_info(Filename, FileInfo) -> ok | {error, Reason}</name>
+ <name name="write_file_info" arity="2"/>
<fsummary>Change information about a file</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>FileInfo = #file_info{} -- see also read_file_info/1</v>
- <v>Reason = ext_posix()</v>
- </type>
<desc>
<p>Change file information. Returns <c>ok</c> if successful,
- otherwise <c>{error, Reason}</c>. <c>FileInfo</c> is a record
+ otherwise <c>{error, <anno>Reason</anno>}</c>.
+ <c><anno>FileInfo</anno></c> is a record
<c>file_info</c>, defined in the Kernel include file
<c>file.hrl</c>. Include the following directive in the module
from which the function is called:</p>
@@ -1901,7 +1684,7 @@ f.txt: {person, "kalle", 25}.
time). On Windows, this field is the new creation time to
set for the file.</p>
</item>
- <tag><c>mode = int()</c></tag>
+ <tag><c>mode = integer()</c></tag>
<item>
<p>The file permissions as the sum of the following bit
values:</p>
@@ -1932,12 +1715,12 @@ f.txt: {person, "kalle", 25}.
<p>On Unix platforms, other bits than those listed above
may be set.</p>
</item>
- <tag><c>uid = int()</c></tag>
+ <tag><c>uid = integer()</c></tag>
<item>
<p>Indicates the owner of the file. Ignored for non-Unix
file systems.</p>
</item>
- <tag><c>gid = int()</c></tag>
+ <tag><c>gid = integer()</c></tag>
<item>
<p>Gives the group that the owner of the file belongs to.
Ignored non-Unix file systems.</p>
diff --git a/lib/kernel/doc/src/gen_sctp.xml b/lib/kernel/doc/src/gen_sctp.xml
index fb09092f1c..5ceb82ae41 100644
--- a/lib/kernel/doc/src/gen_sctp.xml
+++ b/lib/kernel/doc/src/gen_sctp.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2007</year><year>2010</year>
+ <year>2007</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -65,77 +65,71 @@
<item><seealso marker="#seealso">SEE ALSO</seealso></item>
<item><seealso marker="#authors">AUTHORS</seealso></item>
</list>
+ <marker id="types"></marker>
</section>
- <section>
- <marker id="types"></marker>
- <title>DATA TYPES</title>
- <marker id="type-assoc_id"></marker>
- <taglist>
- <tag><c>assoc_id()</c></tag>
- <item>
+ <datatypes>
+ <datatype>
+ <name name="assoc_id"/>
+ <desc>
<p>An opaque term returned in for example #sctp_paddr_change{}
that identifies an association for an SCTP socket. The term
is opaque except for the special value <c>0</c> that has a
- meaning such as "the whole endpoint" or "all future associations".</p>
- <marker id="type-charlist"></marker>
- </item>
- <tag><c>charlist() = [char()]</c></tag>
- <item> <marker id="type-iolist"></marker>
-</item>
- <tag><c>iolist() = [char() | binary()]</c></tag>
- <item> <marker id="type-ip_address"></marker>
-</item>
- <tag><c>ip_address()</c></tag>
- <item>
+ meaning such as "the whole endpoint" or "all future associations".
+ </p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="hostname"/>
+ </datatype>
+ <datatype>
+ <name name="ip_address"/>
+ <desc>
<p>Represents an address of an SCTP socket.
It is a tuple as explained in
<seealso marker="inet">inet(3)</seealso>.</p>
- <marker id="type-port_number"></marker>
- </item>
- <tag><c>port_number() = 0 .. 65535</c></tag>
- <item> <marker id="type-posix"></marker>
-</item>
- <tag><c>posix()</c></tag>
- <item>
- <p>See
- <seealso marker="inet#error_codes">inet(3); POSIX Error Codes.</seealso></p>
- <marker id="type-sctp_option"></marker>
- </item>
- <tag><c>sctp_option()</c></tag>
- <item>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="port_number"/>
+ </datatype>
+ <datatype>
+ <name name="posix"/>
+ <desc>
+ <p>See <seealso marker="inet#error_codes">
+ inet(3); POSIX Error Codes</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="sctp_option"/>
+ <desc>
<p>One of the
<seealso marker="#options">SCTP Socket Options.</seealso></p>
<marker id="type-sctp_socket"></marker>
- </item>
- <tag><c>sctp_socket()</c></tag>
- <item>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="sctp_socket"/>
+ <desc>
<p>Socket identifier returned from <c>open/*</c>.</p>
- <marker id="type-timeout"></marker>
- </item>
- <tag><c>timeout() = int() | infinity</c></tag>
- <item>
- <p>Timeout used in SCTP connect and receive calls.</p>
- </item>
- </taglist>
- <marker id="exports"></marker>
- </section>
+ <marker id="exports"></marker>
+ </desc>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
- <name>abort(sctp_socket(), Assoc) -&gt; ok | {error, posix()}</name>
+ <name name="abort" arity="2"/>
<fsummary>Abnormally terminate the association given by Assoc, without flushing of unsent data</fsummary>
- <type>
- <v>Assoc = #sctp_assoc_change{}</v>
- </type>
<desc>
- <p>Abnormally terminates the association given by <c>Assoc</c>, without
+ <p>Abnormally terminates the association given by <c><anno>Assoc</anno></c>, without
flushing of unsent data. The socket itself remains open. Other
associations opened on this socket are still valid, and it can be
used in new associations.</p>
</desc>
</func>
<func>
- <name>close(sctp_socket()) -&gt; ok | {error, posix()}</name>
+ <name name="close" arity="1"/>
<fsummary>Completely close the socket and all associations on it</fsummary>
<desc>
<p>Completely closes the socket and all associations on it. The unsent
@@ -148,35 +142,26 @@
</desc>
</func>
<func>
- <name>connect(Socket, Addr, Port, Opts) -&gt; {ok,Assoc} | {error, posix()}</name>
+ <name name="connect" arity="4"/>
<fsummary>Same as <c>connect(Socket, Addr, Port, Opts, infinity)</c>.</fsummary>
<desc>
- <p>Same as <c>connect(Socket, Addr, Port, Opts, infinity)</c>.</p>
+ <p>Same as <c>connect(<anno>Socket</anno>, <anno>Addr</anno>, <anno>Port</anno>, <anno>Opts</anno>, infinity)</c>.</p>
</desc>
</func>
<func>
- <name>connect(Socket, Addr, Port, [Opt], Timeout) -&gt; {ok, Assoc} | {error, posix()}</name>
+ <name name="connect" arity="5"/>
<fsummary>Establish a new association for the socket <c>Socket</c>, with a peer (SCTP server socket)</fsummary>
- <type>
- <v>Socket = sctp_socket()</v>
- <v>Addr = ip_address() | Host</v>
- <v>Port = port_number()</v>
- <v>Opt = sctp_option()</v>
- <v>Timeout = timeout()</v>
- <v>Host = atom() | string()</v>
- <v>Assoc = #sctp_assoc_change{}</v>
- </type>
<desc>
- <p>Establishes a new association for the socket <c>Socket</c>,
+ <p>Establishes a new association for the socket <c><anno>Socket</anno></c>,
with the peer (SCTP server socket) given by
- <c>Addr</c> and <c>Port</c>. The <c>Timeout</c>,
+ <c><anno>Addr</anno></c> and <c><anno>Port</anno></c>. The <c><anno>Timeout</anno></c>,
is expressed in milliseconds. A socket can be associated with multiple peers.</p>
- <p><b>WARNING:</b>Using a value of <c>Timeout</c> less than
+ <p><b>WARNING:</b>Using a value of <c><anno>Timeout</anno></c> less than
the maximum time taken by the OS to establish an association (around 4.5 minutes
if the default values from RFC 4960 are used) can result in
inconsistent or incorrect return values. This is especially
- relevant for associations sharing the same <c>Socket</c>
+ relevant for associations sharing the same <c><anno>Socket</anno></c>
(i.e. source address and port) since the controlling process
blocks until <c>connect/*</c> returns.
<seealso marker="#connect_init/4">connect_init/*</seealso>
@@ -185,7 +170,7 @@
<p><marker id="record-sctp_assoc_change"></marker>
The result of <c>connect/*</c> is an <c>#sctp_assoc_change{}</c>
event which contains, in particular, the new
- <seealso marker="#type-assoc_id">Association ID:</seealso></p>
+ <seealso marker="#type-assoc_id">Association ID</seealso>.</p>
<pre>
#sctp_assoc_change{
state = atom(),
@@ -198,13 +183,13 @@
giving an <c>sctp_initmsg</c> option to <c>connect</c>
as in:</p>
<pre>
- connect(Socket, Ip, Port,
+ connect(<anno>Socket</anno>, Ip, <anno>Port</anno>,
[{sctp_initmsg,#sctp_initmsg{num_ostreams=OutStreams,
max_instreams=MaxInStreams}}]) </pre>
- <p>All options <c>Opt</c> are set on the socket before the
+ <p>All options <c><anno>Opt</anno></c> are set on the socket before the
association is attempted. If an option record has got undefined
field values, the options record is first read from the socket
- for those values. In effect, <c>Opt</c> option records only
+ for those values. In effect, <c><anno>Opt</anno></c> option records only
define field values to change before connecting.</p>
<p>The returned <c>outbound_streams</c> and <c>inbound_streams</c>
are the actual stream numbers on the socket, which may be different
@@ -242,27 +227,19 @@
</desc>
</func>
<func>
- <name>connect_init(Socket, Addr, Port, Opts) -&gt; ok | {error, posix()}</name>
+ <name name="connect_init" arity="4"/>
<fsummary>Same as <c>connect_init(Socket, Addr, Port, Opts, infinity)</c>.</fsummary>
<desc>
- <p>Same as <c>connect_init(Socket, Addr, Port, Opts, infinity)</c>.</p>
+ <p>Same as <c>connect_init(<anno>Socket</anno>, <anno>Addr</anno>, <anno>Port</anno>, <anno>Opts</anno>, infinity)</c>.</p>
</desc>
</func>
<func>
- <name>connect_init(Socket, Addr, Port, [Opt], Timeout) -&gt; ok | {error, posix()}</name>
+ <name name="connect_init" arity="5"/>
<fsummary>Initiate a new association for the socket <c>Socket</c>, with a peer (SCTP server socket)</fsummary>
- <type>
- <v>Socket = sctp_socket()</v>
- <v>Addr = ip_address() | Host</v>
- <v>Port = port_number()</v>
- <v>Opt = sctp_option()</v>
- <v>Timeout = timeout()</v>
- <v>Host = atom() | string()</v>
- </type>
<desc>
- <p>Initiates a new association for the socket <c>Socket</c>,
+ <p>Initiates a new association for the socket <c><anno>Socket</anno></c>,
with the peer (SCTP server socket) given by
- <c>Addr</c> and <c>Port</c>.</p>
+ <c><anno>Addr</anno></c> and <c><anno>Port</anno></c>.</p>
<p>The fundamental difference between this API
and <c>connect/*</c> is that the return value is that of the
underlying OS connect(2) system call. If <c>ok</c> is returned
@@ -275,64 +252,52 @@
active option.</p>
<p>The parameters are as described
in <seealso marker="#connect/5">connect/*</seealso>, with the
- exception of the <c>Timeout</c> value.</p>
- <p>The timer associated with <c>Timeout</c> only supervises
- IP resolution of <c>Addr</c></p>
+ exception of the <c><anno>Timeout</anno></c> value.</p>
+ <p>The timer associated with <c><anno>Timeout</anno></c> only supervises
+ IP resolution of <c><anno>Addr</anno></c></p>
</desc>
</func>
<func>
- <name>controlling_process(sctp_socket(), pid()) -&gt; ok</name>
+ <name name="controlling_process" arity="2"/>
<fsummary>Assign a new controlling process pid to the socket</fsummary>
<desc>
- <p>Assigns a new controlling process Pid to Socket. Same implementation
+ <p>Assigns a new controlling process <c><anno>Pid</anno></c> to <c><anno>Socket</anno></c>. Same implementation
as <c>gen_udp:controlling_process/2</c>.</p>
</desc>
</func>
<func>
- <name>eof(Socket, Assoc) -&gt; ok | {error, Reason}</name>
+ <name name="eof" arity="2"/>
<fsummary>Gracefully terminate the association given by Assoc, with flushing of all unsent data</fsummary>
- <type>
- <v>Socket = sctp_socket()</v>
- <v>Assoc = #sctp_assoc_change{}</v>
- </type>
<desc>
- <p>Gracefully terminates the association given by <c>Assoc</c>, with
+ <p>Gracefully terminates the association given by <c><anno>Assoc</anno></c>, with
flushing of all unsent data. The socket itself remains open. Other
associations opened on this socket are still valid, and it can be
used in new associations.</p>
</desc>
</func>
<func>
- <name>listen(Socket, IsServer) -&gt; ok | {error, Reason}</name>
+ <name name="listen" arity="2"/>
<fsummary>Set up a socket to listen.</fsummary>
- <type>
- <v>Socket = sctp_socket()</v>
- <v>IsServer = bool()</v>
- </type>
<desc>
<p>Sets up a socket to listen on the IP address and port number
- it is bound to. IsServer must be 'true' or 'false'.
+ it is bound to. <c><anno>IsServer</anno></c> must be <c>true</c>
+ or <c>false</c>.
In the contrast to TCP, in SCTP there is no listening queue length.
- If IsServer is 'true' the socket accepts new associations, i.e.
+ If <c><anno>IsServer</anno></c> is <c>true</c> the socket accepts new associations, i.e.
it will become an SCTP server socket.</p>
</desc>
</func>
<func>
- <name>open() -&gt; {ok, Socket} | {error, posix()}</name>
- <name>open(Port) -&gt; {ok, Socket} | {error, posix()}</name>
- <name>open([Opt]) -&gt; {ok, Socket} | {error, posix()}</name>
- <name>open(Port, [Opt]) -&gt; {ok, Socket} | {error, posix()}</name>
+ <name name="open" arity="0"/>
+ <name name="open" arity="1" clause_i="1"/>
+ <name name="open" arity="1" clause_i="2"/>
+ <name name="open" arity="2"/>
<fsummary>Create an SCTP socket and bind it to local addresses</fsummary>
- <type>
- <v>Opt = {ip,IP} | {ifaddr,IP} | {port,Port} | sctp_option()</v>
- <v>IP = ip_address() | any | loopback</v>
- <v>Port = port_number()</v>
- </type>
<desc>
<p>Creates an SCTP socket and binds it to the local addresses
- specified by all <c>{ip,IP}</c> (or synonymously <c>{ifaddr,IP}</c>)
+ specified by all <c>{ip,<anno>IP</anno>}</c> (or synonymously <c>{ifaddr,<anno>IP</anno>}</c>)
options (this feature is called SCTP multi-homing).
- The default <c>IP</c> and <c>Port</c> are <c>any</c>
+ The default <c><anno>IP</anno></c> and <c><anno>Port</anno></c> are <c>any</c>
and <c>0</c>, meaning bind to all local addresses on any
one free port.</p>
<p>A default set of socket <seealso marker="#options">options</seealso>
@@ -345,27 +310,16 @@
</desc>
</func>
<func>
- <name>recv(sctp_socket()) -&gt; {ok, {FromIP, FromPort, AncData, BinMsg}} | {error, Reason}</name>
- <name>recv(sctp_socket(), timeout()) -&gt; {ok, {FromIP, FromPort, AncData, Data}} | {error, Reason}</name>
+ <name name="recv" arity="1"/>
+ <name name="recv" arity="2"/>
<fsummary>Receive a message from a socket</fsummary>
- <type>
- <v>FromIP = ip_address()</v>
- <v>FromPort = port_number()</v>
- <v>AncData = [#sctp_sndrcvinfo{}]</v>
- <v>Data = binary() | charlist() | #sctp_sndrcvinfo{} |
- #sctp_assoc_change{} | #sctp_paddr_change{} |
- #sctp_adaptation_event{} </v>
- <v>Reason = posix() | #sctp_send_failed{} | #scpt_paddr_change{} |
- #sctp_pdapi_event{} | #sctp_remote_error{} |
- #sctp_shutdown_event{}</v>
- </type>
<desc>
- <p>Receives the <c>Data</c> message from any association of the socket.
+ <p>Receives the <c><anno>Data</anno></c> message from any association of the socket.
If the receive times out <c>{error,timeout</c> is returned.
The default timeout is <c>infinity</c>.
- <c>FromIP</c> and <c>FromPort</c> indicate the sender's address.</p>
- <p><c>AncData</c> is a list of Ancillary Data items which
- may be received along with the main <c>Data</c>.
+ <c><anno>FromIP</anno></c> and <c><anno>FromPort</anno></c> indicate the sender's address.</p>
+ <p><c><anno>AncData</anno></c> is a list of Ancillary Data items which
+ may be received along with the main <c><anno>Data</anno></c>.
This list can be empty, or contain a single
<seealso marker="#record-sctp_sndrcvinfo">#sctp_sndrcvinfo{}</seealso>
record, if receiving of such ancillary data is enabled
@@ -375,10 +329,10 @@
provide an easy way of determining the association and stream
over which the message has been received.
(An alternative way would be to get the Association ID from the
- <c>FromIP</c> and <c>FromPort</c> using the
+ <c><anno>FromIP</anno></c> and <c><anno>FromPort</anno></c> using the
<seealso marker="#option-sctp_get_peer_addr_info">sctp_get_peer_addr_info</seealso> socket option,
but this would still not produce the Stream number).</p>
- <p>The actual <c>Data</c> received may be a <c>binary()</c>,
+ <p>The actual <c><anno>Data</anno></c> received may be a <c>binary()</c>,
or <c>list()</c> of bytes (integers in the range 0 through 255)
depending on the socket mode, or an SCTP Event.
<marker id="sctp_events"></marker>
@@ -476,15 +430,10 @@
</desc>
</func>
<func>
- <name>send(Socket, SndRcvInfo, Data) -&gt; ok | {error, Reason}</name>
+ <name name="send" arity="3"/>
<fsummary>Send a message using an <c>#sctp_sndrcvinfo{}</c>record</fsummary>
- <type>
- <v>Socket = sctp_socket()</v>
- <v>SndRcvInfo = #sctp_sndrcvinfo{}</v>
- <v>Data = binary() | iolist()</v>
- </type>
<desc>
- <p>Sends the <c>Data</c> message with all sending parameters from a
+ <p>Sends the <c><anno>Data</anno></c> message with all sending parameters from a
<seealso marker="#record-sctp_sndrcvinfo">#sctp_sndrcvinfo{}</seealso> record.
This way, the user can specify the PPID (passed to the remote end)
and Context (passed to the local SCTP layer) which can be used
@@ -494,21 +443,15 @@
</desc>
</func>
<func>
- <name>send(Socket, Assoc, Stream, Data) -&gt; ok | {error, Reason}</name>
+ <name name="send" arity="4"/>
<fsummary>Send a message over an existing association and given stream</fsummary>
- <type>
- <v>Socket = sctp_socket()</v>
- <v>Assoc = #sctp_assoc_change{} | assoc_id()</v>
- <v>Stream = integer()</v>
- <v>Data = binary() | iolist()</v>
- </type>
<desc>
- <p>Sends <c>Data</c> message over an existing association and given
+ <p>Sends <c><anno>Data</anno></c> message over an existing association and given
stream.</p>
</desc>
</func>
<func>
- <name>error_string(integer()) -> ok | string() | undefined</name>
+ <name name="error_string" arity="1"/>
<fsummary>Translate an SCTP error number into a string</fsummary>
<desc>
<p>Translates an SCTP error number from for example
diff --git a/lib/kernel/doc/src/gen_tcp.xml b/lib/kernel/doc/src/gen_tcp.xml
index aa171c77c2..f1d42d9faa 100644
--- a/lib/kernel/doc/src/gen_tcp.xml
+++ b/lib/kernel/doc/src/gen_tcp.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2010</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -63,36 +63,45 @@ do_recv(Sock, Bs) ->
<p>For more examples, see the <seealso marker="#examples">examples</seealso> section.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-ip_address()
- see inet(3)
-
-posix()
- see inet(3)
+ <datatypes>
+ <datatype>
+ <name name="hostname"/>
+ </datatype>
+ <datatype>
+ <name name="ip_address"/>
+ <desc>
+ <p>Represents an address of a TCP socket.
+ It is a tuple as explained in
+ <seealso marker="inet">inet(3)</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="port_number"/>
+ </datatype>
+ <datatype>
+ <name name="posix"/>
+ <desc>
+ <p>See <seealso marker="inet#error_codes">
+ inet(3); POSIX Error Codes</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name><marker id="type-socket">socket()</marker></name>
+ <desc>
+ <p>As returned by accept/1,2 and connect/3,4.</p>
+ <marker id="connect"></marker>
+ </desc>
+ </datatype>
+ </datatypes>
-socket()
- as returned by accept/1,2 and connect/3,4</code>
- <marker id="connect"></marker>
- </section>
<funcs>
<func>
- <name>connect(Address, Port, Options) -> {ok, Socket} | {error, Reason}</name>
- <name>connect(Address, Port, Options, Timeout) -> {ok, Socket} | {error, Reason}</name>
+ <name name="connect" arity="3"/>
+ <name name="connect" arity="4"/>
<fsummary>Connect to a TCP port</fsummary>
- <type>
- <v>Address = string() | atom() | ip_address()</v>
- <v>Port = 0..65535</v>
- <v>Options = [Opt]</v>
- <v>&nbsp;Opt -- see below</v>
- <v>Timeout = int() | infinity</v>
- <v>Socket = socket()</v>
- <v>Reason = posix()</v>
- </type>
<desc>
- <p>Connects to a server on TCP port <c>Port</c> on the host
- with IP address <c>Address</c>. The <c>Address</c> argument
+ <p>Connects to a server on TCP port <c><anno>Port</anno></c> on the host
+ with IP address <c><anno>Address</anno></c>. The <c><anno>Address</anno></c> argument
can be either a hostname, or an IP address.</p>
<p>The available options are:</p>
<taglist>
@@ -127,13 +136,13 @@ socket()
<item>
<p>Set up the socket for IPv4.</p>
</item>
- <tag>Opt</tag>
+ <tag><c>Opt</c></tag>
<item>
<p>See
<seealso marker="inet#setopts/2">inet:setopts/2</seealso>.</p>
</item>
</taglist>
- <p>Packets can be sent to the returned socket <c>Socket</c>
+ <p>Packets can be sent to the returned socket <c><anno>Socket</anno></c>
using <c>send/2</c>. Packets sent from the peer are delivered
as messages:</p>
<code type="none">
@@ -148,7 +157,7 @@ socket()
<p>unless <c>{active, false}</c> is specified in the option list
for the socket, in which case packets are retrieved by
calling <c>recv/2</c>.</p>
- <p>The optional <c>Timeout</c> parameter specifies a timeout in
+ <p>The optional <c><anno>Timeout</anno></c> parameter specifies a timeout in
milliseconds. The default value is <c>infinity</c>.</p>
<note>
<p>The default values for options given to <c>connect</c> can
@@ -159,19 +168,12 @@ socket()
</desc>
</func>
<func>
- <name>listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}</name>
+ <name name="listen" arity="2"/>
<fsummary>Set up a socket to listen on a port</fsummary>
- <type>
- <v>Port = 0..65535</v>
- <v>Options = [Opt]</v>
- <v>&nbsp;Opt -- see below</v>
- <v>ListenSocket -- see below</v>
- <v>Reason = posix()</v>
- </type>
<desc>
- <p>Sets up a socket to listen on the port <c>Port</c> on
+ <p>Sets up a socket to listen on the port <c><anno>Port</anno></c> on
the local host.</p>
- <p>If <c>Port == 0</c>, the underlying OS assigns an available
+ <p>If <c><anno>Port</anno> == 0</c>, the underlying OS assigns an available
port number, use <c>inet:port/1</c> to retrieve it.</p>
<p>The available options are:</p>
<taglist>
@@ -214,7 +216,7 @@ socket()
<seealso marker="inet#setopts/2">inet:setopts/2</seealso>.</p>
</item>
</taglist>
- <p>The returned socket <c>ListenSocket</c> can only be used in
+ <p>The returned socket <c><anno>ListenSocket</anno></c> can only be used in
calls to <c>accept/1,2</c>.</p>
<note>
<p>The default values for options given to <c>listen</c> can
@@ -225,27 +227,23 @@ socket()
</desc>
</func>
<func>
- <name>accept(ListenSocket) -> {ok, Socket} | {error, Reason}</name>
- <name>accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}</name>
+ <name name="accept" arity="1"/>
+ <name name="accept" arity="2"/>
<fsummary>Accept an incoming connection request on a listen socket</fsummary>
- <type>
- <v>ListenSocket -- see listen/2</v>
- <v>Timeout = int() | infinity</v>
- <v>Socket = socket()</v>
- <v>Reason = closed | timeout | posix()</v>
- </type>
+ <type_desc variable="ListenSocket">Returned by <c>listen/2</c>.
+ </type_desc>
<desc>
<p>Accepts an incoming connection request on a listen socket.
- <c>Socket</c> must be a socket returned from <c>listen/2</c>.
- <c>Timeout</c> specifies a timeout value in ms, defaults to
+ <c><anno>Socket</anno></c> must be a socket returned from <c>listen/2</c>.
+ <c><anno>Timeout</anno></c> specifies a timeout value in ms, defaults to
<c>infinity</c>.</p>
- <p>Returns <c>{ok, Socket}</c> if a connection is established,
- or <c>{error, closed}</c> if <c>ListenSocket</c> is closed,
+ <p>Returns <c>{ok, <anno>Socket</anno>}</c> if a connection is established,
+ or <c>{error, closed}</c> if <c><anno>ListenSocket</anno></c> is closed,
or <c>{error, timeout}</c> if no connection is established
within the specified time. May also return a POSIX error
value if something else goes wrong, see inet(3) for possible
error values.</p>
- <p>Packets can be sent to the returned socket <c>Socket</c>
+ <p>Packets can be sent to the returned socket <c><anno>Socket</anno></c>
using <c>send/2</c>. Packets sent from the peer are delivered
as messages:</p>
<code type="none">
@@ -264,13 +262,8 @@ socket()
</desc>
</func>
<func>
- <name>send(Socket, Packet) -> ok | {error, Reason}</name>
+ <name name="send" arity="2"/>
<fsummary>Send a packet</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Packet = [char()] | binary()</v>
- <v>Reason = posix()</v>
- </type>
<desc>
<p>Sends a packet on a socket. </p>
<p>There is no <c>send</c> call with timeout option, you use the
@@ -279,70 +272,52 @@ socket()
</desc>
</func>
<func>
- <name>recv(Socket, Length) -> {ok, Packet} | {error, Reason}</name>
- <name>recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason}</name>
+ <name name="recv" arity="2"/>
+ <name name="recv" arity="3"/>
<fsummary>Receive a packet from a passive socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Length = int()</v>
- <v>Packet = [char()] | binary() | HttpPacket</v>
- <v>Timeout = int() | infinity</v>
- <v>Reason = closed | posix()</v>
- <v>HttpPacket = see the description of <c>HttpPacket</c> in <seealso marker="erts:erlang#decode_packet/3">erlang:decode_packet/3</seealso></v>
- </type>
+ <type_desc variable="HttpPacket">See the description of
+ <c>HttpPacket</c> in <seealso marker="erts:erlang#decode_packet/3">
+ erlang:decode_packet/3</seealso>.
+ </type_desc>
<desc>
<p>This function receives a packet from a socket in passive
mode. A closed socket is indicated by a return value
<c>{error, closed}</c>.</p>
- <p>The <c>Length</c> argument is only meaningful when
+ <p>The <c><anno>Length</anno></c> argument is only meaningful when
the socket is in <c>raw</c> mode and denotes the number of
- bytes to read. If <c>Length</c> = 0, all available bytes are
- returned. If <c>Length</c> &gt; 0, exactly <c>Length</c>
+ bytes to read. If <c><anno>Length</anno></c> = 0, all available bytes are
+ returned. If <c><anno>Length</anno></c> &gt; 0, exactly <c><anno>Length</anno></c>
bytes are returned, or an error; possibly discarding less
- than <c>Length</c> bytes of data when the socket gets closed
+ than <c><anno>Length</anno></c> bytes of data when the socket gets closed
from the other side.</p>
- <p>The optional <c>Timeout</c> parameter specifies a timeout in
+ <p>The optional <c><anno>Timeout</anno></c> parameter specifies a timeout in
milliseconds. The default value is <c>infinity</c>.</p>
</desc>
</func>
<func>
- <name>controlling_process(Socket, Pid) -> ok | {error, Reason}</name>
+ <name name="controlling_process" arity="2"/>
<fsummary>Change controlling process of a socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Pid = pid()</v>
- <v>Reason = closed | not_owner | posix()</v>
- </type>
<desc>
- <p>Assigns a new controlling process <c>Pid</c> to
- <c>Socket</c>. The controlling process is the process which
+ <p>Assigns a new controlling process <c><anno>Pid</anno></c> to
+ <c><anno>Socket</anno></c>. The controlling process is the process which
receives messages from the socket. If called by any other
process than the current controlling process,
<c>{error, eperm}</c> is returned.</p>
</desc>
</func>
<func>
- <name>close(Socket) -> ok | {error, Reason}</name>
+ <name name="close" arity="1"/>
<fsummary>Close a TCP socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Reason = posix()</v>
- </type>
<desc>
<p>Closes a TCP socket.</p>
</desc>
</func>
<func>
- <name>shutdown(Socket, How) -> ok | {error, Reason}</name>
+ <name name="shutdown" arity="2"/>
<fsummary>Immediately close a socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>How = read | write | read_write</v>
- <v>Reason = posix()</v>
- </type>
<desc>
<p>Immediately close a socket in one or two directions.</p>
- <p><c>How == write</c> means closing the socket for writing,
+ <p><c><anno>How</anno> == write</c> means closing the socket for writing,
reading from it is still possible.</p>
<p>To be able to handle that the peer has done a shutdown on
the write side, the <c>{exit_on_close, false}</c> option
diff --git a/lib/kernel/doc/src/gen_udp.xml b/lib/kernel/doc/src/gen_udp.xml
index 71f2e9bd83..c0e783f508 100644
--- a/lib/kernel/doc/src/gen_udp.xml
+++ b/lib/kernel/doc/src/gen_udp.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2009</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -34,32 +34,43 @@
with sockets using the UDP protocol.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-ip_address()
- see inet(3)
-
-posix()
- see inet(3)
+ <datatypes>
+ <datatype>
+ <name name="hostname"/>
+ </datatype>
+ <datatype>
+ <name name="ip_address"/>
+ <desc>
+ <p>Represents an address of a TCP socket.
+ It is a tuple as explained in
+ <seealso marker="inet">inet(3)</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="port_number"/>
+ </datatype>
+ <datatype>
+ <name name="posix"/>
+ <desc>
+ <p>See <seealso marker="inet#error_codes">
+ inet(3); POSIX Error Codes</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name><marker id="type-socket">socket()</marker></name>
+ <desc>
+ <p>As returned by open/1,2.</p>
+ </desc>
+ </datatype>
+ </datatypes>
-socket()
- as returned by open/1,2</code>
- </section>
<funcs>
<func>
- <name>open(Port) -> {ok, Socket} | {error, Reason}</name>
- <name>open(Port, Options) -> {ok, Socket} | {error, Reason}</name>
+ <name name="open" arity="1"/>
+ <name name="open" arity="2"/>
<fsummary>Associate a UDP port number with the process calling it</fsummary>
- <type>
- <v>Port = 0..65535</v>
- <v>Options = [Opt]</v>
- <v>&nbsp;Opt -- see below</v>
- <v>Socket = socket()</v>
- <v>Reason = posix()</v>
- </type>
<desc>
- <p>Associates a UDP port number (<c>Port</c>) with the calling
+ <p>Associates a UDP port number (<c><anno>Port</anno></c>) with the calling
process.</p>
<p>The available options are:</p>
<taglist>
@@ -96,7 +107,7 @@ socket()
<seealso marker="inet#setopts/2">inet:setopts/2</seealso>.</p>
</item>
</taglist>
- <p>The returned socket <c>Socket</c> is used to send packets
+ <p>The returned socket <c><anno>Socket</anno></c> is used to send packets
from this port with <c>send/4</c>. When UDP packets arrive at
the opened port, they are delivered as messages:</p>
<code type="none">
@@ -110,66 +121,42 @@ socket()
binary if the option <c>binary</c> was specified.</p>
<p>Default value for the receive buffer option is
<c>{recbuf, 8192}</c>.</p>
- <p>If <c>Port == 0</c>, the underlying OS assigns a free UDP
+ <p>If <c><anno>Port</anno> == 0</c>, the underlying OS assigns a free UDP
port, use <c>inet:port/1</c> to retrieve it.</p>
</desc>
</func>
<func>
- <name>send(Socket, Address, Port, Packet) -> ok | {error, Reason}</name>
+ <name name="send" arity="4"/>
<fsummary>Send a packet</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Address = string() | atom() | ip_address()</v>
- <v>Port = 0..65535</v>
- <v>Packet = [char()] | binary()</v>
- <v>Reason = not_owner | posix()</v>
- </type>
<desc>
<p>Sends a packet to the specified address and port.
- The <c>Address</c> argument can be either a hostname, or an
+ The <c><anno>Address</anno></c> argument can be either a hostname, or an
IP address.</p>
</desc>
</func>
<func>
- <name>recv(Socket, Length) -> {ok, {Address, Port, Packet}} | {error, Reason}</name>
- <name>recv(Socket, Length, Timeout) -> {ok, {Address, Port, Packet}} | {error, Reason}</name>
+ <name name="recv" arity="2"/>
+ <name name="recv" arity="3"/>
<fsummary>Receive a packet from a passive socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Length = int()</v>
- <v>Address = ip_address()</v>
- <v>Port = 0..65535</v>
- <v>Packet = [char()] | binary()</v>
- <v>Timeout = int() | infinity</v>
- <v>Reason = not_owner | posix()</v>
- </type>
<desc>
<p>This function receives a packet from a socket in passive
mode.</p>
- <p>The optional <c>Timeout</c> parameter specifies a timeout in
+ <p>The optional <c><anno>Timeout</anno></c> parameter specifies a timeout in
milliseconds. The default value is <c>infinity</c>.</p>
</desc>
</func>
<func>
- <name>controlling_process(Socket, Pid) -> ok</name>
+ <name name="controlling_process" arity="2"/>
<fsummary>Change controlling process of a socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Pid = pid()</v>
- </type>
<desc>
- <p>Assigns a new controlling process <c>Pid</c> to
- <c>Socket</c>. The controlling process is the process which
+ <p>Assigns a new controlling process <c><anno>Pid</anno></c> to
+ <c><anno>Socket</anno></c>. The controlling process is the process which
receives messages from the socket.</p>
</desc>
</func>
<func>
- <name>close(Socket) -> ok | {error, Reason}</name>
+ <name name="close" arity="1"/>
<fsummary>Close a UDP socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Reason = not_owner | posix()</v>
- </type>
<desc>
<p>Closes a UDP socket.</p>
</desc>
diff --git a/lib/kernel/doc/src/global.xml b/lib/kernel/doc/src/global.xml
index 077109d6c9..304a9b1d88 100644
--- a/lib/kernel/doc/src/global.xml
+++ b/lib/kernel/doc/src/global.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -106,45 +106,37 @@
</description>
+ <datatypes>
+ <datatype>
+ <name name="id"/>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
- <name>del_lock(Id)</name>
- <name>del_lock(Id, Nodes) -> void()</name>
+ <name name="del_lock" arity="1"/>
+ <name name="del_lock" arity="2"/>
<fsummary>Delete a lock</fsummary>
- <type>
- <v>Id = {ResourceId, LockRequesterId}</v>
- <v>&nbsp;ResourceId = term()</v>
- <v>&nbsp;LockRequesterId = term()</v>
- <v>Nodes = [node()]</v>
- </type>
<desc>
- <p>Deletes the lock <c>Id</c> synchronously.</p>
+ <p>Deletes the lock <c><anno>Id</anno></c> synchronously.</p>
</desc>
</func>
<func>
- <name>notify_all_name(Name, Pid1, Pid2) -> none</name>
+ <name name="notify_all_name" arity="3"/>
<fsummary>Name resolving function that notifies both pids</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid1 = Pid2 = pid()</v>
- </type>
<desc>
<p>This function can be used as a name resolving function for
<c>register_name/3</c> and <c>re_register_name/3</c>. It
unregisters both pids, and sends the message
- <c>{global_name_conflict, Name, OtherPid}</c> to both
+ <c>{global_name_conflict, <anno>Name</anno>, OtherPid}</c> to both
processes.</p>
</desc>
</func>
<func>
- <name>random_exit_name(Name, Pid1, Pid2) -> Pid1 | Pid2</name>
+ <name name="random_exit_name" arity="3"/>
<fsummary>Name resolving function that kills one pid</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid1 = Pid2 = pid()</v>
- </type>
<desc>
<p>This function can be used as a name resolving function for
<c>register_name/3</c> and <c>re_register_name/3</c>. It
@@ -154,33 +146,27 @@
</func>
<func>
- <name>random_notify_name(Name, Pid1, Pid2) -> Pid1 | Pid2</name>
+ <name name="random_notify_name" arity="3"/>
<fsummary>Name resolving function that notifies one pid</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid1 = Pid2 = pid()</v>
- </type>
<desc>
<p>This function can be used as a name resolving function for
<c>register_name/3</c> and <c>re_register_name/3</c>. It
randomly chooses one of the pids for registration, and sends
- the message <c>{global_name_conflict, Name}</c> to the other
+ the message <c>{global_name_conflict, <anno>Name</anno>}</c> to the other
pid.</p>
</desc>
</func>
<func>
- <name>register_name(Name, Pid)</name>
- <name>register_name(Name, Pid, Resolve) -> yes | no</name>
+ <name name="register_name" arity="2"/>
+ <name name="register_name" arity="3"/>
<fsummary>Globally register a name for a pid</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid = pid()</v>
- <v>Resolve = fun() or {Module, Function} where</v>
- <v>&nbsp;&nbsp;Resolve(Name, Pid, Pid2) -> Pid | Pid2 | none</v>
- </type>
+ <type name="method"/>
+ <type_desc name="method">{<c>Module</c>, <c>Function</c>}
+ is also allowed
+ </type_desc>
<desc>
- <p>Globally associates the name <c>Name</c> with a pid, that is,
+ <p>Globally associates the name <c><anno>Name</anno></c> with a pid, that is,
Globally notifies all nodes of a new global name in a network
of Erlang nodes.</p>
@@ -188,7 +174,7 @@
of the globally registered names that already exist.
The network is also informed of any global names in newly
connected nodes. If any name clashes are discovered,
- the <c>Resolve</c> function is called. Its purpose is to
+ the <c><anno>Resolve</anno></c> function is called. Its purpose is to
decide which pid is correct. If the function crashes, or
returns anything other than one of the pids, the name is
unregistered. This function is called once for each name
@@ -196,7 +182,7 @@
<p>There are three pre-defined resolve functions:
<c>random_exit_name/3</c>, <c>random_notify_name/3</c>, and
- <c>notify_all_name/3</c>. If no <c>Resolve</c> function is
+ <c>notify_all_name/3</c>. If no <c><anno>Resolve</anno></c> function is
defined, <c>random_exit_name</c> is used. This means that one
of the two registered processes will be selected as correct
while the other is killed.</p>
@@ -225,78 +211,63 @@
</func>
<func>
- <name>registered_names() -> [Name]</name>
+ <name name="registered_names" arity="0"/>
<fsummary>All globally registered names</fsummary>
- <type>
- <v>Name = term()</v>
- </type>
<desc>
<p>Returns a lists of all globally registered names.</p>
</desc>
</func>
<func>
- <name>re_register_name(Name, Pid)</name>
- <name>re_register_name(Name, Pid, Resolve) -> void()</name>
+ <name name="re_register_name" arity="2"/>
+ <name name="re_register_name" arity="3"/>
<fsummary>Atomically re-register a name</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid = pid()</v>
- <v>Resolve = fun() or {Module, Function} where</v>
- <v>&nbsp;&nbsp;Resolve(Name, Pid, Pid2) -> Pid | Pid2 | none</v>
- </type>
+ <type name="method"/>
+ <type_desc name="method">{<c>Module</c>, <c>Function</c>}
+ is also allowed
+ </type_desc>
<desc>
- <p>Atomically changes the registered name <c>Name</c> on all
- nodes to refer to <c>Pid</c>.</p>
+ <p>Atomically changes the registered name <c><anno>Name</anno></c> on all
+ nodes to refer to <c><anno>Pid</anno></c>.</p>
- <p>The <c>Resolve</c> function has the same behavior as in
+ <p>The <c><anno>Resolve</anno></c> function has the same behavior as in
<c>register_name/2,3</c>.</p>
</desc>
</func>
<func>
- <name>send(Name, Msg) -> Pid</name>
+ <name name="send" arity="2"/>
<fsummary>Send a message to a globally registered pid</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Msg = term()</v>
- <v>Pid = pid()</v>
- </type>
<desc>
- <p>Sends the message <c>Msg</c> to the pid globally registered
- as <c>Name</c>.</p>
+ <p>Sends the message <c><anno>Msg</anno></c> to the pid globally registered
+ as <c><anno>Name</anno></c>.</p>
- <p>Failure: If <c>Name</c> is not a globally registered
+ <p>Failure: If <c><anno>Name</anno></c> is not a globally registered
name, the calling function will exit with reason
- <c>{badarg, {Name, Msg}}</c>.</p>
+ <c>{badarg, {<anno>Name</anno>, <anno>Msg</anno>}}</c>.</p>
</desc>
</func>
<func>
- <name>set_lock(Id)</name>
- <name>set_lock(Id, Nodes)</name>
- <name>set_lock(Id, Nodes, Retries) -> boolean()</name>
+ <name name="set_lock" arity="1"/>
+ <name name="set_lock" arity="2"/>
+ <name name="set_lock" arity="3"/>
<fsummary>Set a lock on the specified nodes</fsummary>
- <type>
- <v>Id = {ResourceId, LockRequesterId}</v>
- <v>&nbsp;ResourceId = term()</v>
- <v>&nbsp;LockRequesterId = term()</v>
- <v>Nodes = [node()]</v>
- <v>Retries = int() >= 0 | infinity</v>
- </type>
+ <type name="id"/>
+ <type name="retries"/>
<desc>
<p>Sets a lock on the specified nodes (or on all nodes if none
- are specified) on <c>ResourceId</c> for
- <c>LockRequesterId</c>. If a lock already exists on
- <c>ResourceId</c> for another requester than
- <c>LockRequesterId</c>, and <c>Retries</c> is not equal to 0,
+ are specified) on <c><anno>ResourceId</anno></c> for
+ <c><anno>LockRequesterId</anno></c>. If a lock already exists on
+ <c><anno>ResourceId</anno></c> for another requester than
+ <c><anno>LockRequesterId</anno></c>, and <c><anno>Retries</anno></c> is not equal to 0,
the process sleeps for a while and will try to execute
- the action later. When <c>Retries</c> attempts have been made,
+ the action later. When <c><anno>Retries</anno></c> attempts have been made,
<c>false</c> is returned, otherwise <c>true</c>. If
- <c>Retries</c> is <c>infinity</c>, <c>true</c> is eventually
+ <c><anno>Retries</anno></c> is <c>infinity</c>, <c>true</c> is eventually
returned (unless the lock is never released).</p>
- <p>If no value for <c>Retries</c> is given, <c>infinity</c> is
+ <p>If no value for <c><anno>Retries</anno></c> is given, <c>infinity</c> is
used.</p>
<p>This function is completely synchronous.</p>
@@ -315,7 +286,7 @@
application to detect and rectify a deadlock.</p>
<note>
- <p>Some values of <c>ResourceId</c> should be avoided or
+ <p>Some values of <c><anno>ResourceId</anno></c> should be avoided or
Erlang/OTP will not work properly. A list of resources to
avoid: <c>global</c>, <c>dist_ac</c>,
<c>mnesia_table_lock</c>, <c>mnesia_adjust_log_writes</c>,
@@ -326,7 +297,7 @@
</func>
<func>
- <name>sync() -> void()</name>
+ <name name="sync" arity="0"/>
<fsummary>Synchronize the global name server</fsummary>
<desc>
<p>Synchronizes the global name server with all nodes known to
@@ -335,56 +306,45 @@
the global name server will receive global information from
all nodes. This function can be called when new nodes are
added to the network.</p>
+ <p>The only possible error reason <c>Reason</c> is
+ <c>{"global_groups definition error", Error}</c>.</p>
</desc>
</func>
<func>
- <name>trans(Id, Fun)</name>
- <name>trans(Id, Fun, Nodes)</name>
- <name>trans(Id, Fun, Nodes, Retries) -> Res | aborted</name>
+ <name name="trans" arity="2"/>
+ <name name="trans" arity="3"/>
+ <name name="trans" arity="4"/>
<fsummary>Micro transaction facility</fsummary>
- <type>
- <v>Id = {ResourceId, LockRequesterId}</v>
- <v>&nbsp;ResourceId = term()</v>
- <v>&nbsp;LockRequesterId = term()</v>
- <v>Fun = fun() | {M, F}</v>
- <v>Nodes = [node()]</v>
- <v>Retries = int() >= 0 | infinity</v>
- <v>Res = term()</v>
- </type>
+ <type name="retries"/>
+ <type name="trans_fun"/>
<desc>
- <p>Sets a lock on <c>Id</c> (using <c>set_lock/3</c>). If this
- succeeds, <c>Fun()</c> is evaluated and the result <c>Res</c>
+ <p>Sets a lock on <c><anno>Id</anno></c> (using <c>set_lock/3</c>). If this
+ succeeds, <c><anno>Fun</anno>()</c> is evaluated and the result <c><anno>Res</anno></c>
is returned. Returns <c>aborted</c> if the lock attempt
- failed. If <c>Retries</c> is set to <c>infinity</c>,
+ failed. If <c><anno>Retries</anno></c> is set to <c>infinity</c>,
the transaction will not abort.</p>
<p><c>infinity</c> is the default setting and will be used if
- no value is given for <c>Retries</c>.</p>
+ no value is given for <c><anno>Retries</anno></c>.</p>
</desc>
</func>
<func>
- <name>unregister_name(Name) -> void()</name>
+ <name name="unregister_name" arity="1"/>
<fsummary>Remove a globally registered name for a pid</fsummary>
- <type>
- <v>Name = term()</v>
- </type>
<desc>
- <p>Removes the globally registered name <c>Name</c> from
+ <p>Removes the globally registered name <c><anno>Name</anno></c> from
the network of Erlang nodes.</p>
</desc>
</func>
<func>
- <name>whereis_name(Name) -> pid() | undefined</name>
+ <name name="whereis_name" arity="1"/>
<fsummary>Get the pid with a given globally registered name</fsummary>
- <type>
- <v>Name = term()</v>
- </type>
<desc>
<p>Returns the pid with the globally registered name
- <c>Name</c>. Returns <c>undefined</c> if the name is not
+ <c><anno>Name</anno></c>. Returns <c>undefined</c> if the name is not
globally registered.</p>
</desc>
</func>
diff --git a/lib/kernel/doc/src/global_group.xml b/lib/kernel/doc/src/global_group.xml
index 4facf4a4aa..abf6178fc4 100644
--- a/lib/kernel/doc/src/global_group.xml
+++ b/lib/kernel/doc/src/global_group.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1998</year><year>2009</year>
+ <year>1998</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -42,26 +42,7 @@
<seealso marker="kernel_app">kernel(6)</seealso>,
<seealso marker="config">config(4)</seealso>:</p>
<code type="none">
-{global_groups, [GroupTuple]}</code>
- <p>Types:</p>
- <list type="bulleted">
- <item><c>GroupTuple = {GroupName, [Node]} | {GroupName, PublishType, [Node]}</c></item>
- <item><c>GroupName = atom()</c> (naming a global group)</item>
- <item><c>PublishType = normal | hidden</c></item>
- <item><c>Node = atom()</c> (naming a node)</item>
- </list>
- <p>A <c>GroupTuple</c> without <c>PublishType</c> is the same as a
- <c>GroupTuple</c> with <c>PublishType == normal</c>.</p>
- <p>A node started with the command line flag <c>-hidden</c>, see
- <seealso marker="erts:erl">erl(1)</seealso>, is said to be a
- <em>hidden</em> node. A hidden node will establish hidden
- connections to nodes not part of the same global group, but
- normal (visible) connections to nodes part of the same global
- group.</p>
- <p>A global group defined with <c>PublishType == hidden</c>, is
- said to be a hidden global group. All nodes in a hidden global
- group are hidden nodes, regardless if they are started with
- the <c>-hidden</c> command line flag or not.</p>
+{global_groups, [GroupTuple :: group_tuple()]}</code>
<p>For the processes and nodes to run smoothly using the global
group functionality, the following criteria must be met:</p>
<list type="bulleted">
@@ -82,14 +63,44 @@
<p>In the following description, a <em>group node</em> is a node
belonging to the same global group as the local node.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="group_tuple"/>
+ <desc>
+ <p>A <c>GroupTuple</c> without <c>PublishType</c> is the same as a
+ <c>GroupTuple</c> with <c>PublishType == normal</c>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="group_name"/>
+ </datatype>
+ <datatype>
+ <name name="publish_type"/>
+ <desc>
+ <p>A node started with the command line flag <c>-hidden</c>, see
+ <seealso marker="erts:erl">erl(1)</seealso>, is said to be a
+ <em>hidden</em> node. A hidden node will establish hidden
+ connections to nodes not part of the same global group, but
+ normal (visible) connections to nodes part of the same global
+ group.</p>
+ <p>A global group defined with <c>PublishType == hidden</c>, is
+ said to be a hidden global group. All nodes in a hidden global
+ group are hidden nodes, regardless if they are started with
+ the <c>-hidden</c> command line flag or not.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="name"/>
+ <desc><p>A registered name.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="where"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>global_groups() -> {GroupName, GroupNames} | undefined</name>
+ <name name="global_groups" arity="0"/>
<fsummary>Return the global group names</fsummary>
- <type>
- <v>GroupName = atom()</v>
- <v>GroupNames = [GroupName]</v>
- </type>
<desc>
<p>Returns a tuple containing the name of the global group
the local node belongs to, and the list of all other known
@@ -98,53 +109,52 @@
</desc>
</func>
<func>
- <name>info() -> [{Item, Info}]</name>
+ <name name="info" arity="0"/>
<fsummary>Information about global groups</fsummary>
- <type>
- <v>Item, Info -- see below</v>
- </type>
+ <type name="info_item"/>
+ <type name="sync_state"/>
<desc>
<p>Returns a list containing information about the global
groups. Each element of the list is a tuple. The order of
the tuples is not defined.</p>
<taglist>
- <tag><c>{state, State}</c></tag>
+ <tag><c>{state, <anno>State</anno>}</c></tag>
<item>
<p>If the local node is part of a global group,
- <c>State == synced</c>. If no global groups are defined,
- <c>State == no_conf</c>.</p>
+ <c><anno>State</anno> == synced</c>. If no global groups are defined,
+ <c><anno>State</anno> == no_conf</c>.</p>
</item>
- <tag><c>{own_group_name, GroupName}</c></tag>
+ <tag><c>{own_group_name, <anno>GroupName</anno>}</c></tag>
<item>
<p>The name (atom) of the group that the local node belongs
to.</p>
</item>
- <tag><c>{own_group_nodes, Nodes}</c></tag>
+ <tag><c>{own_group_nodes, <anno>Nodes</anno>}</c></tag>
<item>
<p>A list of node names (atoms), the group nodes.</p>
</item>
- <tag><c>{synced_nodes, Nodes}</c></tag>
+ <tag><c>{synced_nodes, <anno>Nodes</anno>}</c></tag>
<item>
<p>A list of node names, the group nodes currently
synchronized with the local node.</p>
</item>
- <tag><c>{sync_error, Nodes}</c></tag>
+ <tag><c>{sync_error, <anno>Nodes</anno>}</c></tag>
<item>
<p>A list of node names, the group nodes with which
the local node has failed to synchronize.</p>
</item>
- <tag><c>{no_contact, Nodes}</c></tag>
+ <tag><c>{no_contact, <anno>Nodes</anno>}</c></tag>
<item>
<p>A list of node names, the group nodes to which there are
currently no connections.</p>
</item>
- <tag><c>{other_groups, Groups}</c></tag>
+ <tag><c>{other_groups, <anno>Groups</anno>}</c></tag>
<item>
- <p><c>Groups</c> is a list of tuples
- <c>{GroupName, Nodes}</c>, specifying the name and nodes
+ <p><c><anno>Groups</anno></c> is a list of tuples
+ <c>{<anno>GroupName</anno>, <anno>Nodes</anno>}</c>, specifying the name and nodes
of the other global groups.</p>
</item>
- <tag><c>{monitoring, Pids}</c></tag>
+ <tag><c>{monitoring, <anno>Pids</anno>}</c></tag>
<item>
<p>A list of pids, specifying the processes which have
subscribed to <c>nodeup</c> and <c>nodedown</c> messages.</p>
@@ -153,73 +163,52 @@
</desc>
</func>
<func>
- <name>monitor_nodes(Flag) -> ok </name>
+ <name name="monitor_nodes" arity="1"/>
<fsummary>Subscribe to node status changes</fsummary>
- <type>
- <v>Flag = bool()</v>
- </type>
<desc>
- <p>Depending on <c>Flag</c>, the calling process starts
- subscribing (<c>Flag == true</c>) or stops subscribing
- (<c>Flag == false</c>) to node status change messages.</p>
+ <p>Depending on <c><anno>Flag</anno></c>, the calling process starts
+ subscribing (<c><anno>Flag</anno> == true</c>) or stops subscribing
+ (<c><anno>Flag</anno> == false</c>) to node status change messages.</p>
<p>A process which has subscribed will receive the messages
<c>{nodeup, Node}</c> and <c>{nodedown, Node}</c> when a
group node connects or disconnects, respectively.</p>
</desc>
</func>
<func>
- <name>own_nodes() -> Nodes</name>
+ <name name="own_nodes" arity="0"/>
<fsummary>Return the group nodes</fsummary>
- <type>
- <v>Nodes = [Node]</v>
- <v>&nbsp;Node = node()</v>
- </type>
<desc>
<p>Returns the names of all group nodes, regardless of their
current status.</p>
</desc>
</func>
<func>
- <name>registered_names(Where) -> Names</name>
+ <name name="registered_names" arity="1"/>
<fsummary>Return globally registered names</fsummary>
- <type>
- <v>Where = {node, Node} | {group, GroupName}</v>
- <v>&nbsp;Node = node()</v>
- <v>&nbsp;GroupName = atom()</v>
- <v>Names = [Name]</v>
- <v>&nbsp;Name = atom()</v>
- </type>
<desc>
<p>Returns a list of all names which are globally registered
on the specified node or in the specified global group.</p>
</desc>
</func>
<func>
- <name>send(Name, Msg) -> pid() | {badarg, {Name, Msg}}</name>
- <name>send(Where, Name, Msg) -> pid() | {badarg, {Name, Msg}}</name>
+ <name name="send" arity="2"/>
+ <name name="send" arity="3"/>
<fsummary>Send a message to a globally registered pid</fsummary>
- <type>
- <v>Where = {node, Node} | {group, GroupName}</v>
- <v>&nbsp;Node = node()</v>
- <v>&nbsp;GroupName = atom()</v>
- <v>Name = atom()</v>
- <v>Msg = term()</v>
- </type>
<desc>
- <p>Searches for <c>Name</c>, globally registered on
+ <p>Searches for <c><anno>Name</anno></c>, globally registered on
the specified node or in the specified global group, or --
- if the <c>Where</c> argument is not provided -- in any global
+ if the <c><anno>Where</anno></c> argument is not provided -- in any global
group. The global groups are searched in the order in which
they appear in the value of the <c>global_groups</c>
configuration parameter.</p>
- <p>If <c>Name</c> is found, the message <c>Msg</c> is sent to
+ <p>If <c><anno>Name</anno></c> is found, the message <c><anno>Msg</anno></c> is sent to
the corresponding pid. The pid is also the return value of
the function. If the name is not found, the function returns
- <c>{badarg, {Name, Msg}}</c>.</p>
+ <c>{badarg, {<anno>Name</anno>, <anno>Msg</anno>}}</c>.</p>
</desc>
</func>
<func>
- <name>sync() -> ok</name>
+ <name name="sync" arity="0"/>
<fsummary>Synchronize the group nodes</fsummary>
<desc>
<p>Synchronizes the group nodes, that is, the global name
@@ -235,23 +224,17 @@
</desc>
</func>
<func>
- <name>whereis_name(Name) -> pid() | undefined</name>
- <name>whereis_name(Where, Name) -> pid() | undefined</name>
+ <name name="whereis_name" arity="1"/>
+ <name name="whereis_name" arity="2"/>
<fsummary>Get the pid with a given globally registered name</fsummary>
- <type>
- <v>Where = {node, Node} | {group, GroupName}</v>
- <v>&nbsp;Node = node()</v>
- <v>&nbsp;GroupName = atom()</v>
- <v>Name = atom()</v>
- </type>
<desc>
- <p>Searches for <c>Name</c>, globally registered on
+ <p>Searches for <c><anno>Name</anno></c>, globally registered on
the specified node or in the specified global group, or -- if
- the <c>Where</c> argument is not provided -- in any global
+ the <c><anno>Where</anno></c> argument is not provided -- in any global
group. The global groups are searched in the order in which
they appear in the value of the <c>global_groups</c>
configuration parameter.</p>
- <p>If <c>Name</c> is found, the corresponding pid is returned.
+ <p>If <c><anno>Name</anno></c> is found, the corresponding pid is returned.
If the name is not found, the function returns
<c>undefined</c>.</p>
</desc>
diff --git a/lib/kernel/doc/src/heart.xml b/lib/kernel/doc/src/heart.xml
index 0df699572d..e2dbcbe63d 100644
--- a/lib/kernel/doc/src/heart.xml
+++ b/lib/kernel/doc/src/heart.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -76,11 +76,8 @@
</description>
<funcs>
<func>
- <name>set_cmd(Cmd) -> ok | {error, {bad_cmd, Cmd}}</name>
+ <name name="set_cmd" arity="1"/>
<fsummary>Set a temporary reboot command</fsummary>
- <type>
- <v>Cmd = string()</v>
- </type>
<desc>
<p>Sets a temporary reboot command. This command is used if
a <c>HEART_COMMAND</c> other than the one specified with
@@ -88,12 +85,12 @@
the system. The new Erlang runtime system will (if it
misbehaves) use the environment variable
<c>HEART_COMMAND</c> to reboot.</p>
- <p>Limitations: The length of the <c>Cmd</c> command string
+ <p>Limitations: The length of the <c><anno>Cmd</anno></c> command string
must be less than 2047 characters.</p>
</desc>
</func>
<func>
- <name>clear_cmd() -> ok</name>
+ <name name="clear_cmd" arity="0"/>
<fsummary>Clear the temporary boot command</fsummary>
<desc>
<p>Clears the temporary boot command. If the system terminates,
@@ -101,11 +98,8 @@
</desc>
</func>
<func>
- <name>get_cmd() -> {ok, Cmd}</name>
+ <name name="get_cmd" arity="0"/>
<fsummary>Get the temporary reboot command</fsummary>
- <type>
- <v>Cmd = string()</v>
- </type>
<desc>
<p>Get the temporary reboot command. If the command is cleared,
the empty string will be returned.</p>
diff --git a/lib/kernel/doc/src/inet.xml b/lib/kernel/doc/src/inet.xml
index f05a224f33..fd843b00d9 100644
--- a/lib/kernel/doc/src/inet.xml
+++ b/lib/kernel/doc/src/inet.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2010</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -54,33 +54,6 @@ $ <input>erl -sname test -kernel \</input>
<input>inet_default_listen_options '[{delay_send,true}]'</input></pre>
<p>Note that the default option <c>{active, true}</c> currently
cannot be changed, for internal reasons.</p>
- </description>
-
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-#hostent{h_addr_list = [ip_address()] % list of addresses for this host
- h_addrtype = inet | inet6
- h_aliases = [hostname()] % list of aliases
- h_length = int() % length of address in bytes
- h_name = hostname() % official name for host
- The record is defined in the Kernel include file "inet.hrl"
- Add the following directive to the module:
- -include_lib("kernel/include/inet.hrl").
-
-hostname() = atom() | string()
-
-ip_address() = {N1,N2,N3,N4} % IPv4
- | {K1,K2,K3,K4,K5,K6,K7,K8} % IPv6
- Ni = 0..255
- Ki = 0..65535
-
-posix()
- an atom which is named from the Posix error codes used in
- Unix, and in the runtime libraries of most C compilers
-
-socket()
- see gen_tcp(3), gen_udp(3)</code>
<p>Addresses as inputs to functions can be either a string or a
tuple. For instance, the IP address 150.236.20.73 can be passed to
<c>gethostbyaddr/1</c> either as the string "150.236.20.73"
@@ -109,24 +82,58 @@ fe80::204:acff:fe17:bf38
{ok,{192,168,42,2}}
2> <input>inet_parse:address("FFFF::192.168.42.2").</input>
{ok,{65535,0,0,0,0,0,49320,10754}}</pre>
- </section>
+ </description>
+
+ <datatypes>
+ <datatype>
+ <name name="hostent"/>
+ <desc>
+ <p>The record is defined in the Kernel include file "inet.hrl".
+ Add the following directive to the module:</p>
+<code>-include_lib("kernel/include/inet.hrl").</code></desc>
+ </datatype>
+ <datatype>
+ <name name="hostname"/>
+ </datatype>
+ <datatype>
+ <name name="ip_address"/>
+ </datatype>
+ <datatype>
+ <name name="ip4_address"/>
+ </datatype>
+ <datatype>
+ <name name="ip6_address"/>
+ </datatype>
+ <datatype>
+ <name name="posix"/>
+ <desc><p>An atom which is named from the Posix error codes
+ used in Unix, and in the runtime libraries of most
+ C compilers. See
+ <seealso marker="#error_codes">POSIX Error Codes</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name><marker id="type-socket">socket()</marker></name>
+ <desc><p>See <seealso marker="gen_tcp#type-socket">gen_tcp(3)</seealso>
+ and <seealso marker="gen_udp#type-socket">gen_udp(3)</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="family_option"/>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
- <name>close(Socket) -> ok</name>
+ <name name="close" arity="1"/>
<fsummary>Close a socket of any type</fsummary>
- <type>
- <v>Socket = socket()</v>
- </type>
<desc>
<p>Closes a socket of any type.</p>
</desc>
</func>
<func>
- <name>get_rc() -> [{Par, Val}]</name>
+ <name name="get_rc" arity="0"/>
<fsummary>Return a list of IP configuration parameters</fsummary>
- <type>
- <v>Par, Val -- see below</v>
- </type>
<desc>
<p>Returns the state of the Inet configuration database in
form of a list of recorded configuration parameters. (See the
@@ -135,116 +142,74 @@ fe80::204:acff:fe17:bf38
</desc>
</func>
<func>
- <name>format_error(Posix) -> string()</name>
+ <name name="format_error" arity="1"/>
<fsummary>Return a descriptive string for an error reason</fsummary>
- <type>
- <v>Posix = posix()</v>
- </type>
<desc>
<p>Returns a diagnostic error string. See the section below
- for possible <c>Posix</c> values and the corresponding
+ for possible <c><anno>Posix</anno></c> values and the corresponding
strings.</p>
</desc>
</func>
<func>
- <name>getaddr(Host, Family) -> {ok, Address} | {error, posix()}</name>
+ <name name="getaddr" arity="2"/>
<fsummary>Return the IP-address for a host</fsummary>
- <type>
- <v>Host = ip_address() | string() | atom()</v>
- <v>Family = inet | inet6</v>
- <v>Address = ip_address()</v>
- <v>posix() = term()</v>
- </type>
<desc>
- <p>Returns the IP-address for <c>Host</c> as a tuple of
- integers. <c>Host</c> can be an IP-address, a single hostname
+ <p>Returns the IP-address for <c><anno>Host</anno></c> as a tuple of
+ integers. <c><anno>Host</anno></c> can be an IP-address, a single hostname
or a fully qualified hostname.</p>
</desc>
</func>
<func>
- <name>getaddrs(Host, Family) -> {ok, Addresses} | {error, posix()}</name>
+ <name name="getaddrs" arity="2"/>
<fsummary>Return the IP-addresses for a host</fsummary>
- <type>
- <v>Host = ip_address() | string() | atom()</v>
- <v>Addresses = [ip_address()]</v>
- <v>Family = inet | inet6</v>
- </type>
<desc>
- <p>Returns a list of all IP-addresses for <c>Host</c>.
- <c>Host</c> can be an IP-address, a single hostname or a fully
+ <p>Returns a list of all IP-addresses for <c><anno>Host</anno></c>.
+ <c><anno>Host</anno></c> can be an IP-address, a single hostname or a fully
qualified hostname.</p>
</desc>
</func>
<func>
- <name>gethostbyaddr(Address) -> {ok, Hostent} | {error, posix()}</name>
+ <name name="gethostbyaddr" arity="1"/>
<fsummary>Return a hostent record for the host with the given address</fsummary>
- <type>
- <v>Address = string() | ip_address()</v>
- <v>Hostent = #hostent{}</v>
- </type>
<desc>
<p>Returns a <c>hostent</c> record given an address.</p>
</desc>
</func>
<func>
- <name>gethostbyname(Name) -> {ok, Hostent} | {error, posix()}</name>
+ <name name="gethostbyname" arity="1"/>
<fsummary>Return a hostent record for the host with the given name</fsummary>
- <type>
- <v>Hostname = hostname()</v>
- <v>Hostent = #hostent{}</v>
- </type>
<desc>
<p>Returns a <c>hostent</c> record given a hostname.</p>
</desc>
</func>
<func>
- <name>gethostbyname(Name, Family) -> {ok, Hostent} | {error, posix()}</name>
+ <name name="gethostbyname" arity="2"/>
<fsummary>Return a hostent record for the host with the given name</fsummary>
- <type>
- <v>Hostname = hostname()</v>
- <v>Family = inet | inet6</v>
- <v>Hostent = #hostent{}</v>
- </type>
<desc>
<p>Returns a <c>hostent</c> record given a hostname, restricted
to the given address family.</p>
</desc>
</func>
<func>
- <name>gethostname() -> {ok, Hostname}</name>
+ <name name="gethostname" arity="0"/>
<fsummary>Return the local hostname</fsummary>
- <type>
- <v>Hostname = string()</v>
- </type>
<desc>
<p>Returns the local hostname. Will never fail.</p>
</desc>
</func>
<func>
- <name>getifaddrs() -> {ok,Iflist} | {error,posix}</name>
+ <name name="getifaddrs" arity="0"/>
<fsummary>Return a list of interfaces and their addresses</fsummary>
- <type>
- <v>Iflist = {Ifname,[Ifopt]}</v>
- <v>Ifname = string()</v>
- <v>Ifopt = {flag,[Flag]} | {addr,Addr} | {netmask,Netmask}
- | {broadaddr,Broadaddr} | {dstaddr,Dstaddr}
- | {hwaddr,Hwaddr}</v>
- <v>Flag = up | broadcast | loopback | pointtopoint
- | running | multicast</v>
- <v>Addr = Netmask = Broadadddr = Dstaddr = ip_address()</v>
- <v>Hwaddr = [byte()]</v>
- </type>
- </func>
<desc>
<p>
Returns a list of 2-tuples containing interface names and the
- interface's addresses. <c>Ifname</c> is a Unicode string.
- <c>Hwaddr</c> is hardware dependent, e.g on Ethernet interfaces
+ interface's addresses. <c><anno>Ifname</anno></c> is a Unicode string.
+ <c><anno>Hwaddr</anno></c> is hardware dependent, e.g on Ethernet interfaces
it is the 6-byte Ethernet address (MAC address (EUI-48 address)).
</p>
<p>
- The <c>{addr,Addr}</c>, <c>{netmask,_}</c> and <c>{broadaddr,_}</c>
+ The <c>{addr,<anno>Addr</anno>}</c>, <c>{netmask,_}</c> and <c>{broadaddr,_}</c>
tuples are repeated in the result list iff the interface has multiple
addresses. If you come across an interface that has
multiple <c>{flag,_}</c> or <c>{hwaddr,_}</c> tuples you have
@@ -252,8 +217,8 @@ fe80::204:acff:fe17:bf38
The <c>{flag,_}</c> tuple is mandatory, all other optional.
</p>
<p>
- Do not rely too much on the order of <c>Flag</c> atoms or
- <c>Ifopt</c> tuples. There are some rules, though:
+ Do not rely too much on the order of <c><anno>Flag</anno></c> atoms or
+ <c><anno>Ifopt</anno></c> tuples. There are some rules, though:
<list>
<item>
Immediately after <c>{addr,_}</c> follows <c>{netmask,_}</c>
@@ -261,7 +226,7 @@ fe80::204:acff:fe17:bf38
<item>
Immediately thereafter follows <c>{broadaddr,_}</c> if
the <c>broadcast</c> flag is <em>not</em> set and the
- <c>pointtopoint</c>flag <em>is</em> set.
+ <c>pointtopoint</c> flag <em>is</em> set.
</item>
<item>
Any <c>{netmask,_}</c>, <c>{broadaddr,_}</c> or
@@ -277,11 +242,12 @@ fe80::204:acff:fe17:bf38
</p>
<p>
On Windows, the data is fetched from quite different OS API
- functions, so the <c>Netmask</c> and <c>Broadaddr</c>
- values may be calculated, just as some <c>Flag</c> values.
+ functions, so the <c><anno>Netmask</anno></c> and <c><anno>Broadaddr</anno></c>
+ values may be calculated, just as some <c><anno>Flag</anno></c> values.
You have been warned. Report flagrant bugs.
</p>
</desc>
+ </func>
<func>
<name>getopts(Socket, Options) -> {ok, OptionValues} | {error, posix()}</name>
@@ -291,13 +257,14 @@ fe80::204:acff:fe17:bf38
<v>Options = [Opt | RawOptReq]</v>
<v>Opt = atom()</v>
<v>RawOptReq = {raw, Protocol, OptionNum, ValueSpec}</v>
- <v>Protocol = int()</v>
- <v>OptionNum = int()</v>
+ <v>Protocol = integer()</v>
+ <v>OptionNum = integer()</v>
<v>ValueSpec = ValueSize | ValueBin</v>
- <v>ValueSize = int()</v>
+ <v>ValueSize = integer()</v>
<v>ValueBin = binary()</v>
<v>OptionValues = [{Opt, Val} | {raw, Protocol, OptionNum, ValueBin}]</v>
</type>
+ <type name="socket_getopt"/>
<desc>
<p>Gets one or more options for a socket.
See <seealso marker="#setopts/2">setopts/2</seealso>
@@ -419,13 +386,8 @@ fe80::204:acff:fe17:bf38
</func>
<func>
- <name>peername(Socket) -> {ok, {Address, Port}} | {error, posix()}</name>
+ <name name="peername" arity="1"/>
<fsummary>Return the address and port for the other end of a connection</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Address = ip_address()</v>
- <v>Port = int()</v>
- </type>
<desc>
<p>Returns the address and port for the other end of a
connection.</p>
@@ -436,20 +398,15 @@ fe80::204:acff:fe17:bf38
<fsummary>Return the local port number for a socket</fsummary>
<type>
<v>Socket = socket()</v>
- <v>Port = int()</v>
+ <v>Port = integer()</v>
</type>
<desc>
<p>Returns the local port number for a socket.</p>
</desc>
</func>
<func>
- <name>sockname(Socket) -> {ok, {Address, Port}} | {error, posix()}</name>
+ <name name="sockname" arity="1"/>
<fsummary>Return the local address and port number for a socket</fsummary>
- <type>
- <v>Socket = socket()</v>
- <v>Address = ip_address()</v>
- <v>Port = int()</v>
- </type>
<desc>
<p>Returns the local address and port number for a socket.</p>
</desc>
@@ -460,8 +417,8 @@ fe80::204:acff:fe17:bf38
<type>
<v>Socket = term()</v>
<v>Options = [{Opt, Val} | {raw, Protocol, Option, ValueBin}]</v>
- <v>Protocol = int()</v>
- <v>OptionNum = int()</v>
+ <v>Protocol = integer()</v>
+ <v>OptionNum = integer()</v>
<v>ValueBin = binary()</v>
<v>&nbsp;Opt, Val -- see below</v>
</type>
diff --git a/lib/kernel/doc/src/inet_res.xml b/lib/kernel/doc/src/inet_res.xml
index d8fe23544b..bf73ccf13d 100644
--- a/lib/kernel/doc/src/inet_res.xml
+++ b/lib/kernel/doc/src/inet_res.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2009</year><year>2009</year>
+ <year>2009</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -76,64 +76,38 @@
query is tried for the <c>alt_nameservers</c>.</p>
</section>
-
-
-
- <section>
- <title>DATA TYPES</title>
- <p>As defined in the module
- <seealso marker="kernel:inet">inet</seealso>:</p>
- <code type="none">
-hostent() = #hostent{}
-posix() = some atom()s
-ip_address() = tuple of integers of arity 4 or 8</code>
-
+ <datatypes>
<p>Resolver types:</p>
- <code type="none">These correspond to resolver options:
-
-res_option() =
- [ {alt_nameservers, [ nameserver() ]}
- | {edns, 0 | false} % Use EDNS
- | {inet6, bool()} % Return IPv6 addresses
- | {nameservers, [ nameserver() ]} % List of nameservers
- | {recurse, bool()} % Request server recursion
- | {retry, integer()} % UDP retries
- | {timeout, integer()} % UDP query timeout
- | {udp_payload_size, integer()} % EDNS payload size
- | {usevc, bool()} ] % Use TCP (Virtual Circuit)
-
-nameserver() = {ip_address(),Port}
- Port = integer(1..65535)
-
-res_error() =
- formerr |
- qfmterror |
- servfail |
- nxdomain |
- notimp |
- refused |
- badvers |
- timeout
-</code>
-
- <p>DNS types:</p>
- <marker id="dns_types"/>
- <code type="none">dns_name() = string() with no adjacent dots
-
-rr_type() = a | aaaa | cname | gid | hinfo | ns | mb | md | mg | mf
- | minfo | mx | naptr | null | ptr | soa | spf | srv | txt
- | uid | uinfo | unspec | wks
-
-query_type() = axfr | mailb | maila | any | rr_type()
-
-dns_class() = in | chaos | hs | any
-
+ <datatype>
+ <name name="res_option"/>
+ </datatype>
+ <datatype>
+ <name name="nameserver"/>
+ </datatype>
+ <datatype>
+ <name name="res_error"/>
+ </datatype>
+
+ <p><marker id="dns_types"/>DNS types:</p>
+ <datatype>
+ <name name="dns_name"/>
+ <desc><p>A string with no adjacent dots.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="rr_type"/>
+ </datatype>
+ <datatype>
+ <name name="dns_class"/>
+ </datatype>
+ <datatype>
+ <name name="dns_msg"/>
+ <desc>
+ <p>This is the start of a hiearchy of opaque data structures
+ that can be examined with access functions in inet_dns that
+ return lists of {Field,Value} tuples. The arity 2 functions
+ just return the value for a given field.
+<pre>
dns_msg() = DnsMsg
- This is the start of a hiearchy of opaque data structures
- that can be examined with access functions in inet_dns
- that return lists of {Field,Value} tuples. The arity 2
- functions just return the value for a given field.
-
inet_dns:msg(DnsMsg) ->
[ {header, dns_header()}
| {qdlist, dns_query()}
@@ -143,19 +117,21 @@ dns_msg() = DnsMsg
inet_dns:msg(DnsMsg, header) -> dns_header() % for example
inet_dns:msg(DnsMsg, Field) -> Value
-dhs_header() = DnsHeader
+dns_header() = DnsHeader
inet_dns:header(DnsHeader) ->
[ {id, integer()}
- | {qr, bool()}
+ | {qr, boolean()}
| {opcode, 'query' | iquery | status | integer()}
- | {aa, bool()}
- | {tc, bool()}
- | {rd, bool()}
- | {ra, bool()}
- | {pr, bool()}
+ | {aa, boolean()}
+ | {tc, boolean()}
+ | {rd, boolean()}
+ | {ra, boolean()}
+ | {pr, boolean()}
| {rcode, integer(0..16)} ]
inet_dns:header(DnsHeader, Field) -> Value
+query_type() = axfr | mailb | maila | any | rr_type()
+
dns_query() = DnsQuery
inet_dns:dns_query(DnsQuery) ->
[ {domain, dns_name()}
@@ -179,32 +155,6 @@ dns_rr() = DnsRr
| {data, dns_data()} ]
inet_dns:rr(DnsRr, Field) -> Value
-dns_data() = % for dns_type()
- [ dns_name() % ns, md, mf, cname, mb, mg, mr, ptr
- | ip_address(v4) % a
- | ip_address(v6) % aaaa
- | {MName,RName,Serial,Refresh,Retry,Expiry,Minimum} % soa
- | {ip_address(v4),Proto,BitMap} % wks
- | {CpuString,OsString} % hinfo
- | {RM,EM} % minfo
- | {Prio,dns_name()} % mx
- | {Prio,Weight,Port,dns_name()} % srv
- | {Order,Preference,Flags,Services,Regexp,dns_name()} % naptr
- | [ string() ] % txt, spf
- | binary() ] % null, integer()
-MName, RName = dns_name()
-Serial, Refresh, Retry, Expiry, Minimum = integer(),
-Proto = integer()
-BitMap = binary()
-CpuString, OsString = string()
-RM = EM = dns_name()
-Prio, Weight, Port = integer()
-Order, Preference = integer()
-Flags, Services = string(),
-Regexp = string(utf8)
-
-
-
There is an info function for the types above:
inet_dns:record_type(dns_msg()) -> msg;
@@ -214,26 +164,25 @@ inet_dns:record_type(dns_rr()) -> rr;
inet_dns:record_type(_) -> undefined.
So; inet_dns:(inet_dns:record_type(X))(X) will convert
-any of these data structures into a {Field,Value} list.</code>
- </section>
-
+any of these data structures into a {Field,Value} list.</pre></p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="dns_data"/>
+ <desc><p><c><anno>Regexp</anno></c> is a string with characters encoded in the
+ UTF-8 coding standard.</p>
+ </desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>getbyname(Name, Type) -> {ok,hostent()} | {error,Reason}</name>
- <name>getbyname(Name, Type, Timeout) ->
- {ok,hostent()} | {error,Reason}
- </name>
+ <name name="getbyname" arity="2"/>
+ <name name="getbyname" arity="3"/>
<fsummary>Resolve a DNS record of the given type for the given host
</fsummary>
- <type>
- <v>Name = dns_name()</v>
- <v>Type = rr_type()</v>
- <v>Timeout = integer() >= 0 | infinity</v>
- <v>Reason = posix() | res_error()</v>
- </type>
<desc>
<p>Resolve a DNS record of the given type for the given host,
of class <c>in</c>. On success returns a <c>hostent()</c> record with
@@ -252,17 +201,10 @@ any of these data structures into a {Field,Value} list.</code>
</func>
<func>
- <name>gethostbyaddr(Address) -> {ok,hostent()} | {error,Reason}</name>
- <name>gethostbyaddr(Address, Timeout) ->
- {ok,hostent()} | {error,Reason}
- </name>
+ <name name="gethostbyaddr" arity="1"/>
+ <name name="gethostbyaddr" arity="2"/>
<fsummary>Return a hostent record for the host with the given address
</fsummary>
- <type>
- <v>Address = ip_address()</v>
- <v>Timeout = integer() >= 0 | infinity</v>
- <v>Reason = posix() | res_error()</v>
- </type>
<desc>
<p>Backend functions used by
<seealso marker="kernel:inet#gethostbyaddr/1">
@@ -273,20 +215,11 @@ any of these data structures into a {Field,Value} list.</code>
</func>
<func>
- <name>gethostbyname(Name) -> {ok,hostent()} | Reason}</name>
- <name>gethostbyname(Name, Family) ->
- {ok,hostent()} | {error,Reason}}
- </name>
- <name>gethostbyname(Name, Family, Timeout) ->
- {ok,hostent()} | {error,Reason}
- </name>
+ <name name="gethostbyname" arity="1"/>
+ <name name="gethostbyname" arity="2"/>
+ <name name="gethostbyname" arity="3"/>
<fsummary>Return a hostent record for the host with the given name
</fsummary>
- <type>
- <v>Name = dns_name()</v>
- <v>Timeout = integer() >= 0 | infinity</v>
- <v>Reason = posix() | res_error()</v>
- </type>
<desc>
<p>Backend functions used by
<seealso marker="kernel:inet#gethostbyname/1">
@@ -305,26 +238,16 @@ any of these data structures into a {Field,Value} list.</code>
</func>
<func>
- <name>lookup(Name, Class, Type) -> [ dns_data() ]
- </name>
- <name>lookup(Name, Class, Type, Opts) -> [ dns_data() ]
- </name>
- <name>lookup(Name, Class, Type, Opts, Timeout) -> [ dns_data() ]
- </name>
+ <name name="lookup" arity="3"/>
+ <name name="lookup" arity="4"/>
+ <name name="lookup" arity="5"/>
<fsummary>Resolve the DNS data for the record of the given type and class
for the given name
</fsummary>
- <type>
- <v>Name = dns_name() | ip_address()</v>
- <v>Type = rr_type()</v>
- <v>Opts = res_option() | verbose</v>
- <v>Timeout = integer() >= 0 | infinity</v>
- <v>Reason = posix() | res_error()</v>
- </type>
<desc>
<p>Resolve the DNS data for the record of the given type and class
for the given name. On success filters out the answer records
- with the correct <c>Class</c> and <c>Type</c> and returns
+ with the correct <c><anno>Class</anno></c> and <c><anno>Type</anno></c> and returns
a list of their data fields. So a lookup for type <c>any</c>
will give an empty answer since the answer records have
specific types that are not <c>any</c>. An empty answer
@@ -332,44 +255,33 @@ any of these data structures into a {Field,Value} list.</code>
</p><p>
Calls <seealso marker="#resolve/3">resolve/2..4</seealso>
with the same arguments and filters the result, so
- <c>Opts</c> is explained there.
+ <c><anno>Opts</anno></c> is explained there.
</p>
</desc>
</func>
<func>
- <name>resolve(Name, Class, Type) -> {ok,dns_msg()} | Error
- </name>
- <name>resolve(Name, Class, Type, Opts) -> {ok,dns_msg()} | Error
- </name>
- <name>resolve(Name, Class, Type, Opts, Timeout) -> {ok,dns_msg()} | Error
- </name>
+ <name name="resolve" arity="3"/>
+ <name name="resolve" arity="4"/>
+ <name name="resolve" arity="5"/>
<fsummary>Resolve a DNS record of the given type and class
for the given name
</fsummary>
- <type>
- <v>Name = dns_name() | ip_address()</v>
- <v>Type = rr_type()</v>
- <v>Opts = res_option() | verbose | atom()</v>
- <v>Timeout = integer() >= 0 | infinity</v>
- <v>Error = {error,Reason} | {error,{Reason,dns_msg()}}</v>
- <v>Reason = posix() | res_error()</v>
- </type>
<desc>
<p>Resolve a DNS record of the given type and class for the given name.
The returned <c>dns_msg()</c> can be examined using
access functions in <c>inet_db</c> as described
in <seealso marker="#dns_types">DNS types</seealso>.
</p><p>
- If <c>Name</c> is an <c>ip_address()</c>, the domain name
+ If <c><anno>Name</anno></c> is an <c>ip_address()</c>, the domain name
to query for is generated as the standard reverse
".IN-ADDR.ARPA." name for an IPv4 address, or the
".IP6.ARPA." name for an IPv6 address.
In this case you most probably want to use
- <c>Class = in</c> and <c>Type = ptr</c> but it
+ <c><anno>Class</anno> = in</c> and <c><anno>Type</anno> = ptr</c> but it
is not done automatically.
</p><p>
- <c>Opts</c> override the corresponding resolver options.
+ <c><anno>Opts</anno></c> override the corresponding resolver options.
If the option <c>nameservers</c> is given, it is
also assumed that it is the complete list of nameserves,
so the resolver option <c>alt_nameserves</c> is ignored.
@@ -382,14 +294,14 @@ any of these data structures into a {Field,Value} list.</code>
of queries, replies retransmissions, etc, similar
to from utilities like <c>dig</c>, <c>nslookup</c> et.al.
</p><p>
- If <c>Opt</c> is an arbitrary atom it is interpreted
- as <c>{Opt,true}</c> unless the atom string starts with
- <c>"no"</c> making the interpretation <c>{Opt,false}</c>.
+ If <c><anno>Opt</anno></c> is an arbitrary atom it is interpreted
+ as <c>{<anno>Opt</anno>,true}</c> unless the atom string starts with
+ <c>"no"</c> making the interpretation <c>{<anno>Opt</anno>,false}</c>.
For example: <c>usevc</c> is an alias for <c>{usevc,true}</c>,
and <c>nousevc</c> an alias for <c>{usevc,false}</c>.
</p><p>
The <c>inet6</c> option currently has no effect on this function.
- You probably want to use <c>Type = a | aaaa</c> instead.
+ You probably want to use <c><anno>Type</anno> = a | aaaa</c> instead.
</p>
</desc>
</func>
@@ -430,24 +342,18 @@ any of these data structures into a {Field,Value} list.</code>
<funcs>
<func>
- <name>nslookup(Name, Class, Type) -> {ok,dns_msg()} | {error,Reason}
- </name>
- <name>nslookup(Name, Class, Type, Timeout) ->
- {ok,dns_msg()} | {error,Reason}
- </name>
- <name>nslookup(Name, Class, Type, Nameservers) ->
- {ok,dns_msg()} | {error,Reason}
- </name>
+ <name name="nslookup" arity="3"/>
+ <name name="nslookup" arity="4" clause_i="1"/>
+ <name name="nslookup" arity="4" clause_i="2"/>
<fsummary>Resolve a DNS record of the given type and class
for the given name
</fsummary>
- <type>
- <v>Name = dns_name() | ip_address()</v>
- <v>Type = rr_type()</v>
- <v>Nameservers = [ nameserver() ]</v>
- <v>Timeout = integer() >= 0 | infinity</v>
- <v>Reason = posix() | res_error()</v>
- </type>
+ <type variable="Name"/>
+ <type variable="Class"/>
+ <type variable="Type"/>
+ <type variable="Timeout" name_i="2"/>
+ <type variable="Nameservers"/>
+ <type variable="Reason"/>
<desc>
<p>Resolve a DNS record of the given type and class for the given name.
</p>
@@ -455,22 +361,11 @@ any of these data structures into a {Field,Value} list.</code>
</func>
<func>
- <name>nnslookup(Name, Class, Type, Nameservers) ->
- {ok,dns_msg()} | {error,posix()}
- </name>
- <name>nnslookup(Name, Class, Type, Nameservers, Timeout) ->
- {ok,dns_msg()} | {error,posix()}
- </name>
+ <name name="nnslookup" arity="4"/>
+ <name name="nnslookup" arity="5"/>
<fsummary>Resolve a DNS record of the given type and class
for the given name
</fsummary>
- <type>
- <v>Name = dns_name() | ip_address()</v>
- <v>Type = rr_type()</v>
- <v>Nameservers = [ nameserver() ]</v>
- <v>Timeout = integer() >= 0 | infinity</v>
- <v>Reason = posix() | res_error()</v>
- </type>
<desc>
<p>Resolve a DNS record of the given type and class for the given name.
</p>
diff --git a/lib/kernel/doc/src/net_adm.xml b/lib/kernel/doc/src/net_adm.xml
index 7ec4f7f0e7..f2aac9282c 100644
--- a/lib/kernel/doc/src/net_adm.xml
+++ b/lib/kernel/doc/src/net_adm.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -34,94 +34,70 @@
</description>
<funcs>
<func>
- <name>dns_hostname(Host) -> {ok, Name} | {error, Host}</name>
+ <name name="dns_hostname" arity="1"/>
<fsummary>Official name of a host</fsummary>
- <type>
- <v>Host = atom() | string()</v>
- <v>Name = string()</v>
- </type>
<desc>
- <p>Returns the official name of <c>Host</c>, or
- <c>{error, Host}</c> if no such name is found. See also
+ <p>Returns the official name of <c><anno>Host</anno></c>, or
+ <c>{error, <anno>Host</anno>}</c> if no such name is found. See also
<c>inet(3)</c>.</p>
</desc>
</func>
<func>
- <name>host_file() -> Hosts | {error, Reason}</name>
+ <name name="host_file" arity="0"/>
<fsummary>Read the <c>.hosts.erlang</c>file</fsummary>
- <type>
- <v>Hosts = [Host]</v>
- <v>&nbsp;Host = atom()</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Reads the <c>.hosts.erlang</c> file, see the section
<em>Files</em> below. Returns the hosts in this file as a
- list, or returns <c>{error, Reason}</c> if the file could not
- be read. See <c>file(3)</c> for possible values of
- <c>Reason</c>.</p>
+ list, or returns <c>{error, <anno>Reason</anno>}</c> if the file could not
+ be read or the Erlang terms on the file could not be interpreted.</p>
</desc>
</func>
<func>
- <name>localhost() -> Name</name>
+ <name name="localhost" arity="0"/>
<fsummary>Name of the local host</fsummary>
- <type>
- <v>Name = string()</v>
- </type>
<desc>
<p>Returns the name of the local host. If Erlang was started
- with the <c>-name</c> command line flag, <c>Name</c> is
+ with the <c>-name</c> command line flag, <c><anno>Name</anno></c> is
the fully qualified name.</p>
</desc>
</func>
<func>
- <name>names() -> {ok, [{Name, Port}]} | {error, Reason}</name>
- <name>names(Host) -> {ok, [{Name, Port}]} | {error, Reason}</name>
+ <name name="names" arity="0"/>
+ <name name="names" arity="1"/>
<fsummary>Names of Erlang nodes at a host</fsummary>
- <type>
- <v>Name = string()</v>
- <v>Port = int()</v>
- <v>Reason = address | term()</v>
- </type>
<desc>
<p>Similar to <c>epmd -names</c>, see <c>epmd(1)</c>.
- <c>Host</c> defaults to the local host. Returns the names and
+ <c><anno>Host</anno></c> defaults to the local host. Returns the names and
associated port numbers of the Erlang nodes that <c>epmd</c>
at the specified host has registered.</p>
<p>Returns <c>{error, address}</c> if <c>epmd</c> is not
- running. See <c>inet(3)</c> for other possible values of
- <c>Reason</c>.</p>
+ running.</p>
<pre>
(arne@dunn)1> <input>net_adm:names().</input>
{ok,[{"arne",40262}]}</pre>
</desc>
</func>
<func>
- <name>ping(Node) -> pong | pang</name>
+ <name name="ping" arity="1"/>
<fsummary>Set up a connection to a node</fsummary>
- <type>
- <v>Node = node()</v>
- </type>
<desc>
- <p>Tries to set up a connection to <c>Node</c>. Returns
+ <p>Tries to set up a connection to <c><anno>Node</anno></c>. Returns
<c>pang</c> if it fails, or <c>pong</c> if it is successful.</p>
</desc>
</func>
<func>
- <name>world() -> [node()]</name>
- <name>world(Arg) -> [node()]</name>
+ <name name="world" arity="0"/>
+ <name name="world" arity="1"/>
+ <type name="verbosity"/>
<fsummary>Lookup and connect to all nodes at all hosts in <c>.hosts.erlang</c></fsummary>
- <type>
- <v>Arg = silent | verbose</v>
- </type>
<desc>
<p>This function calls <c>names(Host)</c> for all hosts which
are specified in the Erlang host file <c>.hosts.erlang</c>,
collects the replies and then evaluates <c>ping(Node)</c> on
all those nodes. Returns the list of all nodes that were,
successfully pinged.</p>
- <p><c>Arg</c> defaults to <c>silent</c>.
- If <c>Arg == verbose</c>, the function writes information about which
+ <p><c><anno>Arg</anno></c> defaults to <c>silent</c>.
+ If <c><anno>Arg</anno> == verbose</c>, the function writes information about which
nodes it is pinging to stdout.</p>
<p>This function can be useful when a node is started, and
the names of the other nodes in the network are not initially
@@ -131,14 +107,10 @@
</desc>
</func>
<func>
- <name>world_list(Hosts) -> [node()]</name>
- <name>world_list(Hosts, Arg) -> [node()]</name>
+ <name name="world_list" arity="1"/>
+ <name name="world_list" arity="2"/>
+ <type name="verbosity"/>
<fsummary>Lookup and connect to all nodes at specified hosts</fsummary>
- <type>
- <v>Hosts = [Host]</v>
- <v>&nbsp;Host = atom()</v>
- <v>Arg = silent | verbose</v>
- </type>
<desc>
<p>As <c>world/0,1</c>, but the hosts are given as argument
instead of being read from <c>.hosts.erlang</c>.</p>
diff --git a/lib/kernel/doc/src/net_kernel.xml b/lib/kernel/doc/src/net_kernel.xml
index a18226e779..96e2aa665d 100644
--- a/lib/kernel/doc/src/net_kernel.xml
+++ b/lib/kernel/doc/src/net_kernel.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -64,50 +64,38 @@ $ <input>erl -sname foobar</input></pre>
</description>
<funcs>
<func>
- <name>allow(Nodes) -> ok | error</name>
+ <name name="allow" arity="1"/>
<fsummary>Limit access to a specified set of nodes</fsummary>
- <type>
- <v>Nodes = [node()]</v>
- </type>
<desc>
<p>Limits access to the specified set of nodes. Any access
- attempts made from (or to) nodes not in <c>Nodes</c> will be
+ attempts made from (or to) nodes not in <c><anno>Nodes</anno></c> will be
rejected.</p>
- <p>Returns <c>error</c> if any element in <c>Nodes</c> is not
+ <p>Returns <c>error</c> if any element in <c><anno>Nodes</anno></c> is not
an atom.</p>
</desc>
</func>
<func>
- <name>connect_node(Node) -> true | false | ignored</name>
+ <name name="connect_node" arity="1"/>
<fsummary>Establish a connection to a node</fsummary>
- <type>
- <v>Node = node()</v>
- </type>
<desc>
- <p>Establishes a connection to <c>Node</c>. Returns <c>true</c>
+ <p>Establishes a connection to <c><anno>Node</anno></c>. Returns <c>true</c>
if successful, <c>false</c> if not, and <c>ignored</c> if
the local node is not alive.</p>
</desc>
</func>
<func>
- <name>monitor_nodes(Flag) -> ok | Error</name>
- <name>monitor_nodes(Flag, Options) -> ok | Error</name>
+ <name name="monitor_nodes" arity="1"/>
+ <name name="monitor_nodes" arity="2"/>
<fsummary>Subscribe to node status change messages</fsummary>
- <type>
- <v>Flag = true | false</v>
- <v>Options = [Option]</v>
- <v>&nbsp;Option -- see below</v>
- <v>Error = error | {error, term()}</v>
- </type>
<desc>
<p>The calling process subscribes or unsubscribes to node
status change messages. A <c>nodeup</c> message is delivered
to all subscribing process when a new node is connected, and
a <c>nodedown</c> message is delivered when a node is
disconnected.</p>
- <p>If <c>Flag</c> is <c>true</c>, a new subscription is started.
- If <c>Flag</c> is <c>false</c>, all previous subscriptions --
- started with the same <c>Options</c> -- are stopped. Two
+ <p>If <c><anno>Flag</anno></c> is <c>true</c>, a new subscription is started.
+ If <c><anno>Flag</anno></c> is <c>false</c>, all previous subscriptions --
+ started with the same <c><anno>Options</anno></c> -- are stopped. Two
option lists are considered the same if they contain the same
set of options.</p>
<p>As of <c>kernel</c> version 2.11.4, and <c>erts</c> version
@@ -139,23 +127,23 @@ $ <input>erl -sname foobar</input></pre>
<p>Note, that this is <em>not</em> guaranteed for <c>kernel</c>
versions before 2.13.</p>
<p>The format of the node status change messages depends on
- <c>Options</c>. If <c>Options</c> is [], which is the default,
+ <c><anno>Options</anno></c>. If <c><anno>Options</anno></c> is [], which is the default,
the format is:</p>
<code type="none">
{nodeup, Node} | {nodedown, Node}
Node = node()</code>
- <p>If <c>Options /= []</c>, the format is:</p>
+ <p>If <c><anno>Options</anno> /= []</c>, the format is:</p>
<code type="none">
{nodeup, Node, InfoList} | {nodedown, Node, InfoList}
Node = node()
InfoList = [{Tag, Val}]</code>
<p><c>InfoList</c> is a list of tuples. Its contents depends on
- <c>Options</c>, see below.</p>
+ <c><anno>Options</anno></c>, see below.</p>
<p>Also, when <c>OptionList == []</c> only visible nodes, that
is, nodes that appear in the result of
<seealso marker="erts:erlang#nodes/0">nodes/0</seealso>, are
monitored.</p>
- <p><c>Option</c> can be any of the following:</p>
+ <p><c><anno>Option</anno></c> can be any of the following:</p>
<taglist>
<tag><c>{node_type, NodeType}</c></tag>
<item>
@@ -209,61 +197,51 @@ $ <input>erl -sname foobar</input></pre>
</desc>
</func>
<func>
- <name>get_net_ticktime() -> Res</name>
+ <name name="get_net_ticktime" arity="0"/>
<fsummary>Get <c>net_ticktime</c></fsummary>
- <type>
- <v>Res = NetTicktime | {ongoing_change_to, NetTicktime}</v>
- <v>&nbsp;NetTicktime = int()</v>
- </type>
<desc>
<p>Gets <c>net_ticktime</c> (see
<seealso marker="kernel_app">kernel(6)</seealso>).</p>
- <p>Currently defined return values (<c>Res</c>):</p>
+ <p>Currently defined return values (<c><anno>Res</anno></c>):</p>
<taglist>
- <tag><c>NetTicktime</c></tag>
+ <tag><c><anno>NetTicktime</anno></c></tag>
<item>
- <p><c>net_ticktime</c> is <c>NetTicktime</c> seconds.</p>
+ <p><c>net_ticktime</c> is <c><anno>NetTicktime</anno></c> seconds.</p>
</item>
- <tag><c>{ongoing_change_to, NetTicktime}</c></tag>
+ <tag><c>{ongoing_change_to, <anno>NetTicktime</anno>}</c></tag>
<item>
<p><c>net_kernel</c> is currently changing
- <c>net_ticktime</c> to <c>NetTicktime</c> seconds.</p>
+ <c>net_ticktime</c> to <c><anno>NetTicktime</anno></c> seconds.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>set_net_ticktime(NetTicktime) -> Res</name>
- <name>set_net_ticktime(NetTicktime, TransitionPeriod) -> Res</name>
+ <name name="set_net_ticktime" arity="1"/>
+ <name name="set_net_ticktime" arity="2"/>
<fsummary>Set <c>net_ticktime</c></fsummary>
- <type>
- <v>NetTicktime = int() > 0</v>
- <v>TransitionPeriod = int() >= 0</v>
- <v>Res = unchanged | change_initiated | {ongoing_change_to, NewNetTicktime}</v>
- <v>&nbsp;NewNetTicktime = int() > 0</v>
- </type>
<desc>
<p>Sets <c>net_ticktime</c> (see
<seealso marker="kernel_app">kernel(6)</seealso>) to
- <c>NetTicktime</c> seconds. <c>TransitionPeriod</c> defaults
+ <c><anno>NetTicktime</anno></c> seconds. <c><anno>TransitionPeriod</anno></c> defaults
to 60.</p>
<p>Some definitions:</p>
<p></p>
<taglist>
<tag>The minimum transition traffic interval (<c>MTTI</c>)</tag>
<item>
- <p><c>minimum(NetTicktime, PreviousNetTicktime)*1000 div 4</c> milliseconds.</p>
+ <p><c>minimum(<anno>NetTicktime</anno>, PreviousNetTicktime)*1000 div 4</c> milliseconds.</p>
</item>
<tag>The transition period</tag>
<item>
<p>The time of the least number of consecutive <c>MTTI</c>s
- to cover <c>TransitionPeriod</c> seconds following
+ to cover <c><anno>TransitionPeriod</anno></c> seconds following
the call to <c>set_net_ticktime/2</c> (i.e.
- ((<c>TransitionPeriod*1000 - 1) div MTTI + 1)*MTTI</c>
+ ((<c><anno>TransitionPeriod</anno>*1000 - 1) div MTTI + 1)*MTTI</c>
milliseconds).</p>
</item>
</taglist>
- <p>If <c><![CDATA[NetTicktime < PreviousNetTicktime]]></c>, the actual
+ <p>If <c><![CDATA[<anno>NetTicktime</anno> < PreviousNetTicktime]]></c>, the actual
<c>net_ticktime</c> change will be done at the end of
the transition period; otherwise, at the beginning. During
the transition period, <c>net_kernel</c> will ensure that
@@ -271,7 +249,7 @@ $ <input>erl -sname foobar</input></pre>
every <c>MTTI</c> millisecond.</p>
<note>
<p>The <c>net_ticktime</c> changes have to be initiated on all
- nodes in the network (with the same <c>NetTicktime</c>)
+ nodes in the network (with the same <c><anno>NetTicktime</anno></c>)
before the end of any transition period on any node;
otherwise, connections may erroneously be disconnected.</p>
</note>
@@ -280,18 +258,18 @@ $ <input>erl -sname foobar</input></pre>
<tag><c>unchanged</c></tag>
<item>
<p><c>net_ticktime</c> already had the value of
- <c>NetTicktime</c> and was left unchanged.</p>
+ <c><anno>NetTicktime</anno></c> and was left unchanged.</p>
</item>
<tag><c>change_initiated</c></tag>
<item>
<p><c>net_kernel</c> has initiated the change of
- <c>net_ticktime</c> to <c>NetTicktime</c> seconds.</p>
+ <c>net_ticktime</c> to <c><anno>NetTicktime</anno></c> seconds.</p>
</item>
- <tag><c>{ongoing_change_to, NewNetTicktime}</c></tag>
+ <tag><c>{ongoing_change_to, <anno>NewNetTicktime</anno>}</c></tag>
<item>
<p>The request was <em>ignored</em>; because,
<c>net_kernel</c> was busy changing <c>net_ticktime</c> to
- <c>NewTicktime</c> seconds.</p>
+ <c><anno>NewNetTicktime</anno></c> seconds.</p>
</item>
</taglist>
</desc>
@@ -315,7 +293,7 @@ $ <input>erl -sname foobar</input></pre>
</desc>
</func>
<func>
- <name>stop() -> ok | {error, not_allowed | not_found}</name>
+ <name name="stop" arity="0"/>
<fsummary>Turn a node into a non-distributed Erlang runtime system</fsummary>
<desc>
<p>Turns a distributed node into a non-distributed node. For
diff --git a/lib/kernel/doc/src/notes.xml b/lib/kernel/doc/src/notes.xml
index 065b24c53d..f92837dfe5 100644
--- a/lib/kernel/doc/src/notes.xml
+++ b/lib/kernel/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/kernel/doc/src/os.xml b/lib/kernel/doc/src/os.xml
index 2c9cc33eb7..56fc1834ec 100644
--- a/lib/kernel/doc/src/os.xml
+++ b/lib/kernel/doc/src/os.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2009</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -38,13 +38,10 @@
</description>
<funcs>
<func>
- <name>cmd(Command) -> string()</name>
+ <name name="cmd" arity="1"/>
<fsummary>Execute a command in a shell of the target OS</fsummary>
- <type>
- <v>Command = string() | atom()</v>
- </type>
<desc>
- <p>Executes <c>Command</c> in a command shell of the target OS,
+ <p>Executes <c><anno>Command</anno></c> in a command shell of the target OS,
captures the standard output of the command and returns this
result as a string. This function is a replacement of
the previous <c>unix:cmd/1</c>; on a Unix platform they are
@@ -60,23 +57,18 @@ DirOut = os:cmd("dir"), % on Win32 platform</code>
</desc>
</func>
<func>
- <name>find_executable(Name) -> Filename | false</name>
- <name>find_executable(Name, Path) -> Filename | false</name>
+ <name name="find_executable" arity="1"/>
+ <name name="find_executable" arity="2"/>
<fsummary>Absolute filename of a program</fsummary>
- <type>
- <v>Name = string()</v>
- <v>Path = string()</v>
- <v>Filename = string()</v>
- </type>
<desc>
<p>These two functions look up an executable program given its
name and a search path, in the same way as the underlying
operating system. <c>find_executable/1</c> uses the current
execution path (that is, the environment variable PATH on
Unix and Windows).</p>
- <p><c>Path</c>, if given, should conform to the syntax of
+ <p><c><anno>Path</anno></c>, if given, should conform to the syntax of
execution paths on the operating system. The absolute
- filename of the executable program <c>Name</c> is returned,
+ filename of the executable program <c><anno>Name</anno></c> is returned,
or <c>false</c> if the program was not found.</p>
</desc>
</func>
@@ -137,7 +129,7 @@ DirOut = os:cmd("dir"), % on Win32 platform</code>
<name>timestamp() -> {MegaSecs, Secs, MicroSecs}</name>
<fsummary>Returna a timestamp from the OS in the erlang:now/0 format</fsummary>
<type>
- <v>MegaSecs = Secs = MicroSecs = int()</v>
+ <v>MegaSecs = Secs = MicroSecs = integer() >= 0</v>
</type>
<desc>
<p>Returns a tuple in the same format as <seealso marker="erts:erlang#now/0">erlang:now/0</seealso>. The difference is that this function returns what the operating system thinks (a.k.a. the wall clock time) without any attempts at time correction. The result of two different calls to this function is <em>not</em> guaranteed to be different.</p>
@@ -165,19 +157,15 @@ format_utc_timestamp() ->
</desc>
</func>
<func>
- <name>type() -> {Osfamily, Osname} | Osfamily</name>
+ <name name="type" arity="0"/>
<fsummary>Return the OS family and, in some cases, OS name of the current operating system</fsummary>
- <type>
- <v>Osfamily = win32 | unix | vxworks</v>
- <v>Osname = atom()</v>
- </type>
<desc>
- <p>Returns the <c>Osfamily</c> and, in some cases, <c>Osname</c>
+ <p>Returns the <c><anno>Osfamily</anno></c> and, in some cases, <c><anno>Osname</anno></c>
of the current operating system.</p>
- <p>On Unix, <c>Osname</c> will have same value as
+ <p>On Unix, <c><anno>Osname</anno></c> will have same value as
<c>uname -s</c> returns, but in lower case. For example, on
Solaris 1 and 2, it will be <c>sunos</c>.</p>
- <p>In Windows, <c>Osname</c> will be either <c>nt</c> (on
+ <p>In Windows, <c><anno>Osname</anno></c> will be either <c>nt</c> (on
Windows NT), or <c>windows</c> (on Windows 95).</p>
<p>On VxWorks the OS family alone is returned, that is
<c>vxworks</c>.</p>
@@ -185,17 +173,13 @@ format_utc_timestamp() ->
<p>Think twice before using this function. Use the
<c>filename</c> module if you want to inspect or build
file names in a portable way.
- Avoid matching on the <c>Osname</c> atom.</p>
+ Avoid matching on the <c><anno>Osname</anno></c> atom.</p>
</note>
</desc>
</func>
<func>
- <name>version() -> {Major, Minor, Release} | VersionString</name>
+ <name name="version" arity="0"/>
<fsummary>Return the Operating System version</fsummary>
- <type>
- <v>Major = Minor = Release = integer()</v>
- <v>VersionString = string()</v>
- </type>
<desc>
<p>Returns the operating system version.
On most systems, this function returns a tuple, but a string
diff --git a/lib/kernel/doc/src/pg2.xml b/lib/kernel/doc/src/pg2.xml
index 7463fd10f5..d26ff0fc6b 100644
--- a/lib/kernel/doc/src/pg2.xml
+++ b/lib/kernel/doc/src/pg2.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2009</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -60,13 +60,16 @@
to avoid name clashes.</p>
</warning>
</description>
+ <datatypes>
+ <datatype>
+ <name name="name"/>
+ <desc><p>The name of a process group.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>create(Name) -> void()</name>
+ <name name="create" arity="1"/>
<fsummary>Create a new, empty process group</fsummary>
- <type>
- <v>Name = term()</v>
- </type>
<desc>
<p>Creates a new, empty process group. The group is globally
visible on all nodes. If the group exists, nothing happens.
@@ -74,24 +77,16 @@
</desc>
</func>
<func>
- <name>delete(Name) -> void()</name>
+ <name name="delete" arity="1"/>
<fsummary>Delete a process group</fsummary>
- <type>
- <v>Name = term()</v>
- </type>
<desc>
<p>Deletes a process group.
</p>
</desc>
</func>
<func>
- <name>get_closest_pid(Name) -> Pid | {error, Reason}</name>
+ <name name="get_closest_pid" arity="1"/>
<fsummary>Common dispatch function</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid = pid()</v>
- <v>Reason = {no_process, Name} | {no_such_group, Name}</v>
- </type>
<desc>
<p>This is a useful dispatch function which can be used from
client functions. It returns a process on the local node, if
@@ -100,13 +95,8 @@
</desc>
</func>
<func>
- <name>get_members(Name) -> [Pid] | {error, Reason}</name>
+ <name name="get_members" arity="1"/>
<fsummary>Return all processes in a group</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid = pid()</v>
- <v>Reason = {no_such_group, Name}</v>
- </type>
<desc>
<p>Returns all processes in the group <c>Name</c>. This
function should be used from within a client function that
@@ -115,13 +105,8 @@
</desc>
</func>
<func>
- <name>get_local_members(Name) -> [Pid] | {error, Reason}</name>
+ <name name="get_local_members" arity="1"/>
<fsummary>Return all local processes in a group</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid = pid()</v>
- <v>Reason = {no_such_group, Name}</v>
- </type>
<desc>
<p>Returns all processes running on the local node in the
group <c>Name</c>. This function should to be used from
@@ -131,13 +116,8 @@
</desc>
</func>
<func>
- <name>join(Name, Pid) -> ok | {error, Reason}</name>
+ <name name="join" arity="2"/>
<fsummary>Join a process to a group</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid = pid()</v>
- <v>Reason = {no_such_group, Name}</v>
- </type>
<desc>
<p>Joins the process <c>Pid</c> to the group <c>Name</c>.
A process can join a group several times; it must then
@@ -146,13 +126,8 @@
</desc>
</func>
<func>
- <name>leave(Name, Pid) -> ok | {error, Reason}</name>
+ <name name="leave" arity="2"/>
<fsummary>Make a process leave a group</fsummary>
- <type>
- <v>Name = term()</v>
- <v>Pid = pid()</v>
- <v>Reason = {no_such_group, Name}</v>
- </type>
<desc>
<p>Makes the process <c>Pid</c> leave the group <c>Name</c>.
If the process is not a member of the group, <c>ok</c> is
@@ -161,24 +136,17 @@
</desc>
</func>
<func>
- <name>which_groups() -> [Name]</name>
+ <name name="which_groups" arity="0"/>
<fsummary>Return a list of all known groups</fsummary>
- <type>
- <v>Name = term()</v>
- </type>
<desc>
<p>Returns a list of all known groups.
</p>
</desc>
</func>
<func>
- <name>start()</name>
- <name>start_link() -> {ok, Pid} | {error, Reason}</name>
+ <name name="start" arity="0"/>
+ <name name="start_link" arity="0"/>
<fsummary>Start the pg2 server</fsummary>
- <type>
- <v>Pid = pid()</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Starts the pg2 server. Normally, the server does not need
to be started explicitly, as it is started dynamically if it
diff --git a/lib/kernel/doc/src/rpc.xml b/lib/kernel/doc/src/rpc.xml
index 2b81de170d..b01ff16c85 100644
--- a/lib/kernel/doc/src/rpc.xml
+++ b/lib/kernel/doc/src/rpc.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -37,40 +37,34 @@
for collecting information on a remote node, or for running a
function with some specific side effects on the remote node.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="key"/>
+ <desc>
+ <p>As returned by <seealso marker="#async_call/4">
+ <c>async_call/4</c>.</seealso></p>
+ </desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>call(Node, Module, Function, Args) -> Res | {badrpc, Reason}</name>
+ <name name="call" arity="4"/>
<fsummary>Evaluate a function call on a node</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Res = term()</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Evaluates <c>apply(Module, Function, Args)</c> on the node
- <c>Node</c> and returns the corresponding value <c>Res</c>, or
- <c>{badrpc, Reason}</c> if the call fails.</p>
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c> on the node
+ <c><anno>Node</anno></c> and returns the corresponding value <c><anno>Res</anno></c>, or
+ <c>{badrpc, <anno>Reason</anno>}</c> if the call fails.</p>
</desc>
</func>
<func>
- <name>call(Node, Module, Function, Args, Timeout) -> Res | {badrpc, Reason}</name>
+ <name name="call" arity="5"/>
<fsummary>Evaluate a function call on a node</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Res = term()</v>
- <v>Reason = timeout | term()</v>
- <v>Timeout = int() | infinity</v>
- </type>
<desc>
- <p>Evaluates <c>apply(Module, Function, Args)</c> on the node
- <c>Node</c> and returns the corresponding value <c>Res</c>, or
- <c>{badrpc, Reason}</c> if the call fails. <c>Timeout</c> is
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c> on the node
+ <c><anno>Node</anno></c> and returns the corresponding value <c><anno>Res</anno></c>, or
+ <c>{badrpc, <anno>Reason</anno>}</c> if the call fails. <c><anno>Timeout</anno></c> is
a timeout value in milliseconds. If the call times out,
- <c>Reason</c> is <c>timeout</c>.</p>
+ <c><anno>Reason</anno></c> is <c>timeout</c>.</p>
<p>If the reply arrives after the call times out, no message
will contaminate the caller's message queue, since this
function spawns off a middleman process to act as (a void)
@@ -80,17 +74,10 @@
</desc>
</func>
<func>
- <name>block_call(Node, Module, Function, Args) -> Res | {badrpc, Reason}</name>
+ <name name="block_call" arity="4"/>
<fsummary>Evaluate a function call on a node in the RPC server's context</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Res = term()</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Like <c>call/4</c>, but the RPC server at <c>Node</c> does
+ <p>Like <c>call/4</c>, but the RPC server at <c><anno>Node</anno></c> does
not create a separate process to handle the call. Thus,
this function can be used if the intention of the call is to
block the RPC server from any other incoming requests until
@@ -101,50 +88,31 @@
</desc>
</func>
<func>
- <name>block_call(Node, Module, Function, Args, Timeout) -> Res | {badrpc, Reason}</name>
+ <name name="block_call" arity="5"/>
<fsummary>Evaluate a function call on a node in the RPC server's context</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Timeout = int() | infinity</v>
- <v>Res = term()</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Like <c>block_call/4</c>, but with a timeout value in
the same manner as <c>call/5</c>.</p>
</desc>
</func>
<func>
- <name>async_call(Node, Module, Function, Args) -> Key</name>
+ <name name="async_call" arity="4"/>
<fsummary>Evaluate a function call on a node, asynchronous version</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Key -- see below</v>
- </type>
<desc>
<p>Implements <em>call streams with promises</em>, a type of
RPC which does not suspend the caller until the result is
finished. Instead, a key is returned which can be used at a
later stage to collect the value. The key can be viewed as a
promise to deliver the answer.</p>
- <p>In this case, the key <c>Key</c> is returned, which can be
+ <p>In this case, the key <c><anno>Key</anno></c> is returned, which can be
used in a subsequent call to <c>yield/1</c> or
<c>nb_yield/1,2</c> to retrieve the value of evaluating
- <c>apply(Module, Function, Args)</c> on the node <c>Node</c>.</p>
+ <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c> on the node <c><anno>Node</anno></c>.</p>
</desc>
</func>
<func>
- <name>yield(Key) -> Res | {badrpc, Reason}</name>
+ <name name="yield" arity="1"/>
<fsummary>Deliver the result of evaluating a function call on a node (blocking)</fsummary>
- <type>
- <v>Key -- see async_call/4</v>
- <v>Res = term()</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Returns the promised answer from a previous
<c>async_call/4</c>. If the answer is available, it is
@@ -153,87 +121,46 @@
</desc>
</func>
<func>
- <name>nb_yield(Key) -> {value, Val} | timeout</name>
+ <name name="nb_yield" arity="1"/>
<fsummary>Deliver the result of evaluating a function call on a node (non-blocking)</fsummary>
- <type>
- <v>Key -- see async_call/4</v>
- <v>Val = Res | {badrpc, Reason}</v>
- <v>&nbsp;Res = term()</v>
- <v>&nbsp;Reason = term()</v>
- </type>
<desc>
- <p>Equivalent to <c>nb_yield(Key, 0)</c>.</p>
+ <p>Equivalent to <c>nb_yield(<anno>Key</anno>, 0)</c>.</p>
</desc>
</func>
<func>
- <name>nb_yield(Key, Timeout) -> {value, Val} | timeout</name>
+ <name name="nb_yield" arity="2"/>
<fsummary>Deliver the result of evaluating a function call on a node (non-blocking)</fsummary>
- <type>
- <v>Key -- see async_call/4</v>
- <v>Timeout = int() | infinity</v>
- <v>Val = Res | {badrpc, Reason}</v>
- <v>&nbsp;Res = term()</v>
- <v>&nbsp;Reason = term()</v>
- </type>
<desc>
<p>This is a non-blocking version of <c>yield/1</c>. It returns
- the tuple <c>{value, Val}</c> when the computation has
- finished, or <c>timeout</c> when <c>Timeout</c> milliseconds
+ the tuple <c>{value, <anno>Val</anno>}</c> when the computation has
+ finished, or <c>timeout</c> when <c><anno>Timeout</anno></c> milliseconds
has elapsed.</p>
</desc>
</func>
<func>
- <name>multicall(Module, Function, Args) -> {ResL, BadNodes}</name>
+ <name name="multicall" arity="3"/>
<fsummary>Evaluate a function call on a number of nodes</fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>ResL = [term()]</v>
- <v>BadNodes = [node()]</v>
- </type>
<desc>
- <p>Equivalent to <c>multicall([node()|nodes()], Module, Function, Args, infinity)</c>.</p>
+ <p>Equivalent to <c>multicall([node()|nodes()], <anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>, infinity)</c>.</p>
</desc>
</func>
<func>
- <name>multicall(Nodes, Module, Function, Args) -> {ResL, BadNodes}</name>
+ <name name="multicall" arity="4" clause_i="1"/>
<fsummary>Evaluate a function call on a number of nodes</fsummary>
- <type>
- <v>Nodes = [node()]</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>ResL = [term()]</v>
- <v>BadNodes = [node()]</v>
- </type>
<desc>
- <p>Equivalent to <c>multicall(Nodes, Module, Function, Args, infinity)</c>.</p>
+ <p>Equivalent to <c>multicall(<anno>Nodes</anno>, <anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>, infinity)</c>.</p>
</desc>
</func>
<func>
- <name>multicall(Module, Function, Args, Timeout) -> {ResL, BadNodes}</name>
+ <name name="multicall" arity="4" clause_i="2"/>
<fsummary>Evaluate a function call on a number of nodes</fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Timeout = int() | infinity</v>
- <v>ResL = [term()]</v>
- <v>BadNodes = [node()]</v>
- </type>
<desc>
- <p>Equivalent to <c>multicall([node()|nodes()], Module, Function, Args, Timeout)</c>.</p>
+ <p>Equivalent to <c>multicall([node()|nodes()], <anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>, <anno>Timeout</anno>)</c>.</p>
</desc>
</func>
<func>
- <name>multicall(Nodes, Module, Function, Args, Timeout) -> {ResL, BadNodes}</name>
+ <name name="multicall" arity="5"/>
<fsummary>Evaluate a function call on a number of nodes</fsummary>
- <type>
- <v>Nodes = [node()]</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Timeout = int() | infinity</v>
- <v>ResL = [term()]</v>
- <v>BadNodes = [node()]</v>
- </type>
<desc>
<p>In contrast to an RPC, a multicall is an RPC which is sent
concurrently from one client to multiple servers. This is
@@ -243,12 +170,12 @@
making a series of RPCs on all the nodes, but the multicall
is faster as all the requests are sent at the same time
and are collected one by one as they come back.</p>
- <p>The function evaluates <c>apply(Module, Function, Args)</c>
+ <p>The function evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c>
on the specified nodes and collects the answers. It returns
- <c>{ResL, Badnodes}</c>, where <c>Badnodes</c> is a list
+ <c>{<anno>ResL</anno>, <anno>BadNodes</anno>}</c>, where <c><anno>BadNodes</anno></c> is a list
of the nodes that terminated or timed out during computation,
- and <c>ResL</c> is a list of the return values.
- <c>Timeout</c> is a time (integer) in milliseconds, or
+ and <c><anno>ResL</anno></c> is a list of the return values.
+ <c><anno>Timeout</anno></c> is a time (integer) in milliseconds, or
<c>infinity</c>.</p>
<p>The following example is useful when new object code is to
be loaded on all nodes in the network, and also indicates
@@ -264,93 +191,60 @@
</desc>
</func>
<func>
- <name>cast(Node, Module, Function, Args) -> void()</name>
+ <name name="cast" arity="4"/>
<fsummary>Run a function on a node ignoring the result</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
- <p>Evaluates <c>apply(Module, Function, Args)</c> on the node
- <c>Node</c>. No response is delivered and the calling
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c> on the node
+ <c><anno>Node</anno></c>. No response is delivered and the calling
process is not suspended until the evaluation is complete, as
is the case with <c>call/4,5</c>.</p>
</desc>
</func>
<func>
- <name>eval_everywhere(Module, Funtion, Args) -> void()</name>
+ <name name="eval_everywhere" arity="3"/>
<fsummary>Run a function on all nodes, ignoring the result</fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
- <p>Equivalent to <c>eval_everywhere([node()|nodes()], Module, Function, Args)</c>.</p>
+ <p>Equivalent to <c>eval_everywhere([node()|nodes()], <anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c>.</p>
</desc>
</func>
<func>
- <name>eval_everywhere(Nodes, Module, Function, Args) -> void()</name>
+ <name name="eval_everywhere" arity="4"/>
<fsummary>Run a function on specific nodes, ignoring the result</fsummary>
- <type>
- <v>Nodes = [node()]</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
- <p>Evaluates <c>apply(Module, Function, Args)</c> on
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c> on
the specified nodes. No answers are collected.</p>
</desc>
</func>
<func>
- <name>abcast(Name, Msg) -> void()</name>
+ <name name="abcast" arity="2"/>
<fsummary>Broadcast a message asynchronously to a registered process on all nodes</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Msg = term()</v>
- </type>
<desc>
- <p>Equivalent to <c>abcast([node()|nodes()], Name, Msg)</c>.</p>
+ <p>Equivalent to <c>abcast([node()|nodes()], <anno>Name</anno>, <anno>Msg</anno>)</c>.</p>
</desc>
</func>
<func>
- <name>abcast(Nodes, Name, Msg) -> void()</name>
+ <name name="abcast" arity="3"/>
<fsummary>Broadcast a message asynchronously to a registered process on specific nodes</fsummary>
- <type>
- <v>Nodes = [node()]</v>
- <v>Name = atom()</v>
- <v>Msg = term()</v>
- </type>
<desc>
- <p>Broadcasts the message <c>Msg</c> asynchronously to
- the registered process <c>Name</c> on the specified nodes.</p>
+ <p>Broadcasts the message <c><anno>Msg</anno></c> asynchronously to
+ the registered process <c><anno>Name</anno></c> on the specified nodes.</p>
</desc>
</func>
<func>
- <name>sbcast(Name, Msg) -> {GoodNodes, BadNodes}</name>
+ <name name="sbcast" arity="2"/>
<fsummary>Broadcast a message synchronously to a registered process on all nodes</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Msg = term()</v>
- <v>GoodNodes = BadNodes = [node()]</v>
- </type>
<desc>
- <p>Equivalent to <c>sbcast([node()|nodes()], Name, Msg)</c>.</p>
+ <p>Equivalent to <c>sbcast([node()|nodes()], <anno>Name</anno>, <anno>Msg</anno>)</c>.</p>
</desc>
</func>
<func>
- <name>sbcast(Nodes, Name, Msg) -> {GoodNodes, BadNodes}</name>
+ <name name="sbcast" arity="3"/>
<fsummary>Broadcast a message synchronously to a registered process on specific nodes</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Msg = term()</v>
- <v>Nodes = GoodNodes = BadNodes = [node()]</v>
- </type>
<desc>
- <p>Broadcasts the message <c>Msg</c> synchronously to
- the registered process <c>Name</c> on the specified nodes.</p>
- <p>Returns <c>{GoodNodes, BadNodes}</c>, where <c>GoodNodes</c>
- is the list of nodes which have <c>Name</c> as a registered
+ <p>Broadcasts the message <c><anno>Msg</anno></c> synchronously to
+ the registered process <c><anno>Name</anno></c> on the specified nodes.</p>
+ <p>Returns <c>{<anno>GoodNodes</anno>, <anno>BadNodes</anno>}</c>, where <c><anno>GoodNodes</anno></c>
+ is the list of nodes which have <c><anno>Name</anno></c> as a registered
process.</p>
<p>The function is synchronous in the sense that it is known
that all servers have received the message when the call
@@ -362,67 +256,46 @@
</desc>
</func>
<func>
- <name>server_call(Node, Name, ReplyWrapper, Msg) -> Reply | {error, Reason}</name>
+ <name name="server_call" arity="4"/>
<fsummary>Interact with a server on a node</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Name = atom()</v>
- <v>ReplyWrapper = Msg = Reply = term()</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>This function can be used when interacting with a server
- called <c>Name</c> at node <c>Node</c>. It is assumed that
+ called <c><anno>Name</anno></c> at node <c><anno>Node</anno></c>. It is assumed that
the server receives messages in the format
- <c>{From, Msg}</c> and replies using <c>From ! {ReplyWrapper, Node, Reply}</c>. This function makes such
+ <c>{From, <anno>Msg</anno>}</c> and replies using <c>From ! {<anno>ReplyWrapper</anno>, <anno>Node</anno>, <anno>Reply</anno>}</c>. This function makes such
a server call and ensures that the entire call is packed into
an atomic transaction which either succeeds or fails. It
never hangs, unless the server itself hangs.</p>
- <p>The function returns the answer <c>Reply</c> as produced by
- the server <c>Name</c>, or <c>{error, Reason}</c>.</p>
+ <p>The function returns the answer <c><anno>Reply</anno></c> as produced by
+ the server <c><anno>Name</anno></c>, or <c>{error, <anno>Reason</anno>}</c>.</p>
</desc>
</func>
<func>
- <name>multi_server_call(Name, Msg) -> {Replies, BadNodes}</name>
+ <name name="multi_server_call" arity="2"/>
<fsummary>Interact with the servers on a number of nodes</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Msg = term()</v>
- <v>Replies = [Reply]</v>
- <v>&nbsp;Reply = term()</v>
- <v>BadNodes = [node()]</v>
- </type>
<desc>
- <p>Equivalent to <c>multi_server_call([node()|nodes()], Name, Msg)</c>.</p>
+ <p>Equivalent to <c>multi_server_call([node()|nodes()], <anno>Name</anno>, <anno>Msg</anno>)</c>.</p>
</desc>
</func>
<func>
- <name>multi_server_call(Nodes, Name, Msg) -> {Replies, BadNodes}</name>
+ <name name="multi_server_call" arity="3"/>
<fsummary>Interact with the servers on a number of nodes</fsummary>
- <type>
- <v>Nodes = [node()]</v>
- <v>Name = atom()</v>
- <v>Msg = term()</v>
- <v>Replies = [Reply]</v>
- <v>&nbsp;Reply = term()</v>
- <v>BadNodes = [node()]</v>
- </type>
<desc>
<p>This function can be used when interacting with servers
- called <c>Name</c> on the specified nodes. It is assumed that
- the servers receive messages in the format <c>{From, Msg}</c>
- and reply using <c>From ! {Name, Node, Reply}</c>, where
+ called <c><anno>Name</anno></c> on the specified nodes. It is assumed that
+ the servers receive messages in the format <c>{From, <anno>Msg</anno>}</c>
+ and reply using <c>From ! {<anno>Name</anno>, Node, <anno>Reply</anno>}</c>, where
<c>Node</c> is the name of the node where the server is
- located. The function returns <c>{Replies, Badnodes}</c>,
- where <c>Replies</c> is a list of all <c>Reply</c> values and
- <c>BadNodes</c> is a list of the nodes which did not exist, or
+ located. The function returns <c>{<anno>Replies</anno>, <anno>BadNodes</anno>}</c>,
+ where <c><anno>Replies</anno></c> is a list of all <c><anno>Reply</anno></c> values and
+ <c><anno>BadNodes</anno></c> is a list of the nodes which did not exist, or
where the server did not exist, or where the server terminated
before sending any reply.</p>
</desc>
</func>
<func>
- <name>safe_multi_server_call(Name, Msg) -> {Replies, BadNodes}</name>
- <name>safe_multi_server_call(Nodes, Name, Msg) -> {Replies, BadNodes}</name>
+ <name name="safe_multi_server_call" arity="2"/>
+ <name name="safe_multi_server_call" arity="3"/>
<fsummary>Interact with the servers on a number of nodes (deprecated)</fsummary>
<desc>
<warning>
@@ -432,66 +305,47 @@
<p>In Erlang/OTP R6B and earlier releases,
<c>multi_server_call/2,3</c> could not handle the case
where the remote node exists, but there is no server called
- <c>Name</c>. Instead this function had to be used. In
+ <c><anno>Name</anno></c>. Instead this function had to be used. In
Erlang/OTP R7B and later releases, however, the functions are
equivalent, except for this function being slightly slower.</p>
</desc>
</func>
<func>
- <name>parallel_eval(FuncCalls) -> ResL</name>
+ <name name="parallel_eval" arity="1"/>
<fsummary>Evaluate several function calls on all nodes in parallel</fsummary>
- <type>
- <v>FuncCalls = [{Module, Function, Args}]</v>
- <v>&nbsp;Module = Function = atom()</v>
- <v>&nbsp;Args = [term()]</v>
- <v>ResL = [term()]</v>
- </type>
<desc>
- <p>For every tuple in <c>FuncCalls</c>, evaluates
- <c>apply(Module, Function, Args)</c> on some node in
+ <p>For every tuple in <c><anno>FuncCalls</anno></c>, evaluates
+ <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Args</anno>)</c> on some node in
the network. Returns the list of return values, in the same
- order as in <c>FuncCalls</c>.</p>
+ order as in <c><anno>FuncCalls</anno></c>.</p>
</desc>
</func>
<func>
- <name>pmap({Module, Function}, ExtraArgs, List1) -> List2</name>
+ <name name="pmap" arity="3"/>
<fsummary>Parallell evaluation of mapping a function over a list </fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>ExtraArgs = [term()]</v>
- <v>List1 = [Elem]</v>
- <v>&nbsp;Elem = term()</v>
- <v>List2 = [term()]</v>
- </type>
<desc>
- <p>Evaluates <c>apply(Module, Function, [Elem|ExtraArgs])</c>,
- for every element <c>Elem</c> in <c>List1</c>, in parallel.
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, [<anno>Elem</anno>|<anno>ExtraArgs</anno>])</c>,
+ for every element <c><anno>Elem</anno></c> in <c><anno>List1</anno></c>, in parallel.
Returns the list of return values, in the same order as in
- <c>List1</c>.</p>
+ <c><anno>List1</anno></c>.</p>
</desc>
</func>
<func>
- <name>pinfo(Pid) -> [{Item, Info}] | undefined</name>
+ <name name="pinfo" arity="1"/>
<fsummary>Information about a process</fsummary>
- <type>
- <v>Pid = pid()</v>
- <v>Item, Info -- see erlang:process_info/1</v>
- </type>
<desc>
<p>Location transparent version of the BIF
- <c>process_info/1</c>.</p>
+ <seealso marker="erts:erlang#process_info/1">
+ <c>process_info/1</c></seealso>.</p>
</desc>
</func>
<func>
- <name>pinfo(Pid, Item) -> {Item, Info} | undefined | []</name>
+ <name name="pinfo" arity="2"/>
<fsummary>Information about a process</fsummary>
- <type>
- <v>Pid = pid()</v>
- <v>Item, Info -- see erlang:process_info/1</v>
- </type>
<desc>
<p>Location transparent version of the BIF
- <c>process_info/2</c>.</p>
+ <seealso marker="erts:erlang#process_info/2">
+ <c>process_info/2</c></seealso>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/kernel/doc/src/seq_trace.xml b/lib/kernel/doc/src/seq_trace.xml
index 6c043dd767..1ab955bd8a 100644
--- a/lib/kernel/doc/src/seq_trace.xml
+++ b/lib/kernel/doc/src/seq_trace.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1998</year><year>2009</year>
+ <year>1998</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -47,17 +47,22 @@
from users.</p>
</note>
</description>
+ <datatypes>
+ <datatype>
+ <name name="token"/>
+ <desc>
+ <p>An opaque term (a tuple) representing a trace token.</p>
+ </desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>set_token(Token) -> PreviousToken</name>
+ <name name="set_token" arity="1"/>
<fsummary>Set the trace token</fsummary>
- <type>
- <v>Token = PreviousToken = term() | []</v>
- </type>
<desc>
- <p>Sets the trace token for the calling process to <c>Token</c>.
- If <c>Token == []</c> then tracing is disabled, otherwise
- <c>Token</c> should be an Erlang term returned from
+ <p>Sets the trace token for the calling process to <c><anno>Token</anno></c>.
+ If <c><anno>Token</anno> == []</c> then tracing is disabled, otherwise
+ <c><anno>Token</anno></c> should be an Erlang term returned from
<c>get_token/0</c> or <c>set_token/1</c>. <c>set_token/1</c>
can be used to temporarily exclude message passing from
the trace by setting the trace token to empty like this:</p>
@@ -72,18 +77,16 @@ seq_trace:set_token(OldToken), % activate the trace token again
</desc>
</func>
<func>
- <name>set_token(Component, Val) -> {Component, OldVal}</name>
+ <name name="set_token" arity="2"/>
<fsummary>Set a component of the trace token</fsummary>
- <type>
- <v>Component = label | serial | Flag</v>
- <v>&nbsp;Flag = send | 'receive' | print | timestamp </v>
- <v>Val = OldVal -- see below</v>
- </type>
+ <type name="component"/>
+ <type name="flag"/>
+ <type name="value"/>
<desc>
- <p>Sets the individual <c>Component</c> of the trace token to
- <c>Val</c>. Returns the previous value of the component.</p>
+ <p>Sets the individual <c><anno>Component</anno></c> of the trace token to
+ <c><anno>Val</anno></c>. Returns the previous value of the component.</p>
<taglist>
- <tag><c>set_token(label, Int)</c></tag>
+ <tag><c>set_token(label, <anno>Integer</anno>)</c></tag>
<item>
<p>The <c>label</c> component is an integer which
identifies all events belonging to the same sequential
@@ -93,31 +96,31 @@ seq_trace:set_token(OldToken), % activate the trace token again
</item>
<tag><c>set_token(serial, SerialValue)</c></tag>
<item>
- <p><c>SerialValue = {Previous, Current}</c>.
+ <p><c>SerialValue = {<anno>Previous</anno>, <anno>Current</anno>}</c>.
The <c>serial</c> component contains counters which
enables the traced messages to be sorted, should never be
set explicitly by the user as these counters are updated
automatically. Default is <c>{0, 0}</c>.</p>
</item>
- <tag><c>set_token(send, Bool)</c></tag>
+ <tag><c>set_token(send, <anno>Bool</anno>)</c></tag>
<item>
<p>A trace token flag (<c>true | false</c>) which
enables/disables tracing on message sending. Default is
<c>false</c>.</p>
</item>
- <tag><c>set_token('receive', Bool)</c></tag>
+ <tag><c>set_token('receive', <anno>Bool</anno>)</c></tag>
<item>
<p>A trace token flag (<c>true | false</c>) which
enables/disables tracing on message reception. Default is
<c>false</c>.</p>
</item>
- <tag><c>set_token(print, Bool)</c></tag>
+ <tag><c>set_token(print, <anno>Bool</anno>)</c></tag>
<item>
<p>A trace token flag (<c>true | false</c>) which
enables/disables tracing on explicit calls to
<c>seq_trace:print/1</c>. Default is <c>false</c>.</p>
</item>
- <tag><c>set_token(timestamp, Bool)</c></tag>
+ <tag><c>set_token(timestamp, <anno>Bool</anno>)</c></tag>
<item>
<p>A trace token flag (<c>true | false</c>) which
enables/disables a timestamp to be generated for each
@@ -127,11 +130,8 @@ seq_trace:set_token(OldToken), % activate the trace token again
</desc>
</func>
<func>
- <name>get_token() -> TraceToken</name>
+ <name name="get_token" arity="0"/>
<fsummary>Return the value of the trace token</fsummary>
- <type>
- <v>TraceToken = term() | []</v>
- </type>
<desc>
<p>Returns the value of the trace token for the calling process.
If <c>[]</c> is returned, it means that tracing is not active.
@@ -141,13 +141,11 @@ seq_trace:set_token(OldToken), % activate the trace token again
</desc>
</func>
<func>
- <name>get_token(Component) -> {Component, Val}</name>
+ <name name="get_token" arity="1"/>
<fsummary>Return the value of a trace token component</fsummary>
- <type>
- <v>Component = label | serial | Flag</v>
- <v>&nbsp;Flag = send | 'receive' | print | timestamp </v>
- <v>Val -- see set_token/2</v>
- </type>
+ <type name="component"/>
+ <type name="flag"/>
+ <type name="value"/>
<desc>
<p>Returns the value of the trace token component
<c>Component</c>. See
@@ -156,33 +154,26 @@ seq_trace:set_token(OldToken), % activate the trace token again
</desc>
</func>
<func>
- <name>print(TraceInfo) -> void()</name>
+ <name name="print" arity="1"/>
<fsummary>Put the Erlang term <c>TraceInfo</c>into the sequential trace output</fsummary>
- <type>
- <v>TraceInfo = term()</v>
- </type>
<desc>
- <p>Puts the Erlang term <c>TraceInfo</c> into the sequential
+ <p>Puts the Erlang term <c><anno>TraceInfo</anno></c> into the sequential
trace output if the calling process currently is executing
within a sequential trace and the <c>print</c> flag of
the trace token is set.</p>
</desc>
</func>
<func>
- <name>print(Label, TraceInfo) -> void()</name>
+ <name name="print" arity="2"/>
<fsummary>Put the Erlang term <c>TraceInfo</c>into the sequential trace output</fsummary>
- <type>
- <v>Label = int()</v>
- <v>TraceInfo = term()</v>
- </type>
<desc>
<p>Same as <c>print/1</c> with the additional condition that
- <c>TraceInfo</c> is output only if <c>Label</c> is equal to
+ <c><anno>TraceInfo</anno></c> is output only if <c>Label</c> is equal to
the label component of the trace token.</p>
</desc>
</func>
<func>
- <name>reset_trace() -> void()</name>
+ <name name="reset_trace" arity="0"/>
<fsummary>Stop all sequential tracing on the local node</fsummary>
<desc>
<p>Sets the trace token to empty for all processes on the
@@ -194,26 +185,22 @@ seq_trace:set_token(OldToken), % activate the trace token again
</desc>
</func>
<func>
- <name>set_system_tracer(Tracer) -> OldTracer</name>
+ <name name="set_system_tracer" arity="1"/>
<fsummary>Set the system tracer</fsummary>
- <type>
- <v>Tracer = OldTracer = pid() | port() | false</v>
- </type>
+ <type name="tracer"/>
<desc>
<p>Sets the system tracer. The system tracer can be either a
- process or port denoted by <c>Tracer</c>. Returns the previous
+ process or port denoted by <c><anno>Tracer</anno></c>. Returns the previous
value (which can be <c>false</c> if no system tracer is
active).</p>
- <p>Failure: <c>{badarg, Info}}</c> if <c>Pid</c> is not an
+ <p>Failure: <c>{badarg, Info}}</c> if <c><anno>Pid</anno></c> is not an
existing local pid.</p>
</desc>
</func>
<func>
- <name>get_system_tracer() -> Tracer</name>
+ <name name="get_system_tracer" arity="0"/>
<fsummary>Return the pid() or port() of the current system tracer.</fsummary>
- <type>
- <v>Tracer = pid() | port() | false</v>
- </type>
+ <type name="tracer"/>
<desc>
<p>Returns the pid or port identifier of the current system
tracer or <c>false</c> if no system tracer is activated.</p>
diff --git a/lib/kernel/doc/src/specs.xml b/lib/kernel/doc/src/specs.xml
new file mode 100644
index 0000000000..b41addaa0c
--- /dev/null
+++ b/lib/kernel/doc/src/specs.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="latin1" ?>
+<specs xmlns:xi="http://www.w3.org/2001/XInclude">
+ <xi:include href="../specs/specs_application.xml"/>
+ <xi:include href="../specs/specs_auth.xml"/>
+ <xi:include href="../specs/specs_code.xml"/>
+ <xi:include href="../specs/specs_disk_log.xml"/>
+ <xi:include href="../specs/specs_erl_boot_server.xml"/>
+ <xi:include href="../specs/specs_erl_ddll.xml"/>
+ <xi:include href="../specs/specs_erl_prim_loader_stub.xml"/>
+ <xi:include href="../specs/specs_erlang_stub.xml"/>
+ <xi:include href="../specs/specs_error_handler.xml"/>
+ <xi:include href="../specs/specs_error_logger.xml"/>
+ <xi:include href="../specs/specs_file.xml"/>
+ <xi:include href="../specs/specs_gen_tcp.xml"/>
+ <xi:include href="../specs/specs_gen_udp.xml"/>
+ <xi:include href="../specs/specs_gen_sctp.xml"/>
+ <xi:include href="../specs/specs_global.xml"/>
+ <xi:include href="../specs/specs_global_group.xml"/>
+ <xi:include href="../specs/specs_heart.xml"/>
+ <xi:include href="../specs/specs_inet.xml"/>
+ <xi:include href="../specs/specs_inet_res.xml"/>
+ <xi:include href="../specs/specs_init_stub.xml"/>
+ <xi:include href="../specs/specs_net_adm.xml"/>
+ <xi:include href="../specs/specs_net_kernel.xml"/>
+ <xi:include href="../specs/specs_os.xml"/>
+ <xi:include href="../specs/specs_pg2.xml"/>
+ <xi:include href="../specs/specs_rpc.xml"/>
+ <xi:include href="../specs/specs_seq_trace.xml"/>
+ <xi:include href="../specs/specs_user.xml"/>
+ <xi:include href="../specs/specs_wrap_log_reader.xml"/>
+ <xi:include href="../specs/specs_zlib_stub.xml"/>
+ <xi:include href="../specs/specs_packages.xml"/>
+</specs>
diff --git a/lib/kernel/doc/src/wrap_log_reader.xml b/lib/kernel/doc/src/wrap_log_reader.xml
index 18664a029f..6cf480b532 100644
--- a/lib/kernel/doc/src/wrap_log_reader.xml
+++ b/lib/kernel/doc/src/wrap_log_reader.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1998</year><year>2009</year>
+ <year>1998</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -50,18 +50,20 @@
the called node, it is entirely up to the user to be sure that all items are read.
</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="continuation"/>
+ <desc><p>Continuation returned by
+ <c>open/1,2</c> or <c>chunk/1,2</c>.</p>
+ </desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>chunk(Continuation)</name>
- <name>chunk(Continuation, N) -> {Continuation2, Terms} | {Continuation2, Terms, Badbytes} | {Continuation2, eof} | {error, Reason}</name>
+ <name name="chunk" arity="1"/>
+ <name name="chunk" arity="2"/>
<fsummary>Read a chunk of objects written to a wrap log.</fsummary>
- <type>
- <v>Continuation = continuation()</v>
- <v>N = int() > 0 | infinity</v>
- <v>Continuation2 = continuation()</v>
- <v>Terms= [term()]</v>
- <v>Badbytes = integer()</v>
- </type>
+ <type name="chunk_ret"/>
<desc>
<p>This function makes it possible to efficiently read the
terms which have been appended to a log. It minimises disk
@@ -70,29 +72,29 @@
<p>The first time <c>chunk</c> is called an initial
continuation returned from the <c>open/1</c>, <c>open/2</c> must be provided.
</p>
- <p>When <c>chunk/3</c> is called, <c>N</c> controls the
+ <p>When <c>chunk/3</c> is called, <c><anno>N</anno></c> controls the
maximum number of terms that are read from the log in each
chunk. Default is <c>infinity</c>, which means that all the
terms contained in the 8K chunk are read. If less than
- <c>N</c> terms are returned, this does not necessarily mean
+ <c><anno>N</anno></c> terms are returned, this does not necessarily mean
that end of file is reached.
</p>
<p>The <c>chunk</c> function returns a tuple
- <c>{Continuation2, Terms}</c>, where <c>Terms</c> is a list
- of terms found in the log. <c>Continuation2</c> is yet
+ <c>{<anno>Continuation2</anno>, <anno>Terms</anno>}</c>, where <c><anno>Terms</anno></c> is a list
+ of terms found in the log. <c><anno>Continuation2</anno></c> is yet
another continuation which must be passed on into any
subsequent calls to <c>chunk</c>. With a series of calls to
<c>chunk</c> it is then possible to extract all terms from a
log.
</p>
<p>The <c>chunk</c> function returns a tuple
- <c>{Continuation2, Terms, Badbytes}</c> if the log is opened
- in read only mode and the read chunk is corrupt. <c>Badbytes</c>
+ <c>{<anno>Continuation2</anno>, <anno>Terms</anno>, <anno>Badbytes</anno>}</c> if the log is opened
+ in read only mode and the read chunk is corrupt. <c><anno>Badbytes</anno></c>
indicates the number of non-Erlang terms found in the chunk.
Note also that the log is not repaired.
</p>
- <p><c>chunk</c> returns <c>{Continuation2, eof}</c> when the end of the log is
- reached, and <c>{error, Reason}</c> if an error occurs.
+ <p><c>chunk</c> returns <c>{<anno>Continuation2</anno>, eof}</c> when the end of the log is
+ reached, and <c>{error, <anno>Reason</anno>}</c> if an error occurs.
</p>
<p>The returned continuation may or may not be valid in the next call to
<c>chunk</c>. This is because the log may wrap and delete
@@ -103,37 +105,29 @@
</desc>
</func>
<func>
- <name>close(Continuation) -> ok </name>
+ <name name="close" arity="1"/>
<fsummary>Close a log</fsummary>
- <type>
- <v>Continuation = continuation()</v>
- </type>
<desc>
<p>This function closes a log file properly.
</p>
</desc>
</func>
<func>
- <name>open(Filename) -> OpenRet</name>
- <name>open(Filename, N) -> OpenRet</name>
+ <name name="open" arity="1"/>
+ <name name="open" arity="2"/>
<fsummary>Open a log file</fsummary>
- <type>
- <v>File = string() | atom()</v>
- <v>N = integer()</v>
- <v>OpenRet = {ok, Continuation} | {error, Reason} </v>
- <v>Continuation = continuation()</v>
- </type>
+ <type name="open_ret"/>
<desc>
- <p><c>Filename</c> specifies the name of the file which is to be read. </p>
- <p><c>N</c> specifies the index of the file which is to be read.
- If <c>N</c> is omitted the whole wrap log file will be read; if it
+ <p><c><anno>Filename</anno></c> specifies the name of the file which is to be read. </p>
+ <p><c><anno>N</anno></c> specifies the index of the file which is to be read.
+ If <c><anno>N</anno></c> is omitted the whole wrap log file will be read; if it
is specified only the specified index file will be read.
</p>
- <p>The <c>open</c> function returns <c>{ok, Continuation}</c> if the
- log/index file was successfully opened. The <c>Continuation</c>
+ <p>The <c>open</c> function returns <c>{ok, <anno>Continuation</anno>}</c> if the
+ log/index file was successfully opened. The <c><anno>Continuation</anno></c>
is to be used when chunking or closing the file.
</p>
- <p>The function returns <c>{error, Reason}</c> for all errors.
+ <p>The function returns <c>{error, <anno>Reason</anno>}</c> for all errors.
</p>
</desc>
</func>
diff --git a/lib/kernel/include/inet.hrl b/lib/kernel/include/inet.hrl
index 929b2ee294..3e64d4bb79 100644
--- a/lib/kernel/include/inet.hrl
+++ b/lib/kernel/include/inet.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
+%% 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
@@ -19,18 +19,11 @@
%% This record is returned by inet:gethostbyaddr/2 and inet:gethostbyname/2.
--type hostname() :: atom() | string().
--type ip4_address() :: {0..255,0..255,0..255,0..255}.
--type ip6_address() :: {0..65535,0..65535,0..65535,0..65535,
- 0..65535,0..65535,0..65535,0..65535}.
--type ip_address() :: ip4_address() | ip6_address().
--type ip_port() :: 0..65535.
-
-record(hostent,
{
- h_name :: hostname(), %% offical name of host
- h_aliases = [] :: [hostname()], %% alias list
+ h_name :: inet:hostname(), %% offical name of host
+ h_aliases = [] :: [inet:hostname()], %% alias list
h_addrtype :: 'inet' | 'inet6', %% host address type
h_length :: non_neg_integer(), %% length of address
- h_addr_list = [] :: [ip_address()] %% list of addresses from name server
+ h_addr_list = [] :: [inet:ip_address()]%% list of addresses from name server
}).
diff --git a/lib/kernel/src/application.erl b/lib/kernel/src/application.erl
index 2a193affd4..fa3a4c3d36 100644
--- a/lib/kernel/src/application.erl
+++ b/lib/kernel/src/application.erl
@@ -32,20 +32,30 @@
%%%-----------------------------------------------------------------
+-type start_type() :: 'normal'
+ | {'takeover', Node :: node()}
+ | {'failover', Node :: node()}.
-type restart_type() :: 'permanent' | 'transient' | 'temporary'.
--type application_opt() :: {'description', string()}
- | {'vsn', string()}
- | {'id', string()}
- | {'modules', [atom() | {atom(), any()}]}
- | {'registered', [atom()]}
- | {'applications', [atom()]}
- | {'included_applications', [atom()]}
- | {'env', [{atom(), any()}]}
- | {'start_phases', [{atom(), any()}] | 'undefined'}
- | {'maxT', timeout()} % max timeout
- | {'maxP', integer() | 'infinity'} % max processes
- | {'mod', {atom(), any()}}.
--type application_spec() :: {'application', atom(), [application_opt()]}.
+-type application_opt() :: {'description', Description :: string()}
+ | {'vsn', Vsn :: string()}
+ | {'id', Id :: string()}
+ | {'modules', [(Module :: module()) |
+ {Module :: module(), Version :: term()}]}
+ | {'registered', Names :: [Name :: atom()]}
+ | {'applications', [Application :: atom()]}
+ | {'included_applications', [Application :: atom()]}
+ | {'env', [{Par :: atom(), Val :: term()}]}
+ | {'start_phases',
+ [{Phase :: atom(), PhaseArgs :: term()}] | 'undefined'}
+ | {'maxT', MaxT :: timeout()} % max timeout
+ | {'maxP',
+ MaxP :: pos_integer() | 'infinity'} % max processes
+ | {'mod', Start :: {Module :: module(), StartArgs :: term()}}.
+-type application_spec() :: {'application',
+ Application :: atom(),
+ AppSpecKeys :: [application_opt()]}.
+
+-type(tuple_of(_T) :: tuple()).
%%------------------------------------------------------------------
@@ -61,16 +71,29 @@ behaviour_info(_Other) ->
%%% application_master.
%%%-----------------------------------------------------------------
--spec load(Application :: atom() | application_spec()) ->
- 'ok' | {'error', term()}.
+-spec load(AppDescr) -> 'ok' | {'error', Reason} when
+ AppDescr :: Application | (AppSpec :: application_spec()),
+ Application :: atom(),
+ Reason :: term().
load(Application) ->
- load(Application, []).
-
--spec load(Application :: atom() | application_spec(),
- Distributed :: any()) -> 'ok' | {'error', term()}.
+ load1(Application, []).
+
+-spec load(AppDescr, Distributed) -> 'ok' | {'error', Reason} when
+ AppDescr :: Application | (AppSpec :: application_spec()),
+ Application :: atom(),
+ Distributed :: {Application,Nodes}
+ | {Application,Time,Nodes}
+ | 'default',
+ Nodes :: [node() | tuple_of(node())],
+ Time :: pos_integer(),
+ Reason :: term().
load(Application, DistNodes) ->
+ load1(Application, DistNodes).
+
+%% Workaround due to specs.
+load1(Application, DistNodes) ->
case application_controller:load_application(Application) of
ok when DistNodes =/= [] ->
AppName = get_appl_name(Application),
@@ -85,18 +108,24 @@ load(Application, DistNodes) ->
Else
end.
--spec unload(Application :: atom()) -> 'ok' | {'error', term()}.
+-spec unload(Application) -> 'ok' | {'error', Reason} when
+ Application :: atom(),
+ Reason :: term().
unload(Application) ->
application_controller:unload_application(Application).
--spec start(Application :: atom()) -> 'ok' | {'error', term()}.
+-spec start(Application) -> 'ok' | {'error', Reason} when
+ Application :: atom(),
+ Reason :: term().
start(Application) ->
start(Application, temporary).
--spec start(Application :: atom() | application_spec(),
- RestartType :: restart_type()) -> any().
+-spec start(Application, Type) -> 'ok' | {'error', Reason} when
+ Application :: atom(),
+ Type :: restart_type(),
+ Reason :: term().
start(Application, RestartType) ->
case load(Application) of
@@ -120,12 +149,18 @@ start_boot(Application) ->
start_boot(Application, RestartType) ->
application_controller:start_boot_application(Application, RestartType).
--spec takeover(Application :: atom(), RestartType :: restart_type()) -> any().
+-spec takeover(Application, Type) -> 'ok' | {'error', Reason} when
+ Application :: atom(),
+ Type :: restart_type(),
+ Reason :: term().
takeover(Application, RestartType) ->
dist_ac:takeover_application(Application, RestartType).
--spec permit(Application :: atom(), Bool :: boolean()) -> 'ok' | {'error', term()}.
+-spec permit(Application, Permission) -> 'ok' | {'error', Reason} when
+ Application :: atom(),
+ Permission :: boolean(),
+ Reason :: term().
permit(Application, Bool) ->
case Bool of
@@ -142,105 +177,146 @@ permit(Application, Bool) ->
LocalResult
end.
--spec stop(Application :: atom()) -> 'ok' | {'error', term()}.
+-spec stop(Application) -> 'ok' | {'error', Reason} when
+ Application :: atom(),
+ Reason :: term().
stop(Application) ->
application_controller:stop_application(Application).
--spec which_applications() -> [{atom(), string(), string()}].
+-spec which_applications() -> [{Application, Description, Vsn}] when
+ Application :: atom(),
+ Description :: string(),
+ Vsn :: string().
which_applications() ->
application_controller:which_applications().
--spec which_applications(timeout()) -> [{atom(), string(), string()}].
+-spec which_applications(Timeout) -> [{Application, Description, Vsn}] when
+ Timeout :: timeout(),
+ Application :: atom(),
+ Description :: string(),
+ Vsn :: string().
which_applications(infinity) ->
application_controller:which_applications(infinity);
which_applications(Timeout) when is_integer(Timeout), Timeout>=0 ->
application_controller:which_applications(Timeout).
--spec loaded_applications() -> [{atom(), string(), string()}].
+-spec loaded_applications() -> [{Application, Description, Vsn}] when
+ Application :: atom(),
+ Description :: string(),
+ Vsn :: string().
loaded_applications() ->
application_controller:loaded_applications().
--spec info() -> any().
+-spec info() -> term().
info() ->
application_controller:info().
--spec set_env(Application :: atom(), Key :: atom(), Value :: any()) -> 'ok'.
+-spec set_env(Application, Par, Val) -> 'ok' when
+ Application :: atom(),
+ Par :: atom(),
+ Val :: term().
set_env(Application, Key, Val) ->
application_controller:set_env(Application, Key, Val).
--spec set_env(Application :: atom(), Key :: atom(),
- Value :: any(), Timeout :: timeout()) -> 'ok'.
+-spec set_env(Application, Par, Val, Timeout) -> 'ok' when
+ Application :: atom(),
+ Par :: atom(),
+ Val :: term(),
+ Timeout :: timeout().
set_env(Application, Key, Val, infinity) ->
application_controller:set_env(Application, Key, Val, infinity);
set_env(Application, Key, Val, Timeout) when is_integer(Timeout), Timeout>=0 ->
application_controller:set_env(Application, Key, Val, Timeout).
--spec unset_env(atom(), atom()) -> 'ok'.
+-spec unset_env(Application, Par) -> 'ok' when
+ Application :: atom(),
+ Par :: atom().
unset_env(Application, Key) ->
application_controller:unset_env(Application, Key).
--spec unset_env(atom(), atom(), timeout()) -> 'ok'.
+-spec unset_env(Application, Par, Timeout) -> 'ok' when
+ Application :: atom(),
+ Par :: atom(),
+ Timeout :: timeout().
unset_env(Application, Key, infinity) ->
application_controller:unset_env(Application, Key, infinity);
unset_env(Application, Key, Timeout) when is_integer(Timeout), Timeout>=0 ->
application_controller:unset_env(Application, Key, Timeout).
--spec get_env(atom()) -> 'undefined' | {'ok', term()}.
+-spec get_env(Par) -> 'undefined' | {'ok', Val} when
+ Par :: atom(),
+ Val :: term().
get_env(Key) ->
application_controller:get_pid_env(group_leader(), Key).
--spec get_env(atom(), atom()) -> 'undefined' | {'ok', term()}.
+-spec get_env(Application, Par) -> 'undefined' | {'ok', Val} when
+ Application :: atom(),
+ Par :: atom(),
+ Val :: term().
get_env(Application, Key) ->
application_controller:get_env(Application, Key).
--spec get_all_env() -> [{atom(), any()}].
+-spec get_all_env() -> Env when
+ Env :: [{Par :: atom(), Val :: term()}].
get_all_env() ->
application_controller:get_pid_all_env(group_leader()).
--spec get_all_env(atom()) -> [{atom(), any()}].
+-spec get_all_env(Application) -> Env when
+ Application :: atom(),
+ Env :: [{Par :: atom(), Val :: term()}].
get_all_env(Application) ->
application_controller:get_all_env(Application).
--spec get_key(atom()) -> 'undefined' | {'ok', term()}.
+-spec get_key(Key) -> 'undefined' | {'ok', Val} when
+ Key :: atom(),
+ Val :: term().
get_key(Key) ->
application_controller:get_pid_key(group_leader(), Key).
--spec get_key(atom(), atom()) -> 'undefined' | {'ok', term()}.
+-spec get_key(Application, Key) -> 'undefined' | {'ok', Val} when
+ Application :: atom(),
+ Key :: atom(),
+ Val :: term().
get_key(Application, Key) ->
application_controller:get_key(Application, Key).
--spec get_all_key() -> 'undefined' | [] | {'ok', [{atom(),any()},...]}.
+-spec get_all_key() -> [] | {'ok', Keys} when
+ Keys :: [{Key :: atom(),Val :: term()},...].
get_all_key() ->
application_controller:get_pid_all_key(group_leader()).
--spec get_all_key(atom()) -> 'undefined' | {'ok', [{atom(),any()},...]}.
+-spec get_all_key(Application) -> 'undefined' | Keys when
+ Application :: atom(),
+ Keys :: {'ok', [{Key :: atom(),Val :: term()},...]}.
get_all_key(Application) ->
application_controller:get_all_key(Application).
--spec get_application() -> 'undefined' | {'ok', atom()}.
+-spec get_application() -> 'undefined' | {'ok', Application} when
+ Application :: atom().
get_application() ->
application_controller:get_application(group_leader()).
--spec get_application(Pid :: pid()) -> 'undefined' | {'ok', atom()}
- ; (Module :: atom()) -> 'undefined' | {'ok', atom()}.
+-spec get_application(PidOrModule) -> 'undefined' | {'ok', Application} when
+ PidOrModule :: (Pid :: pid()) | (Module :: module()),
+ Application :: atom().
get_application(Pid) when is_pid(Pid) ->
case process_info(Pid, group_leader) of
@@ -252,8 +328,8 @@ get_application(Pid) when is_pid(Pid) ->
get_application(Module) when is_atom(Module) ->
application_controller:get_application_module(Module).
--spec start_type() -> 'undefined' | 'local' | 'normal'
- | {'takeover', node()} | {'failover', node()}.
+-spec start_type() -> StartType | 'undefined' | 'local' when
+ StartType :: start_type().
start_type() ->
application_controller:start_type(group_leader()).
diff --git a/lib/kernel/src/auth.erl b/lib/kernel/src/auth.erl
index 5c7fe2421d..25c88a4e1d 100644
--- a/lib/kernel/src/auth.erl
+++ b/lib/kernel/src/auth.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -57,7 +57,8 @@ start_link() ->
%%--Deprecated interface------------------------------------------------
--spec is_auth(Node :: node()) -> 'yes' | 'no'.
+-spec is_auth(Node) -> 'yes' | 'no' when
+ Node :: Node :: node().
is_auth(Node) ->
case net_adm:ping(Node) of
@@ -65,12 +66,15 @@ is_auth(Node) ->
pang -> no
end.
--spec cookie() -> cookie().
+-spec cookie() -> Cookie when
+ Cookie :: cookie().
cookie() ->
get_cookie().
--spec cookie(Cookies :: [cookie(),...] | cookie()) -> 'true'.
+-spec cookie(TheCookie) -> 'true' when
+ TheCookie :: Cookie | [Cookie],
+ Cookie :: cookie().
cookie([Cookie]) ->
set_cookie(Cookie);
@@ -82,7 +86,9 @@ cookie(Cookie) ->
node_cookie([Node, Cookie]) ->
node_cookie(Node, Cookie).
--spec node_cookie(Node :: node(), Cookie :: cookie()) -> 'yes' | 'no'.
+-spec node_cookie(Node, Cookie) -> 'yes' | 'no' when
+ Node :: node(),
+ Cookie :: cookie().
node_cookie(Node, Cookie) ->
set_cookie(Node, Cookie),
diff --git a/lib/kernel/src/disk_log.erl b/lib/kernel/src/disk_log.erl
index 7f1b5f9ec6..9b8d2db437 100644
--- a/lib/kernel/src/disk_log.erl
+++ b/lib/kernel/src/disk_log.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
+%% 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
@@ -70,9 +70,10 @@
%%% Contract type specifications
%%%----------------------------------------------------------------------
+-opaque continuation() :: #continuation{}.
+
-type bytes() :: binary() | [byte()].
--type log() :: term(). % XXX: refine
-type file_error() :: term(). % XXX: refine
-type invalid_header() :: term(). % XXX: refine
@@ -87,27 +88,30 @@
-type open_error_rsn() :: 'no_such_log'
| {'badarg', term()}
- | {'size_mismatch', dlog_size(), dlog_size()}
- | {'arg_mismatch', dlog_optattr(), term(), term()}
- | {'name_already_open', log()}
- | {'open_read_write', log()}
- | {'open_read_only', log()}
- | {'need_repair', log()}
- | {'not_a_log_file', string()}
- | {'invalid_index_file', string()}
+ | {'size_mismatch', CurrentSize :: dlog_size(),
+ NewSize :: dlog_size()}
+ | {'arg_mismatch', OptionName :: dlog_optattr(),
+ CurrentValue :: term(), Value :: term()}
+ | {'name_already_open', Log :: log()}
+ | {'open_read_write', Log :: log()}
+ | {'open_read_only', Log :: log()}
+ | {'need_repair', Log :: log()}
+ | {'not_a_log_file', FileName :: file:filename()}
+ | {'invalid_index_file', FileName :: file:filename()}
| {'invalid_header', invalid_header()}
| {'file_error', file:filename(), file_error()}
- | {'node_already_open', log()}.
+ | {'node_already_open', Log :: log()}.
-type dist_error_rsn() :: 'nodedown' | open_error_rsn().
--type ret() :: {'ok', log()}
- | {'repaired', log(), {'recovered', non_neg_integer()},
- {'badbytes', non_neg_integer()}}.
+-type ret() :: {'ok', Log :: log()}
+ | {'repaired', Log :: log(),
+ {'recovered', Rec :: non_neg_integer()},
+ {'badbytes', Bad :: non_neg_integer()}}.
-type open_ret() :: ret() | {'error', open_error_rsn()}.
-type dist_open_ret() :: {[{node(), ret()}],
[{node(), {'error', dist_error_rsn()}}]}.
--type all_open_ret() :: open_ret() | dist_open_ret().
--spec open(Args :: dlog_options()) -> all_open_ret().
+-spec open(ArgL) -> open_ret() | dist_open_ret() when
+ ArgL :: dlog_options().
open(A) ->
disk_log_server:open(check_arg(A, #arg{options = A})).
@@ -116,40 +120,57 @@ open(A) ->
| {'full', log()} | {'invalid_header', invalid_header()}
| {'file_error', file:filename(), file_error()}.
--spec log(Log :: log(), Term :: term()) -> 'ok' | {'error', log_error_rsn()}.
+-spec log(Log, Term) -> ok | {error, Reason :: log_error_rsn()} when
+ Log :: log(),
+ Term :: term().
log(Log, Term) ->
req(Log, {log, term_to_binary(Term)}).
--spec blog(Log :: log(), Bytes :: bytes()) -> 'ok' | {'error', log_error_rsn()}.
+-spec blog(Log, Bytes) -> ok | {error, Reason :: log_error_rsn()} when
+ Log :: log(),
+ Bytes :: bytes().
blog(Log, Bytes) ->
req(Log, {blog, check_bytes(Bytes)}).
--spec log_terms(Log :: log(), Terms :: [term()]) -> 'ok' | {'error', term()}.
+-spec log_terms(Log, TermList) -> ok | {error, Resaon :: log_error_rsn()} when
+ Log :: log(),
+ TermList :: [term()].
log_terms(Log, Terms) ->
Bs = terms2bins(Terms),
req(Log, {log, Bs}).
--spec blog_terms(Log :: log(), Bytes :: [bytes()]) -> 'ok' | {'error', term()}.
+-spec blog_terms(Log, BytesList) ->
+ ok | {error, Reason :: log_error_rsn()} when
+ Log :: log(),
+ BytesList :: [bytes()].
blog_terms(Log, Bytess) ->
Bs = check_bytes_list(Bytess, Bytess),
req(Log, {blog, Bs}).
-type notify_ret() :: 'ok' | {'error', 'no_such_log'}.
--spec alog(Log :: log(), Term :: term()) -> notify_ret().
+-spec alog(Log, Term) -> notify_ret() when
+ Log :: log(),
+ Term :: term().
alog(Log, Term) ->
notify(Log, {alog, term_to_binary(Term)}).
--spec alog_terms(Log :: log(), Terms :: [term()]) -> notify_ret().
+-spec alog_terms(Log, TermList) -> notify_ret() when
+ Log :: log(),
+ TermList :: [term()].
alog_terms(Log, Terms) ->
Bs = terms2bins(Terms),
notify(Log, {alog, Bs}).
--spec balog(Log :: log(), Bytes :: bytes()) -> notify_ret().
+-spec balog(Log, Bytes) -> notify_ret() when
+ Log :: log(),
+ Bytes :: bytes().
balog(Log, Bytes) ->
notify(Log, {balog, check_bytes(Bytes)}).
--spec balog_terms(Log :: log(), Bytes :: [bytes()]) -> notify_ret().
+-spec balog_terms(Log, ByteList) -> notify_ret() when
+ Log :: log(),
+ ByteList :: [bytes()].
balog_terms(Log, Bytess) ->
Bs = check_bytes_list(Bytess, Bytess),
notify(Log, {balog, Bs}).
@@ -157,18 +178,22 @@ balog_terms(Log, Bytess) ->
-type close_error_rsn() ::'no_such_log' | 'nonode'
| {'file_error', file:filename(), file_error()}.
--spec close(Log :: log()) -> 'ok' | {'error', close_error_rsn()}.
+-spec close(Log) -> 'ok' | {'error', close_error_rsn()} when
+ Log :: log().
close(Log) ->
req(Log, close).
-type lclose_error_rsn() :: 'no_such_log'
| {'file_error', file:filename(), file_error()}.
--spec lclose(Log :: log()) -> 'ok' | {'error', lclose_error_rsn()}.
+-spec lclose(Log) -> 'ok' | {'error', lclose_error_rsn()} when
+ Log :: log().
lclose(Log) ->
lclose(Log, node()).
--spec lclose(Log :: log(), Node :: node()) -> 'ok' | {'error', lclose_error_rsn()}.
+-spec lclose(Log, Node) -> 'ok' | {'error', lclose_error_rsn()} when
+ Log :: log(),
+ Node :: node().
lclose(Log, Node) ->
lreq(Log, close, Node).
@@ -178,29 +203,49 @@ lclose(Log, Node) ->
| {'invalid_header', invalid_header()}
| {'file_error', file:filename(), file_error()}.
--spec truncate(Log :: log()) -> 'ok' | {'error', trunc_error_rsn()}.
+-spec truncate(Log) -> 'ok' | {'error', trunc_error_rsn()} when
+ Log :: log().
truncate(Log) ->
req(Log, {truncate, none, truncate, 1}).
--spec truncate(Log :: log(), Head :: term()) -> 'ok' | {'error', trunc_error_rsn()}.
+-spec truncate(Log, Head) -> 'ok' | {'error', trunc_error_rsn()} when
+ Log :: log(),
+ Head :: term().
truncate(Log, Head) ->
req(Log, {truncate, {ok, term_to_binary(Head)}, truncate, 2}).
--spec btruncate(Log :: log(), Head :: bytes()) -> 'ok' | {'error', trunc_error_rsn()}.
+-spec btruncate(Log, BHead) -> 'ok' | {'error', trunc_error_rsn()} when
+ Log :: log(),
+ BHead :: bytes().
btruncate(Log, Head) ->
req(Log, {truncate, {ok, check_bytes(Head)}, btruncate, 2}).
--spec reopen(Log :: log(), Filename :: file:filename()) -> 'ok' | {'error', term()}.
+-type reopen_error_rsn() :: no_such_log
+ | nonode
+ | {read_only_mode, log()}
+ | {blocked_log, log()}
+ | {same_file_name, log()} |
+ {invalid_index_file, file:filename()}
+ | {invalid_header, invalid_header()}
+ | {'file_error', file:filename(), file_error()}.
+
+-spec reopen(Log, File) -> 'ok' | {'error', reopen_error_rsn()} when
+ Log :: log(),
+ File :: file:filename().
reopen(Log, NewFile) ->
req(Log, {reopen, NewFile, none, reopen, 2}).
--spec reopen(Log :: log(), Filename :: file:filename(), Head :: term()) ->
- 'ok' | {'error', term()}.
+-spec reopen(Log, File, Head) -> 'ok' | {'error', reopen_error_rsn()} when
+ Log :: log(),
+ File :: file:filename(),
+ Head :: term().
reopen(Log, NewFile, NewHead) ->
req(Log, {reopen, NewFile, {ok, term_to_binary(NewHead)}, reopen, 3}).
--spec breopen(Log :: log(), Filename :: file:filename(), Head :: bytes()) ->
- 'ok' | {'error', term()}.
+-spec breopen(Log, File, BHead) -> 'ok' | {'error', reopen_error_rsn()} when
+ Log :: log(),
+ File :: file:filename(),
+ BHead :: bytes().
breopen(Log, NewFile, NewHead) ->
req(Log, {reopen, NewFile, {ok, check_bytes(NewHead)}, breopen, 3}).
@@ -210,21 +255,36 @@ breopen(Log, NewFile, NewHead) ->
| {'invalid_header', invalid_header()}
| {'file_error', file:filename(), file_error()}.
--spec inc_wrap_file(Log :: log()) -> 'ok' | {'error', inc_wrap_error_rsn()}.
+-spec inc_wrap_file(Log) -> 'ok' | {'error', inc_wrap_error_rsn()} when
+ Log :: log().
inc_wrap_file(Log) ->
req(Log, inc_wrap_file).
--spec change_size(Log :: log(), Size :: dlog_size()) -> 'ok' | {'error', term()}.
+-spec change_size(Log, Size) -> 'ok' | {'error', Reason} when
+ Log :: log(),
+ Size :: dlog_size(),
+ Reason :: no_such_log | nonode | {read_only_mode, Log}
+ | {blocked_log, Log}
+ | {new_size_too_small, CurrentSize :: pos_integer()}
+ | {badarg, size}
+ | {file_error, file:filename(), file_error()}.
change_size(Log, NewSize) ->
req(Log, {change_size, NewSize}).
--spec change_notify(Log :: log(), Pid :: pid(), Notify :: boolean()) ->
- 'ok' | {'error', term()}.
+-spec change_notify(Log, Owner, Notify) -> 'ok' | {'error', Reason} when
+ Log :: log(),
+ Owner :: pid(),
+ Notify :: boolean(),
+ Reason :: no_such_log | nonode | {blocked_log, Log}
+ | {badarg, notify} | {not_owner, Owner}.
change_notify(Log, Pid, NewNotify) ->
req(Log, {change_notify, Pid, NewNotify}).
--spec change_header(Log :: log(), Head :: {atom(), term()}) ->
- 'ok' | {'error', term()}.
+-spec change_header(Log, Header) -> 'ok' | {'error', Reason} when
+ Log :: log(),
+ Header :: {head, dlog_head_opt()} | {head_func, mfa()},
+ Reason :: no_such_log | nonode | {read_only_mode, Log}
+ | {blocked_log, Log} | {badarg, head}.
change_header(Log, NewHead) ->
req(Log, {change_header, NewHead}).
@@ -232,17 +292,21 @@ change_header(Log, NewHead) ->
| {'blocked_log', log()}
| {'file_error', file:filename(), file_error()}.
--spec sync(Log :: log()) -> 'ok' | {'error', sync_error_rsn()}.
+-spec sync(Log) -> 'ok' | {'error', sync_error_rsn()} when
+ Log :: log().
sync(Log) ->
req(Log, sync).
-type block_error_rsn() :: 'no_such_log' | 'nonode' | {'blocked_log', log()}.
--spec block(Log :: log()) -> 'ok' | {'error', block_error_rsn()}.
+-spec block(Log) -> 'ok' | {'error', block_error_rsn()} when
+ Log :: log().
block(Log) ->
block(Log, true).
--spec block(Log :: log(), QueueLogRecords :: boolean()) -> 'ok' | {'error', term()}.
+-spec block(Log, QueueLogRecords) -> 'ok' | {'error', block_error_rsn()} when
+ Log :: log(),
+ QueueLogRecords :: boolean().
block(Log, QueueLogRecords) ->
req(Log, {block, QueueLogRecords}).
@@ -250,19 +314,46 @@ block(Log, QueueLogRecords) ->
| {'not_blocked', log()}
| {'not_blocked_by_pid', log()}.
--spec unblock(Log :: log()) -> 'ok' | {'error', unblock_error_rsn()}.
+-spec unblock(Log) -> 'ok' | {'error', unblock_error_rsn()} when
+ Log :: log().
unblock(Log) ->
req(Log, unblock).
--spec format_error(Error :: term()) -> string().
+-spec format_error(Error) -> io_lib:chars() when
+ Error :: term().
format_error(Error) ->
do_format_error(Error).
--spec info(Log :: log()) -> [{atom(), any()}] | {'error', term()}.
+-type dlog_info() :: {name, Log :: log()}
+ | {file, File :: file:filename()}
+ | {type, Type :: dlog_type()}
+ | {format, Format :: dlog_format()}
+ | {size, Size :: dlog_size()}
+ | {mode, Mode :: dlog_mode()}
+ | {owners, [{pid(), Notify :: boolean()}]}
+ | {users, Users :: non_neg_integer()}
+ | {status, Status ::
+ ok | {blocked, QueueLogRecords :: boolean()}}
+ | {node, Node :: node()}
+ | {distributed, Dist :: local | [node()]}
+ | {head, Head :: none | {head, term()} | mfa()}
+ | {no_written_items, NoWrittenItems ::non_neg_integer()}
+ | {full, Full :: boolean}
+ | {no_current_bytes, non_neg_integer()}
+ | {no_current_items, non_neg_integer()}
+ | {no_items, non_neg_integer()}
+ | {current_file, pos_integer()}
+ | {no_overflows, {SinceLogWasOpened :: non_neg_integer(),
+ SinceLastInfo :: non_neg_integer()}}.
+-spec info(Log) -> InfoList | {'error', no_such_log} when
+ Log :: log(),
+ InfoList :: [dlog_info()].
info(Log) ->
sreq(Log, info).
--spec pid2name(Pid :: pid()) -> {'ok', log()} | 'undefined'.
+-spec pid2name(Pid) -> {'ok', Log} | 'undefined' when
+ Pid :: pid(),
+ Log :: log().
pid2name(Pid) ->
disk_log_server:start(),
case ets:lookup(?DISK_LOG_PID_TABLE, Pid) of
@@ -274,13 +365,31 @@ pid2name(Pid) ->
%% It retuns a {Cont2, ObjList} | eof | {error, Reason}
%% The initial continuation is the atom 'start'
--spec chunk(Log :: log(), Cont :: any()) ->
- {'error', term()} | 'eof' | {any(), [any()]} | {any(), [any()], integer()}.
+-type chunk_error_rsn() :: no_such_log
+ | {format_external, log()}
+ | {blocked_log, log()}
+ | {badarg, continuation}
+ | {not_internal_wrap, log()}
+ | {corrupt_log_file, FileName :: file:filename()}
+ | {file_error, file:filename(), file_error()}.
+
+-type chunk_ret() :: {Continuation2 :: continuation(), Terms :: [term()]}
+ | {Continuation2 :: continuation(),
+ Terms :: [term()],
+ Badbytes :: non_neg_integer()}
+ | eof
+ | {error, Reason :: chunk_error_rsn()}.
+
+-spec chunk(Log, Continuation) -> chunk_ret() when
+ Log :: log(),
+ Continuation :: start | continuation().
chunk(Log, Cont) ->
chunk(Log, Cont, infinity).
--spec chunk(Log :: log(), Cont :: any(), N :: pos_integer() | 'infinity') ->
- {'error', term()} | 'eof' | {any(), [any()]} | {any(), [any()], integer()}.
+-spec chunk(Log, Continuation, N) -> chunk_ret() when
+ Log :: log(),
+ Continuation :: start | continuation(),
+ N :: pos_integer() | infinity.
chunk(Log, Cont, infinity) ->
%% There cannot be more than ?MAX_CHUNK_SIZE terms in a chunk.
ichunk(Log, Cont, ?MAX_CHUNK_SIZE);
@@ -346,13 +455,24 @@ ichunk_bad_end([B | Bs], Mode, Log, C, Bad, A) ->
ichunk_bad_end(Bs, Mode, Log, C, Bad, [T | A])
end.
--spec bchunk(Log :: log(), Cont :: any()) ->
- {'error', any()} | 'eof' | {any(), [binary()]} | {any(), [binary()], integer()}.
+-type bchunk_ret() :: {Continuation2 :: continuation(),
+ Binaries :: [binary()]}
+ | {Continuation2 :: continuation(),
+ Binaries :: [binary()],
+ Badbytes :: non_neg_integer()}
+ | eof
+ | {error, Reason :: chunk_error_rsn()}.
+
+-spec bchunk(Log, Continuation) -> bchunk_ret() when
+ Log :: log(),
+ Continuation :: start | continuation().
bchunk(Log, Cont) ->
bchunk(Log, Cont, infinity).
--spec bchunk(Log :: log(), Cont :: any(), N :: 'infinity' | pos_integer()) ->
- {'error', any()} | 'eof' | {any(), [binary()]} | {any(), [binary()], integer()}.
+-spec bchunk(Log, Continuation, N) -> bchunk_ret() when
+ Log :: log(),
+ Continuation :: start | continuation(),
+ N :: pos_integer() | infinity.
bchunk(Log, Cont, infinity) ->
%% There cannot be more than ?MAX_CHUNK_SIZE terms in a chunk.
bichunk(Log, Cont, ?MAX_CHUNK_SIZE);
@@ -375,8 +495,14 @@ bichunk_end({C = #continuation{}, R, Bad}) ->
bichunk_end(R) ->
R.
--spec chunk_step(Log :: log(), Cont :: any(), N :: integer()) ->
- {'ok', any()} | {'error', term()}.
+-spec chunk_step(Log, Continuation, Step) ->
+ {'ok', any()} | {'error', Reason} when
+ Log :: log(),
+ Continuation :: start | continuation(),
+ Step :: integer(),
+ Reason :: no_such_log | end_of_log | {format_external, Log}
+ | {blocked_log, Log} | {badarg, continuation}
+ | {file_error, file:filename(), file_error()}.
chunk_step(Log, Cont, N) when is_integer(N) ->
ichunk_step(Log, Cont, N).
@@ -387,14 +513,18 @@ ichunk_step(_Log, More, N) when is_record(More, continuation) ->
ichunk_step(_Log, _, _) ->
{error, {badarg, continuation}}.
--spec chunk_info(More :: any()) ->
- [{'node', node()},...] | {'error', {'no_continuation', any()}}.
+-spec chunk_info(Continuation) -> InfoList | {error, Reason} when
+ Continuation :: continuation(),
+ InfoList :: [{node, Node :: node()}, ...],
+ Reason :: {no_continuation, Continuation}.
chunk_info(More = #continuation{}) ->
[{node, node(More#continuation.pid)}];
chunk_info(BadCont) ->
{error, {no_continuation, BadCont}}.
--spec accessible_logs() -> {[_], [_]}.
+-spec accessible_logs() -> {[LocalLog], [DistributedLog]} when
+ LocalLog :: log(),
+ DistributedLog :: log().
accessible_logs() ->
disk_log_server:accessible_logs().
diff --git a/lib/kernel/src/disk_log.hrl b/lib/kernel/src/disk_log.hrl
index 9a94d4d3b9..259967650f 100644
--- a/lib/kernel/src/disk_log.hrl
+++ b/lib/kernel/src/disk_log.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -53,18 +53,34 @@
%% Types -- alphabetically
%%------------------------------------------------------------------------
+-type dlog_byte() :: [dlog_byte()] | byte().
-type dlog_format() :: 'external' | 'internal'.
-type dlog_format_type() :: 'halt_ext' | 'halt_int' | 'wrap_ext' | 'wrap_int'.
-type dlog_head() :: 'none' | {'ok', binary()} | mfa().
+-type dlog_head_opt() :: none | term() | binary() | [dlog_byte()].
+-type log() :: term(). % XXX: refine
-type dlog_mode() :: 'read_only' | 'read_write'.
-type dlog_name() :: atom() | string().
-type dlog_optattr() :: 'name' | 'file' | 'linkto' | 'repair' | 'type'
| 'format' | 'size' | 'distributed' | 'notify'
| 'head' | 'head_func' | 'mode'.
--type dlog_options() :: [{dlog_optattr(), any()}].
+-type dlog_option() :: {name, Log :: log()}
+ | {file, FileName :: file:filename()}
+ | {linkto, LinkTo :: none | pid()}
+ | {repair, Repair :: true | false | truncate}
+ | {type, Type :: dlog_type}
+ | {format, Format :: dlog_format()}
+ | {size, Size :: dlog_size()}
+ | {distributed, Nodes :: [node()]}
+ | {notify, boolean()}
+ | {head, Head :: dlog_head_opt()}
+ | {head_func, mfa()}
+ | {mode, Mode :: dlog_mode()}.
+-type dlog_options() :: [dlog_option()].
-type dlog_repair() :: 'truncate' | boolean().
-type dlog_size() :: 'infinity' | pos_integer()
- | {pos_integer(), pos_integer()}.
+ | {MaxNoBytes :: pos_integer(),
+ MaxNoFiles :: pos_integer()}.
-type dlog_status() :: 'ok' | {'blocked', 'false' | [_]}. %QueueLogRecords
-type dlog_type() :: 'halt' | 'wrap'.
@@ -75,7 +91,7 @@
%% record of args for open
-record(arg, {name = 0,
version = undefined,
- file = none :: 'none' | string(),
+ file = none :: 'none' | file:filename(),
repair = true :: dlog_repair(),
size = infinity :: dlog_size(),
type = halt :: dlog_type(),
diff --git a/lib/kernel/src/erl_boot_server.erl b/lib/kernel/src/erl_boot_server.erl
index b4c5f5e27c..0d68d3e198 100644
--- a/lib/kernel/src/erl_boot_server.erl
+++ b/lib/kernel/src/erl_boot_server.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -59,7 +59,11 @@
-type ip4_address() :: {0..255,0..255,0..255,0..255}.
--spec start(Slaves :: [atom()]) -> {'ok', pid()} | {'error', any()}.
+-spec start(Slaves) -> {'ok', Pid} | {'error', What} when
+ Slaves :: [Host],
+ Host :: atom(),
+ Pid :: pid(),
+ What :: any().
start(Slaves) ->
case check_arg(Slaves) of
@@ -69,7 +73,11 @@ start(Slaves) ->
{error, {badarg, Slaves}}
end.
--spec start_link(Slaves :: [atom()]) -> {'ok', pid()} | {'error', any()}.
+-spec start_link(Slaves) -> {'ok', Pid} | {'error', What} when
+ Slaves :: [Host],
+ Host :: atom(),
+ Pid :: pid(),
+ What :: any().
start_link(Slaves) ->
case check_arg(Slaves) of
@@ -95,7 +103,10 @@ check_arg([], Result) ->
check_arg(_, _Result) ->
error.
--spec add_slave(Slave :: atom()) -> 'ok' | {'error', any()}.
+-spec add_slave(Slave) -> 'ok' | {'error', What} when
+ Slave :: Host,
+ Host :: atom(),
+ What :: any().
add_slave(Slave) ->
case inet:getaddr(Slave, inet) of
@@ -105,7 +116,10 @@ add_slave(Slave) ->
{error, {badarg, Slave}}
end.
--spec delete_slave(Slave :: atom()) -> 'ok' | {'error', any()}.
+-spec delete_slave(Slave) -> 'ok' | {'error', What} when
+ Slave :: Host,
+ Host :: atom(),
+ What :: any().
delete_slave(Slave) ->
case inet:getaddr(Slave, inet) of
@@ -131,7 +145,9 @@ add_subnet(Mask, Addr) when is_tuple(Mask), is_tuple(Addr) ->
delete_subnet(Mask, Addr) when is_tuple(Mask), is_tuple(Addr) ->
gen_server:call(boot_server, {delete, {Mask, Addr}}).
--spec which_slaves() -> [atom()].
+-spec which_slaves() -> Slaves when
+ Slaves :: [Host],
+ Host :: atom().
which_slaves() ->
gen_server:call(boot_server, which).
diff --git a/lib/kernel/src/erl_ddll.erl b/lib/kernel/src/erl_ddll.erl
index ce64589a29..646cac99c5 100644
--- a/lib/kernel/src/erl_ddll.erl
+++ b/lib/kernel/src/erl_ddll.erl
@@ -44,14 +44,18 @@ start() ->
stop() ->
ok.
--spec load_driver(Path :: path(), Driver :: driver()) ->
- 'ok' | {'error', any()}.
+-spec load_driver(Path, Name) -> 'ok' | {'error', ErrorDesc} when
+ Path :: path(),
+ Name :: driver(),
+ ErrorDesc :: term().
load_driver(Path, Driver) ->
do_load_driver(Path, Driver, [{driver_options,[kill_ports]}]).
--spec load(Path :: path(), Driver :: driver()) ->
- 'ok' | {'error', any()}.
+-spec load(Path, Name) -> 'ok' | {'error', ErrorDesc} when
+ Path :: path(),
+ Name :: driver(),
+ ErrorDesc ::term().
load(Path, Driver) ->
do_load_driver(Path, Driver, []).
@@ -100,30 +104,41 @@ do_unload_driver(Driver,Flags) ->
end
end.
--spec unload_driver(Driver :: driver()) -> 'ok' | {'error', any()}.
+-spec unload_driver(Name) -> 'ok' | {'error', ErrorDesc} when
+ Name :: driver(),
+ ErrorDesc :: term().
unload_driver(Driver) ->
do_unload_driver(Driver,[{monitor,pending_driver},kill_ports]).
--spec unload(Driver :: driver()) -> 'ok' | {'error', any()}.
+-spec unload(Name) -> 'ok' | {'error', ErrorDesc} when
+ Name :: driver(),
+ ErrorDesc :: term().
unload(Driver) ->
do_unload_driver(Driver,[]).
--spec reload(Path :: path(), Driver :: driver()) ->
- 'ok' | {'error', any()}.
+-spec reload(Path, Name) -> 'ok' | {'error', ErrorDesc} when
+ Path :: path(),
+ Name :: driver(),
+ ErrorDesc :: pending_process | OpaqueError,
+ OpaqueError :: term().
reload(Path,Driver) ->
do_load_driver(Path, Driver, [{reload,pending_driver}]).
--spec reload_driver(Path :: path(), Driver :: driver()) ->
- 'ok' | {'error', any()}.
+-spec reload_driver(Path, Name) -> 'ok' | {'error', ErrorDesc} when
+ Path :: path(),
+ Name :: driver(),
+ ErrorDesc :: pending_process | OpaqueError,
+ OpaqueError :: term().
reload_driver(Path,Driver) ->
do_load_driver(Path, Driver, [{reload,pending_driver},
{driver_options,[kill_ports]}]).
--spec format_error(Code :: atom()) -> string().
+-spec format_error(ErrorDesc) -> string() when
+ ErrorDesc :: term().
format_error(Code) ->
case Code of
@@ -135,7 +150,10 @@ format_error(Code) ->
erl_ddll:format_error_int(Code)
end.
--spec info(Driver :: driver()) -> [{atom(), any()}, ...].
+-spec info(Name) -> InfoList when
+ Name :: driver(),
+ InfoList :: [InfoItem, ...],
+ InfoItem :: {Tag :: atom(), Value :: term()}.
info(Driver) ->
[{processes, erl_ddll:info(Driver,processes)},
@@ -146,7 +164,12 @@ info(Driver) ->
{awaiting_load, erl_ddll:info(Driver,awaiting_load)},
{awaiting_unload, erl_ddll:info(Driver,awaiting_unload)}].
--spec info() -> [{string(), [{atom(), any()}]}].
+-spec info() -> AllInfoList when
+ AllInfoList :: [DriverInfo],
+ DriverInfo :: {DriverName, InfoList},
+ DriverName :: string(),
+ InfoList :: [InfoItem],
+ InfoItem :: {Tag :: atom(), Value :: term()}.
info() ->
{ok,DriverList} = erl_ddll:loaded_drivers(),
diff --git a/lib/kernel/src/error_handler.erl b/lib/kernel/src/error_handler.erl
index 6f69f4ccb9..e1f99bf417 100644
--- a/lib/kernel/src/error_handler.erl
+++ b/lib/kernel/src/error_handler.erl
@@ -28,8 +28,11 @@
-export([undefined_function/3, undefined_lambda/3, stub_function/3,
breakpoint/3]).
--spec undefined_function(Module :: atom(), Function :: atom(), Args :: [_]) ->
- any().
+-spec undefined_function(Module, Function, Args) ->
+ any() when
+ Module :: atom(),
+ Function :: atom(),
+ Args :: list().
undefined_function(Module, Func, Args) ->
case ensure_loaded(Module) of
@@ -51,8 +54,10 @@ undefined_function(Module, Func, Args) ->
crash(Module, Func, Args)
end.
--spec undefined_lambda(Module :: atom(), Function :: fun(), Args :: [_]) ->
- any().
+-spec undefined_lambda(Module, Fun, Args) -> term() when
+ Module :: atom(),
+ Fun :: fun(),
+ Args :: list().
undefined_lambda(Module, Fun, Args) ->
case ensure_loaded(Module) of
diff --git a/lib/kernel/src/error_logger.erl b/lib/kernel/src/error_logger.erl
index cafdc52e84..f94cca000f 100644
--- a/lib/kernel/src/error_logger.erl
+++ b/lib/kernel/src/error_logger.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -69,17 +69,22 @@ start_link() ->
%% Used for simple messages; error or information.
%%-----------------------------------------------------------------
--spec error_msg(Format :: string()) -> 'ok'.
+-spec error_msg(Format) -> 'ok' when
+ Format :: string().
error_msg(Format) ->
error_msg(Format,[]).
--spec error_msg(Format :: string(), Args :: list()) -> 'ok'.
+-spec error_msg(Format, Data) -> 'ok' when
+ Format :: string(),
+ Data :: list().
error_msg(Format, Args) ->
notify({error, group_leader(), {self(), Format, Args}}).
--spec format(Format :: string(), Args :: list()) -> 'ok'.
+-spec format(Format, Data) -> 'ok' when
+ Format :: string(),
+ Data :: list().
format(Format, Args) ->
notify({error, group_leader(), {self(), Format, Args}}).
@@ -90,12 +95,18 @@ format(Format, Args) ->
%% The 'std_error' error_report type can always be used.
%%-----------------------------------------------------------------
--spec error_report(Report :: any()) -> 'ok'.
+-type report() ::
+ [{Tag :: term(), Data :: term()} | term()] | string() | term().
+
+-spec error_report(Report) -> 'ok' when
+ Report :: report().
error_report(Report) ->
error_report(std_error, Report).
--spec error_report(Type :: any(), Report :: any()) -> 'ok'.
+-spec error_report(Type, Report) -> 'ok' when
+ Type :: term(),
+ Report :: report().
error_report(Type, Report) ->
notify({error_report, group_leader(), {self(), Type, Report}}).
@@ -109,12 +120,15 @@ error_report(Type, Report) ->
%% mapped to std_info or std_error accordingly.
%%-----------------------------------------------------------------
--spec warning_report(Report :: any()) -> 'ok'.
+-spec warning_report(Report) -> 'ok' when
+ Report :: report().
warning_report(Report) ->
warning_report(std_warning, Report).
--spec warning_report(Type :: any(), Report :: any()) -> 'ok'.
+-spec warning_report(Type, Report) -> 'ok' when
+ Type :: any(),
+ Report :: report().
warning_report(Type, Report) ->
{Tag, NType} = case error_logger:warning_map() of
@@ -143,12 +157,15 @@ warning_report(Type, Report) ->
%% other types of reports.
%%-----------------------------------------------------------------
--spec warning_msg(Format :: string()) -> 'ok'.
+-spec warning_msg(Format) -> 'ok' when
+ Format :: string().
warning_msg(Format) ->
warning_msg(Format,[]).
--spec warning_msg(Format :: string(), Args :: list()) -> 'ok'.
+-spec warning_msg(Format, Data) -> 'ok' when
+ Format :: string(),
+ Data :: list().
warning_msg(Format, Args) ->
Tag = case error_logger:warning_map() of
@@ -167,12 +184,15 @@ warning_msg(Format, Args) ->
%% The 'std_info' info_report type can always be used.
%%-----------------------------------------------------------------
--spec info_report(Report :: any()) -> 'ok'.
+-spec info_report(Report) -> 'ok' when
+ Report :: report().
info_report(Report) ->
info_report(std_info, Report).
--spec info_report(Type :: any(), Report :: any()) -> 'ok'.
+-spec info_report(Type, Report) -> 'ok' when
+ Type :: any(),
+ Report :: report().
info_report(Type, Report) ->
notify({info_report, group_leader(), {self(), Type, Report}}).
@@ -182,12 +202,15 @@ info_report(Type, Report) ->
%% information messages.
%%-----------------------------------------------------------------
--spec info_msg(Format :: string()) -> 'ok'.
+-spec info_msg(Format) -> 'ok' when
+ Format :: string().
info_msg(Format) ->
info_msg(Format,[]).
--spec info_msg(Format :: string(), Args :: list()) -> 'ok'.
+-spec info_msg(Format, Data) -> 'ok' when
+ Format :: string(),
+ Data :: list().
info_msg(Format, Args) ->
notify({info_msg, group_leader(), {self(), Format, Args}}).
@@ -223,17 +246,23 @@ swap_handler(silent) ->
swap_handler(false) ->
ok. % keep primitive event handler as-is
--spec add_report_handler(Module :: atom()) -> any().
+-spec add_report_handler(Handler) -> any() when
+ Handler :: module().
add_report_handler(Module) when is_atom(Module) ->
gen_event:add_handler(error_logger, Module, []).
--spec add_report_handler(atom(), any()) -> any().
+-spec add_report_handler(Handler, Args) -> Result when
+ Handler :: module(),
+ Args :: gen_event:handler_args(),
+ Result :: gen_event:add_handler_ret().
add_report_handler(Module, Args) when is_atom(Module) ->
gen_event:add_handler(error_logger, Module, Args).
--spec delete_report_handler(Module :: atom()) -> any().
+-spec delete_report_handler(Handler) -> Result when
+ Handler :: module(),
+ Result :: gen_event:del_handler_ret().
delete_report_handler(Module) when is_atom(Module) ->
gen_event:delete_handler(error_logger, Module, []).
@@ -250,9 +279,16 @@ simple_logger() ->
%% Log all errors to File for all eternity
--spec logfile(Request :: {'open', string()}) -> 'ok' | {'error',any()}
- ; (Request :: 'close') -> 'ok' | {'error', any()}
- ; (Request :: 'filename') -> atom() | string() | {'error', any()}.
+-type open_error() :: file:posix() | badarg | system_limit.
+
+-spec logfile(Request :: {open, Filename}) -> ok | {error, OpenReason} when
+ Filename ::file:name(),
+ OpenReason :: allready_have_logfile | open_error()
+ ; (Request :: close) -> ok | {error, CloseReason} when
+ CloseReason :: module_not_found
+ ; (Request :: filename) -> Filename | {error, FilenameReason} when
+ Filename :: file:name(),
+ FilenameReason :: no_log_file.
logfile({open, File}) ->
case lists:member(error_logger_file_h,
@@ -280,7 +316,8 @@ logfile(filename) ->
%% Possibly turn off all tty printouts, maybe we only want the errors
%% to go to a file
--spec tty(Flag :: boolean()) -> 'ok'.
+-spec tty(Flag) -> 'ok' when
+ Flag :: boolean().
tty(true) ->
Hs = gen_event:which_handlers(error_logger),
diff --git a/lib/kernel/src/file.erl b/lib/kernel/src/file.erl
index 88bcf9a9cc..f1a8aa9f77 100644
--- a/lib/kernel/src/file.erl
+++ b/lib/kernel/src/file.erl
@@ -79,15 +79,19 @@
-type file_info() :: #file_info{}.
-type fd() :: #file_descriptor{}.
-type io_device() :: pid() | fd().
--type location() :: integer() | {'bof', integer()} | {'cur', integer()}
- | {'eof', integer()} | 'bof' | 'cur' | 'eof'.
+-type location() :: integer() | {'bof', Offset :: integer()}
+ | {'cur', Offset :: integer()}
+ | {'eof', Offset :: integer()} | 'bof' | 'cur' | 'eof'.
-type mode() :: 'read' | 'write' | 'append'
| 'exclusive' | 'raw' | 'binary'
- | {'delayed_write', non_neg_integer(), non_neg_integer()}
- | 'delayed_write' | {'read_ahead', pos_integer()}
+ | {'delayed_write',
+ Size :: non_neg_integer(),
+ Delay :: non_neg_integer()}
+ | 'delayed_write' | {'read_ahead', Size :: pos_integer()}
| 'read_ahead' | 'compressed'
| {'encoding', unicode:encoding()}.
--type name() :: string() | atom() | [name()] | binary().
+-type deep_list() :: [char() | atom() | deep_list()].
+-type name() :: string() | atom() | deep_list() | (RawFilename :: binary()).
-type posix() :: 'eacces' | 'eagain' | 'ebadf' | 'ebusy' | 'edquot'
| 'eexist' | 'efault' | 'efbig' | 'eintr' | 'einval'
| 'eio' | 'eisdir' | 'eloop' | 'emfile' | 'emlink'
@@ -96,10 +100,14 @@
| 'enotblk' | 'enotdir' | 'enotsup' | 'enxio' | 'eperm'
| 'epipe' | 'erofs' | 'espipe' | 'esrch' | 'estale'
| 'exdev'.
--type bindings() :: any().
-
--type date() :: {pos_integer(), pos_integer(), pos_integer()}.
--type time() :: {non_neg_integer(), non_neg_integer(), non_neg_integer()}.
+-type bindings() :: erl_eval:binding_struct().
+
+-type date() :: {Year :: pos_integer(),
+ Month :: pos_integer(),
+ Day ::pos_integer()}.
+-type time() :: {Hour :: non_neg_integer(),
+ Minute :: non_neg_integer(),
+ Second :: non_neg_integer()}.
-type date_time() :: {date(), time()}.
-type posix_file_advise() :: 'normal' | 'sequential' | 'random'
| 'no_reuse' | 'will_need' | 'dont_need'.
@@ -107,8 +115,10 @@
%%%-----------------------------------------------------------------
%%% General functions
--spec format_error(Reason :: posix() | {integer(), atom(), any()}) ->
- string().
+-spec format_error(Reason) -> Chars when
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()},
+ Chars :: string().
format_error({_Line, ?MODULE, undefined_script}) ->
"no value returned from script";
@@ -129,7 +139,9 @@ format_error(terminated) ->
format_error(ErrorId) ->
erl_posix_msg:message(ErrorId).
--spec pid2name(Pid :: pid()) -> {'ok', filename()} | 'undefined'.
+-spec pid2name(Pid) -> {ok, Filename} | undefined when
+ Filename :: filename(),
+ Pid :: pid().
pid2name(Pid) when is_pid(Pid) ->
case whereis(?FILE_SERVER) of
@@ -148,42 +160,61 @@ pid2name(Pid) when is_pid(Pid) ->
%%% File server functions.
%%% Functions that do not operate on a single open file.
%%% Stateless.
--spec get_cwd() -> {'ok', filename()} | {'error', posix()}.
+-spec get_cwd() -> {ok, Dir} | {error, Reason} when
+ Dir :: filename(),
+ Reason :: posix().
get_cwd() ->
call(get_cwd, []).
--spec get_cwd(Drive :: string()) -> {'ok', filename()} | {'error', posix()}.
+-spec get_cwd(Drive) -> {ok, Dir} | {error, Reason} when
+ Drive :: string(),
+ Dir :: filename(),
+ Reason :: posix() | badarg.
get_cwd(Drive) ->
check_and_call(get_cwd, [file_name(Drive)]).
--spec set_cwd(Dirname :: name()) -> 'ok' | {'error', posix()}.
+-spec set_cwd(Dir) -> ok | {error, Reason} when
+ Dir :: name(),
+ Reason :: posix() | badarg.
set_cwd(Dirname) ->
check_and_call(set_cwd, [file_name(Dirname)]).
--spec delete(Name :: name()) -> 'ok' | {'error', posix()}.
+-spec delete(Filename) -> ok | {error, Reason} when
+ Filename :: name(),
+ Reason :: posix() | badarg.
delete(Name) ->
check_and_call(delete, [file_name(Name)]).
--spec rename(From :: name(), To :: name()) -> 'ok' | {'error', posix()}.
+-spec rename(Source, Destination) -> ok | {error, Reason} when
+ Source :: name(),
+ Destination :: name(),
+ Reason :: posix() | badarg.
rename(From, To) ->
check_and_call(rename, [file_name(From), file_name(To)]).
--spec make_dir(Name :: name()) -> 'ok' | {'error', posix()}.
+-spec make_dir(Dir) -> ok | {error, Reason} when
+ Dir :: name(),
+ Reason :: posix() | badarg.
make_dir(Name) ->
check_and_call(make_dir, [file_name(Name)]).
--spec del_dir(Name :: name()) -> 'ok' | {'error', posix()}.
+-spec del_dir(Dir) -> ok | {error, Reason} when
+ Dir :: name(),
+ Reason :: posix() | badarg.
del_dir(Name) ->
check_and_call(del_dir, [file_name(Name)]).
--spec read_file_info(Name :: name()) -> {'ok', file_info()} | {'error', posix()}.
+-spec read_file_info(Filename) -> {ok, FileInfo} | {error, Reason} when
+ Filename :: name(),
+ FileInfo :: file_info(),
+ Reason :: posix() | badarg.
read_file_info(Name) ->
check_and_call(read_file_info, [file_name(Name)]).
@@ -193,45 +224,66 @@ read_file_info(Name) ->
altname(Name) ->
check_and_call(altname, [file_name(Name)]).
--spec read_link_info(Name :: name()) -> {'ok', file_info()} | {'error', posix()}.
+-spec read_link_info(Name) -> {ok, FileInfo} | {error, Reason} when
+ Name :: name(),
+ FileInfo :: file_info(),
+ Reason :: posix() | badarg.
read_link_info(Name) ->
check_and_call(read_link_info, [file_name(Name)]).
--spec read_link(Name :: name()) -> {'ok', filename()} | {'error', posix()}.
+-spec read_link(Name) -> {ok, Filename} | {error, Reason} when
+ Name :: name(),
+ Filename :: filename(),
+ Reason :: posix() | badarg.
read_link(Name) ->
check_and_call(read_link, [file_name(Name)]).
--spec write_file_info(Name :: name(), Info :: file_info()) ->
- 'ok' | {'error', posix()}.
+-spec write_file_info(Filename, FileInfo) -> ok | {error, Reason} when
+ Filename :: name(),
+ FileInfo :: file_info(),
+ Reason :: posix() | badarg.
write_file_info(Name, Info = #file_info{}) ->
check_and_call(write_file_info, [file_name(Name), Info]).
--spec list_dir(Name :: name()) -> {'ok', [filename()]} | {'error', posix()}.
+-spec list_dir(Dir) -> {ok, Filenames} | {error, Reason} when
+ Dir :: name(),
+ Filenames :: [filename()],
+ Reason :: posix() | badarg.
list_dir(Name) ->
check_and_call(list_dir, [file_name(Name)]).
--spec read_file(Name :: name()) ->
- {'ok', binary()} | {'error', posix() | 'terminated' | 'system_limit'}.
+-spec read_file(Filename) -> {ok, Binary} | {error, Reason} when
+ Filename :: name(),
+ Binary :: binary(),
+ Reason :: posix() | badarg | terminated | system_limit.
read_file(Name) ->
check_and_call(read_file, [file_name(Name)]).
--spec make_link(Old :: name(), New :: name()) -> 'ok' | {'error', posix()}.
+-spec make_link(Existing, New) -> ok | {error, Reason} when
+ Existing :: name(),
+ New :: name(),
+ Reason :: posix() | badarg.
make_link(Old, New) ->
check_and_call(make_link, [file_name(Old), file_name(New)]).
--spec make_symlink(Old :: name(), New :: name()) -> 'ok' | {'error', posix()}.
+-spec make_symlink(Name1, Name2) -> ok | {error, Reason} when
+ Name1 :: name(),
+ Name2 :: name(),
+ Reason :: posix() | badarg.
make_symlink(Old, New) ->
check_and_call(make_symlink, [file_name(Old), file_name(New)]).
--spec write_file(Name :: name(), Bin :: iodata()) ->
- 'ok' | {'error', posix() | 'terminated' | 'system_limit'}.
+-spec write_file(Filename, Bytes) -> ok | {error, Reason} when
+ Filename :: name(),
+ Bytes :: iodata(),
+ Reason :: posix() | badarg | terminated | system_limit.
write_file(Name, Bin) ->
check_and_call(write_file, [file_name(Name), make_binary(Bin)]).
@@ -240,8 +292,11 @@ write_file(Name, Bin) ->
%% when it is time to change file server protocol again.
%% Meanwhile, it is implemented here, slightly less efficient.
--spec write_file(Name :: name(), Bin :: iodata(), Modes :: [mode()]) ->
- 'ok' | {'error', posix()}.
+-spec write_file(Filename, Bytes, Modes) -> ok | {error, Reason} when
+ Filename :: name(),
+ Bytes :: iodata(),
+ Modes :: [mode()],
+ Reason :: posix() | badarg | terminated | system_limit.
write_file(Name, Bin, ModeList) when is_list(ModeList) ->
case make_binary(Bin) of
@@ -295,8 +350,11 @@ raw_write_file_info(Name, #file_info{} = Info) ->
%% Contemporary mode specification - list of options
--spec open(Name :: name(), Modes :: [mode()]) ->
- {'ok', io_device()} | {'error', posix() | 'system_limit'}.
+-spec open(Filename, Modes) -> {ok, IoDevice} | {error, Reason} when
+ Filename :: name(),
+ Modes :: [mode()],
+ IoDevice :: io_device(),
+ Reason :: posix() | badarg | system_limit.
open(Item, ModeList) when is_list(ModeList) ->
case lists:member(raw, ModeList) of
@@ -349,7 +407,9 @@ open(Item, Mode) ->
%%% The File argument must be either a Pid or a handle
%%% returned from ?PRIM_FILE:open.
--spec close(File :: io_device()) -> 'ok' | {'error', posix() | 'terminated'}.
+-spec close(IoDevice) -> ok | {error, Reason} when
+ IoDevice :: io_device(),
+ Reason :: posix() | badarg | terminated.
close(File) when is_pid(File) ->
R = file_request(File, close),
@@ -367,9 +427,12 @@ close(#file_descriptor{module = Module} = Handle) ->
close(_) ->
{error, badarg}.
--spec advise(File :: io_device(), Offset :: integer(),
- Length :: integer(), Advise :: posix_file_advise()) ->
- 'ok' | {'error', posix()}.
+-spec advise(IoDevice, Offset, Length, Advise) -> ok | {error, Reason} when
+ IoDevice :: io_device(),
+ Offset :: integer(),
+ Length :: integer(),
+ Advise :: posix_file_advise(),
+ Reason :: posix() | badarg.
advise(File, Offset, Length, Advise) when is_pid(File) ->
R = file_request(File, {advise, Offset, Length, Advise}),
@@ -379,8 +442,11 @@ advise(#file_descriptor{module = Module} = Handle, Offset, Length, Advise) ->
advise(_, _, _, _) ->
{error, badarg}.
--spec read(File :: io_device() | atom(), Size :: non_neg_integer()) ->
- 'eof' | {'ok', [char()] | binary()} | {'error', posix()}.
+-spec read(IoDevice, Number) -> {ok, Data} | eof | {error, Reason} when
+ IoDevice :: io_device() | atom(),
+ Number :: non_neg_integer(),
+ Data :: string() | binary(),
+ Reason :: posix() | badarg | terminated.
read(File, Sz) when (is_pid(File) orelse is_atom(File)), is_integer(Sz), Sz >= 0 ->
case io:request(File, {get_chars, '', Sz}) of
@@ -395,8 +461,10 @@ read(#file_descriptor{module = Module} = Handle, Sz)
read(_, _) ->
{error, badarg}.
--spec read_line(File :: io_device() | atom()) ->
- 'eof' | {'ok', [char()] | binary()} | {'error', posix()}.
+-spec read_line(IoDevice) -> {ok, Data} | eof | {error, Reason} when
+ IoDevice :: io_device() | atom(),
+ Data :: string() | binary(),
+ Reason :: posix() | badarg | terminated.
read_line(File) when (is_pid(File) orelse is_atom(File)) ->
case io:request(File, {get_line, ''}) of
@@ -410,9 +478,12 @@ read_line(#file_descriptor{module = Module} = Handle) ->
read_line(_) ->
{error, badarg}.
--spec pread(File :: io_device(),
- LocationNumbers :: [{location(), non_neg_integer()}]) ->
- {'ok', [string() | binary() | 'eof']} | {'error', posix()}.
+-spec pread(IoDevice, LocNums) -> {ok, DataL} | eof | {error, Reason} when
+ IoDevice :: io_device(),
+ LocNums :: [{Location :: location(), Number :: non_neg_integer()}],
+ DataL :: [Data],
+ Data :: string() | binary() | eof,
+ Reason :: posix() | badarg | terminated.
pread(File, L) when is_pid(File), is_list(L) ->
pread_int(File, L, []);
@@ -435,10 +506,13 @@ pread_int(File, [{At, Sz} | T], R) when is_integer(Sz), Sz >= 0 ->
pread_int(_, _, _) ->
{error, badarg}.
--spec pread(File :: io_device(),
- Location :: location(),
- Size :: non_neg_integer()) ->
- 'eof' | {'ok', string() | binary()} | {'error', posix()}.
+-spec pread(IoDevice, Location, Number) ->
+ {ok, Data} | eof | {error, Reason} when
+ IoDevice :: io_device(),
+ Location :: location(),
+ Number :: non_neg_integer(),
+ Data :: string() | binary(),
+ Reason :: posix() | badarg | terminated.
pread(File, At, Sz) when is_pid(File), is_integer(Sz), Sz >= 0 ->
R = file_request(File, {pread, At, Sz}),
@@ -449,8 +523,10 @@ pread(#file_descriptor{module = Module} = Handle, Offs, Sz)
pread(_, _, _) ->
{error, badarg}.
--spec write(File :: io_device() | atom(), Byte :: iodata()) ->
- 'ok' | {'error', posix() | 'terminated'}.
+-spec write(IoDevice, Bytes) -> ok | {error, Reason} when
+ IoDevice :: io_device() | atom(),
+ Bytes :: iodata(),
+ Reason :: posix() | badarg | terminated.
write(File, Bytes) when (is_pid(File) orelse is_atom(File)) ->
case make_binary(Bytes) of
@@ -464,8 +540,11 @@ write(#file_descriptor{module = Module} = Handle, Bytes) ->
write(_, _) ->
{error, badarg}.
--spec pwrite(File :: io_device(), L :: [{location(), iodata()}]) ->
- 'ok' | {'error', {non_neg_integer(), posix()}}.
+-spec pwrite(IoDevice, LocBytes) -> ok | {error, {N, Reason}} when
+ IoDevice :: io_device(),
+ LocBytes :: [{Location :: location(), Bytes :: iodata()}],
+ N :: non_neg_integer(),
+ Reason :: posix() | badarg | terminated.
pwrite(File, L) when is_pid(File), is_list(L) ->
pwrite_int(File, L, 0);
@@ -486,10 +565,11 @@ pwrite_int(File, [{At, Bytes} | T], R) ->
pwrite_int(_, _, _) ->
{error, badarg}.
--spec pwrite(File :: io_device(),
- Location :: location(),
- Bytes :: iodata()) ->
- 'ok' | {'error', posix()}.
+-spec pwrite(IoDevice, Location, Bytes) -> ok | {error, Reason} when
+ IoDevice :: io_device(),
+ Location :: location(),
+ Bytes :: iodata(),
+ Reason :: posix() | badarg | terminated.
pwrite(File, At, Bytes) when is_pid(File) ->
R = file_request(File, {pwrite, At, Bytes}),
@@ -499,7 +579,9 @@ pwrite(#file_descriptor{module = Module} = Handle, Offs, Bytes) ->
pwrite(_, _, _) ->
{error, badarg}.
--spec datasync(File :: io_device()) -> 'ok' | {'error', posix()}.
+-spec datasync(IoDevice) -> ok | {error, Reason} when
+ IoDevice :: io_device(),
+ Reason :: posix() | badarg | terminated.
datasync(File) when is_pid(File) ->
R = file_request(File, datasync),
@@ -509,7 +591,9 @@ datasync(#file_descriptor{module = Module} = Handle) ->
datasync(_) ->
{error, badarg}.
--spec sync(File :: io_device()) -> 'ok' | {'error', posix()}.
+-spec sync(IoDevice) -> ok | {error, Reason} when
+ IoDevice :: io_device(),
+ Reason :: posix() | badarg | terminated.
sync(File) when is_pid(File) ->
R = file_request(File, sync),
@@ -519,8 +603,11 @@ sync(#file_descriptor{module = Module} = Handle) ->
sync(_) ->
{error, badarg}.
--spec position(File :: io_device(), Location :: location()) ->
- {'ok',integer()} | {'error', posix()}.
+-spec position(IoDevice, Location) -> {ok, NewPosition} | {error, Reason} when
+ IoDevice :: io_device(),
+ Location :: location(),
+ NewPosition :: integer(),
+ Reason :: posix() | badarg | terminated.
position(File, At) when is_pid(File) ->
R = file_request(File, {position,At}),
@@ -530,7 +617,9 @@ position(#file_descriptor{module = Module} = Handle, At) ->
position(_, _) ->
{error, badarg}.
--spec truncate(File :: io_device()) -> 'ok' | {'error', posix()}.
+-spec truncate(IoDevice) -> ok | {error, Reason} when
+ IoDevice :: io_device(),
+ Reason :: posix() | badarg | terminated.
truncate(File) when is_pid(File) ->
R = file_request(File, truncate),
@@ -540,17 +629,26 @@ truncate(#file_descriptor{module = Module} = Handle) ->
truncate(_) ->
{error, badarg}.
--spec copy(Source :: io_device() | name() | {name(), [mode()]},
- Destination :: io_device() | name() | {name(), [mode()]}) ->
- {'ok', non_neg_integer()} | {'error', posix()}.
+-spec copy(Source, Destination) -> {ok, BytesCopied} | {error, Reason} when
+ Source :: io_device() | Filename | {Filename, Modes},
+ Destination :: io_device() | Filename | {Filename, Modes},
+ Filename :: name(),
+ Modes :: [mode()],
+ BytesCopied :: non_neg_integer(),
+ Reason :: posix() | badarg | terminated.
copy(Source, Dest) ->
copy_int(Source, Dest, infinity).
--spec copy(Source :: io_device() | name() | {name(), [mode()]},
- Destination :: io_device() | name() | {name(), [mode()]},
- Length :: non_neg_integer() | 'infinity') ->
- {'ok', non_neg_integer()} | {'error', posix()}.
+-spec copy(Source, Destination, ByteCount) ->
+ {ok, BytesCopied} | {error, Reason} when
+ Source :: io_device() | Filename | {Filename, Modes},
+ Destination :: io_device() | Filename | {Filename, Modes},
+ Filename :: name(),
+ Modes :: [mode()],
+ ByteCount :: non_neg_integer() | infinity,
+ BytesCopied :: non_neg_integer(),
+ Reason :: posix() | badarg | terminated.
copy(Source, Dest, Length)
when is_integer(Length), Length >= 0;
@@ -772,8 +870,11 @@ ipread_s32bu_p32bu_2(File,
%%% The following functions, built upon the other interface functions,
%%% provide a higher-lever interface to files.
--spec consult(File :: name()) ->
- {'ok', list()} | {'error', posix() | {integer(), atom(), any()}}.
+-spec consult(Filename) -> {ok, Terms} | {error, Reason} when
+ Filename :: name(),
+ Terms :: [term()],
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
consult(File) ->
case open(File, [read]) of
@@ -785,8 +886,14 @@ consult(File) ->
Error
end.
--spec path_consult(Paths :: [name()], File :: name()) ->
- {'ok', list(), filename()} | {'error', posix() | {integer(), atom(), any()}}.
+-spec path_consult(Path, Filename) -> {ok, Terms, FullName} | {error, Reason} when
+ Path :: [Dir],
+ Dir :: name(),
+ Filename :: name(),
+ Terms :: [term()],
+ FullName :: filename(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
path_consult(Path, File) ->
case path_open(Path, File, [read]) of
@@ -803,13 +910,19 @@ path_consult(Path, File) ->
E2
end.
--spec eval(File :: name()) -> 'ok' | {'error', posix()}.
+-spec eval(Filename) -> ok | {error, Reason} when
+ Filename :: name(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
eval(File) ->
eval(File, erl_eval:new_bindings()).
--spec eval(File :: name(), Bindings :: bindings()) ->
- 'ok' | {'error', posix()}.
+-spec eval(Filename, Bindings) -> ok | {error, Reason} when
+ Filename :: name(),
+ Bindings :: bindings(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
eval(File, Bs) ->
case open(File, [read]) of
@@ -821,14 +934,24 @@ eval(File, Bs) ->
Error
end.
--spec path_eval(Paths :: [name()], File :: name()) ->
- {'ok', filename()} | {'error', posix() | {integer(), atom(), any()}}.
+-spec path_eval(Path, Filename) -> {ok, FullName} | {error, Reason} when
+ Path :: [Dir :: name()],
+ Filename :: name(),
+ FullName :: filename(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
path_eval(Path, File) ->
path_eval(Path, File, erl_eval:new_bindings()).
--spec path_eval(Paths :: [name()], File :: name(), Bindings :: bindings()) ->
- {'ok', filename()} | {'error', posix() | {integer(), atom(), any()}}.
+-spec path_eval(Path, Filename, Bindings) ->
+ {ok, FullName} | {error, Reason} when
+ Path :: [Dir :: name()],
+ Filename :: name(),
+ Bindings :: bindings(),
+ FullName :: filename(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
path_eval(Path, File, Bs) ->
case path_open(Path, File, [read]) of
@@ -845,14 +968,21 @@ path_eval(Path, File, Bs) ->
E2
end.
--spec script(File :: name()) ->
- {'ok', any()} | {'error', posix() | {integer(), atom(), any()}}.
+-spec script(Filename) -> {ok, Value} | {error, Reason} when
+ Filename :: name(),
+ Value :: term(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
script(File) ->
script(File, erl_eval:new_bindings()).
--spec script(File :: name(), Bindings :: bindings()) ->
- {'ok', any()} | {'error', posix() | {integer(), atom(), any()}}.
+-spec script(Filename, Bindings) -> {ok, Value} | {error, Reason} when
+ Filename :: name(),
+ Bindings :: bindings(),
+ Value :: term(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
script(File, Bs) ->
case open(File, [read]) of
@@ -864,16 +994,27 @@ script(File, Bs) ->
Error
end.
--spec path_script/2 :: (Paths :: [name()], File :: name()) ->
- {'ok', term(), filename()} | {'error', posix() | {integer(), atom(), _}}.
+-spec path_script(Path, Filename) ->
+ {ok, Value, FullName} | {error, Reason} when
+ Path :: [Dir :: name()],
+ Filename :: name(),
+ Value :: term(),
+ FullName :: filename(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
path_script(Path, File) ->
path_script(Path, File, erl_eval:new_bindings()).
--spec path_script(Paths :: [name()],
- File :: name(),
- Bindings :: bindings()) ->
- {'ok', term(), filename()} | {'error', posix() | {integer(), atom(), _}}.
+-spec path_script(Path, Filename, Bindings) ->
+ {ok, Value, FullName} | {error, Reason} when
+ Path :: [Dir :: name()],
+ Filename :: name(),
+ Bindings :: bindings(),
+ Value :: term(),
+ FullName :: filename(),
+ Reason :: posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
path_script(Path, File, Bs) ->
case path_open(Path, File, [read]) of
@@ -898,8 +1039,14 @@ path_script(Path, File, Bs) ->
%% Searches the Paths for file Filename which can be opened with Mode.
%% The path list is ignored if Filename contains an absolute path.
--spec path_open(Paths :: [name()], Name :: name(), Modes :: [mode()]) ->
- {'ok', io_device(), filename()} | {'error', posix()}.
+-spec path_open(Path, Filename, Modes) ->
+ {ok, IoDevice, FullName} | {error, Reason} when
+ Path :: [Dir :: name()],
+ Filename :: name(),
+ Modes :: [mode()],
+ IoDevice :: io_device(),
+ FullName :: filename(),
+ Reason :: posix() | badarg | system_limit.
path_open(PathList, Name, Mode) ->
case file_name(Name) of
@@ -919,47 +1066,57 @@ path_open(PathList, Name, Mode) ->
end
end.
--spec change_mode(Name :: name(), Mode :: integer()) ->
- 'ok' | {'error', posix()}.
+-spec change_mode(Filename, Mode) -> ok | {error, Reason} when
+ Filename :: name(),
+ Mode :: integer(),
+ Reason :: posix() | badarg.
change_mode(Name, Mode)
when is_integer(Mode) ->
write_file_info(Name, #file_info{mode=Mode}).
--spec change_owner(Name :: name(), OwnerId :: integer()) ->
- 'ok' | {'error', posix()}.
+-spec change_owner(Filename, Uid) -> ok | {error, Reason} when
+ Filename :: name(),
+ Uid :: integer(),
+ Reason :: posix() | badarg.
change_owner(Name, OwnerId)
when is_integer(OwnerId) ->
write_file_info(Name, #file_info{uid=OwnerId}).
--spec change_owner(Name :: name(),
- OwnerId :: integer(),
- GroupId :: integer()) ->
- 'ok' | {'error', posix()}.
+-spec change_owner(Filename, Uid, Gid) -> ok | {error, Reason} when
+ Filename :: name(),
+ Uid :: integer(),
+ Gid :: integer(),
+ Reason :: posix() | badarg.
change_owner(Name, OwnerId, GroupId)
when is_integer(OwnerId), is_integer(GroupId) ->
write_file_info(Name, #file_info{uid=OwnerId, gid=GroupId}).
--spec change_group(Name :: name(), GroupId :: integer()) ->
- 'ok' | {'error', posix()}.
+-spec change_group(Filename, Gid) -> ok | {error, Reason} when
+ Filename :: name(),
+ Gid :: integer(),
+ Reason :: posix() | badarg.
change_group(Name, GroupId)
when is_integer(GroupId) ->
write_file_info(Name, #file_info{gid=GroupId}).
--spec change_time(Name :: name(), Time :: date_time()) ->
- 'ok' | {'error', posix()}.
+-spec change_time(Filename, Mtime) -> ok | {error, Reason} when
+ Filename :: name(),
+ Mtime :: date_time(),
+ Reason :: posix() | badarg.
change_time(Name, Time)
when is_tuple(Time) ->
write_file_info(Name, #file_info{mtime=Time}).
--spec change_time(Name :: name(),
- ATime :: date_time(),
- MTime :: date_time()) ->
- 'ok' | {'error', posix()}.
+-spec change_time(Filename, Atime, Mtime) -> ok | {error, Reason} when
+ Filename :: name(),
+ Atime :: date_time(),
+ Mtime :: date_time(),
+ Reason :: posix() | badarg.
change_time(Name, Atime, Mtime)
when is_tuple(Atime), is_tuple(Mtime) ->
diff --git a/lib/kernel/src/gen_sctp.erl b/lib/kernel/src/gen_sctp.erl
index cccfa75005..004f03f231 100644
--- a/lib/kernel/src/gen_sctp.erl
+++ b/lib/kernel/src/gen_sctp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2007-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2007-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
@@ -33,11 +33,57 @@
-export([error_string/1]).
-export([controlling_process/2]).
-
+-opaque assoc_id() :: term().
+-type hostname() :: inet:hostname().
+-type ip_address() :: inet:ip_address().
+-type port_number() :: 0..65535.
+-type posix() :: inet:posix().
+-type sctp_option() ::
+ {mode, list | binary} | list | binary
+ | {active, true | false | once}
+ | {buffer, non_neg_integer()}
+ | {tos, integer()}
+ | {priority, integer()}
+ | {dontroute, boolean()}
+ | {reuseaddr, boolean()}
+ | {linger, {boolean(), non_neg_integer()}}
+ | {sndbuf, non_neg_integer()}
+ | {recbuf, non_neg_integer()}
+ | {sctp_rtoinfo, #sctp_rtoinfo{}}
+ | {sctp_associnfo, #sctp_assocparams{}}
+ | {sctp_initmsg, #sctp_initmsg{}}
+ | {sctp_autoclose, timeout()}
+ | {sctp_nodelay, boolean()}
+ | {sctp_disable_fragments, boolean()}
+ | {sctp_i_want_mapped_v4_addr, boolean()}
+ | {sctp_maxseg, non_neg_integer()}
+ | {sctp_primary_addr, #sctp_prim{}}
+ | {sctp_set_peer_primary_addr, #sctp_setpeerprim{}}
+ | {sctp_adaptation_layer, #sctp_setadaptation{}}
+ | {sctp_peer_addr_params, #sctp_paddrparams{}}
+ | {sctp_default_send_param, #sctp_sndrcvinfo{}}
+ | {sctp_events, #sctp_event_subscribe{}}
+ | {sctp_delayed_ack_time, #sctp_assoc_value{}}
+ | {sctp_status, #sctp_status{}}
+ | {sctp_get_peer_addr_info, #sctp_paddrinfo{}}.
+-opaque sctp_socket() :: port().
+
+-spec open() -> {ok, Socket} | {error, posix()} when
+ Socket :: sctp_socket().
open() ->
open([]).
+-spec open(Port) -> {ok, Socket} | {error, posix()} when
+ Port :: port_number(),
+ Socket :: sctp_socket();
+ (Opts) -> {ok, Socket} | {error, posix()} when
+ Opts :: [Opt],
+ Opt :: {ip,IP} | {ifaddr,IP} | {port,Port} | sctp_option(),
+ IP :: ip_address() | any | loopback,
+ Port :: port_number(),
+ Socket :: sctp_socket().
+
open(Opts) when is_list(Opts) ->
Mod = mod(Opts, undefined),
case Mod:open(Opts) of
@@ -52,11 +98,21 @@ open(Port) when is_integer(Port) ->
open(X) ->
erlang:error(badarg, [X]).
+-spec open(Port, Opts) -> {ok, Socket} | {error, posix()} when
+ Opts :: [Opt],
+ Opt :: {ip,IP} | {ifaddr,IP} | {port,Port} | sctp_option(),
+ IP :: ip_address() | any | loopback,
+ Port :: port_number(),
+ Socket :: sctp_socket().
+
open(Port, Opts) when is_integer(Port), is_list(Opts) ->
open([{port,Port}|Opts]);
open(Port, Opts) ->
erlang:error(badarg, [Port,Opts]).
+-spec close(Socket) -> ok | {error, posix()} when
+ Socket :: sctp_socket().
+
close(S) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok,Mod} ->
@@ -68,6 +124,11 @@ close(S) ->
+-spec listen(Socket, IsServer) -> ok | {error, Reason} when
+ Socket :: sctp_socket(),
+ IsServer :: boolean(),
+ Reason :: term().
+
listen(S, Flag) when is_port(S), is_boolean(Flag) ->
case inet_db:lookup_socket(S) of
{ok,Mod} ->
@@ -77,9 +138,25 @@ listen(S, Flag) when is_port(S), is_boolean(Flag) ->
listen(S, Flag) ->
erlang:error(badarg, [S,Flag]).
+-spec connect(Socket, Addr, Port, Opts) -> {ok, Assoc} | {error, posix()} when
+ Socket :: sctp_socket(),
+ Addr :: ip_address() | hostname(),
+ Port :: port_number(),
+ Opts :: [Opt :: sctp_option()],
+ Assoc :: #sctp_assoc_change{}.
+
connect(S, Addr, Port, Opts) ->
connect(S, Addr, Port, Opts, infinity).
+-spec connect(Socket, Addr, Port, Opts, Timeout) ->
+ {ok, Assoc} | {error, posix()} when
+ Socket :: sctp_socket(),
+ Addr :: ip_address() | hostname(),
+ Port :: port_number(),
+ Opts :: [Opt :: sctp_option()],
+ Timeout :: timeout(),
+ Assoc :: #sctp_assoc_change{}.
+
connect(S, Addr, Port, Opts, Timeout) ->
case do_connect(S, Addr, Port, Opts, Timeout, true) of
badarg ->
@@ -88,9 +165,24 @@ connect(S, Addr, Port, Opts, Timeout) ->
Result
end.
+-spec connect_init(Socket, Addr, Port, Opts) ->
+ ok | {error, posix()} when
+ Socket :: sctp_socket(),
+ Addr :: ip_address() | hostname(),
+ Port :: port_number(),
+ Opts :: [sctp_option()].
+
connect_init(S, Addr, Port, Opts) ->
connect_init(S, Addr, Port, Opts, infinity).
+-spec connect_init(Socket, Addr, Port, Opts, Timeout) ->
+ ok | {error, posix()} when
+ Socket :: sctp_socket(),
+ Addr :: ip_address() | hostname(),
+ Port :: port_number(),
+ Opts :: [sctp_option()],
+ Timeout :: timeout().
+
connect_init(S, Addr, Port, Opts, Timeout) ->
case do_connect(S, Addr, Port, Opts, Timeout, false) of
badarg ->
@@ -130,12 +222,20 @@ do_connect(_S, _Addr, _Port, _Opts, _Timeout, _ConnWait) ->
badarg.
+-spec eof(Socket, Assoc) -> ok | {error, Reason} when
+ Socket :: sctp_socket(),
+ Assoc :: #sctp_assoc_change{},
+ Reason :: term().
eof(S, #sctp_assoc_change{assoc_id=AssocId}) when is_port(S) ->
eof_or_abort(S, AssocId, eof);
eof(S, Assoc) ->
erlang:error(badarg, [S,Assoc]).
+-spec abort(Socket, Assoc) -> ok | {error, posix()} when
+ Socket :: sctp_socket(),
+ Assoc :: #sctp_assoc_change{}.
+
abort(S, #sctp_assoc_change{assoc_id=AssocId}) when is_port(S) ->
eof_or_abort(S, AssocId, abort);
abort(S, Assoc) ->
@@ -151,6 +251,11 @@ eof_or_abort(S, AssocId, Action) ->
end.
+-spec send(Socket, SndRcvInfo, Data) -> ok | {error, Reason} when
+ Socket :: sctp_socket(),
+ SndRcvInfo :: #sctp_sndrcvinfo{},
+ Data :: binary | iolist(),
+ Reason :: term().
%% Full-featured send. Rarely needed.
send(S, #sctp_sndrcvinfo{}=SRI, Data) when is_port(S) ->
@@ -162,6 +267,13 @@ send(S, #sctp_sndrcvinfo{}=SRI, Data) when is_port(S) ->
send(S, SRI, Data) ->
erlang:error(badarg, [S,SRI,Data]).
+-spec send(Socket, Assoc, Stream, Data) -> ok | {error, Reason} when
+ Socket :: sctp_socket(),
+ Assoc :: #sctp_assoc_change{} | assoc_id(),
+ Stream :: integer(),
+ Data :: binary | iolist(),
+ Reason :: term().
+
send(S, #sctp_assoc_change{assoc_id=AssocId}, Stream, Data)
when is_port(S), is_integer(Stream) ->
case inet_db:lookup_socket(S) of
@@ -179,9 +291,36 @@ send(S, AssocId, Stream, Data)
send(S, AssocChange, Stream, Data) ->
erlang:error(badarg, [S,AssocChange,Stream,Data]).
+-spec recv(Socket) -> {ok, {FromIP, FromPort, AncData, Data}}
+ | {error, Reason} when
+ Socket :: sctp_socket(),
+ FromIP :: ip_address(),
+ FromPort :: port_number(),
+ AncData :: [#sctp_sndrcvinfo{}],
+ Data :: binary() | string() | #sctp_sndrcvinfo{}
+ | #sctp_assoc_change{} | #sctp_paddr_change{}
+ | #sctp_adaptation_event{},
+ Reason :: posix() | #sctp_send_failed{} | #sctp_paddr_change{}
+ | #sctp_pdapi_event{} | #sctp_remote_error{}
+ | #sctp_shutdown_event{}.
+
recv(S) ->
recv(S, infinity).
+-spec recv(Socket, Timeout) -> {ok, {FromIP, FromPort, AncData, Data}}
+ | {error, Reason} when
+ Socket :: sctp_socket(),
+ Timeout :: timeout(),
+ FromIP :: ip_address(),
+ FromPort :: port_number(),
+ AncData :: [#sctp_sndrcvinfo{}],
+ Data :: binary() | string() | #sctp_sndrcvinfo{}
+ | #sctp_assoc_change{} | #sctp_paddr_change{}
+ | #sctp_adaptation_event{},
+ Reason :: posix() | #sctp_send_failed{} | #sctp_paddr_change{}
+ | #sctp_pdapi_event{} | #sctp_remote_error{}
+ | #sctp_shutdown_event{}.
+
recv(S, Timeout) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok,Mod} ->
@@ -192,6 +331,8 @@ recv(S, Timeout) ->
erlang:error(badarg, [S,Timeout]).
+-spec error_string(ErrorNumber) -> ok | string() | unknown_error when
+ ErrorNumber :: integer().
error_string(0) ->
ok;
@@ -224,6 +365,9 @@ error_string(X) ->
erlang:error(badarg, [X]).
+-spec controlling_process(Socket, Pid) -> ok when
+ Socket :: sctp_socket(),
+ Pid :: pid().
controlling_process(S, Pid) when is_port(S), is_pid(Pid) ->
inet:udp_controlling_process(S, Pid);
diff --git a/lib/kernel/src/gen_tcp.erl b/lib/kernel/src/gen_tcp.erl
index 16a87d71b6..bee61ca84a 100644
--- a/lib/kernel/src/gen_tcp.erl
+++ b/lib/kernel/src/gen_tcp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -28,12 +28,35 @@
-include("inet_int.hrl").
+-type hostname() :: inet:hostname().
+-type ip_address() :: inet:ip_address().
+-type port_number() :: 0..65535.
+-type posix() :: inet:posix().
+-type socket() :: port().
+
%%
%% Connect a socket
%%
+
+-spec connect(Address, Port, Options) -> {ok, Socket} | {error, Reason} when
+ Address :: ip_address() | hostname(),
+ Port :: port_number(),
+ Options :: [Opt :: term()],
+ Socket :: socket(),
+ Reason :: posix().
+
connect(Address, Port, Opts) ->
connect(Address,Port,Opts,infinity).
+-spec connect(Address, Port, Options, Timeout) ->
+ {ok, Socket} | {error, Reason} when
+ Address :: ip_address() | hostname(),
+ Port :: port_number(),
+ Options :: [Opt :: term()],
+ Timeout :: timeout(),
+ Socket :: socket(),
+ Reason :: posix().
+
connect(Address, Port, Opts, Time) ->
Timer = inet:start_timer(Time),
Res = (catch connect1(Address,Port,Opts,Timer)),
@@ -72,6 +95,13 @@ try_connect([], _Port, _Opts, _Timer, _Mod, Err) ->
%%
%% Listen on a tcp port
%%
+
+-spec listen(Port, Options) -> {ok, ListenSocket} | {error, Reason} when
+ Port :: port_number(),
+ Options :: [Opt :: term()],
+ ListenSocket :: socket(),
+ Reason :: posix().
+
listen(Port, Opts) ->
Mod = mod(Opts, undefined),
case Mod:getserv(Port) of
@@ -85,6 +115,12 @@ listen(Port, Opts) ->
%%
%% Generic tcp accept
%%
+
+-spec accept(ListenSocket) -> {ok, Socket} | {error, Reason} when
+ ListenSocket :: socket(),
+ Socket :: socket(),
+ Reason :: closed | timeout | posix().
+
accept(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -93,6 +129,12 @@ accept(S) ->
Error
end.
+-spec accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason} when
+ ListenSocket :: socket(),
+ Timeout :: timeout(),
+ Socket :: socket(),
+ Reason :: closed | timeout | posix().
+
accept(S, Time) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -104,6 +146,12 @@ accept(S, Time) when is_port(S) ->
%%
%% Generic tcp shutdown
%%
+
+-spec shutdown(Socket, How) -> ok | {error, Reason} when
+ Socket :: socket(),
+ How :: read | write | read_write,
+ Reason :: posix().
+
shutdown(S, How) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -115,12 +163,22 @@ shutdown(S, How) when is_port(S) ->
%%
%% Close
%%
+
+-spec close(Socket) -> ok when
+ Socket :: socket().
+
close(S) ->
inet:tcp_close(S).
%%
%% Send
%%
+
+-spec send(Socket, Packet) -> ok | {error, Reason} when
+ Socket :: socket(),
+ Packet :: string() | binary(),
+ Reason :: posix().
+
send(S, Packet) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -132,6 +190,14 @@ send(S, Packet) when is_port(S) ->
%%
%% Receive data from a socket (passive mode)
%%
+
+-spec recv(Socket, Length) -> {ok, Packet} | {error, Reason} when
+ Socket :: socket(),
+ Length :: non_neg_integer(),
+ Packet :: string() | binary() | HttpPacket,
+ Reason :: closed | posix(),
+ HttpPacket :: term().
+
recv(S, Length) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -140,6 +206,14 @@ recv(S, Length) when is_port(S) ->
Error
end.
+-spec recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason} when
+ Socket :: socket(),
+ Length :: non_neg_integer(),
+ Timeout :: timeout(),
+ Packet :: string() | binary() | HttpPacket,
+ Reason :: closed | posix(),
+ HttpPacket :: term().
+
recv(S, Length, Time) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -159,6 +233,12 @@ unrecv(S, Data) when is_port(S) ->
%%
%% Set controlling process
%%
+
+-spec controlling_process(Socket, Pid) -> ok | {error, Reason} when
+ Socket :: socket(),
+ Pid :: pid(),
+ Reason :: closed | not_owner | posix().
+
controlling_process(S, NewOwner) ->
case inet_db:lookup_socket(S) of
{ok, _Mod} -> % Just check that this is an open socket
diff --git a/lib/kernel/src/gen_udp.erl b/lib/kernel/src/gen_udp.erl
index 99020c7b6c..7d14615c04 100644
--- a/lib/kernel/src/gen_udp.erl
+++ b/lib/kernel/src/gen_udp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -25,17 +25,44 @@
-include("inet_int.hrl").
+-type hostname() :: inet:hostname().
+-type ip_address() :: inet:ip_address().
+-type port_number() :: 0..65535.
+-type posix() :: inet:posix().
+-type socket() :: port().
+
+-spec open(Port) -> {ok, Socket} | {error, Reason} when
+ Port :: port_number(),
+ Socket :: socket(),
+ Reason :: posix().
+
open(Port) ->
open(Port, []).
+-spec open(Port, Opts) -> {ok, Socket} | {error, Reason} when
+ Port :: port_number(),
+ Opts :: [Opt :: term()],
+ Socket :: socket(),
+ Reason :: posix().
+
open(Port, Opts) ->
Mod = mod(Opts, undefined),
{ok,UP} = Mod:getserv(Port),
Mod:open(UP, Opts).
+-spec close(Socket) -> ok when
+ Socket :: socket().
+
close(S) ->
inet:udp_close(S).
+-spec send(Socket, Address, Port, Packet) -> ok | {error, Reason} when
+ Socket :: socket(),
+ Address :: ip_address() | hostname(),
+ Port :: port_number(),
+ Packet :: string() | binary(),
+ Reason :: not_owner | posix().
+
send(S, Address, Port, Packet) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -61,6 +88,15 @@ send(S, Packet) when is_port(S) ->
Error
end.
+-spec recv(Socket, Length) ->
+ {ok, {Address, Port, Packet}} | {error, Reason} when
+ Socket :: socket(),
+ Length :: non_neg_integer(),
+ Address :: ip_address(),
+ Port :: port_number(),
+ Packet :: string() | binary(),
+ Reason :: not_owner | posix().
+
recv(S,Len) when is_port(S), is_integer(Len) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -69,6 +105,16 @@ recv(S,Len) when is_port(S), is_integer(Len) ->
Error
end.
+-spec recv(Socket, Length, Timeout) ->
+ {ok, {Address, Port, Packet}} | {error, Reason} when
+ Socket :: socket(),
+ Length :: non_neg_integer(),
+ Timeout :: timeout(),
+ Address :: ip_address(),
+ Port :: port_number(),
+ Packet :: string() | binary(),
+ Reason :: not_owner | posix().
+
recv(S,Len,Time) when is_port(S) ->
case inet_db:lookup_socket(S) of
{ok, Mod} ->
@@ -90,6 +136,10 @@ connect(S, Address, Port) when is_port(S) ->
Error
end.
+-spec controlling_process(Socket, Pid) -> ok when
+ Socket :: socket(),
+ Pid :: pid().
+
controlling_process(S, NewOwner) ->
inet:udp_controlling_process(S, NewOwner).
diff --git a/lib/kernel/src/global.erl b/lib/kernel/src/global.erl
index 6343acd000..7d15f8bf83 100644
--- a/lib/kernel/src/global.erl
+++ b/lib/kernel/src/global.erl
@@ -166,7 +166,7 @@ start_link() ->
stop() ->
gen_server:call(global_name_server, stop, infinity).
--spec sync() -> 'ok' | {'error', term()}.
+-spec sync() -> 'ok' | {'error', Reason :: term()}.
sync() ->
case check_sync_nodes() of
{error, _} = Error ->
@@ -175,7 +175,7 @@ sync() ->
gen_server:call(global_name_server, {sync, SyncNodes}, infinity)
end.
--spec sync([node()]) -> 'ok' | {'error', term()}.
+-spec sync([node()]) -> 'ok' | {'error', Reason :: term()}.
sync(Nodes) ->
case check_sync_nodes(Nodes) of
{error, _} = Error ->
@@ -184,7 +184,10 @@ sync(Nodes) ->
gen_server:call(global_name_server, {sync, SyncNodes}, infinity)
end.
--spec send(term(), term()) -> pid().
+-spec send(Name, Msg) -> Pid when
+ Name :: term(),
+ Msg :: term(),
+ Pid :: pid().
send(Name, Msg) ->
case whereis_name(Name) of
Pid when is_pid(Pid) ->
@@ -195,7 +198,8 @@ send(Name, Msg) ->
end.
%% See OTP-3737.
--spec whereis_name(term()) -> pid() | 'undefined'.
+-spec whereis_name(Name) -> pid() | 'undefined' when
+ Name :: term().
whereis_name(Name) ->
where(Name).
@@ -219,13 +223,19 @@ node_disconnected(Node) ->
%% undefined which one of them is used.
%% Method blocks the name registration, but does not affect global locking.
%%-----------------------------------------------------------------
--spec register_name(term(), pid()) -> 'yes' | 'no'.
+-spec register_name(Name, Pid) -> 'yes' | 'no' when
+ Name :: term(),
+ Pid :: pid().
register_name(Name, Pid) when is_pid(Pid) ->
register_name(Name, Pid, fun random_exit_name/3).
--type method() :: fun((term(), pid(), pid()) -> pid() | 'none').
+-type method() :: fun((Name :: term(), Pid :: pid(), Pid2 :: pid()) ->
+ pid() | 'none').
--spec register_name(term(), pid(), method()) -> 'yes' | 'no'.
+-spec register_name(Name, Pid, Resolve) -> 'yes' | 'no' when
+ Name :: term(),
+ Pid :: pid(),
+ Resolve :: method().
register_name(Name, Pid, Method) when is_pid(Pid) ->
Fun = fun(Nodes) ->
case (where(Name) =:= undefined) andalso check_dupname(Name, Pid) of
@@ -257,7 +267,8 @@ check_dupname(Name, Pid) ->
end
end.
--spec unregister_name(term()) -> _.
+-spec unregister_name(Name) -> _ when
+ Name :: term().
unregister_name(Name) ->
case where(Name) of
undefined ->
@@ -273,11 +284,16 @@ unregister_name(Name) ->
gen_server:call(global_name_server, {registrar, Fun}, infinity)
end.
--spec re_register_name(term(), pid()) -> _.
+-spec re_register_name(Name, Pid) -> _ when
+ Name :: term(),
+ Pid :: pid().
re_register_name(Name, Pid) when is_pid(Pid) ->
re_register_name(Name, Pid, fun random_exit_name/3).
--spec re_register_name(term(), pid(), method()) -> _.
+-spec re_register_name(Name, Pid, Resolve) -> _ when
+ Name :: term(),
+ Pid :: pid(),
+ Resolve :: method().
re_register_name(Name, Pid, Method) when is_pid(Pid) ->
Fun = fun(Nodes) ->
gen_server:multi_call(Nodes,
@@ -288,7 +304,8 @@ re_register_name(Name, Pid, Method) when is_pid(Pid) ->
?trace({re_register_name, self(), Name, Pid, Method}),
gen_server:call(global_name_server, {registrar, Fun}, infinity).
--spec registered_names() -> [term()].
+-spec registered_names() -> [Name] when
+ Name :: term().
registered_names() ->
MS = ets:fun2ms(fun({Name,_Pid,_M,_RP,_R}) -> Name end),
ets:select(global_names, MS).
@@ -329,19 +346,25 @@ register_name_external(Name, Pid, Method) when is_pid(Pid) ->
unregister_name_external(Name) ->
unregister_name(Name).
--type id() :: {term(), term()}.
+-type id() :: {ResourceId :: term(), LockRequesterId :: term()}.
--spec set_lock(id()) -> boolean().
+-spec set_lock(Id) -> boolean() when
+ Id :: id().
set_lock(Id) ->
set_lock(Id, [node() | nodes()], infinity, 1).
-type retries() :: non_neg_integer() | 'infinity'.
--spec set_lock(id(), [node()]) -> boolean().
+-spec set_lock(Id, Nodes) -> boolean() when
+ Id :: id(),
+ Nodes :: [node()].
set_lock(Id, Nodes) ->
set_lock(Id, Nodes, infinity, 1).
--spec set_lock(id(), [node()], retries()) -> boolean().
+-spec set_lock(Id, Nodes, Retries) -> boolean() when
+ Id :: id(),
+ Nodes :: [node()],
+ Retries :: retries().
set_lock(Id, Nodes, Retries) when is_integer(Retries), Retries >= 0 ->
set_lock(Id, Nodes, Retries, 1);
set_lock(Id, Nodes, infinity) ->
@@ -363,11 +386,14 @@ set_lock({_ResourceId, _LockRequesterId} = Id, Nodes, Retries, Times) ->
set_lock(Id, Nodes, dec(Retries), Times+1)
end.
--spec del_lock(id()) -> 'true'.
+-spec del_lock(Id) -> 'true' when
+ Id :: id().
del_lock(Id) ->
del_lock(Id, [node() | nodes()]).
--spec del_lock(id(), [node()]) -> 'true'.
+-spec del_lock(Id, Nodes) -> 'true' when
+ Id :: id(),
+ Nodes :: [node()].
del_lock({_ResourceId, _LockRequesterId} = Id, Nodes) ->
?trace({del_lock, {me,self()}, Id, {nodes,Nodes}}),
gen_server:multi_call(Nodes, global_name_server, {del_lock, Id}),
@@ -375,13 +401,25 @@ del_lock({_ResourceId, _LockRequesterId} = Id, Nodes) ->
-type trans_fun() :: function() | {module(), atom()}.
--spec trans(id(), trans_fun()) -> term().
+-spec trans(Id, Fun) -> Res | aborted when
+ Id :: id(),
+ Fun :: trans_fun(),
+ Res :: term().
trans(Id, Fun) -> trans(Id, Fun, [node() | nodes()], infinity).
--spec trans(id(), trans_fun(), [node()]) -> term().
+-spec trans(Id, Fun, Nodes) -> Res | aborted when
+ Id :: id(),
+ Fun :: trans_fun(),
+ Nodes :: [node()],
+ Res :: term().
trans(Id, Fun, Nodes) -> trans(Id, Fun, Nodes, infinity).
--spec trans(id(), trans_fun(), [node()], retries()) -> term().
+-spec trans(Id, Fun, Nodes, Retries) -> Res | aborted when
+ Id :: id(),
+ Fun :: trans_fun(),
+ Nodes :: [node()],
+ Retries :: retries(),
+ Res :: term().
trans(Id, Fun, Nodes, Retries) ->
case set_lock(Id, Nodes, Retries) of
true ->
@@ -1928,7 +1966,10 @@ resolve_it(Method, Name, Pid1, Pid2) ->
minmax(P1,P2) ->
if node(P1) < node(P2) -> {P1, P2}; true -> {P2, P1} end.
--spec random_exit_name(term(), pid(), pid()) -> pid().
+-spec random_exit_name(Name, Pid1, Pid2) -> 'none' when
+ Name :: term(),
+ Pid1 :: pid(),
+ Pid2 :: pid().
random_exit_name(Name, Pid, Pid2) ->
{Min, Max} = minmax(Pid, Pid2),
error_logger:info_msg("global: Name conflict terminating ~w\n",
@@ -1936,12 +1977,19 @@ random_exit_name(Name, Pid, Pid2) ->
exit(Max, kill),
Min.
+-spec random_notify_name(Name, Pid1, Pid2) -> 'none' when
+ Name :: term(),
+ Pid1 :: pid(),
+ Pid2 :: pid().
random_notify_name(Name, Pid, Pid2) ->
{Min, Max} = minmax(Pid, Pid2),
Max ! {global_name_conflict, Name},
Min.
--spec notify_all_name(term(), pid(), pid()) -> 'none'.
+-spec notify_all_name(Name, Pid1, Pid2) -> 'none' when
+ Name :: term(),
+ Pid1 :: pid(),
+ Pid2 :: pid().
notify_all_name(Name, Pid, Pid2) ->
Pid ! {global_name_conflict, Name, Pid2},
Pid2 ! {global_name_conflict, Name, Pid},
diff --git a/lib/kernel/src/global_group.erl b/lib/kernel/src/global_group.erl
index 7e141ac5c7..025a9b8a5b 100644
--- a/lib/kernel/src/global_group.erl
+++ b/lib/kernel/src/global_group.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1998-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1998-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
@@ -62,9 +62,10 @@
-type sync_state() :: 'no_conf' | 'synced'.
-type group_name() :: atom().
--type group_tuple() :: {group_name(), [node()]}
- | {group_name(), publish_type(), [node()]}.
-
+-type group_tuple() :: {GroupName :: group_name(), [node()]}
+ | {GroupName :: group_name(),
+ PublishType :: publish_type(),
+ [node()]}.
%%%====================================================================================
%%% The state of the global_group process
@@ -97,11 +98,14 @@
%%% External exported
%%%====================================================================================
--spec global_groups() -> {group_name(), [group_name()]} | 'undefined'.
+-spec global_groups() -> {GroupName, GroupNames} | undefined when
+ GroupName :: group_name(),
+ GroupNames :: [GroupName].
global_groups() ->
request(global_groups).
--spec monitor_nodes(boolean()) -> 'ok'.
+-spec monitor_nodes(Flag) -> 'ok' when
+ Flag :: boolean().
monitor_nodes(Flag) ->
case Flag of
true -> request({monitor_nodes, Flag});
@@ -109,30 +113,41 @@ monitor_nodes(Flag) ->
_ -> {error, not_boolean}
end.
--spec own_nodes() -> [node()].
+-spec own_nodes() -> Nodes when
+ Nodes :: [Node :: node()].
own_nodes() ->
request(own_nodes).
-type name() :: atom().
-type where() :: {'node', node()} | {'group', group_name()}.
--spec registered_names(where()) -> [name()].
+-spec registered_names(Where) -> Names when
+ Where :: where(),
+ Names :: [Name :: name()].
registered_names(Arg) ->
request({registered_names, Arg}).
--spec send(name(), term()) -> pid() | {'badarg', {name(), term()}}.
+-spec send(Name, Msg) -> pid() | {'badarg', {Name, Msg}} when
+ Name :: name(),
+ Msg :: term().
send(Name, Msg) ->
request({send, Name, Msg}).
--spec send(where(), name(), term()) -> pid() | {'badarg', {name(), term()}}.
+-spec send(Where, Name, Msg) -> pid() | {'badarg', {Name, Msg}} when
+ Where :: where(),
+ Name :: name(),
+ Msg :: term().
send(Group, Name, Msg) ->
request({send, Group, Name, Msg}).
--spec whereis_name(name()) -> pid() | 'undefined'.
+-spec whereis_name(Name) -> pid() | 'undefined' when
+ Name :: name().
whereis_name(Name) ->
request({whereis_name, Name}).
--spec whereis_name(where(), name()) -> pid() | 'undefined'.
+-spec whereis_name(Where, Name) -> pid() | 'undefined' when
+ Where :: where(),
+ Name :: name().
whereis_name(Group, Name) ->
request({whereis_name, Group, Name}).
@@ -155,14 +170,14 @@ ng_add_check(Node, OthersNG) ->
ng_add_check(Node, PubType, OthersNG) ->
request({ng_add_check, Node, PubType, OthersNG}).
--type info_item() :: {'state', sync_state()}
- | {'own_group_name', group_name()}
- | {'own_group_nodes', [node()]}
- | {'synched_nodes', [node()]}
- | {'sync_error', [node()]}
- | {'no_contact', [node()]}
- | {'other_groups', [group_tuple()]}
- | {'monitoring', [pid()]}.
+-type info_item() :: {'state', State :: sync_state()}
+ | {'own_group_name', GroupName :: group_name()}
+ | {'own_group_nodes', Nodes :: [node()]}
+ | {'synched_nodes', Nodes :: [node()]}
+ | {'sync_error', Nodes :: [node()]}
+ | {'no_contact', Nodes :: [node()]}
+ | {'other_groups', Groups :: [group_tuple()]}
+ | {'monitoring', Pids :: [pid()]}.
-spec info() -> [info_item()].
info() ->
@@ -1012,6 +1027,7 @@ grp_tuple({Name, normal, Nodes}) ->
%%% The special process which checks that all nodes in the own global group
%%% agrees on the configuration.
%%%====================================================================================
+-spec sync_init(_, _, _, _) -> no_return().
sync_init(Type, Cname, PubType, Nodes) ->
{Up, Down} = sync_check_node(lists:delete(node(), Nodes), [], []),
sync_check_init(Type, Up, Cname, Nodes, Down, PubType).
@@ -1032,9 +1048,11 @@ sync_check_node([Node|Nodes], Up, Down) ->
%%% Check that all nodes are in agreement of the global
%%% group configuration.
%%%-------------------------------------------------------------
+-spec sync_check_init(_, _, _, _, _, _) -> no_return().
sync_check_init(Type, Up, Cname, Nodes, Down, PubType) ->
sync_check_init(Type, Up, Cname, Nodes, 3, [], Down, PubType).
+-spec sync_check_init(_, _, _, _, _, _, _, _) -> no_return().
sync_check_init(_Type, NoContact, _Cname, _Nodes, 0, ErrorNodes, Down, _PubType) ->
case ErrorNodes of
[] ->
diff --git a/lib/kernel/src/global_search.erl b/lib/kernel/src/global_search.erl
index b723e18a1b..0bf53e29b8 100644
--- a/lib/kernel/src/global_search.erl
+++ b/lib/kernel/src/global_search.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1998-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1998-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
@@ -69,6 +69,7 @@ start(Flag, Arg) ->
%%%====================================================================================
%%%====================================================================================
+-spec init_send(_) -> no_return().
init_send({any, NodesList, Name, Msg, From}) ->
case whereis_any_loop(NodesList, Name) of
undefined ->
@@ -115,6 +116,7 @@ init_send({node, Node, Name, Msg, From}) ->
%%%====================================================================================
%%%====================================================================================
+-spec init_whereis(_) -> no_return().
init_whereis({any, NodesList, Name, From}) ->
R = whereis_any_loop(NodesList, Name),
gen_server:cast(global_group, {find_name_res, R, self(), From}),
@@ -146,6 +148,7 @@ init_whereis({node, Node, Name, From}) ->
%%%====================================================================================
%%%====================================================================================
%%%====================================================================================
+-spec init_names(_) -> no_return().
init_names({group, Nodes, From}) ->
case names_group_loop(Nodes) of
group_down ->
diff --git a/lib/kernel/src/heart.erl b/lib/kernel/src/heart.erl
index e78acfc7a6..255ae4e51b 100644
--- a/lib/kernel/src/heart.erl
+++ b/lib/kernel/src/heart.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -85,19 +85,21 @@ init(Starter, Parent) ->
Starter ! {start_error, self()}
end.
--spec set_cmd(string()) -> 'ok' | {'error', {'bad_cmd', string()}}.
+-spec set_cmd(Cmd) -> 'ok' | {'error', {'bad_cmd', Cmd}} when
+ Cmd :: string().
set_cmd(Cmd) ->
heart ! {self(), set_cmd, Cmd},
wait().
--spec get_cmd() -> 'ok'.
+-spec get_cmd() -> {ok, Cmd} when
+ Cmd :: string().
get_cmd() ->
heart ! {self(), get_cmd},
wait().
--spec clear_cmd() -> {'ok', string()}.
+-spec clear_cmd() -> ok.
clear_cmd() ->
heart ! {self(), clear_cmd},
diff --git a/lib/kernel/src/inet.erl b/lib/kernel/src/inet.erl
index 327e0f93f1..5649188c38 100644
--- a/lib/kernel/src/inet.erl
+++ b/lib/kernel/src/inet.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -63,7 +63,8 @@
%% timer interface
-export([start_timer/1, timeout/1, timeout/2, stop_timer/1]).
--export_type([ip_address/0, socket/0]).
+-export_type([family_option/0, hostent/0, hostname/0, ip4_address/0,
+ ip6_address/0, ip_address/0, posix/0, socket/0]).
%% imports
-import(lists, [append/1, duplicate/2, filter/2, foldl/3]).
@@ -79,8 +80,16 @@
%%% ---------------------------------
%%% Contract type definitions
+
+-type hostent() :: #hostent{}.
+-type hostname() :: atom() | string().
+-type ip4_address() :: {0..255,0..255,0..255,0..255}.
+-type ip6_address() :: {0..65535,0..65535,0..65535,0..65535,
+ 0..65535,0..65535,0..65535,0..65535}.
+-type ip_address() :: ip4_address() | ip6_address().
+-type ip_port() :: 0..65535.
+-type posix() :: exbadport | exbadseq | file:posix().
-type socket() :: port().
--type posix() :: atom().
-type socket_setopt() ::
{'raw', non_neg_integer(), non_neg_integer(), binary()} |
@@ -106,7 +115,7 @@
{'packet',
0 | 1 | 2 | 4 | 'raw' | 'sunrm' | 'asn1' |
'cdr' | 'fcgi' | 'line' | 'tpkt' | 'http' | 'httph' | 'http_bin' | 'httph_bin' } |
- {'mode', list() | binary()} |
+ {'mode', 'list' | 'binary'} |
{'port', 'port', 'term'} |
{'exit_on_close', boolean()} |
{'low_watermark', non_neg_integer()} |
@@ -195,12 +204,13 @@
%%% ---------------------------------
--spec get_rc() -> [{any(),any()}].
+-spec get_rc() -> [{Par :: any(), Val :: any()}].
get_rc() ->
inet_db:get_rc().
--spec close(Socket :: socket()) -> 'ok'.
+-spec close(Socket) -> 'ok' when
+ Socket :: socket().
close(Socket) ->
prim_inet:close(Socket),
@@ -211,8 +221,10 @@ close(Socket) ->
ok
end.
--spec peername(Socket :: socket()) ->
- {'ok', {ip_address(), non_neg_integer()}} | {'error', posix()}.
+-spec peername(Socket) -> {ok, {Address, Port}} | {error, posix()} when
+ Socket :: socket(),
+ Address :: ip_address(),
+ Port :: non_neg_integer().
peername(Socket) ->
prim_inet:peername(Socket).
@@ -226,8 +238,10 @@ setpeername(Socket, undefined) ->
prim_inet:setpeername(Socket, undefined).
--spec sockname(Socket :: socket()) ->
- {'ok', {ip_address(), non_neg_integer()}} | {'error', posix()}.
+-spec sockname(Socket) -> {ok, {Address, Port}} | {error, posix()} when
+ Socket :: socket(),
+ Address :: ip_address(),
+ Port :: non_neg_integer().
sockname(Socket) ->
prim_inet:sockname(Socket).
@@ -260,8 +274,10 @@ send(Socket, Packet) ->
setopts(Socket, Opts) ->
prim_inet:setopts(Socket, Opts).
--spec getopts(Socket :: socket(), Opts :: [socket_getopt()]) ->
- {'ok', [socket_setopt()]} | {'error', posix()}.
+-spec getopts(Socket, Options) ->
+ {'ok', [socket_setopt()]} | {'error', posix()} when
+ Socket :: socket(),
+ Options :: [socket_getopt()].
getopts(Socket, Opts) ->
prim_inet:getopts(Socket, Opts).
@@ -272,7 +288,19 @@ getopts(Socket, Opts) ->
getifaddrs(Socket) ->
prim_inet:getifaddrs(Socket).
--spec getifaddrs() -> {'ok', [string()]} | {'error', posix()}.
+-spec getifaddrs() -> {ok, Iflist} | {error, posix()} when
+ Iflist :: [{Ifname,[Ifopt]}],
+ Ifname :: string(),
+ Ifopt :: {flag,[Flag]} | {addr,Addr} | {netmask,Netmask}
+ | {broadaddr,Broadaddr} | {dstaddr,Dstaddr}
+ | {hwaddr,Hwaddr},
+ Flag :: up | broadcast | loopback | pointtopoint
+ | running | multicast,
+ Addr :: ip_address(),
+ Netmask :: ip_address(),
+ Broadaddr :: ip_address(),
+ Dstaddr :: ip_address(),
+ Hwaddr :: [byte()].
getifaddrs() ->
withsocket(fun(S) -> prim_inet:getifaddrs(S) end).
@@ -371,7 +399,8 @@ popf(_Socket) ->
% use of the DHCP-protocol
% should never fail
--spec gethostname() -> {'ok', string()}.
+-spec gethostname() -> {'ok', Hostname} when
+ Hostname :: string().
gethostname() ->
case inet_udp:open(0,[]) of
@@ -402,19 +431,23 @@ getstat(Socket) ->
getstat(Socket,What) ->
prim_inet:getstat(Socket, What).
--spec gethostbyname(Name :: string() | atom()) ->
- {'ok', #hostent{}} | {'error', posix()}.
+-spec gethostbyname(Hostname) -> {ok, Hostent} | {error, posix()} when
+ Hostname :: hostname(),
+ Hostent :: hostent().
gethostbyname(Name) ->
gethostbyname_tm(Name, inet, false).
--spec gethostbyname(Name :: string() | atom(), Family :: family_option()) ->
- {'ok', #hostent{}} | {'error', posix()}.
+-spec gethostbyname(Hostname, Family) ->
+ {ok, Hostent} | {error, posix()} when
+ Hostname :: hostname(),
+ Family :: family_option(),
+ Hostent :: hostent().
gethostbyname(Name,Family) ->
gethostbyname_tm(Name, Family, false).
--spec gethostbyname(Name :: string() | atom(),
+-spec gethostbyname(Name :: hostname(),
Family :: family_option(),
Timeout :: non_neg_integer() | 'infinity') ->
{'ok', #hostent{}} | {'error', posix()}.
@@ -439,8 +472,9 @@ gethostbyname_tm(Name,Family,Timer) ->
gethostbyname_tm(Name, Family, Timer, Opts).
--spec gethostbyaddr(Address :: string() | ip_address()) ->
- {'ok', #hostent{}} | {'error', posix()}.
+-spec gethostbyaddr(Address) -> {ok, Hostent} | {error, posix()} when
+ Address :: string() | ip_address(),
+ Hostent :: hostent().
gethostbyaddr(Address) ->
gethostbyaddr_tm(Address, false).
@@ -491,14 +525,15 @@ getfd(Socket) ->
%% Lookup an ip address
%%
--spec getaddr(Host :: ip_address() | string() | atom(),
- Family :: family_option()) ->
- {'ok', ip_address()} | {'error', posix()}.
+-spec getaddr(Host, Family) -> {ok, Address} | {error, posix()} when
+ Host :: ip_address() | hostname(),
+ Family :: family_option(),
+ Address :: ip_address().
getaddr(Address, Family) ->
getaddr(Address, Family, infinity).
--spec getaddr(Host :: ip_address() | string() | atom(),
+-spec getaddr(Host :: ip_address() | hostname(),
Family :: family_option(),
Timeout :: non_neg_integer() | 'infinity') ->
{'ok', ip_address()} | {'error', posix()}.
@@ -515,9 +550,11 @@ getaddr_tm(Address, Family, Timer) ->
Error -> Error
end.
--spec getaddrs(Host :: ip_address() | string() | atom(),
- Family :: family_option()) ->
- {'ok', [ip_address()]} | {'error', posix()}.
+-spec getaddrs(Host, Family) ->
+ {ok, Addresses} | {error, posix()} when
+ Host :: ip_address() | hostname(),
+ Family :: family_option(),
+ Addresses :: [ip_address()].
getaddrs(Address, Family) ->
getaddrs(Address, Family, infinity).
@@ -1237,7 +1274,8 @@ port_list(Name) ->
%% utils
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec format_error(posix()) -> string().
+-spec format_error(Posix) -> string() when
+ Posix :: posix().
format_error(exbadport) -> "invalid port state";
format_error(exbadseq) -> "bad command sequence";
diff --git a/lib/kernel/src/inet_res.erl b/lib/kernel/src/inet_res.erl
index 93563c6011..2276ddcd08 100644
--- a/lib/kernel/src/inet_res.erl
+++ b/lib/kernel/src/inet_res.erl
@@ -47,18 +47,93 @@
false -> ok
end).
+-type res_option() ::
+ {alt_nameservers, [nameserver()]}
+ | {edns, 0 | false}
+ | {inet6, boolean()}
+ | {nameservers, [nameserver()]}
+ | {recurse, boolean()}
+ | {retry, integer()}
+ | {timeout, integer()}
+ | {udp_payload_size, integer()}
+ | {usevc, boolean()}.
+
+-type nameserver() :: {inet:ip_address(), Port :: 1..65535}.
+
+-type res_error() :: formerr | qfmterror | servfail | nxdomain |
+ notimp | refused | badvers | timeout.
+
+-type dns_name() :: string().
+
+-type rr_type() :: a | aaaa | cname | gid | hinfo | ns | mb | md | mg | mf
+ | minfo | mx | naptr | null | ptr | soa | spf | srv | txt
+ | uid | uinfo | unspec | wks.
+
+-type dns_class() :: in | chaos | hs | any.
+
+-opaque dns_msg() :: term().
+
+-type dns_data() ::
+ dns_name()
+ | inet:ip4_address()
+ | inet:ip6_address()
+ | {MName :: dns_name(),
+ RName :: dns_name(),
+ Serial :: integer(),
+ Refresh :: integer(),
+ Retry :: integer(),
+ Expiry :: integer(),
+ Minimum :: integer()}
+ | {inet:ip4_address(), Proto :: integer(), BitMap :: binary()}
+ | {CpuString :: string(), OsString :: string()}
+ | {RM :: dns_name(), EM :: dns_name()}
+ | {Prio :: integer(), dns_name()}
+ | {Prio :: integer(),Weight :: integer(),Port :: integer(),dns_name()}
+ | {Order :: integer(),Preference :: integer(),Flags :: string(),
+ Services :: string(),Regexp :: string(), dns_name()}
+ | [string()]
+ | binary().
+
%% --------------------------------------------------------------------------
%% resolve:
%%
%% Nameserver query
%%
+-spec resolve(Name, Class, Type) -> {ok, dns_msg()} | Error when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Error :: {error, Reason} | {error,{Reason,dns_msg()}},
+ Reason :: inet:posix() | res_error().
+
resolve(Name, Class, Type) ->
resolve(Name, Class, Type, [], infinity).
+-spec resolve(Name, Class, Type, Opts) ->
+ {ok, dns_msg()} | Error when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Opts :: [Opt],
+ Opt :: res_option() | verbose | atom(),
+ Error :: {error, Reason} | {error,{Reason,dns_msg()}},
+ Reason :: inet:posix() | res_error().
+
resolve(Name, Class, Type, Opts) ->
resolve(Name, Class, Type, Opts, infinity).
+-spec resolve(Name, Class, Type, Opts, Timeout) ->
+ {ok, dns_msg()} | Error when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Opts :: [Opt],
+ Opt :: res_option() | verbose | atom(),
+ Timeout :: timeout(),
+ Error :: {error, Reason} | {error,{Reason,dns_msg()}},
+ Reason :: inet:posix() | res_error().
+
resolve(Name, Class, Type, Opts, Timeout) ->
case nsdname(Name) of
{ok, Nm} ->
@@ -76,12 +151,30 @@ resolve(Name, Class, Type, Opts, Timeout) ->
%% Convenience wrapper to resolve/3,4,5 that filters out all answer data
%% fields of the class and type asked for.
+-spec lookup(Name, Class, Type) -> [dns_data()] when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type().
+
lookup(Name, Class, Type) ->
lookup(Name, Class, Type, []).
+-spec lookup(Name, Class, Type, Opts) -> [dns_data()] when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Opts :: [res_option() | verbose].
+
lookup(Name, Class, Type, Opts) ->
lookup(Name, Class, Type, Opts, infinity).
+-spec lookup(Name, Class, Type, Opts, Timeout) -> [dns_data()] when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Opts :: [res_option() | verbose],
+ Timeout :: timeout().
+
lookup(Name, Class, Type, Opts, Timeout) ->
lookup_filter(resolve(Name, Class, Type, Opts, Timeout),
Class, Type).
@@ -101,17 +194,55 @@ lookup_filter({error,_}, _, _) -> [].
%%
%% To be deprecated
+-spec nslookup(Name, Class, Type) -> {ok, dns_msg()} | {error, Reason} when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Reason :: inet:posix() | res_error().
+
nslookup(Name, Class, Type) ->
do_nslookup(Name, Class, Type, [], infinity).
+-spec nslookup(Name, Class, Type, Timeout) ->
+ {ok, dns_msg()} | {error, Reason} when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Timeout :: timeout(),
+ Reason :: inet:posix() | res_error();
+ (Name, Class, Type, Nameservers) ->
+ {ok, dns_msg()} | {error, Reason} when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Nameservers :: [nameserver()],
+ Reason :: inet:posix() | res_error().
+
nslookup(Name, Class, Type, Timeout) when is_integer(Timeout), Timeout >= 0 ->
do_nslookup(Name, Class, Type, [], Timeout);
nslookup(Name, Class, Type, NSs) -> % For backwards compatibility
nnslookup(Name, Class, Type, NSs). % with OTP R6B only
+-spec nnslookup(Name, Class, Type, Nameservers) ->
+ {ok, dns_msg()} | {error, Reason} when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Nameservers :: [nameserver()],
+ Reason :: inet:posix().
+
nnslookup(Name, Class, Type, NSs) ->
nnslookup(Name, Class, Type, NSs, infinity).
+-spec nnslookup(Name, Class, Type, Nameservers, Timeout) ->
+ {ok, dns_msg()} | {error, Reason} when
+ Name :: dns_name() | inet:ip_address(),
+ Class :: dns_class(),
+ Type :: rr_type(),
+ Timeout :: timeout(),
+ Nameservers :: [nameserver()],
+ Reason :: inet:posix().
+
nnslookup(Name, Class, Type, NSs, Timeout) ->
do_nslookup(Name, Class, Type, [{nameservers,NSs}], Timeout).
@@ -192,8 +323,19 @@ make_options(Opts, [Name|Names]) ->
%%
%% --------------------------------------------------------------------------
+-spec gethostbyaddr(Address) -> {ok, Hostent} | {error, Reason} when
+ Address :: inet:ip_address(),
+ Hostent :: inet:hostent(),
+ Reason :: inet:posix() | res_error().
+
gethostbyaddr(IP) -> gethostbyaddr_tm(IP,false).
+-spec gethostbyaddr(Address, Timeout) -> {ok, Hostent} | {error, Reason} when
+ Address :: inet:ip_address(),
+ Timeout :: timeout(),
+ Hostent :: inet:hostent(),
+ Reason :: inet:posix() | res_error().
+
gethostbyaddr(IP,Timeout) ->
Timer = inet:start_timer(Timeout),
Res = gethostbyaddr_tm(IP,Timer),
@@ -249,6 +391,11 @@ res_gethostbyaddr(Addr, IP, Timer) ->
%% Caches the answer.
%% --------------------------------------------------------------------------
+-spec gethostbyname(Name) -> {ok, Hostent} | {error, Reason} when
+ Name :: dns_name(),
+ Hostent :: inet:hostent(),
+ Reason :: inet:posix() | res_error().
+
gethostbyname(Name) ->
case inet_db:res_option(inet6) of
true ->
@@ -257,9 +404,23 @@ gethostbyname(Name) ->
gethostbyname_tm(Name, inet, false)
end.
+-spec gethostbyname(Name, Family) -> {ok, Hostent} | {error, Reason} when
+ Name :: dns_name(),
+ Hostent :: inet:hostent(),
+ Family :: inet:family_option(),
+ Reason :: inet:posix() | res_error().
+
gethostbyname(Name,Family) ->
gethostbyname_tm(Name,Family,false).
+-spec gethostbyname(Name, Family, Timeout) ->
+ {ok, Hostent} | {error, Reason} when
+ Name :: dns_name(),
+ Hostent :: inet:hostent(),
+ Timeout :: timeout(),
+ Family :: inet:family_option(),
+ Reason :: inet:posix() | res_error().
+
gethostbyname(Name,Family,Timeout) ->
Timer = inet:start_timer(Timeout),
Res = gethostbyname_tm(Name,Family,Timer),
@@ -298,14 +459,27 @@ gethostbyname_tm(_Name, _Family, _Timer) ->
%%
%% getbyname(domain_name(), Type) => {ok, hostent()} | {error, Reason}
%%
-%% where domain_name() is domain string or atom and Type is ?S_A, ?S_MX ...
+%% where domain_name() is domain string and Type is ?S_A, ?S_MX ...
%%
%% Caches the answer.
%% --------------------------------------------------------------------------
+-spec getbyname(Name, Type) -> {ok, Hostent} | {error, Reason} when
+ Name :: dns_name(),
+ Type :: rr_type(),
+ Hostent :: inet:hostent(),
+ Reason :: inet:posix() | res_error().
+
getbyname(Name, Type) ->
getbyname_tm(Name,Type,false).
+-spec getbyname(Name, Type, Timeout) -> {ok, Hostent} | {error, Reason} when
+ Name :: dns_name(),
+ Type :: rr_type(),
+ Timeout :: timeout(),
+ Hostent :: inet:hostent(),
+ Reason :: inet:posix() | res_error().
+
getbyname(Name, Type, Timeout) ->
Timer = inet:start_timer(Timeout),
Res = getbyname_tm(Name, Type, Timer),
@@ -698,7 +872,7 @@ query_ns(S0, Id, Buffer, IP, Port, Timer, Retry, I,
end
end.
-query_udp(_S, _Id, _Buffer, _IP, _Port, 0, Verbose) ->
+query_udp(_S, _Id, _Buffer, _IP, _Port, 0, _Verbose) ->
timeout;
query_udp(S, Id, Buffer, IP, Port, Timeout, Verbose) ->
?verbose(Verbose, "Try UDP server : ~p:~p (timeout=~w)\n",
@@ -734,7 +908,7 @@ query_udp(S, Id, Buffer, IP, Port, Timeout, Verbose) ->
{error,econnrefused}
end.
-query_tcp(0, _Id, _Buffer, _IP, _Port, Verbose) ->
+query_tcp(0, _Id, _Buffer, _IP, _Port, _Verbose) ->
timeout;
query_tcp(Timeout, Id, Buffer, IP, Port, Verbose) ->
?verbose(Verbose, "Try TCP server : ~p:~p (timeout=~w)\n",
diff --git a/lib/kernel/src/inet_udp.erl b/lib/kernel/src/inet_udp.erl
index 9a4089ab19..60bd96f332 100644
--- a/lib/kernel/src/inet_udp.erl
+++ b/lib/kernel/src/inet_udp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
+%% 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
@@ -39,8 +39,10 @@ getserv(Name) when is_atom(Name) -> inet:getservbyname(Name,udp).
getaddr(Address) -> inet:getaddr(Address, inet).
getaddr(Address,Timer) -> inet:getaddr_tm(Address, inet, Timer).
+-spec open(_) -> {ok, inet:socket()} | {error, atom()}.
open(Port) -> open(Port, []).
+-spec open(_, _) -> {ok, inet:socket()} | {error, atom()}.
open(Port, Opts) ->
case inet:udp_options(
[{port,Port}, {recbuf, ?RECBUF} | Opts],
@@ -69,6 +71,8 @@ recv(S,Len) ->
recv(S,Len,Time) ->
prim_inet:recvfrom(S, Len, Time).
+-spec close(inet:socket()) -> ok.
+
close(S) ->
inet:udp_close(S).
diff --git a/lib/kernel/src/net_adm.erl b/lib/kernel/src/net_adm.erl
index 737b1ecee9..9b2dac9544 100644
--- a/lib/kernel/src/net_adm.erl
+++ b/lib/kernel/src/net_adm.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -35,7 +35,11 @@
%% Try to read .hosts.erlang file in
%% 1. cwd , 2. $HOME 3. init:root_dir()
--spec host_file() -> [atom()] | {'error',atom() | {integer(),atom(),_}}.
+-spec host_file() -> Hosts | {error, Reason} when
+ Hosts :: [Host :: atom()],
+ %% Copied from file:path_consult/2:
+ Reason :: file:posix() | badarg | terminated | system_limit
+ | {Line :: integer(), Mod :: module(), Term :: term()}.
host_file() ->
Home = case init:get_argument(home) of
@@ -50,7 +54,8 @@ host_file() ->
%% Check whether a node is up or down
%% side effect: set up a connection to Node if there not yet is one.
--spec ping(atom()) -> 'pang' | 'pong'.
+-spec ping(Node) -> pong | pang when
+ Node :: atom().
ping(Node) when is_atom(Node) ->
case catch gen:call({net_kernel, Node},
@@ -63,7 +68,8 @@ ping(Node) when is_atom(Node) ->
pang
end.
--spec localhost() -> string().
+-spec localhost() -> Name when
+ Name :: string().
localhost() ->
{ok, Host} = inet:gethostname(),
@@ -73,12 +79,20 @@ localhost() ->
end.
--spec names() -> {'ok', [{string(), integer()}]} | {'error', _}.
+-spec names() -> {ok, [{Name, Port}]} | {error, Reason} when
+ Name :: string(),
+ Port :: non_neg_integer(),
+ Reason :: address | file:posix().
names() ->
names(localhost()).
--spec names(atom() | string()) -> {'ok', [{string(), integer()}]} | {'error', _}.
+
+-spec names(Host) -> {ok, [{Name, Port}]} | {error, Reason} when
+ Host :: atom() | string(),
+ Name :: string(),
+ Port :: non_neg_integer(),
+ Reason :: address | file:posix().
names(Hostname) ->
case inet:gethostbyname(Hostname) of
@@ -88,8 +102,9 @@ names(Hostname) ->
Else
end.
--spec dns_hostname(atom() | string()) ->
- {'ok', string()} | {'error', atom() | string()}.
+-spec dns_hostname(Host) -> {ok, Name} | {error, Host} when
+ Host :: atom() | string(),
+ Name :: string().
dns_hostname(Hostname) ->
case inet:gethostbyname(Hostname) of
@@ -164,7 +179,8 @@ collect_new(Sofar, Nodelist) ->
world() ->
world(silent).
--spec world(verbosity()) -> [node()].
+-spec world(Arg) -> [node()] when
+ Arg :: verbosity().
world(Verbose) ->
case net_adm:host_file() of
@@ -172,12 +188,15 @@ world(Verbose) ->
Hosts -> expand_hosts(Hosts, Verbose)
end.
--spec world_list([atom()]) -> [node()].
+-spec world_list(Hosts) -> [node()] when
+ Hosts :: [atom()].
world_list(Hosts) when is_list(Hosts) ->
expand_hosts(Hosts, silent).
--spec world_list([atom()], verbosity()) -> [node()].
+-spec world_list(Hosts, Arg) -> [node()] when
+ Hosts :: [atom()],
+ Arg :: verbosity().
world_list(Hosts, Verbose) when is_list(Hosts) ->
expand_hosts(Hosts, Verbose).
diff --git a/lib/kernel/src/net_kernel.erl b/lib/kernel/src/net_kernel.erl
index 5228d4fe01..9e3d730cee 100644
--- a/lib/kernel/src/net_kernel.erl
+++ b/lib/kernel/src/net_kernel.erl
@@ -145,8 +145,15 @@
%% Interface functions
kernel_apply(M,F,A) -> request({apply,M,F,A}).
+
+-spec allow(Nodes) -> ok | error when
+ Nodes :: [node()].
allow(Nodes) -> request({allow, Nodes}).
+
longnames() -> request(longnames).
+
+-spec stop() -> ok | {error, Reason} when
+ Reason :: not_allowed | not_found.
stop() -> erl_distribution:stop().
node_info(Node) -> get_node_info(Node).
@@ -158,10 +165,28 @@ i(Node) -> print_info(Node).
verbose(Level) when is_integer(Level) ->
request({verbose, Level}).
+-spec set_net_ticktime(NetTicktime, TransitionPeriod) -> Res when
+ NetTicktime :: pos_integer(),
+ TransitionPeriod :: non_neg_integer(),
+ Res :: unchanged
+ | change_initiated
+ | {ongoing_change_to, NewNetTicktime},
+ NewNetTicktime :: pos_integer().
set_net_ticktime(T, TP) when is_integer(T), T > 0, is_integer(TP), TP >= 0 ->
ticktime_res(request({new_ticktime, T*250, TP*1000})).
+
+-spec set_net_ticktime(NetTicktime) -> Res when
+ NetTicktime :: pos_integer(),
+ Res :: unchanged
+ | change_initiated
+ | {ongoing_change_to, NewNetTicktime},
+ NewNetTicktime :: pos_integer().
set_net_ticktime(T) when is_integer(T) ->
set_net_ticktime(T, ?DEFAULT_TRANSITION_PERIOD).
+
+-spec get_net_ticktime() -> Res when
+ Res :: NetTicktime | {ongoing_change_to, NetTicktime} | ignored,
+ NetTicktime :: pos_integer().
get_net_ticktime() ->
ticktime_res(request(ticktime)).
@@ -171,6 +196,9 @@ get_net_ticktime() ->
%% flags (we may want to move it elsewhere later). In order to easily
%% be backward compatible, errors are created here when process_flag()
%% fails.
+-spec monitor_nodes(Flag) -> ok | Error when
+ Flag :: boolean(),
+ Error :: error | {error, term()}.
monitor_nodes(Flag) ->
case catch process_flag(monitor_nodes, Flag) of
true -> ok;
@@ -178,6 +206,13 @@ monitor_nodes(Flag) ->
_ -> mk_monitor_nodes_error(Flag, [])
end.
+-spec monitor_nodes(Flag, Options) -> ok | Error when
+ Flag :: boolean(),
+ Options :: [Option],
+ Option :: {node_type, NodeType}
+ | nodedown_reason,
+ NodeType :: visible | hidden | all,
+ Error :: error | {error, term()}.
monitor_nodes(Flag, Opts) ->
case catch process_flag({monitor_nodes, Opts}, Flag) of
true -> ok;
@@ -209,6 +244,8 @@ publish_on_node(Node) when is_atom(Node) ->
update_publish_nodes(Ns) ->
request({update_publish_nodes, Ns}).
+-spec connect_node(Node) -> boolean() | ignored when
+ Node :: node().
%% explicit connects
connect_node(Node) when is_atom(Node) ->
request({connect, normal, Node}).
diff --git a/lib/kernel/src/os.erl b/lib/kernel/src/os.erl
index d1feae771d..f6769df585 100644
--- a/lib/kernel/src/os.erl
+++ b/lib/kernel/src/os.erl
@@ -24,7 +24,10 @@
-include("file.hrl").
--spec type() -> 'vxworks' | {'unix',atom()} | {'win32',atom()} | {'ose',atom()}.
+-spec type() -> vxworks | {Osfamily, Osname} when
+ Osfamily :: unix | win32,
+ Osname :: atom().
+
type() ->
case erlang:system_info(os_type) of
{vxworks, _} ->
@@ -32,18 +35,27 @@ type() ->
Else -> Else
end.
--spec version() -> string() | {non_neg_integer(),non_neg_integer(),non_neg_integer()}.
+-spec version() -> VersionString | {Major, Minor, Release} when
+ VersionString :: string(),
+ Major :: non_neg_integer(),
+ Minor :: non_neg_integer(),
+ Release :: non_neg_integer().
version() ->
erlang:system_info(os_version).
--spec find_executable(string()) -> string() | 'false'.
+-spec find_executable(Name) -> Filename | 'false' when
+ Name :: string(),
+ Filename :: string().
find_executable(Name) ->
case os:getenv("PATH") of
false -> find_executable(Name, []);
Path -> find_executable(Name, Path)
end.
--spec find_executable(string(), string()) -> string() | 'false'.
+-spec find_executable(Name, Path) -> Filename | 'false' when
+ Name :: string(),
+ Path :: string(),
+ Filename :: string().
find_executable(Name, Path) ->
Extensions = extensions(),
case filename:pathtype(Name) of
@@ -147,7 +159,8 @@ extensions() ->
end.
%% Executes the given command in the default shell for the operating system.
--spec cmd(atom() | string() | [string()]) -> string().
+-spec cmd(Command) -> string() when
+ Command :: atom() | io_lib:chars().
cmd(Cmd) ->
validate(Cmd),
case type() of
diff --git a/lib/kernel/src/pg2.erl b/lib/kernel/src/pg2.erl
index 956a900adc..0d5838716e 100644
--- a/lib/kernel/src/pg2.erl
+++ b/lib/kernel/src/pg2.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -30,17 +30,19 @@
%%% Exported functions
%%%
--spec start_link() -> {'ok', pid()} | {'error', term()}.
+-spec start_link() -> {'ok', pid()} | {'error', any()}.
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
--spec start() -> {'ok', pid()} | {'error', term()}.
+-spec start() -> {'ok', pid()} | {'error', any()}.
start() ->
ensure_started().
--spec create(term()) -> 'ok'.
+-type name() :: any().
+
+-spec create(Name :: name()) -> 'ok'.
create(Name) ->
ensure_started(),
@@ -55,9 +57,7 @@ create(Name) ->
ok
end.
--type name() :: term().
-
--spec delete(name()) -> 'ok'.
+-spec delete(Name :: name()) -> 'ok'.
delete(Name) ->
ensure_started(),
@@ -67,7 +67,8 @@ delete(Name) ->
end),
ok.
--spec join(name(), pid()) -> 'ok' | {'error', {'no_such_group', term()}}.
+-spec join(Name, Pid :: pid()) -> 'ok' | {'error', {'no_such_group', Name}}
+ when Name :: name().
join(Name, Pid) when is_pid(Pid) ->
ensure_started(),
@@ -83,7 +84,8 @@ join(Name, Pid) when is_pid(Pid) ->
ok
end.
--spec leave(name(), pid()) -> 'ok' | {'error', {'no_such_group', name()}}.
+-spec leave(Name, Pid :: pid()) -> 'ok' | {'error', {'no_such_group', Name}}
+ when Name :: name().
leave(Name, Pid) when is_pid(Pid) ->
ensure_started(),
@@ -99,10 +101,9 @@ leave(Name, Pid) when is_pid(Pid) ->
ok
end.
--type get_members_ret() :: [pid()] | {'error', {'no_such_group', name()}}.
+-spec get_members(Name) -> [pid()] | {'error', {'no_such_group', Name}}
+ when Name :: name().
--spec get_members(name()) -> get_members_ret().
-
get_members(Name) ->
ensure_started(),
case ets:member(pg2_table, {group, Name}) of
@@ -112,7 +113,8 @@ get_members(Name) ->
{error, {no_such_group, Name}}
end.
--spec get_local_members(name()) -> get_members_ret().
+-spec get_local_members(Name) -> [pid()] | {'error', {'no_such_group', Name}}
+ when Name :: name().
get_local_members(Name) ->
ensure_started(),
@@ -123,15 +125,15 @@ get_local_members(Name) ->
{error, {no_such_group, Name}}
end.
--spec which_groups() -> [name()].
+-spec which_groups() -> [Name :: name()].
which_groups() ->
ensure_started(),
all_groups().
--type gcp_error_reason() :: {'no_process', term()} | {'no_such_group', term()}.
-
--spec get_closest_pid(term()) -> pid() | {'error', gcp_error_reason()}.
+-spec get_closest_pid(Name) -> pid() | {'error', Reason} when
+ Name :: name(),
+ Reason :: {'no_process', Name} | {'no_such_group', Name}.
get_closest_pid(Name) ->
case get_local_members(Name) of
@@ -157,7 +159,9 @@ get_closest_pid(Name) ->
-record(state, {}).
--spec init([]) -> {'ok', #state{}}.
+-opaque state() :: #state{}.
+
+-spec init(Arg :: []) -> {'ok', state()}.
init([]) ->
Ns = nodes(),
@@ -169,13 +173,13 @@ init([]) ->
pg2_table = ets:new(pg2_table, [ordered_set, protected, named_table]),
{ok, #state{}}.
--type call() :: {'create', name()}
- | {'delete', name()}
- | {'join', name(), pid()}
- | {'leave', name(), pid()}.
-
--spec handle_call(call(), _, #state{}) ->
- {'reply', 'ok', #state{}}.
+-spec handle_call(Call :: {'create', Name}
+ | {'delete', Name}
+ | {'join', Name, Pid :: pid()}
+ | {'leave', Name, Pid :: pid()},
+ From :: {pid(),Tag :: any()},
+ State :: state()) -> {'reply', 'ok', state()}
+ when Name :: name().
handle_call({create, Name}, _From, S) ->
assure_group(Name),
@@ -195,11 +199,10 @@ handle_call(Request, From, S) ->
[Request, From]),
{noreply, S}.
--type all_members() :: [[name(),...]].
--type cast() :: {'exchange', node(), all_members()}
- | {'del_member', name(), pid()}.
-
--spec handle_cast(cast(), #state{}) -> {'noreply', #state{}}.
+-spec handle_cast(Cast :: {'exchange', node(), Names :: [[Name,...]]}
+ | {'del_member', Name, Pid :: pid()},
+ State :: state()) -> {'noreply', state()}
+ when Name :: name().
handle_cast({exchange, _Node, List}, S) ->
store(List),
@@ -208,7 +211,8 @@ handle_cast(_, S) ->
%% Ignore {del_member, Name, Pid}.
{noreply, S}.
--spec handle_info(tuple(), #state{}) -> {'noreply', #state{}}.
+-spec handle_info(Tuple :: tuple(), State :: state()) ->
+ {'noreply', state()}.
handle_info({'DOWN', MonitorRef, process, _Pid, _Info}, S) ->
member_died(MonitorRef),
@@ -222,7 +226,7 @@ handle_info({new_pg2, Node}, S) ->
handle_info(_, S) ->
{noreply, S}.
--spec terminate(term(), #state{}) -> 'ok'.
+-spec terminate(Reason :: any(), State :: state()) -> 'ok'.
terminate(_Reason, _S) ->
true = ets:delete(pg2_table),
diff --git a/lib/kernel/src/rpc.erl b/lib/kernel/src/rpc.erl
index e09acb5024..be35f99ed2 100644
--- a/lib/kernel/src/rpc.erl
+++ b/lib/kernel/src/rpc.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -263,14 +263,28 @@ proxy_user_flush() ->
%% THE rpc client interface
--spec call(node(), atom(), atom(), [term()]) -> term().
+-spec call(Node, Module, Function, Args) -> Res | {badrpc, Reason} when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Res :: term(),
+ Reason :: term().
call(N,M,F,A) when node() =:= N -> %% Optimize local call
local_call(M, F, A);
call(N,M,F,A) ->
do_call(N, {call,M,F,A,group_leader()}, infinity).
--spec call(node(), atom(), atom(), [term()], timeout()) -> term().
+-spec call(Node, Module, Function, Args, Timeout) ->
+ Res | {badrpc, Reason} when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Res :: term(),
+ Reason :: term(),
+ Timeout :: timeout().
call(N,M,F,A,_Timeout) when node() =:= N -> %% Optimize local call
local_call(M,F,A);
@@ -279,14 +293,28 @@ call(N,M,F,A,infinity) ->
call(N,M,F,A,Timeout) when is_integer(Timeout), Timeout >= 0 ->
do_call(N, {call,M,F,A,group_leader()}, Timeout).
--spec block_call(node(), atom(), atom(), [term()]) -> term().
+-spec block_call(Node, Module, Function, Args) -> Res | {badrpc, Reason} when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Res :: term(),
+ Reason :: term().
block_call(N,M,F,A) when node() =:= N -> %% Optimize local call
local_call(M,F,A);
block_call(N,M,F,A) ->
do_call(N, {block_call,M,F,A,group_leader()}, infinity).
--spec block_call(node(), atom(), atom(), [term()], timeout()) -> term().
+-spec block_call(Node, Module, Function, Args, Timeout) ->
+ Res | {badrpc, Reason} when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Res :: term(),
+ Reason :: term(),
+ Timeout :: timeout().
block_call(N,M,F,A,_Timeout) when node() =:= N -> %% Optimize local call
local_call(M, F, A);
@@ -339,7 +367,13 @@ rpc_check(X) -> X.
%% The entire call is packed into an atomic transaction which
%% either succeeds or fails, i.e. never hangs (unless the server itself hangs).
--spec server_call(node(), atom(), term(), term()) -> term() | {'error', 'nodedown'}.
+-spec server_call(Node, Name, ReplyWrapper, Msg) -> Reply | {error, Reason} when
+ Node :: node(),
+ Name :: atom(),
+ ReplyWrapper :: term(),
+ Msg :: term(),
+ Reply :: term(),
+ Reason :: nodedown.
server_call(Node, Name, ReplyWrapper, Msg)
when is_atom(Node), is_atom(Name) ->
@@ -362,7 +396,11 @@ server_call(Node, Name, ReplyWrapper, Msg)
end
end.
--spec cast(node(), atom(), atom(), [term()]) -> 'true'.
+-spec cast(Node, Module, Function, Args) -> true when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
cast(Node, Mod, Fun, Args) when Node =:= node() ->
catch spawn(Mod, Fun, Args),
@@ -373,12 +411,17 @@ cast(Node, Mod, Fun, Args) ->
%% Asynchronous broadcast, returns nothing, it's just send'n prey
--spec abcast(atom(), term()) -> 'abcast'.
+-spec abcast(Name, Msg) -> abcast when
+ Name :: atom(),
+ Msg :: term().
abcast(Name, Mess) ->
abcast([node() | nodes()], Name, Mess).
--spec abcast([node()], atom(), term()) -> 'abcast'.
+-spec abcast(Nodes, Name, Msg) -> abcast when
+ Nodes :: [node()],
+ Name :: atom(),
+ Msg :: term().
abcast([Node|Tail], Name, Mess) ->
Dest = {Name,Node},
@@ -396,23 +439,39 @@ abcast([], _,_) -> abcast.
%% message when we return from the call, we can't know that they have
%% processed the message though.
--spec sbcast(atom(), term()) -> {[node()], [node()]}.
+-spec sbcast(Name, Msg) -> {GoodNodes, BadNodes} when
+ Name :: atom(),
+ Msg :: term(),
+ GoodNodes :: [node()],
+ BadNodes :: [node()].
sbcast(Name, Mess) ->
sbcast([node() | nodes()], Name, Mess).
--spec sbcast([node()], atom(), term()) -> {[node()], [node()]}.
+-spec sbcast(Nodes, Name, Msg) -> {GoodNodes, BadNodes} when
+ Name :: atom(),
+ Msg :: term(),
+ Nodes :: [node()],
+ GoodNodes :: [node()],
+ BadNodes :: [node()].
sbcast(Nodes, Name, Mess) ->
Monitors = send_nodes(Nodes, ?NAME, {sbcast, Name, Mess}, []),
rec_nodes(?NAME, Monitors).
--spec eval_everywhere(atom(), atom(), [term()]) -> 'abcast'.
+-spec eval_everywhere(Module, Function, Args) -> abcast when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
eval_everywhere(Mod, Fun, Args) ->
eval_everywhere([node() | nodes()] , Mod, Fun, Args).
--spec eval_everywhere([node()], atom(), atom(), [term()]) -> 'abcast'.
+-spec eval_everywhere(Nodes, Module, Function, Args) -> abcast when
+ Nodes :: [node()],
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
eval_everywhere(Nodes, Mod, Fun, Args) ->
gen_server:abcast(Nodes, ?NAME, {cast,Mod,Fun,Args,group_leader()}).
@@ -453,20 +512,45 @@ unmonitor(Ref) when is_reference(Ref) ->
%% Call apply(M,F,A) on all nodes in parallel
--spec multicall(atom(), atom(), [term()]) -> {[_], [node()]}.
+-spec multicall(Module, Function, Args) -> {ResL, BadNodes} when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ ResL :: [term()],
+ BadNodes :: [node()].
multicall(M, F, A) ->
multicall(M, F, A, infinity).
--spec multicall([node()], atom(), atom(), [term()]) -> {[_], [node()]}
- ; (atom(), atom(), [term()], timeout()) -> {[_], [node()]}.
+-spec multicall(Nodes, Module, Function, Args) -> {ResL, BadNodes} when
+ Nodes :: [node()],
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ ResL :: [term()],
+ BadNodes :: [node()];
+ (Module, Function, Args, Timeout) -> {ResL, BadNodes} when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Timeout :: timeout(),
+ ResL :: [term()],
+ BadNodes :: [node()].
multicall(Nodes, M, F, A) when is_list(Nodes) ->
multicall(Nodes, M, F, A, infinity);
multicall(M, F, A, Timeout) ->
multicall([node() | nodes()], M, F, A, Timeout).
--spec multicall([node()], atom(), atom(), [term()], timeout()) -> {[_], [node()]}.
+-spec multicall(Nodes, Module, Function, Args, Timeout) ->
+ {ResL, BadNodes} when
+ Nodes :: [node()],
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Timeout :: timeout(),
+ ResL :: [term()],
+ BadNodes :: [node()].
multicall(Nodes, M, F, A, infinity)
when is_list(Nodes), is_atom(M), is_atom(F), is_list(A) ->
@@ -495,12 +579,21 @@ do_multicall(Nodes, M, F, A, Timeout) ->
%%
%% There is no apparent order among the replies.
--spec multi_server_call(atom(), term()) -> {[_], [node()]}.
+-spec multi_server_call(Name, Msg) -> {Replies, BadNodes} when
+ Name :: atom(),
+ Msg :: term(),
+ Replies :: [Reply :: term()],
+ BadNodes :: [node()].
multi_server_call(Name, Msg) ->
multi_server_call([node() | nodes()], Name, Msg).
--spec multi_server_call([node()], atom(), term()) -> {[_], [node()]}.
+-spec multi_server_call(Nodes, Name, Msg) -> {Replies, BadNodes} when
+ Nodes :: [node()],
+ Name :: atom(),
+ Msg :: term(),
+ Replies :: [Reply :: term()],
+ BadNodes :: [node()].
multi_server_call(Nodes, Name, Msg)
when is_list(Nodes), is_atom(Name) ->
@@ -509,9 +602,22 @@ multi_server_call(Nodes, Name, Msg)
%% Deprecated functions. Were only needed when communicating with R6 nodes.
+-spec safe_multi_server_call(Name, Msg) -> {Replies, BadNodes} when
+ Name :: atom(),
+ Msg :: term(),
+ Replies :: [Reply :: term()],
+ BadNodes :: [node()].
+
safe_multi_server_call(Name, Msg) ->
multi_server_call(Name, Msg).
+-spec safe_multi_server_call(Nodes, Name, Msg) -> {Replies, BadNodes} when
+ Nodes :: [node()],
+ Name :: atom(),
+ Msg :: term(),
+ Replies :: [Reply :: term()],
+ BadNodes :: [node()].
+
safe_multi_server_call(Nodes, Name, Msg) ->
multi_server_call(Nodes, Name, Msg).
@@ -539,7 +645,14 @@ rec_nodes(Name, [{N,R} | Tail], Badnodes, Replies) ->
%% rpc's towards the same node. I.e. it returns immediately and
%% it returns a Key that can be used in a subsequent yield(Key).
--spec async_call(node(), atom(), atom(), [term()]) -> pid().
+-opaque key() :: pid().
+
+-spec async_call(Node, Module, Function, Args) -> Key when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Key :: key().
async_call(Node, Mod, Fun, Args) ->
ReplyTo = self(),
@@ -549,20 +662,27 @@ async_call(Node, Mod, Fun, Args) ->
ReplyTo ! {self(), {promise_reply, R}} %% self() is key
end).
--spec yield(pid()) -> term().
+-spec yield(Key) -> {value, Val} | timeout when
+ Key :: key(),
+ Val :: (Res :: term()) | {badrpc, Reason :: term()}.
yield(Key) when is_pid(Key) ->
{value,R} = do_yield(Key, infinity),
R.
--spec nb_yield(pid(), timeout()) -> {'value', _} | 'timeout'.
+-spec nb_yield(Key, Timeout) -> {value, Val} | timeout when
+ Key :: key(),
+ Timeout :: timeout(),
+ Val :: (Res :: term()) | {badrpc, Reason :: term()}.
nb_yield(Key, infinity=Inf) when is_pid(Key) ->
do_yield(Key, Inf);
nb_yield(Key, Timeout) when is_pid(Key), is_integer(Timeout), Timeout >= 0 ->
do_yield(Key, Timeout).
--spec nb_yield(pid()) -> {'value', _} | 'timeout'.
+-spec nb_yield(Key) -> {value, Val} | timeout when
+ Key :: key(),
+ Val :: (Res :: term()) | {badrpc, Reason :: term()}.
nb_yield(Key) when is_pid(Key) ->
do_yield(Key, 0).
@@ -582,7 +702,12 @@ do_yield(Key, Timeout) ->
%% ArgL === [{M,F,Args},........]
%% Returns a lists of the evaluations in the same order as
%% given to ArgL
--spec parallel_eval([{atom(), atom(), [_]}]) -> [_].
+-spec parallel_eval(FuncCalls) -> ResL when
+ FuncCalls :: [{Module, Function, Args}],
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ ResL :: [term()].
parallel_eval(ArgL) ->
Nodes = [node() | nodes()],
@@ -599,7 +724,13 @@ map_nodes([{M,F,A}|Tail],[Node|MoreNodes], Original) ->
%% Parallel version of lists:map/3 with exactly the same
%% arguments and return value as lists:map/3,
%% except that it calls exit/1 if a network error occurs.
--spec pmap({atom(),atom()}, [term()], [term()]) -> [term()].
+-spec pmap(FuncSpec, ExtraArgs, List1) -> List2 when
+ FuncSpec :: {Module,Function},
+ Module :: module(),
+ Function :: atom(),
+ ExtraArgs :: [term()],
+ List1 :: [Elem :: term()],
+ List2 :: [term()].
pmap({M,F}, As, List) ->
check(parallel_eval(build_args(M,F,As, List, [])), []).
@@ -616,15 +747,20 @@ check([], Ack) -> Ack.
%% location transparent version of process_info
--spec pinfo(pid()) -> [{atom(), _}] | 'undefined'.
+-spec pinfo(Pid) -> [{Item, Info}] | undefined when
+ Pid :: pid(),
+ Item :: atom(),
+ Info :: term().
pinfo(Pid) when node(Pid) =:= node() ->
process_info(Pid);
pinfo(Pid) ->
call(node(Pid), erlang, process_info, [Pid]).
--spec pinfo(pid(), Item) -> {Item, _} | 'undefined' | []
- when is_subtype(Item, atom()).
+-spec pinfo(Pid, Item) -> {Item, Info} | undefined | [] when
+ Pid :: pid(),
+ Item :: atom(),
+ Info :: term().
pinfo(Pid, Item) when node(Pid) =:= node() ->
process_info(Pid, Item);
diff --git a/lib/kernel/src/seq_trace.erl b/lib/kernel/src/seq_trace.erl
index 78c3040f21..ea5da2de1c 100644
--- a/lib/kernel/src/seq_trace.erl
+++ b/lib/kernel/src/seq_trace.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1998-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1998-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
@@ -38,15 +38,17 @@
-type flag() :: 'send' | 'receive' | 'print' | 'timestamp'.
-type component() :: 'label' | 'serial' | flag().
--type value() :: non_neg_integer()
- | {non_neg_integer(), non_neg_integer()}
- | boolean().
--type token_pair() :: {component(), value()}.
+-type value() :: (Integer :: non_neg_integer())
+ | {Previous :: non_neg_integer(),
+ Current :: non_neg_integer()}
+ | (Bool :: boolean()).
%%---------------------------------------------------------------------------
--type token() :: [] | {integer(), boolean(), _, _, _}.
--spec set_token(token()) -> token() | 'ok'.
+-opaque token() :: {integer(), boolean(), _, _, _}.
+-spec set_token(Token) -> PreviousToken | 'ok' when
+ Token :: [] | token(),
+ PreviousToken :: [] | token().
set_token([]) ->
erlang:seq_trace(sequential_trace_token,[]);
@@ -58,28 +60,35 @@ set_token({Flags,Label,Serial,_From,Lastcnt}) ->
%% expects that, the BIF can however "unofficially" handle atoms as well, and
%% atoms can be used if only Erlang nodes are involved
--spec set_token(component(), value()) -> token_pair().
+-spec set_token(Component, Val) -> {Component, OldVal} when
+ Component :: component(),
+ Val :: value(),
+ OldVal :: value().
set_token(Type, Val) ->
erlang:seq_trace(Type, Val).
--spec get_token() -> term().
+-spec get_token() -> [] | token().
get_token() ->
element(2,process_info(self(),sequential_trace_token)).
--spec get_token(component()) -> token_pair().
-
+-spec get_token(Component) -> {Component, Val} when
+ Component :: component(),
+ Val :: value().
get_token(Type) ->
erlang:seq_trace_info(Type).
--spec print(term()) -> 'ok'.
+-spec print(TraceInfo) -> 'ok' when
+ TraceInfo :: term().
print(Term) ->
erlang:seq_trace_print(Term),
ok.
--spec print(integer(), term()) -> 'ok'.
+-spec print(Label, TraceInfo) -> 'ok' when
+ Label :: integer(),
+ TraceInfo :: term().
print(Label, Term) when is_atom(Label) ->
erlang:error(badarg, [Label, Term]);
@@ -94,14 +103,17 @@ reset_trace() ->
%% reset_trace(Pid) -> % this might be a useful function too
--type tracer() :: pid() | port() | 'false'.
+-type tracer() :: (Pid :: pid()) | port() | 'false'.
--spec set_system_tracer(tracer()) -> tracer().
+-spec set_system_tracer(Tracer) -> OldTracer when
+ Tracer :: tracer(),
+ OldTracer :: tracer().
set_system_tracer(Pid) ->
erlang:system_flag(sequential_tracer, Pid).
--spec get_system_tracer() -> tracer().
+-spec get_system_tracer() -> Tracer when
+ Tracer :: tracer().
get_system_tracer() ->
element(2, erlang:system_info(sequential_tracer)).
diff --git a/lib/kernel/src/wrap_log_reader.erl b/lib/kernel/src/wrap_log_reader.erl
index fabaa07752..c41e0091e4 100644
--- a/lib/kernel/src/wrap_log_reader.erl
+++ b/lib/kernel/src/wrap_log_reader.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1998-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1998-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
@@ -41,6 +41,8 @@
first_no :: non_neg_integer() | 'one' % first read file number
}).
+-opaque continuation() :: #wrap_reader{}.
+
%%
%% Exported functions
%%
@@ -50,9 +52,11 @@
%% is not yet reached, we are on the first 'round' of filling the wrap
%% files.
--type open_ret() :: {'ok', #wrap_reader{}} | {'error', tuple()}.
+-type open_ret() :: {'ok', Continuation :: continuation()}
+ | {'error', Reason :: tuple()}.
--spec open(atom() | string()) -> open_ret().
+-spec open(Filename) -> open_ret() when
+ Filename :: string() | atom().
open(File) when is_atom(File) ->
open(atom_to_list(File));
@@ -77,7 +81,9 @@ open(File) when is_list(File) ->
Error
end.
--spec open(atom() | string(), integer()) -> open_ret().
+-spec open(Filename, N) -> open_ret() when
+ Filename :: string() | atom(),
+ N :: integer().
open(File, FileNo) when is_atom(File), is_integer(FileNo) ->
open(atom_to_list(File), FileNo);
@@ -100,22 +106,29 @@ open(File, FileNo) when is_list(File), is_integer(FileNo) ->
Error
end.
--spec close(#wrap_reader{}) -> 'ok' | {'error', atom()}.
+-spec close(Continuation) -> 'ok' | {'error', Reason} when
+ Continuation :: continuation(),
+ Reason :: file:posix().
close(#wrap_reader{fd = FD}) ->
file:close(FD).
--type chunk_ret() :: {#wrap_reader{}, [term()]}
- | {#wrap_reader{}, [term()], non_neg_integer()}
- | {#wrap_reader{}, 'eof'}
- | {'error', term()}.
+-type chunk_ret() :: {Continuation2, Terms :: [term()]}
+ | {Continuation2,
+ Terms :: [term()],
+ Badbytes :: non_neg_integer()}
+ | {Continuation2, 'eof'}
+ | {'error', Reason :: term()}.
--spec chunk(#wrap_reader{}) -> chunk_ret().
+-spec chunk(Continuation) -> chunk_ret() when
+ Continuation :: continuation().
chunk(WR = #wrap_reader{}) ->
chunk(WR, ?MAX_CHUNK_SIZE, 0).
--spec chunk(#wrap_reader{}, 'infinity' | pos_integer()) -> chunk_ret().
+-spec chunk(Continuation, N) -> chunk_ret() when
+ Continuation :: continuation(),
+ N :: infinity | pos_integer().
chunk(WR = #wrap_reader{}, infinity) ->
chunk(WR, ?MAX_CHUNK_SIZE, 0);
diff --git a/lib/kernel/test/file_SUITE.erl b/lib/kernel/test/file_SUITE.erl
index 2f73394c4e..fdab2eb02b 100644
--- a/lib/kernel/test/file_SUITE.erl
+++ b/lib/kernel/test/file_SUITE.erl
@@ -360,41 +360,50 @@ make_del_dir(Config) when is_list(Config) ->
?line {error, eexist} = ?FILE_MODULE:make_dir(NewDir),
?line ok = ?FILE_MODULE:del_dir(NewDir),
?line {error, enoent} = ?FILE_MODULE:del_dir(NewDir),
-
- %% Check that we get an error when trying to create...
- %% a deep directory
- ?line NewDir2 = filename:join(RootDir,
- atom_to_list(?MODULE)
- ++"_mk-dir/foo"),
- ?line {error, enoent} = ?FILE_MODULE:make_dir(NewDir2),
- %% a nameless directory
- ?line {error, enoent} = ?FILE_MODULE:make_dir(""),
- %% a directory with illegal name
- ?line {error, badarg} = ?FILE_MODULE:make_dir({1,2,3}),
-
- %% a directory with illegal name, even if it's a (bad) list
- ?line {error, badarg} = ?FILE_MODULE:make_dir([1,2,3,{}]),
-
- %% Maybe this isn't an error, exactly, but worth mentioning anyway:
- %% ok = ?FILE_MODULE:make_dir([$f,$o,$o,0,$b,$a,$r])),
- %% The above line works, and created a directory "./foo"
- %% More elegant would maybe have been to fail, or to really create
- %% a directory, but with a name that incorporates the "bar" part of
- %% the list, so that [$f,$o,$o,0,$f,$o,$o] wouldn't refer to the same
- %% dir. But this would slow it down.
-
- %% Try deleting some bad directories
- %% Deleting the parent directory to the current, sounds dangerous, huh?
- %% Don't worry ;-) the parent directory should never be empty, right?
- case ?FILE_MODULE:del_dir('..') of
- {error, eexist} -> ok;
- {error, einval} -> ok %FreeBSD
+ % Make sure we are not in a directory directly under test_server
+ % as that would result in eacess errors when trying to delere '..',
+ % because there are processes having that directory as current.
+ ?line ok = ?FILE_MODULE:make_dir(NewDir),
+ ?line {ok,CurrentDir} = file:get_cwd(),
+ ?line ok = ?FILE_MODULE:set_cwd(NewDir),
+ try
+ %% Check that we get an error when trying to create...
+ %% a deep directory
+ ?line NewDir2 = filename:join(RootDir,
+ atom_to_list(?MODULE)
+ ++"_mk-dir-noexist/foo"),
+ ?line {error, enoent} = ?FILE_MODULE:make_dir(NewDir2),
+ %% a nameless directory
+ ?line {error, enoent} = ?FILE_MODULE:make_dir(""),
+ %% a directory with illegal name
+ ?line {error, badarg} = ?FILE_MODULE:make_dir({1,2,3}),
+
+ %% a directory with illegal name, even if it's a (bad) list
+ ?line {error, badarg} = ?FILE_MODULE:make_dir([1,2,3,{}]),
+
+ %% Maybe this isn't an error, exactly, but worth mentioning anyway:
+ %% ok = ?FILE_MODULE:make_dir([$f,$o,$o,0,$b,$a,$r])),
+ %% The above line works, and created a directory "./foo"
+ %% More elegant would maybe have been to fail, or to really create
+ %% a directory, but with a name that incorporates the "bar" part of
+ %% the list, so that [$f,$o,$o,0,$f,$o,$o] wouldn't refer to the same
+ %% dir. But this would slow it down.
+
+ %% Try deleting some bad directories
+ %% Deleting the parent directory to the current, sounds dangerous, huh?
+ %% Don't worry ;-) the parent directory should never be empty, right?
+ ?line case ?FILE_MODULE:del_dir('..') of
+ {error, eexist} -> ok;
+ {error, einval} -> ok %FreeBSD
+ end,
+ ?line {error, enoent} = ?FILE_MODULE:del_dir(""),
+ ?line {error, badarg} = ?FILE_MODULE:del_dir([3,2,1,{}]),
+
+ ?line [] = flush(),
+ ?line test_server:timetrap_cancel(Dog)
+ after
+ ?FILE_MODULE:set_cwd(CurrentDir)
end,
- ?line {error, enoent} = ?FILE_MODULE:del_dir(""),
- ?line {error, badarg} = ?FILE_MODULE:del_dir([3,2,1,{}]),
-
- ?line [] = flush(),
- ?line test_server:timetrap_cancel(Dog),
ok.
cur_dir_0(suite) -> [];
diff --git a/lib/kernel/test/prim_file_SUITE.erl b/lib/kernel/test/prim_file_SUITE.erl
index a04ea3cdcd..00eda6292f 100644
--- a/lib/kernel/test/prim_file_SUITE.erl
+++ b/lib/kernel/test/prim_file_SUITE.erl
@@ -250,39 +250,49 @@ make_del_dir(Config, Handle, Suffix) ->
?line ok = ?PRIM_FILE_call(del_dir, Handle, [NewDir]),
?line {error, enoent} = ?PRIM_FILE_call(del_dir, Handle, [NewDir]),
- %% Check that we get an error when trying to create...
- %% a deep directory
- ?line NewDir2 = filename:join(RootDir,
- atom_to_list(?MODULE)
- ++"_mk-dir/foo"),
- ?line {error, enoent} = ?PRIM_FILE_call(make_dir, Handle, [NewDir2]),
- %% a nameless directory
- ?line {error, enoent} = ?PRIM_FILE_call(make_dir, Handle, [""]),
- %% a directory with illegal name
- ?line {error, badarg} = ?PRIM_FILE_call(make_dir, Handle, ['mk-dir']),
-
- %% a directory with illegal name, even if it's a (bad) list
- ?line {error, badarg} = ?PRIM_FILE_call(make_dir, Handle, [[1,2,3,{}]]),
-
- %% Maybe this isn't an error, exactly, but worth mentioning anyway:
- %% ok = ?PRIM_FILE:make_dir([$f,$o,$o,0,$b,$a,$r])),
- %% The above line works, and created a directory "./foo"
- %% More elegant would maybe have been to fail, or to really create
- %% a directory, but with a name that incorporates the "bar" part of
- %% the list, so that [$f,$o,$o,0,$f,$o,$o] wouldn't refer to the same
- %% dir. But this would slow it down.
-
- %% Try deleting some bad directories
- %% Deleting the parent directory to the current, sounds dangerous, huh?
- %% Don't worry ;-) the parent directory should never be empty, right?
- case ?PRIM_FILE_call(del_dir, Handle, [".."]) of
- {error, eexist} -> ok;
- {error, einval} -> ok %FreeBSD
+ % Make sure we are not in a directory directly under test_server
+ % as that would result in eacess errors when trying to delere '..',
+ % because there are processes having that directory as current.
+ ?line ok = ?PRIM_FILE_call(make_dir, Handle, [NewDir]),
+ ?line {ok, CurrentDir} = ?PRIM_FILE_call(get_cwd, Handle, []),
+ ?line ok = ?PRIM_FILE_call(set_cwd, Handle, [NewDir]),
+ try
+ %% Check that we get an error when trying to create...
+ %% a deep directory
+ ?line NewDir2 = filename:join(RootDir,
+ atom_to_list(?MODULE)
+ ++"_mk-dir-noexist/foo"),
+ ?line {error, enoent} = ?PRIM_FILE_call(make_dir, Handle, [NewDir2]),
+ %% a nameless directory
+ ?line {error, enoent} = ?PRIM_FILE_call(make_dir, Handle, [""]),
+ %% a directory with illegal name
+ ?line {error, badarg} = ?PRIM_FILE_call(make_dir, Handle, ['mk-dir']),
+
+ %% a directory with illegal name, even if it's a (bad) list
+ ?line {error, badarg} = ?PRIM_FILE_call(make_dir, Handle, [[1,2,3,{}]]),
+
+ %% Maybe this isn't an error, exactly, but worth mentioning anyway:
+ %% ok = ?PRIM_FILE:make_dir([$f,$o,$o,0,$b,$a,$r])),
+ %% The above line works, and created a directory "./foo"
+ %% More elegant would maybe have been to fail, or to really create
+ %% a directory, but with a name that incorporates the "bar" part of
+ %% the list, so that [$f,$o,$o,0,$f,$o,$o] wouldn't refer to the same
+ %% dir. But this would slow it down.
+
+ %% Try deleting some bad directories
+ %% Deleting the parent directory to the current, sounds dangerous, huh?
+ %% Don't worry ;-) the parent directory should never be empty, right?
+ ?line case ?PRIM_FILE_call(del_dir, Handle, [".."]) of
+ {error, eexist} -> ok;
+ {error, einval} -> ok %FreeBSD
+ end,
+ ?line {error, enoent} = ?PRIM_FILE_call(del_dir, Handle, [""]),
+ ?line {error, badarg} = ?PRIM_FILE_call(del_dir, Handle, [[3,2,1,{}]]),
+
+ ?line test_server:timetrap_cancel(Dog)
+ after
+ ?line ok = ?PRIM_FILE_call(set_cwd, Handle, [CurrentDir])
end,
- ?line {error, enoent} = ?PRIM_FILE_call(del_dir, Handle, [""]),
- ?line {error, badarg} = ?PRIM_FILE_call(del_dir, Handle, [[3,2,1,{}]]),
-
- ?line test_server:timetrap_cancel(Dog),
ok.
cur_dir_0a(suite) -> [];
diff --git a/lib/mnesia/doc/src/Mnesia_chap7.xmlsrc b/lib/mnesia/doc/src/Mnesia_chap7.xmlsrc
index 7078499fbf..21174340d1 100644
--- a/lib/mnesia/doc/src/Mnesia_chap7.xmlsrc
+++ b/lib/mnesia/doc/src/Mnesia_chap7.xmlsrc
@@ -473,6 +473,13 @@ dets:close(N). </pre>
<c>mnesia:table_info(Tab, master_nodes)</c> may be used to
obtain information about the potential master nodes.
</p>
+ <p>Determining which data to keep after communication failure is outside
+ the scope of Mnesia. One approach would be to determine which "island"
+ contains a majority of the nodes. Using the <c>{majority,true}</c> option
+ for critical tables can be a way of ensuring that nodes that are not part
+ of a "majority island" are not able to update those tables. Note that this
+ constitutes a reduction in service on the minority nodes. This would be
+ a tradeoff in favour of higher consistency guarantees.</p>
<p>The function <c>mnesia:force_load_table(Tab)</c> may be used to
force load the table regardless of which table load mechanism
is activated.
diff --git a/lib/mnesia/doc/src/mnesia.xml b/lib/mnesia/doc/src/mnesia.xml
index 16e78ea0af..2a2c7d3a9f 100644
--- a/lib/mnesia/doc/src/mnesia.xml
+++ b/lib/mnesia/doc/src/mnesia.xml
@@ -161,6 +161,14 @@ If a new item is inserted with the same key as
</p>
</item>
<item>
+ <p><c>majority</c> This attribute can be either <c>true</c> or
+ <c>false</c> (default is <c>false</c>). When <c>true</c>, a majority
+ of the table replicas must be available for an update to succeed.
+ Majority checking can be enabled on tables with mission-critical data,
+ where it is vital to avoid inconsistencies due to network splits.
+ </p>
+ </item>
+ <item>
<p><c>snmp</c> Each (set based) Mnesia table can be
automatically turned into an SNMP ordered table as well.
This property specifies the types of the SNMP keys.
@@ -650,6 +658,17 @@ mnesia:change_table_copy_type(person, node(), disc_copies)
</desc>
</func>
<func>
+ <name>change_table_majority(Tab, Majority) -> {aborted, R} | {atomic, ok}</name>
+ <fsummary>Change the majority check setting for the table.</fsummary>
+ <desc>
+ <p><c>Majority</c> must be a boolean; the default is <c>false</c>.
+ When <c>true</c>, a majority of the table's replicas must be available
+ for an update to succeed. When used on fragmented tables, <c>Tab</c>
+ must be the name base table. Directly changing the majority setting on
+ individual fragments is not allowed.</p>
+ </desc>
+ </func>
+ <func>
<name>clear_table(Tab) -> {aborted, R} | {atomic, ok}</name>
<fsummary>Deletes all entries in a table.</fsummary>
<desc>
@@ -753,6 +772,14 @@ mnesia:change_table_copy_type(person, node(), disc_copies)
priority will be loaded first at startup.
</p>
</item>
+ <item>
+ <p><c>{majority, Flag}</c>, where <c>Flag</c> must be a boolean.
+ If <c>true</c>, any (non-dirty) update to the table will abort unless
+ a majority of the table's replicas are available for the commit.
+ When used on a fragmented table, all fragments will be given
+ the same majority setting.
+ </p>
+ </item>
<item>
<p><c>{ram_copies, Nodelist}</c>, where
<c>Nodelist</c> is a list of the nodes where this table
@@ -1737,7 +1764,10 @@ mnesia:create_table(person,
<c>write</c> and <c>sticky_write</c> are supported.
</p>
<p>If the user wants to update the record it is more efficient to
- use <c>write/sticky_write</c> as the LockKind.
+ use <c>write/sticky_write</c> as the LockKind. If majority checking
+ is active on the table, it will be checked as soon as a write lock is
+ attempted. This can be used to quickly abort if the majority condition
+ isn't met.
</p>
</desc>
</func>
diff --git a/lib/mnesia/doc/src/notes.xml b/lib/mnesia/doc/src/notes.xml
index 19574a1434..f1c362261a 100644
--- a/lib/mnesia/doc/src/notes.xml
+++ b/lib/mnesia/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/mnesia/src/mnesia.appup.src b/lib/mnesia/src/mnesia.appup.src
index 7bad6c4ea6..3691aa249a 100644
--- a/lib/mnesia/src/mnesia.appup.src
+++ b/lib/mnesia/src/mnesia.appup.src
@@ -1,33 +1,13 @@
%% -*- erlang -*-
{"%VSN%",
[
- {"4.4.17",[
- {update, mnesia_controller, soft, soft_purge, soft_purge, []}
- ]},
- {"4.4.16",[
- {update, mnesia_controller, soft, soft_purge, soft_purge, []},
- {update, mnesia_frag, soft, soft_purge, soft_purge, []},
- {update, mnesia_schema, soft, soft_purge, soft_purge, []}
- ]},
- {"4.4.15",[
- {update, mnesia_controller, soft, soft_purge, soft_purge, []},
- {update, mnesia_frag, soft, soft_purge, soft_purge, []},
- {update, mnesia, soft, soft_purge, soft_purge, []},
- {update, mnesia_dumper, soft, soft_purge, soft_purge, []}
- ]}
+ {"4.4.18", [{restart_application, mnesia}]},
+ {"4.4.17", [{restart_application, mnesia}]},
+ {"4.4.16", [{restart_application, mnesia}]}
],
- {"4.4.17",[
- {update, mnesia_controller, soft, soft_purge, soft_purge, []}
- ]},
- {"4.4.16",[
- {update, mnesia_controller, soft, soft_purge, soft_purge, []},
- {update, mnesia_frag, soft, soft_purge, soft_purge, []},
- {update, mnesia_schema, soft, soft_purge, soft_purge, []}
- ]},
- {"4.4.15",[
- {update, mnesia_controller, soft, soft_purge, soft_purge, []},
- {update, mnesia_frag, soft, soft_purge, soft_purge, []},
- {update, mnesia, soft, soft_purge, soft_purge, []},
- {update, mnesia_dumper, soft, soft_purge, soft_purge, []}
- ]}
+ [
+ {"4.4.18", [{restart_application, mnesia}]},
+ {"4.4.17", [{restart_application, mnesia}]},
+ {"4.4.16", [{restart_application, mnesia}]}
+ ]
}.
diff --git a/lib/mnesia/src/mnesia.erl b/lib/mnesia/src/mnesia.erl
index 025b32f506..980a9c6213 100644
--- a/lib/mnesia/src/mnesia.erl
+++ b/lib/mnesia/src/mnesia.erl
@@ -39,6 +39,7 @@
%% Access within an activity - Lock acquisition
lock/2, lock/4,
+ lock_table/2,
read_lock_table/1,
write_lock_table/1,
@@ -92,7 +93,7 @@
add_table_copy/3, del_table_copy/2, move_table_copy/3,
add_table_index/2, del_table_index/2,
transform_table/3, transform_table/4,
- change_table_copy_type/3,
+ change_table_copy_type/3, change_table_majority/2,
read_table_property/2, write_table_property/2, delete_table_property/2,
change_table_frag/2,
clear_table/1, clear_table/4,
@@ -415,6 +416,9 @@ lock(LockItem, LockKind) ->
abort(no_transaction)
end.
+lock_table(Tab, LockKind) ->
+ lock({table, Tab}, LockKind).
+
lock(Tid, Ts, LockItem, LockKind) ->
case element(1, Tid) of
tid ->
@@ -467,6 +471,8 @@ lock_table(Tid, Ts, Tab, LockKind) when is_atom(Tab) ->
mnesia_locker:rlock_table(Tid, Store, Tab);
write ->
mnesia_locker:wlock_table(Tid, Store, Tab);
+ load ->
+ mnesia_locker:load_lock_table(Tid, Store, Tab);
sticky_write ->
mnesia_locker:sticky_wlock_table(Tid, Store, Tab);
none ->
@@ -2455,6 +2461,9 @@ change_table_access_mode(T, Access) ->
change_table_load_order(T, O) ->
mnesia_schema:change_table_load_order(T, O).
+change_table_majority(T, M) ->
+ mnesia_schema:change_table_majority(T, M).
+
set_master_nodes(Nodes) when is_list(Nodes) ->
UseDir = system_info(use_dir),
IsRunning = system_info(is_running),
diff --git a/lib/mnesia/src/mnesia.hrl b/lib/mnesia/src/mnesia.hrl
index d488d9364a..26537815a3 100644
--- a/lib/mnesia/src/mnesia.hrl
+++ b/lib/mnesia/src/mnesia.hrl
@@ -62,6 +62,7 @@
disc_only_copies = [], % [Node]
load_order = 0, % Integer
access_mode = read_write, % read_write | read_only
+ majority = false, % true | false
index = [], % [Integer]
snmp = [], % Snmp Ustruct
local_content = false, % true | false
diff --git a/lib/mnesia/src/mnesia_controller.erl b/lib/mnesia/src/mnesia_controller.erl
index 0254769758..d4b2c7b5cc 100644
--- a/lib/mnesia/src/mnesia_controller.erl
+++ b/lib/mnesia/src/mnesia_controller.erl
@@ -72,6 +72,7 @@
add_active_replica/4,
update/1,
change_table_access_mode/1,
+ change_table_majority/1,
del_active_replica/2,
wait_for_tables/2,
get_network_copy/2,
@@ -690,7 +691,8 @@ handle_call({update_where_to_write, [add, Tab, AddNode], _From}, _Dummy, State)
case lists:member(AddNode, Current) and
(State#state.schema_is_merged == true) of
true ->
- mnesia_lib:add_lsort({Tab, where_to_write}, AddNode);
+ mnesia_lib:add_lsort({Tab, where_to_write}, AddNode),
+ update_where_to_wlock(Tab);
false ->
ignore
end,
@@ -1690,6 +1692,8 @@ add_active_replica(Tab, Node, Storage, AccessMode) ->
set(Var, mark_blocked_tab(Blocked, Del)),
mnesia_lib:del({Tab, where_to_write}, Node)
end,
+
+ update_where_to_wlock(Tab),
add({Tab, active_replicas}, Node).
del_active_replica(Tab, Node) ->
@@ -1699,7 +1703,8 @@ del_active_replica(Tab, Node) ->
New = lists:sort(Del),
set(Var, mark_blocked_tab(Blocked, New)), % where_to_commit
mnesia_lib:del({Tab, active_replicas}, Node),
- mnesia_lib:del({Tab, where_to_write}, Node).
+ mnesia_lib:del({Tab, where_to_write}, Node),
+ update_where_to_wlock(Tab).
change_table_access_mode(Cs) ->
W = fun() ->
@@ -1708,7 +1713,22 @@ change_table_access_mode(Cs) ->
val({Tab, active_replicas}))
end,
update(W).
-
+
+change_table_majority(Cs) ->
+ W = fun() ->
+ Tab = Cs#cstruct.name,
+ set({Tab, majority}, Cs#cstruct.majority),
+ update_where_to_wlock(Tab)
+ end,
+ update(W).
+
+update_where_to_wlock(Tab) ->
+ WNodes = val({Tab, where_to_write}),
+ Majority = case catch val({Tab, majority}) of
+ true -> true;
+ _ -> false
+ end,
+ set({Tab, where_to_wlock}, {WNodes, Majority}).
%% node To now has tab loaded, but this must be undone
%% This code is rpc:call'ed from the tab_copier process
diff --git a/lib/mnesia/src/mnesia_dumper.erl b/lib/mnesia/src/mnesia_dumper.erl
index 55b9946ae9..92fd9dfade 100644
--- a/lib/mnesia/src/mnesia_dumper.erl
+++ b/lib/mnesia/src/mnesia_dumper.erl
@@ -900,6 +900,14 @@ insert_op(Tid, _, {op, change_table_access_mode,TabDef, _OldAccess, _Access}, In
end,
insert_cstruct(Tid, Cs, true, InPlace, InitBy);
+insert_op(Tid, _, {op, change_table_majority,TabDef, _OldAccess, _Access}, InPlace, InitBy) ->
+ Cs = mnesia_schema:list2cs(TabDef),
+ case InitBy of
+ startup -> ignore;
+ _ -> mnesia_controller:change_table_majority(Cs)
+ end,
+ insert_cstruct(Tid, Cs, true, InPlace, InitBy);
+
insert_op(Tid, _, {op, change_table_load_order, TabDef, _OldLevel, _Level}, InPlace, InitBy) ->
Cs = mnesia_schema:list2cs(TabDef),
insert_cstruct(Tid, Cs, true, InPlace, InitBy);
diff --git a/lib/mnesia/src/mnesia_lib.erl b/lib/mnesia/src/mnesia_lib.erl
index 36bcfe8de9..7e926a6258 100644
--- a/lib/mnesia/src/mnesia_lib.erl
+++ b/lib/mnesia/src/mnesia_lib.erl
@@ -96,6 +96,8 @@
exists/1,
fatal/2,
get_node_number/0,
+ have_majority/2,
+ have_majority/3,
fix_error/1,
important/2,
incr_counter/1,
@@ -660,6 +662,14 @@ proc_info(_) -> false.
get_node_number() ->
{node(), self()}.
+have_majority(Tab, HaveNodes) ->
+ have_majority(Tab, val({Tab, all_nodes}), HaveNodes).
+
+have_majority(_Tab, AllNodes, HaveNodes) ->
+ Missing = AllNodes -- HaveNodes,
+ Present = AllNodes -- Missing,
+ length(Present) > length(Missing).
+
read_log_files() ->
[{F, catch file:read_file(F)} || F <- mnesia_log:log_files()].
diff --git a/lib/mnesia/src/mnesia_loader.erl b/lib/mnesia/src/mnesia_loader.erl
index 3de329503e..e785b795d1 100644
--- a/lib/mnesia/src/mnesia_loader.erl
+++ b/lib/mnesia/src/mnesia_loader.erl
@@ -702,7 +702,7 @@ send_table(Pid, Tab, RemoteS) ->
prepare_copy(Pid, Tab, Storage) ->
Trans =
fun() ->
- mnesia:write_lock_table(Tab),
+ mnesia:lock_table(Tab, load),
mnesia_subscr:subscribe(Pid, {table, Tab}),
update_where_to_write(Tab, node(Pid)),
mnesia_lib:db_fixtable(Storage, Tab, true),
diff --git a/lib/mnesia/src/mnesia_locker.erl b/lib/mnesia/src/mnesia_locker.erl
index ca0cc79c45..0492d794f3 100644
--- a/lib/mnesia/src/mnesia_locker.erl
+++ b/lib/mnesia/src/mnesia_locker.erl
@@ -40,7 +40,8 @@
sticky_wlock_table/3,
wlock/3,
wlock_no_exist/4,
- wlock_table/3
+ wlock_table/3,
+ load_lock_table/3
]).
%% sys callback functions
@@ -656,16 +657,17 @@ rwlock(Tid, Store, Oid) ->
Lock = write,
case need_lock(Store, Tab, Key, Lock) of
yes ->
- Ns = w_nodes(Tab),
+ {Ns, Majority} = w_nodes(Tab),
+ check_majority(Majority, Tab, Ns),
Res = get_rwlocks_on_nodes(Ns, rwlock, Node, Store, Tid, Oid),
?ets_insert(Store, {{locks, Tab, Key}, Lock}),
Res;
no ->
if
Key == ?ALL ->
- w_nodes(Tab);
+ element(2, w_nodes(Tab));
Tab == ?GLOBAL ->
- w_nodes(Tab);
+ element(2, w_nodes(Tab));
true ->
dirty_rpc(Node, Tab, Key, Lock)
end
@@ -677,12 +679,34 @@ rwlock(Tid, Store, Oid) ->
%% in the local store under the key == nodes
w_nodes(Tab) ->
- Nodes = ?catch_val({Tab, where_to_write}),
- case Nodes of
- [_ | _] -> Nodes;
+ case ?catch_val({Tab, where_to_wlock}) of
+ {[_ | _], _} = Where -> Where;
_ -> mnesia:abort({no_exists, Tab})
end.
+%% If the table has the 'majority' flag set, we can
+%% only take a write lock if we see a majority of the
+%% nodes.
+
+
+check_majority(true, Tab, HaveNs) ->
+ check_majority(Tab, HaveNs);
+check_majority(false, _, _) ->
+ ok.
+
+check_majority(Tab, HaveNs) ->
+ case ?catch_val({Tab, majority}) of
+ true ->
+ case mnesia_lib:have_majority(Tab, HaveNs) of
+ true ->
+ ok;
+ false ->
+ mnesia:abort({no_majority, Tab})
+ end;
+ _ ->
+ ok
+ end.
+
%% aquire a sticky wlock, a sticky lock is a lock
%% which remains at this node after the termination of the
%% transaction.
@@ -708,12 +732,14 @@ sticky_lock(Tid, Store, {Tab, Key} = Oid, Lock) ->
end.
do_sticky_lock(Tid, Store, {Tab, Key} = Oid, Lock) ->
+ {WNodes, Majority} = w_nodes(Tab),
+ sticky_check_majority(Lock, Tab, Majority, WNodes),
?MODULE ! {self(), {test_set_sticky, Tid, Oid, Lock}},
N = node(),
receive
{?MODULE, N, granted} ->
?ets_insert(Store, {{locks, Tab, Key}, write}),
- [?ets_insert(Store, {nodes, Node}) || Node <- w_nodes(Tab)],
+ [?ets_insert(Store, {nodes, Node}) || Node <- WNodes],
granted;
{?MODULE, N, {granted, Val}} -> %% for rwlocks
case opt_lookup_in_client(Val, Oid, write) of
@@ -721,7 +747,7 @@ do_sticky_lock(Tid, Store, {Tab, Key} = Oid, Lock) ->
exit({aborted, C});
Val2 ->
?ets_insert(Store, {{locks, Tab, Key}, write}),
- [?ets_insert(Store, {nodes, Node}) || Node <- w_nodes(Tab)],
+ [?ets_insert(Store, {nodes, Node}) || Node <- WNodes],
Val2
end;
{?MODULE, N, {not_granted, Reason}} ->
@@ -737,6 +763,16 @@ do_sticky_lock(Tid, Store, {Tab, Key} = Oid, Lock) ->
dirty_sticky_lock(Tab, Key, [N], Lock)
end.
+sticky_check_majority(W, Tab, true, WNodes) when W==write; W==read_write ->
+ case mnesia_lib:have_majority(Tab, WNodes) of
+ true ->
+ ok;
+ false ->
+ mnesia:abort({no_majority, Tab})
+ end;
+sticky_check_majority(_, _, _, _) ->
+ ok.
+
not_stuck(Tid, Store, Tab, _Key, Oid, _Lock, N) ->
rlock(Tid, Store, {Tab, ?ALL}), %% needed?
wlock(Tid, Store, Oid), %% perfect sync
@@ -773,22 +809,33 @@ sticky_wlock_table(Tid, Store, Tab) ->
%% local store when we have aquired the lock.
%%
wlock(Tid, Store, Oid) ->
+ wlock(Tid, Store, Oid, _CheckMajority = true).
+
+wlock(Tid, Store, Oid, CheckMajority) ->
{Tab, Key} = Oid,
case need_lock(Store, Tab, Key, write) of
yes ->
- Ns = w_nodes(Tab),
+ {Ns, Majority} = w_nodes(Tab),
+ if CheckMajority ->
+ check_majority(Majority, Tab, Ns);
+ true ->
+ ignore
+ end,
Op = {self(), {write, Tid, Oid}},
?ets_insert(Store, {{locks, Tab, Key}, write}),
get_wlocks_on_nodes(Ns, Ns, Store, Op, Oid);
no when Key /= ?ALL, Tab /= ?GLOBAL ->
[];
no ->
- w_nodes(Tab)
+ element(2, w_nodes(Tab))
end.
wlock_table(Tid, Store, Tab) ->
wlock(Tid, Store, {Tab, ?ALL}).
+load_lock_table(Tid, Store, Tab) ->
+ wlock(Tid, Store, {Tab, ?ALL}, _CheckMajority = false).
+
%% Write lock even if the table does not exist
wlock_no_exist(Tid, Store, Tab, Ns) ->
diff --git a/lib/mnesia/src/mnesia_schema.erl b/lib/mnesia/src/mnesia_schema.erl
index f33a6c7a84..fef72ad39c 100644
--- a/lib/mnesia/src/mnesia_schema.erl
+++ b/lib/mnesia/src/mnesia_schema.erl
@@ -37,6 +37,7 @@
change_table_copy_type/3,
change_table_access_mode/2,
change_table_load_order/2,
+ change_table_majority/2,
change_table_frag/2,
clear_table/1,
create_table/1,
@@ -178,6 +179,8 @@ do_set_schema(Tab, Cs) ->
set({Tab, disc_only_copies}, Cs#cstruct.disc_only_copies),
set({Tab, load_order}, Cs#cstruct.load_order),
set({Tab, access_mode}, Cs#cstruct.access_mode),
+ set({Tab, majority}, Cs#cstruct.majority),
+ set({Tab, all_nodes}, mnesia_lib:cs_to_nodes(Cs)),
set({Tab, snmp}, Cs#cstruct.snmp),
set({Tab, user_properties}, Cs#cstruct.user_properties),
[set({Tab, user_property, element(1, P)}, P) || P <- Cs#cstruct.user_properties],
@@ -651,6 +654,7 @@ list2cs(List) when is_list(List) ->
Snmp = pick(Name, snmp, List, []),
LoadOrder = pick(Name, load_order, List, 0),
AccessMode = pick(Name, access_mode, List, read_write),
+ Majority = pick(Name, majority, List, false),
UserProps = pick(Name, user_properties, List, []),
verify({alt, [nil, list]}, mnesia_lib:etype(UserProps),
{bad_type, Name, {user_properties, UserProps}}),
@@ -676,6 +680,7 @@ list2cs(List) when is_list(List) ->
snmp = Snmp,
load_order = LoadOrder,
access_mode = AccessMode,
+ majority = Majority,
local_content = LC,
record_name = RecName,
attributes = Attrs,
@@ -809,7 +814,16 @@ verify_cstruct(Cs) when is_record(Cs, cstruct) ->
Access = Cs#cstruct.access_mode,
verify({alt, [read_write, read_only]}, Access,
{bad_type, Tab, {access_mode, Access}}),
-
+ Majority = Cs#cstruct.majority,
+ verify({alt, [true, false]}, Majority,
+ {bad_type, Tab, {majority, Majority}}),
+ case Majority of
+ true ->
+ verify(false, LC,
+ {combine_error, Tab, [{local_content,true},{majority,true}]});
+ false ->
+ ok
+ end,
Snmp = Cs#cstruct.snmp,
verify(true, mnesia_snmp_hook:check_ustruct(Snmp),
{badarg, Tab, {snmp, Snmp}}),
@@ -1495,6 +1509,43 @@ make_change_table_load_order(Tab, LoadOrder) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+change_table_majority(Tab, Majority) when is_boolean(Majority) ->
+ schema_transaction(fun() -> do_change_table_majority(Tab, Majority) end).
+
+do_change_table_majority(schema, _Majority) ->
+ mnesia:abort({bad_type, schema});
+do_change_table_majority(Tab, Majority) ->
+ TidTs = get_tid_ts_and_lock(schema, write),
+ get_tid_ts_and_lock(Tab, none),
+ insert_schema_ops(TidTs, make_change_table_majority(Tab, Majority)).
+
+make_change_table_majority(Tab, Majority) ->
+ ensure_writable(schema),
+ Cs = incr_version(val({Tab, cstruct})),
+ ensure_active(Cs),
+ OldMajority = Cs#cstruct.majority,
+ Cs2 = Cs#cstruct{majority = Majority},
+ FragOps = case lists:keyfind(base_table, 1, Cs#cstruct.frag_properties) of
+ {_, Tab} ->
+ FragNames = mnesia_frag:frag_names(Tab) -- [Tab],
+ lists:map(
+ fun(T) ->
+ get_tid_ts_and_lock(Tab, none),
+ CsT = incr_version(val({T, cstruct})),
+ ensure_active(CsT),
+ CsT2 = CsT#cstruct{majority = Majority},
+ verify_cstruct(CsT2),
+ {op, change_table_majority, cs2list(CsT2),
+ OldMajority, Majority}
+ end, FragNames);
+ false -> [];
+ {_, _} -> mnesia:abort({bad_type, Tab})
+ end,
+ verify_cstruct(Cs2),
+ [{op, change_table_majority, cs2list(Cs2), OldMajority, Majority} | FragOps].
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
write_table_property(Tab, Prop) when is_tuple(Prop), size(Prop) >= 1 ->
schema_transaction(fun() -> do_write_table_property(Tab, Prop) end);
write_table_property(Tab, Prop) ->
@@ -2974,6 +3025,7 @@ merge_versions(AnythingNew, Cs, RemoteCs, Force) ->
Cs#cstruct.index == RemoteCs#cstruct.index,
Cs#cstruct.snmp == RemoteCs#cstruct.snmp,
Cs#cstruct.access_mode == RemoteCs#cstruct.access_mode,
+ Cs#cstruct.majority == RemoteCs#cstruct.majority,
Cs#cstruct.load_order == RemoteCs#cstruct.load_order,
Cs#cstruct.user_properties == RemoteCs#cstruct.user_properties ->
do_merge_versions(AnythingNew, Cs, RemoteCs);
diff --git a/lib/mnesia/src/mnesia_text.erl b/lib/mnesia/src/mnesia_text.erl
index ab1362f6b6..0906d18da9 100644
--- a/lib/mnesia/src/mnesia_text.erl
+++ b/lib/mnesia/src/mnesia_text.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -181,9 +181,6 @@ read_term_from_stream(Stream, File, Line) ->
Str = Mod:format_error(What),
io:format("Error in line:~p of:~p ~s\n",
[NewLine, File, Str]),
- error;
- T ->
- io:format("Error2 **~p~n",[T]),
error
end;
{eof,_EndLine} ->
diff --git a/lib/mnesia/src/mnesia_tm.erl b/lib/mnesia/src/mnesia_tm.erl
index bb8e788b40..f62f7cb7c8 100644
--- a/lib/mnesia/src/mnesia_tm.erl
+++ b/lib/mnesia/src/mnesia_tm.erl
@@ -64,7 +64,8 @@
prev_tab = [], % initiate to a non valid table name
prev_types,
prev_snmp,
- types
+ types,
+ majority = []
}).
-record(participant, {tid, pid, commit, disc_nodes = [],
@@ -1100,9 +1101,12 @@ t_commit(Type) ->
case arrange(Tid, Store, Type) of
{N, Prep} when N > 0 ->
multi_commit(Prep#prep.protocol,
+ majority_attr(Prep),
Tid, Prep#prep.records, Store);
{0, Prep} ->
- multi_commit(read_only, Tid, Prep#prep.records, Store)
+ multi_commit(read_only,
+ majority_attr(Prep),
+ Tid, Prep#prep.records, Store)
end;
true ->
%% nested commit
@@ -1117,6 +1121,10 @@ t_commit(Type) ->
do_commit_nested
end.
+majority_attr(#prep{majority = M}) ->
+ M.
+
+
%% This function arranges for all objects we shall write in S to be
%% in a list of {Node, CommitRecord}
%% Important function for the performance of mnesia.
@@ -1222,11 +1230,13 @@ prepare_items(Tid, Tab, Key, Items, Prep) ->
{blocked, _} ->
unblocked = req({unblock_me, Tab}),
prepare_items(Tid, Tab, Key, Items, Prep);
- _ ->
+ _ ->
+ Majority = needs_majority(Tab, Prep),
Snmp = val({Tab, snmp}),
Recs2 = do_prepare_items(Tid, Tab, Key, Types,
Snmp, Items, Prep#prep.records),
Prep2 = Prep#prep{records = Recs2, prev_tab = Tab,
+ majority = Majority,
prev_types = Types, prev_snmp = Snmp},
check_prep(Prep2, Types)
end.
@@ -1235,6 +1245,33 @@ do_prepare_items(Tid, Tab, Key, Types, Snmp, Items, Recs) ->
Recs2 = prepare_snmp(Tid, Tab, Key, Types, Snmp, Items, Recs), % May exit
prepare_nodes(Tid, Types, Items, Recs2, normal).
+
+needs_majority(Tab, #prep{majority = M}) ->
+ case lists:keymember(Tab, 1, M) of
+ true ->
+ M;
+ false ->
+ case ?catch_val({Tab, majority}) of
+ {'EXIT', _} ->
+ M;
+ false ->
+ M;
+ true ->
+ CopyHolders = val({Tab, all_nodes}),
+ [{Tab, CopyHolders} | M]
+ end
+ end.
+
+have_majority([], _) ->
+ ok;
+have_majority([{Tab, AllNodes} | Rest], Nodes) ->
+ case mnesia_lib:have_majority(Tab, AllNodes, Nodes) of
+ true ->
+ have_majority(Rest, Nodes);
+ false ->
+ {error, Tab}
+ end.
+
prepare_snmp(Tab, Key, Items) ->
case val({Tab, snmp}) of
[] ->
@@ -1261,10 +1298,15 @@ prepare_snmp(Tid, Tab, Key, Types, Us, Items, Recs) ->
prepare_nodes(Tid, Types, [{clear_table, Tab}], Recs, snmp)
end.
-check_prep(Prep, Types) when Prep#prep.types == Types ->
+check_prep(#prep{majority = [], types = Types} = Prep, Types) ->
Prep;
-check_prep(Prep, Types) when Prep#prep.types == undefined ->
- Prep#prep{types = Types};
+check_prep(#prep{majority = M, types = undefined} = Prep, Types) ->
+ Protocol = if M == [] ->
+ Prep#prep.protocol;
+ true ->
+ asym_trans
+ end,
+ Prep#prep{protocol = Protocol, types = Types};
check_prep(Prep, _Types) ->
Prep#prep{protocol = asym_trans}.
@@ -1311,7 +1353,7 @@ prepare_node(_Node, _Storage, [], Rec, _Kind) ->
%% multi_commit((Protocol, Tid, CommitRecords, Store)
%% Local work is always performed in users process
-multi_commit(read_only, Tid, CR, _Store) ->
+multi_commit(read_only, _Maj = [], Tid, CR, _Store) ->
%% This featherweight commit protocol is used when no
%% updates has been performed in the transaction.
@@ -1324,7 +1366,7 @@ multi_commit(read_only, Tid, CR, _Store) ->
?MODULE ! {delete_transaction, Tid},
do_commit;
-multi_commit(sym_trans, Tid, CR, Store) ->
+multi_commit(sym_trans, _Maj = [], Tid, CR, Store) ->
%% This lightweight commit protocol is used when all
%% the involved tables are replicated symetrically.
%% Their storage types must match on each node.
@@ -1376,7 +1418,7 @@ multi_commit(sym_trans, Tid, CR, Store) ->
[{tid, Tid}, {outcome, Outcome}]),
Outcome;
-multi_commit(sync_sym_trans, Tid, CR, Store) ->
+multi_commit(sync_sym_trans, _Maj = [], Tid, CR, Store) ->
%% This protocol is the same as sym_trans except that it
%% uses syncronized calls to disk_log and syncronized commits
%% when several nodes are involved.
@@ -1408,7 +1450,7 @@ multi_commit(sync_sym_trans, Tid, CR, Store) ->
[{tid, Tid}, {outcome, Outcome}]),
Outcome;
-multi_commit(asym_trans, Tid, CR, Store) ->
+multi_commit(asym_trans, Majority, Tid, CR, Store) ->
%% This more expensive commit protocol is used when
%% table definitions are changed (schema transactions).
%% It is also used when the involved tables are
@@ -1469,6 +1511,10 @@ multi_commit(asym_trans, Tid, CR, Store) ->
{D2, CR2} = commit_decision(D, CR, [], []),
DiscNs = D2#decision.disc_nodes,
RamNs = D2#decision.ram_nodes,
+ case have_majority(Majority, DiscNs ++ RamNs) of
+ ok -> ok;
+ {error, Tab} -> mnesia:abort({no_majority, Tab})
+ end,
Pending = mnesia_checkpoint:tm_enter_pending(Tid, DiscNs, RamNs),
?ets_insert(Store, Pending),
{WaitFor, Local} = ask_commit(asym_trans, Tid, CR2, DiscNs, RamNs),
diff --git a/lib/mnesia/test/Makefile b/lib/mnesia/test/Makefile
index b165924ef2..ae4c9626c7 100644
--- a/lib/mnesia/test/Makefile
+++ b/lib/mnesia/test/Makefile
@@ -42,6 +42,7 @@ MODULES= \
mnesia_dirty_access_test \
mnesia_atomicity_test \
mnesia_consistency_test \
+ mnesia_majority_test \
mnesia_isolation_test \
mnesia_durability_test \
mnesia_recovery_test \
diff --git a/lib/mnesia/test/mnesia_SUITE.erl b/lib/mnesia/test/mnesia_SUITE.erl
index 8ba8427213..2267a94164 100644
--- a/lib/mnesia/test/mnesia_SUITE.erl
+++ b/lib/mnesia/test/mnesia_SUITE.erl
@@ -78,12 +78,14 @@ groups() ->
[{group, install}, {group, atomicity},
{group, isolation}, {group, durability},
{group, recovery}, {group, consistency},
+ {group, majority},
{group, mnesia_frag_test, medium}]},
{atomicity, [], [{mnesia_atomicity_test, all}]},
{isolation, [], [{mnesia_isolation_test, all}]},
{durability, [], [{mnesia_durability_test, all}]},
{recovery, [], [{mnesia_recovery_test, all}]},
{consistency, [], [{mnesia_consistency_test, all}]},
+ {majority, [], [{mnesia_majority_test, all}]},
%% The 'heavy' test suite runs some resource consuming tests and
%% benchmarks
{heavy, [], [{group, measure}]},
diff --git a/lib/mnesia/test/mnesia_majority_test.erl b/lib/mnesia/test/mnesia_majority_test.erl
new file mode 100644
index 0000000000..41ba0fd601
--- /dev/null
+++ b/lib/mnesia/test/mnesia_majority_test.erl
@@ -0,0 +1,186 @@
+%%
+%% %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(mnesia_majority_test).
+-author('[email protected]').
+-compile(export_all).
+-include("mnesia_test_lib.hrl").
+
+init_per_testcase(Func, Conf) ->
+ mnesia_test_lib:init_per_testcase(Func, Conf).
+
+end_per_testcase(Func, Conf) ->
+ mnesia_test_lib:end_per_testcase(Func, Conf).
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+all() ->
+ [
+ write
+ , wread
+ , delete
+ , clear_table
+ , frag
+ , change_majority
+ , frag_change_majority
+ ].
+
+write(suite) -> [];
+write(Config) when is_list(Config) ->
+ [N1, N2, N3] = ?acquire_nodes(3, Config),
+ Tab = t,
+ Schema = [{name, Tab}, {ram_copies, [N1,N2,N3]}, {majority,true}],
+ ?match({atomic, ok}, mnesia:create_table(Schema)),
+ ?match({[ok,ok,ok],[]},
+ rpc:multicall([N1,N2,N3], mnesia, wait_for_tables, [[Tab], 3000])),
+ ?match({atomic,ok},
+ mnesia:transaction(fun() -> mnesia:write({t,1,a}) end)),
+ mnesia_test_lib:kill_mnesia([N3]),
+ ?match({atomic,ok},
+ mnesia:transaction(fun() -> mnesia:write({t,1,a}) end)),
+ mnesia_test_lib:kill_mnesia([N2]),
+ ?match({aborted,{no_majority,Tab}},
+ mnesia:transaction(fun() -> mnesia:write({t,1,a}) end)).
+
+wread(suite) -> [];
+wread(Config) when is_list(Config) ->
+ [N1, N2] = ?acquire_nodes(2, Config),
+ Tab = t,
+ Schema = [{name, Tab}, {ram_copies, [N1,N2]}, {majority,true}],
+ ?match({atomic, ok}, mnesia:create_table(Schema)),
+ ?match({[ok,ok],[]},
+ rpc:multicall([N1,N2], mnesia, wait_for_tables, [[Tab], 3000])),
+ ?match({atomic,[]},
+ mnesia:transaction(fun() -> mnesia:read(t,1,write) end)),
+ mnesia_test_lib:kill_mnesia([N2]),
+ ?match({aborted,{no_majority,Tab}},
+ mnesia:transaction(fun() -> mnesia:read(t,1,write) end)).
+
+delete(suite) -> [];
+delete(Config) when is_list(Config) ->
+ [N1, N2] = ?acquire_nodes(2, Config),
+ Tab = t,
+ Schema = [{name, Tab}, {ram_copies, [N1,N2]}, {majority,true}],
+ ?match({atomic, ok}, mnesia:create_table(Schema)),
+ ?match({[ok,ok],[]},
+ rpc:multicall([N1,N2], mnesia, wait_for_tables, [[Tab], 3000])),
+ %% works as expected with majority of nodes present
+ ?match({atomic,ok},
+ mnesia:transaction(fun() -> mnesia:write({t,1,a}) end)),
+ ?match({atomic,ok},
+ mnesia:transaction(fun() -> mnesia:delete({t,1}) end)),
+ ?match({atomic,[]},
+ mnesia:transaction(fun() -> mnesia:read({t,1}) end)),
+ %% put the record back
+ ?match({atomic,ok},
+ mnesia:transaction(fun() -> mnesia:write({t,1,a}) end)),
+ ?match({atomic,[{t,1,a}]},
+ mnesia:transaction(fun() -> mnesia:read({t,1}) end)),
+ mnesia_test_lib:kill_mnesia([N2]),
+ ?match({aborted,{no_majority,Tab}},
+ mnesia:transaction(fun() -> mnesia:delete({t,1}) end)).
+
+clear_table(suite) -> [];
+clear_table(Config) when is_list(Config) ->
+ [N1, N2] = ?acquire_nodes(2, Config),
+ Tab = t,
+ Schema = [{name, Tab}, {ram_copies, [N1,N2]}, {majority,true}],
+ ?match({atomic, ok}, mnesia:create_table(Schema)),
+ ?match({[ok,ok],[]},
+ rpc:multicall([N1,N2], mnesia, wait_for_tables, [[Tab], 3000])),
+ %% works as expected with majority of nodes present
+ ?match({atomic,ok},
+ mnesia:transaction(fun() -> mnesia:write({t,1,a}) end)),
+ ?match({atomic,ok}, mnesia:clear_table(t)),
+ ?match({atomic,[]},
+ mnesia:transaction(fun() -> mnesia:read({t,1}) end)),
+ %% put the record back
+ ?match({atomic,ok},
+ mnesia:transaction(fun() -> mnesia:write({t,1,a}) end)),
+ ?match({atomic,[{t,1,a}]},
+ mnesia:transaction(fun() -> mnesia:read({t,1}) end)),
+ mnesia_test_lib:kill_mnesia([N2]),
+ ?match({aborted,{no_majority,Tab}}, mnesia:clear_table(t)).
+
+frag(suite) -> [];
+frag(Config) when is_list(Config) ->
+ [N1] = ?acquire_nodes(1, Config),
+ Tab = t,
+ Schema = [
+ {name, Tab}, {ram_copies, [N1]},
+ {majority,true},
+ {frag_properties, [{n_fragments, 2}]}
+ ],
+ ?match({atomic, ok}, mnesia:create_table(Schema)),
+ ?match(true, mnesia:table_info(t, majority)),
+ ?match(true, mnesia:table_info(t_frag2, majority)).
+
+change_majority(suite) -> [];
+change_majority(Config) when is_list(Config) ->
+ [N1,N2] = ?acquire_nodes(2, Config),
+ Tab = t,
+ Schema = [
+ {name, Tab}, {ram_copies, [N1,N2]},
+ {majority,false}
+ ],
+ ?match({atomic, ok}, mnesia:create_table(Schema)),
+ ?match(false, mnesia:table_info(t, majority)),
+ ?match({atomic, ok},
+ mnesia:change_table_majority(t, true)),
+ ?match(true, mnesia:table_info(t, majority)),
+ ?match(ok,
+ mnesia:activity(transaction, fun() ->
+ mnesia:write({t,1,a})
+ end)),
+ mnesia_test_lib:kill_mnesia([N2]),
+ ?match({'EXIT',{aborted,{no_majority,_}}},
+ mnesia:activity(transaction, fun() ->
+ mnesia:write({t,1,a})
+ end)).
+
+frag_change_majority(suite) -> [];
+frag_change_majority(Config) when is_list(Config) ->
+ [N1,N2] = ?acquire_nodes(2, Config),
+ Tab = t,
+ Schema = [
+ {name, Tab}, {ram_copies, [N1,N2]},
+ {majority,false},
+ {frag_properties,
+ [{n_fragments, 2},
+ {n_ram_copies, 2},
+ {node_pool, [N1,N2]}]}
+ ],
+ ?match({atomic, ok}, mnesia:create_table(Schema)),
+ ?match(false, mnesia:table_info(t, majority)),
+ ?match(false, mnesia:table_info(t_frag2, majority)),
+ ?match({aborted,{bad_type,t_frag2}},
+ mnesia:change_table_majority(t_frag2, true)),
+ ?match({atomic, ok},
+ mnesia:change_table_majority(t, true)),
+ ?match(true, mnesia:table_info(t, majority)),
+ ?match(true, mnesia:table_info(t_frag2, majority)),
+ ?match(ok,
+ mnesia:activity(transaction, fun() ->
+ mnesia:write({t,1,a})
+ end, mnesia_frag)),
+ mnesia_test_lib:kill_mnesia([N2]),
+ ?match({'EXIT',{aborted,{no_majority,_}}},
+ mnesia:activity(transaction, fun() ->
+ mnesia:write({t,1,a})
+ end, mnesia_frag)).
diff --git a/lib/mnesia/test/mt.erl b/lib/mnesia/test/mt.erl
index 322bd52130..f1152a7bc4 100644
--- a/lib/mnesia/test/mt.erl
+++ b/lib/mnesia/test/mt.erl
@@ -57,6 +57,7 @@ alias(heavy) -> {mnesia_SUITE, heavy};
alias(install) -> mnesia_install_test;
alias(isolation) -> mnesia_isolation_test;
alias(light) -> {mnesia_SUITE, light};
+alias(majority) -> mnesia_majority_test;
alias(measure) -> mnesia_measure_test;
alias(medium) -> {mnesia_SUITE, medium};
alias(nice) -> mnesia_nice_coverage_test;
diff --git a/lib/mnesia/vsn.mk b/lib/mnesia/vsn.mk
index 38e1a94545..2fa629d064 100644
--- a/lib/mnesia/vsn.mk
+++ b/lib/mnesia/vsn.mk
@@ -1 +1 @@
-MNESIA_VSN = 4.4.18
+MNESIA_VSN = 4.4.19
diff --git a/lib/observer/doc/src/notes.xml b/lib/observer/doc/src/notes.xml
index b3b9937f1c..73eb992323 100644
--- a/lib/observer/doc/src/notes.xml
+++ b/lib/observer/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/odbc/doc/src/notes.xml b/lib/odbc/doc/src/notes.xml
index b88c7cf1cd..e15e7dea7d 100644
--- a/lib/odbc/doc/src/notes.xml
+++ b/lib/odbc/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/public_key/doc/src/Makefile b/lib/public_key/doc/src/Makefile
index 298c28a740..afb17399da 100644
--- a/lib/public_key/doc/src/Makefile
+++ b/lib/public_key/doc/src/Makefile
@@ -1,7 +1,7 @@
#
# %CopyrightBegin%
#
-# Copyright Ericsson AB 2008-2010. All Rights Reserved.
+# 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
@@ -52,6 +52,7 @@ XML_CHAPTER_FILES = \
introduction.xml \
public_key_records.xml \
cert_records.xml \
+ using_public_key.xml \
notes.xml
BOOK_FILES = book.xml
diff --git a/lib/public_key/doc/src/notes.xml b/lib/public_key/doc/src/notes.xml
index 14b43041ce..30326da114 100644
--- a/lib/public_key/doc/src/notes.xml
+++ b/lib/public_key/doc/src/notes.xml
@@ -5,7 +5,7 @@
<header>
<copyright>
<year>2008</year>
- <year>2010</year>
+ <year>2011</year>
<holder>Ericsson AB, All Rights Reserved</holder>
</copyright>
<legalnotice>
diff --git a/lib/public_key/doc/src/part.xml b/lib/public_key/doc/src/part.xml
index c338a71613..ea3123b5bd 100644
--- a/lib/public_key/doc/src/part.xml
+++ b/lib/public_key/doc/src/part.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE part SYSTEM "part.dtd">
<part xmlns:xi="http://www.w3.org/2001/XInclude">
@@ -38,5 +38,6 @@
<xi:include href="introduction.xml"/>
<xi:include href="public_key_records.xml"/>
<xi:include href="cert_records.xml"/>
+ <xi:include href="using_public_key.xml"/>
</part>
diff --git a/lib/public_key/doc/src/public_key.xml b/lib/public_key/doc/src/public_key.xml
index c5f57214b1..d60d91cd83 100644
--- a/lib/public_key/doc/src/public_key.xml
+++ b/lib/public_key/doc/src/public_key.xml
@@ -43,7 +43,7 @@
<note><p>All records used in this manual
<!-- except #policy_tree_node{} -->
- are generated from asn1 specifications
+ are generated from ASN.1 specifications
and are documented in the User's Guide. See <seealso
marker="public_key_records">Public key records</seealso> and <seealso
marker="cert_records">X.509 Certificate records</seealso>.
@@ -150,12 +150,12 @@
<fsummary> Decodes a public key asn1 der encoded entity.</fsummary>
<type>
<v>Asn1Type = atom() -</v>
- <d> Asn1 type present in the public_key applications
+ <d> ASN.1 type present in the public_key applications
asn1 specifications.</d>
<v>Der = der_encoded()</v>
</type>
<desc>
- <p> Decodes a public key asn1 der encoded entity.</p>
+ <p> Decodes a public key ASN.1 der encoded entity.</p>
</desc>
</func>
@@ -165,25 +165,25 @@
<type>
<v>Asn1Type = atom()</v>
<d> Asn1 type present in the public_key applications
- asn1 specifications.</d>
+ ASN.1 specifications.</d>
<v>Entity = term() - The erlang representation of <c> Asn1Type</c></v>
</type>
<desc>
- <p> Encodes a public key entity with asn1 DER encoding.</p>
+ <p> Encodes a public key entity with ASN.1 DER encoding.</p>
</desc>
</func>
<func>
<name>pem_decode(PemBin) -> [pem_entry()]</name>
<fsummary>Decode PEM binary data and return
- entries as asn1 der encoded entities. </fsummary>
+ entries as ASN.1 der encoded entities. </fsummary>
<type>
<v>PemBin = binary()</v>
<d>Example {ok, PemBin} = file:read_file("cert.pem").</d>
</type>
<desc>
<p>Decode PEM binary data and return
- entries as asn1 der encoded entities.</p>
+ entries as ASN.1 der encoded entities.</p>
</desc>
</func>
@@ -258,13 +258,13 @@
<func>
<name>pkix_decode_cert(Cert, otp|plain) -> #'Certificate'{} | #'OTPCertificate'{}</name>
- <fsummary> Decodes an asn1 der encoded pkix x509 certificate.</fsummary>
+ <fsummary> Decodes an ASN.1 der encoded pkix x509 certificate.</fsummary>
<type>
<v>Cert = der_encoded()</v>
</type>
<desc>
- <p>Decodes an asn1 der encoded pkix certificate. The otp option
- will use the customized asn1 specification OTP-PKIX.asn1 for
+ <p>Decodes an ASN.1 der encoded pkix certificate. The otp option
+ will use the customized ASN.1 specification OTP-PKIX.asn1 for
decoding and also recursively decode most of the standard
parts.</p>
</desc>
@@ -276,7 +276,7 @@
certificate.</fsummary>
<type>
<v>Asn1Type = atom()</v>
- <d>The asn1 type can be 'Certificate', 'OTPCertificate' or a subtype of either .</d>
+ <d>The ASN.1 type can be 'Certificate', 'OTPCertificate' or a subtype of either .</d>
</type>
<desc>
<p>Der encodes a pkix x509 certificate or part of such a
@@ -394,7 +394,7 @@
signed or in the case that digest type is <c>none</c>
it is the hashed value of "plain text" i.e. the digest.</d>
<v>DigestType = rsa_digest_type() | dsa_digest_type()</v>
- <v>Key = rsa_public_key() | dsa_public_key()</v>
+ <v>Key = rsa_private_key() | dsa_private_key()</v>
</type>
<desc>
<p> Creates a digital signature.</p>
diff --git a/lib/public_key/doc/src/using_public_key.xml b/lib/public_key/doc/src/using_public_key.xml
new file mode 100644
index 0000000000..f0eaeb8654
--- /dev/null
+++ b/lib/public_key/doc/src/using_public_key.xml
@@ -0,0 +1,504 @@
+<?xml version="1.0" encoding="iso-8859-1" ?>
+<!DOCTYPE chapter SYSTEM "chapter.dtd">
+
+<chapter>
+ <header>
+ <copyright>
+ <year>2011</year><year>2011</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>Using the public_key API</title>
+ <file>using_public_key.xml</file>
+ </header>
+
+ <section>
+ <title>General information</title>
+
+ <p> This chapter is dedicated to showing some
+ examples of how to use the public_key API. Keys and certificates
+ used in the following sections are generated only for the purpose
+ of testing the public key application.</p>
+
+ <p>Note that some shell printouts, in the following examples,
+ have been abbreviated for increased readability.</p>
+
+ </section>
+
+ <section>
+ <title>PEM files</title>
+ <p> Pulic key data (keys, certificates etc) may be stored in PEM format. PEM files
+ comes from the Private Enhanced Mail Internet standard and has a
+ structure that looks like this:</p>
+
+ <code>&lt;text&gt;
+ -----BEGIN &lt;SOMETHING&gt;-----
+ &lt;Attribute&gt; : &lt;Value&gt;
+ &lt;Base64 encoded DER data&gt;
+ -----END &lt;SOMETHING&gt;-----
+ &lt;text&gt;</code>
+
+ <p>A file can contain several BEGIN/END blocks. Text lines between
+ blocks are ignored. Attributes, if present, are currently ignored except
+ for <c>Proc-Type</c> and <c>DEK-Info</c> that are used when the DER data is
+ encrypted.</p>
+
+ <section>
+ <title>DSA private key</title>
+
+ <p>Note file handling is not done by the public_key application. </p>
+ <code>1> {ok, PemBin} = file:read_file("dsa.pem").
+{ok,&lt;&lt;"-----BEGIN DSA PRIVATE KEY-----\nMIIBuw"...&gt;&gt;}</code>
+
+ <p>This PEM file only has one entry a private DSA key.</p>
+ <code>2> [DSAEntry] = public_key:pem_decode(PemBin).
+[{'DSAPrivateKey',&lt;&lt;48,130,1,187,2,1,0,2,129,129,0,183,
+ 179,230,217,37,99,144,157,21,228,204,
+ 162,207,61,246,...&gt;&gt;,
+ not_encrypted}]</code>
+
+ <code>3> Key = public_key:pem_entry_decode(DSAEntry).
+#'DSAPrivateKey'{version = 0,
+ p = 12900045185019966618...6593,
+ q = 1216700114794736143432235288305776850295620488937,
+ g = 10442040227452349332...47213,
+ y = 87256807980030509074...403143,
+ x = 510968529856012146351317363807366575075645839654}</code>
+ </section>
+
+ <section>
+ <title>RSA private key encrypted with a password.</title>
+
+ <code>1> {ok, PemBin} = file:read_file("rsa.pem").
+{ok,&lt;&lt;"Bag Attribut"...&gt;&gt;}</code>
+
+ <p>This PEM file only has one entry a private RSA key.</p>
+ <code>2>[RSAEntry] = public_key:pem_decode(PemBin).
+[{'RSAPrivateKey',&lt;&lt;224,108,117,203,152,40,15,77,128,126,
+ 221,195,154,249,85,208,202,251,109,
+ 119,120,57,29,89,19,9,...&gt;&gt;,
+ {"DES-EDE3-CBC",&lt;&lt;"k�e��p�L"&gt;&gt;}}]
+
+ </code>
+
+ <p>In this example the password is "abcd1234".</p>
+ <code>3> Key = public_key:pem_entry_decode(RSAEntry, "abcd1234").
+ #'RSAPrivateKey'{version = 'two-prime',
+ modulus = 1112355156729921663373...2737107,
+ publicExponent = 65537,
+ privateExponent = 58064406231183...2239766033,
+ prime1 = 11034766614656598484098...7326883017,
+ prime2 = 10080459293561036618240...77738643771,
+ exponent1 = 77928819327425934607...22152984217,
+ exponent2 = 36287623121853605733...20588523793,
+ coefficient = 924840412626098444...41820968343,
+ otherPrimeInfos = asn1_NOVALUE}</code>
+ </section>
+
+ <section>
+ <title>X509 Certificates</title>
+
+ <code>1> {ok, PemBin} = file:read_file("cacerts.pem").
+{ok,&lt;&lt;"-----BEGIN CERTIFICATE-----\nMIIC7jCCAl"...&gt;&gt;}</code>
+
+ <p>This file includes two certificates</p>
+ <code>2> [CertEntry1, CertEntry2] = public_key:pem_decode(PemBin).
+[{'Certificate',&lt;&lt;48,130,2,238,48,130,2,87,160,3,2,1,2,2,
+ 9,0,230,145,97,214,191,2,120,150,48,13,
+ ...&gt;&gt;,
+ not_encrypted},
+ {'Certificate',&lt;&lt;48,130,3,200,48,130,3,49,160,3,2,1,2,2,1,
+ 1,48,13,6,9,42,134,72,134,247,...&gt;&gt;>,
+ not_encrypted}]</code>
+
+ <p>Certificates may of course be decoded as usual ... </p>
+ <code>2> Cert = public_key:pem_entry_decode(CertEntry1).
+#'Certificate'{
+ tbsCertificate =
+ #'TBSCertificate'{
+ version = v3,serialNumber = 16614168075301976214,
+ signature =
+ #'AlgorithmIdentifier'{
+ algorithm = {1,2,840,113549,1,1,5},
+ parameters = &lt;&lt;5,0&gt;&gt;},
+ issuer =
+ {rdnSequence,
+ [[#'AttributeTypeAndValue'{
+ type = {2,5,4,3},
+ value = &lt;&lt;19,8,101,114,108,97,110,103,67,65&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,11},
+ value = &lt;&lt;19,10,69,114,108,97,110,103,32,79,84,80&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,10},
+ value = &lt;&lt;19,11,69,114,105,99,115,115,111,110,32,65,66&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,7},
+ value = &lt;&lt;19,9,83,116,111,99,107,104,111,108,109&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,6},
+ value = &lt;&lt;19,2,83,69&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {1,2,840,113549,1,9,1},
+ value = &lt;&lt;22,22,112,101,116,101,114,64,101,114,...&gt;&gt;}]]},
+ validity =
+ #'Validity'{
+ notBefore = {utcTime,"080109082929Z"},
+ notAfter = {utcTime,"080208082929Z"}},
+ subject =
+ {rdnSequence,
+ [[#'AttributeTypeAndValue'{
+ type = {2,5,4,3},
+ value = &lt;&lt;19,8,101,114,108,97,110,103,67,65&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,11},
+ value = &lt;&lt;19,10,69,114,108,97,110,103,32,79,84,80&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,10},
+ value = &lt;&lt;19,11,69,114,105,99,115,115,111,110,32,...&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,7},
+ value = &lt;&lt;19,9,83,116,111,99,107,104,111,108,...&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,6},
+ value = &lt;&lt;19,2,83,69&gt;&gt;}],
+ [#'AttributeTypeAndValue'{
+ type = {1,2,840,113549,1,9,1},
+ value = &lt;&lt;22,22,112,101,116,101,114,64,...&gt;&gt;}]]},
+ subjectPublicKeyInfo =
+ #'SubjectPublicKeyInfo'{
+ algorithm =
+ #'AlgorithmIdentifier'{
+ algorithm = {1,2,840,113549,1,1,1},
+ parameters = &lt;&lt;5,0&gt;&gt;},
+ subjectPublicKey =
+ {0,&lt;&lt;48,129,137,2,129,129,0,203,209,187,77,73,231,90,...&gt;&gt;}},
+ issuerUniqueID = asn1_NOVALUE,
+ subjectUniqueID = asn1_NOVALUE,
+ extensions =
+ [#'Extension'{
+ extnID = {2,5,29,19},
+ critical = true,
+ extnValue = [48,3,1,1,255]},
+ #'Extension'{
+ extnID = {2,5,29,15},
+ critical = false,
+ extnValue = [3,2,1,6]},
+ #'Extension'{
+ extnID = {2,5,29,14},
+ critical = false,
+ extnValue = [4,20,27,217,65,152,6,30,142|...]},
+ #'Extension'{
+ extnID = {2,5,29,17},
+ critical = false,
+ extnValue = [48,24,129,22,112,101,116,101|...]}]},
+ signatureAlgorithm =
+ #'AlgorithmIdentifier'{
+ algorithm = {1,2,840,113549,1,1,5},
+ parameters = &lt;&lt;5,0&gt;&gt;},
+ signature =
+ {0,
+ &lt;&lt;163,186,7,163,216,152,63,47,154,234,139,73,154,96,120,
+ 165,2,52,196,195,109,167,192,...&gt;&gt;}}
+</code>
+
+ <p> Parts of certificates can be decoded with
+ public_key:der_decode/2 using that parts ASN.1 type.
+ Although application specific certificate
+ extension requires application specific ASN.1 decode/encode-functions.
+ Example, the first value of the rdnSequence above is of ASN.1 type
+ 'X520CommonName'. ({2,5,4,3} = ?id-at-commonName)</p>
+
+ <code>public_key:der_decode('X520CommonName', &lt;&lt;19,8,101,114,108,97,110,103,67,65&gt;&gt;).
+{printableString,"erlangCA"}</code>
+
+ <p>... but certificates can also be decode using the pkix_decode_cert/2 that
+ can customize and recursively decode standard parts of a certificate.</p>
+ <code>3>{_, DerCert, _} = CertEntry1.</code>
+ <code>4> public_key:pkix_decode_cert(DerCert, otp).
+#'OTPCertificate'{
+ tbsCertificate =
+ #'OTPTBSCertificate'{
+ version = v3,serialNumber = 16614168075301976214,
+ signature =
+ #'SignatureAlgorithm'{
+ algorithm = {1,2,840,113549,1,1,5},
+ parameters = 'NULL'},
+ issuer =
+ {rdnSequence,
+ [[#'AttributeTypeAndValue'{
+ type = {2,5,4,3},
+ value = {printableString,"erlangCA"}}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,11},
+ value = {printableString,"Erlang OTP"}}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,10},
+ value = {printableString,"Ericsson AB"}}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,7},
+ value = {printableString,"Stockholm"}}],
+ [#'AttributeTypeAndValue'{type = {2,5,4,6},value = "SE"}],
+ [#'AttributeTypeAndValue'{
+ type = {1,2,840,113549,1,9,1},
+ value = "[email protected]"}]]},
+ validity =
+ #'Validity'{
+ notBefore = {utcTime,"080109082929Z"},
+ notAfter = {utcTime,"080208082929Z"}},
+ subject =
+ {rdnSequence,
+ [[#'AttributeTypeAndValue'{
+ type = {2,5,4,3},
+ value = {printableString,"erlangCA"}}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,11},
+ value = {printableString,"Erlang OTP"}}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,10},
+ value = {printableString,"Ericsson AB"}}],
+ [#'AttributeTypeAndValue'{
+ type = {2,5,4,7},
+ value = {printableString,"Stockholm"}}],
+ [#'AttributeTypeAndValue'{type = {2,5,4,6},value = "SE"}],
+ [#'AttributeTypeAndValue'{
+ type = {1,2,840,113549,1,9,1},
+ value = "[email protected]"}]]},
+ subjectPublicKeyInfo =
+ #'OTPSubjectPublicKeyInfo'{
+ algorithm =
+ #'PublicKeyAlgorithm'{
+ algorithm = {1,2,840,113549,1,1,1},
+ parameters = 'NULL'},
+ subjectPublicKey =
+ #'RSAPublicKey'{
+ modulus =
+ 1431267547247997...37419,
+ publicExponent = 65537}},
+ issuerUniqueID = asn1_NOVALUE,
+ subjectUniqueID = asn1_NOVALUE,
+ extensions =
+ [#'Extension'{
+ extnID = {2,5,29,19},
+ critical = true,
+ extnValue =
+ #'BasicConstraints'{
+ cA = true,pathLenConstraint = asn1_NOVALUE}},
+ #'Extension'{
+ extnID = {2,5,29,15},
+ critical = false,
+ extnValue = [keyCertSign,cRLSign]},
+ #'Extension'{
+ extnID = {2,5,29,14},
+ critical = false,
+ extnValue = [27,217,65,152,6,30,142,132,245|...]},
+ #'Extension'{
+ extnID = {2,5,29,17},
+ critical = false,
+ extnValue = [{rfc822Name,"[email protected]"}]}]},
+ signatureAlgorithm =
+ #'SignatureAlgorithm'{
+ algorithm = {1,2,840,113549,1,1,5},
+ parameters = 'NULL'},
+ signature =
+ {0,
+ &lt;&lt;163,186,7,163,216,152,63,47,154,234,139,73,154,96,120,
+ 165,2,52,196,195,109,167,192,...&gt;&gt;}}
+</code>
+
+ <p>This call is equivalent to public_key:pem_entry_decode(CertEntry1)</p>
+ <code>5> public_key:pkix_decode_cert(DerCert, plain).
+#'Certificate'{ ...}
+</code>
+ </section>
+
+ <section>
+ <title>Encoding public key data to PEM format</title>
+
+ <p>If you have public key data and and want to create a PEM file
+ you can do that by calling the functions
+ public_key:pem_entry_encode/2 and pem_encode/1 and then saving the
+ result to a file. For example assume you have PubKey =
+ 'RSAPublicKey'{} then you can create a PEM-"RSA PUBLIC KEY" file
+ (ASN.1 type 'RSAPublicKey') or a PEM-"PUBLIC KEY" file
+ ('SubjectPublicKeyInfo' ASN.1 type).</p>
+
+ <p> The second element of the PEM-entry will be the ASN.1 DER encoded
+ key data.</p>
+
+ <code>1> PemEntry = public_key:pem_entry_encode('RSAPublicKey', RSAPubKey).
+{'RSAPublicKey', &lt;&lt;48,72,...&gt;&gt;, not_encrypted}
+
+2> PemBin = public_key:pem_encode([PemEntry]).
+&lt;&lt;"-----BEGIN RSA PUBLIC KEY-----\nMEgC...&gt;&gt;
+
+3> file:write_file("rsa_pub_key.pem", PemBin).
+ok</code>
+
+ <p> or </p>
+
+ <code>1> PemBin = public_key:pem_entry_encode('SubjectPublicKeyInfo', RSAPubKey).
+{'SubjectPublicKeyInfo', &lt;&lt;48,92...&gt;&gt;, not_encrypted}
+
+2> PemBin = public_key:pem_encode([PemEntry]).
+&lt;&lt;"-----BEGIN PUBLIC KEY-----\nMFw...&gt;&gt;
+
+3> file:write_file("pub_key.pem", PemBin).
+ok</code>
+
+ </section>
+</section>
+
+<section>
+ <title>RSA public key cryptography </title>
+ <p> Suppose you have PrivateKey = #'RSAPrivateKey{}' and the
+ plaintext Msg = binary() and the corresponding public key
+ PublicKey = #'RSAPublicKey'{} then you can do the following.
+ Note that you normally will only do one of the encrypt or
+ decrypt operations and the peer will do the other.
+ </p>
+
+ <p>Encrypt with the private key </p>
+ <code>RsaEncrypted = public_key:encrypt_private(Msg, PrivateKey),
+Msg = public_key:decrypt_public(RsaEncrypted, PublicKey),</code>
+
+ <p>Encrypt with the public key </p>
+ <code>RsaEncrypted = public_key:encrypt_public(Msg, PublicKey),
+Msg = public_key:decrypt_private(RsaEncrypted, PrivateKey),</code>
+ </section>
+
+ <section>
+ <title>Digital signatures</title>
+
+ <p> Suppose you have PrivateKey = #'RSAPrivateKey{}'or
+ #'DSAPrivateKey'{} and the plaintext Msg = binary() and the
+ corresponding public key PublicKey = #'RSAPublicKey'{} or
+ {integer(), #'DssParams'{}} then you can do the following. Note
+ that you normally will only do one of the sign or verify operations
+ and the peer will do the other. </p>
+
+ <code>Signature = public_key:sign(Msg, sha, PrivateKey),
+true = public_key:verify(Msg, sha, Signature, PublicKey),</code>
+
+ <p>It might be appropriate to calculate the message digest before
+ calling sign or verify and then you can use the none as second
+ argument.</p>
+
+ <code>Digest = crypto:sha(Msg),
+Signature = public_key:sign(Digest, none, PrivateKey),
+true = public_key:verify(Digest, none, Signature, PublicKey),
+ </code>
+
+ </section>
+
+ <section>
+ <title>SSH files</title>
+
+ <p>SSH typically uses PEM files for private keys but has its
+ own file format for storing public keys. The erlang public_key
+ application can be used to parse the content of SSH public key files.</p>
+
+ <section>
+ <title> RFC 4716 SSH public key files </title>
+
+ <p>RFC 4716 SSH files looks confusingly like PEM files,
+ but there are some differences.</p>
+ <code>1> {ok, SshBin} = file:read_file("ssh2_rsa_pub").
+{ok, &lt;&lt;"---- BEGIN SSH2 PUBLIC KEY ----\nAAAA"...&gt;&gt;}</code>
+
+ <p>This is equivalent to calling public_key:ssh_decode(SshBin, rfc4716_public_key).
+ </p>
+ <code>2> public_key:ssh_decode(SshBin, public_key).
+[{#'RSAPublicKey'{modulus = 794430685...91663,
+ publicExponent = 35}, []}]
+</code>
+
+ </section>
+
+ <section>
+ <title> Openssh public key format </title>
+ <code>1> {ok, SshBin} = file:read_file("openssh_dsa_pub").
+{ok,&lt;&lt;"ssh-dss AAAAB3Nza"...&gt;&gt;}</code>
+
+ <p>This is equivalent to calling public_key:ssh_decode(SshBin, openssh_public_key).
+ </p>
+ <code>2> public_key:ssh_decode(SshBin, public_key).
+[{{15642692...694280725,
+ #'Dss-Parms'{p = 17291273936...696123221,
+ q = 1255626590179665817295475654204371833735706001853,
+ g = 10454211196...480338645}},
+ [{comment,"dhopson@VMUbuntu-DSH"}]}]
+</code>
+ </section>
+
+ <section>
+ <title> Known hosts - openssh format</title>
+
+ <code>1> {ok, SshBin} = file:read_file("known_hosts").
+{ok,&lt;&lt;"hostname.domain.com,192.168.0.1 ssh-rsa AAAAB...&gt;&gt;}</code>
+
+ <p>Returns a list of public keys and their related attributes
+ each pair of key and attributes corresponds to one entry in
+ the known hosts file.</p>
+
+ <code>2> public_key:ssh_decode(SshBin, known_hosts).
+[{#'RSAPublicKey'{modulus = 1498979460408...72721699,
+ publicExponent = 35},
+ [{hostnames,["hostname.domain.com","192.168.0.1"]}]},
+ {#'RSAPublicKey'{modulus = 14989794604088...2721699,
+ publicExponent = 35},
+ [{comment,"[email protected]"},
+ {hostnames,["|1|BWO5qDxk/cFH0wa05JLdHn+j6xQ=|rXQvIxh5cDD3C43k5DPDamawVNA="]}]}]
+</code>
+ </section>
+
+ <section>
+ <title> Authorized keys - openssh format</title>
+
+ <code>1> {ok, SshBin} = file:read_file("auth_keys").
+{ok, &lt;&lt;"command=\"dump /home\",no-pty,no-port-forwarding ssh-rsa AAA...&gt;&gt;}</code>
+
+ <p>Returns a list of public keys and their related attributes
+ each pair of key and attributes corresponds to one entry in
+ the authorized key file.</p>
+
+ <code>2> public_key:ssh_decode(SshBin, auth_keys).
+[{#'RSAPublicKey'{modulus = 794430685...691663,
+ publicExponent = 35},
+ [{comment,"dhopson@VMUbuntu-DSH"},
+ {options,["command=\"dump/home\"","no-pty",
+ "no-port-forwarding"]}]},
+ {{1564269258491...607694280725,
+ #'Dss-Parms'{p = 17291273936185...763696123221,
+ q = 1255626590179665817295475654204371833735706001853,
+ g = 10454211195705...60511039590076780999046480338645}},
+ [{comment,"dhopson@VMUbuntu-DSH"}]}]
+</code>
+ </section>
+
+ <section>
+ <title> Creating an SSH file from public key data </title>
+
+ <p>If you got a public key <c>PubKey</c> and a related list of
+ attributes <c>Attributes</c> as returned
+ by ssh_decode/2 you can create a new ssh file for example</p>
+ <code>N> SshBin = public_key:ssh_encode([{PubKey, Attributes}], openssh_public_key),
+&lt;&lt;"ssh-rsa "...&gt;&gt;
+N+1> file:write_file("id_rsa.pub", SshBin).
+ok</code>
+ </section>
+ </section>
+</chapter>
diff --git a/lib/reltool/src/reltool_server.erl b/lib/reltool/src/reltool_server.erl
index 9743289ca6..692baea0a4 100644
--- a/lib/reltool/src/reltool_server.erl
+++ b/lib/reltool/src/reltool_server.erl
@@ -465,16 +465,16 @@ analyse(#state{common = C,
[MissingApp2 | Apps2]
end,
app_propagate_is_used_by(C, Apps3),
- Apps4 = read_apps(C, Sys, Apps3, []),
+ {Apps4,Status4} = app_recap_dependencies(C, Sys, Apps3, [], Status3),
%% io:format("Missing app: ~p\n",
%% [lists:keysearch(?MISSING_APP_NAME, #app.name, Apps4)]),
Sys2 = Sys#sys{apps = Apps4},
- case verify_config(RelApps2, Sys2, Status3) of
- {ok, _Warnings} = Status4 ->
- {S#state{sys = Sys2}, Status4};
- {error, _} = Status4 ->
- {S, Status4}
+ case verify_config(RelApps2, Sys2, Status4) of
+ {ok, _Warnings} = Status5 ->
+ {S#state{sys = Sys2}, Status5};
+ {error, _} = Status5 ->
+ {S, Status5}
end.
apps_in_rels(Rels, Apps, Status) ->
@@ -548,21 +548,24 @@ app_init_is_included(C,
{derived, [_ | _]} -> % App is included in at least one rel
{true, undefined, true, Status}
end,
- A2 = A#app{is_pre_included = IsPreIncl,
+ {Mods2,Status3} = lists:mapfoldl(fun(Mod,Acc) ->
+ mod_init_is_included(C,
+ Mod,
+ ModCond,
+ AppCond,
+ Default,
+ Acc)
+ end,
+ Status2,
+ Mods),
+ A2 = A#app{mods = Mods2,
+ is_pre_included = IsPreIncl,
is_included = IsIncl,
rels = Rels},
ets:insert(C#common.app_tab, A2),
- lists:foreach(fun(Mod) ->
- mod_init_is_included(C,
- Mod,
- ModCond,
- AppCond,
- Default)
- end,
- Mods),
- {A2, Status2}.
-
-mod_init_is_included(C, M, ModCond, AppCond, Default) ->
+ {A2, Status3}.
+
+mod_init_is_included(C, M, ModCond, AppCond, Default, Status) ->
%% print(M#mod.name, hipe, "incl_cond -> ~p\n", [AppCond]),
IsIncl =
case AppCond of
@@ -595,9 +598,52 @@ mod_init_is_included(C, M, ModCond, AppCond, Default) ->
Default
end
end,
+
M2 = M#mod{is_pre_included = IsIncl, is_included = IsIncl},
+
+ Status2 =
+ case ets:lookup(C#common.mod_tab,M#mod.name) of
+ [Existing] ->
+ case {Existing#mod.is_included,IsIncl} of
+ {false,_} ->
+ Warning =
+ lists:concat(
+ ["Module ",M#mod.name,
+ " exists in applications ", Existing#mod.app_name,
+ " and ", M#mod.app_name,
+ ". Using module from application ",
+ M#mod.app_name, "."]),
+ ets:insert(C#common.mod_tab, M2),
+ reltool_utils:add_warning(Status,Warning);
+ {_,false} ->
+ Warning =
+ lists:concat(
+ ["Module ",M#mod.name,
+ " exists in applications ", Existing#mod.app_name,
+ " and ", M#mod.app_name,
+ ". Using module from application ",
+ Existing#mod.app_name, "."]),
+
+ %% Don't insert in mod_tab - using Existing
+ reltool_utils:add_warning(Status,Warning);
+ {_,_} ->
+ Error =
+ lists:concat(
+ ["Module ",M#mod.name,
+ " potentially included by ",
+ "two different applications: ",
+ Existing#mod.app_name, " and ",
+ M#mod.app_name, "."]),
+ %% Don't insert in mod_tab - using Existing
+ reltool_utils:return_first_error(Status,Error)
+ end;
+ [] ->
+ ets:insert(C#common.mod_tab, M2),
+ Status
+ end,
+
%% print(M#mod.name, hipe, "~p -> ~p\n", [M2, IsIncl]),
- ets:insert(C#common.mod_tab, M2).
+ {M2,Status2}.
false_to_undefined(Bool) ->
case Bool of
@@ -612,21 +658,27 @@ app_propagate_is_included(_C, _Sys, [], Acc) ->
Acc.
mod_propagate_is_included(C, Sys, A, [#mod{name = ModName} | Mods], Acc) ->
- [M2] = ets:lookup(C#common.mod_tab, ModName),
- %% print(ModName, file, "Maybe Prop ~p -> ~p\n",
- %% [M2, M2#mod.is_included]),
- %% print(ModName, filename, "Maybe Prop ~p -> ~p\n",
- %% [M2, M2#mod.is_included]),
Acc2 =
- case M2#mod.is_included of
- true ->
- %% Propagate include mark
- mod_mark_is_included(C, Sys, ModName, M2#mod.uses_mods, Acc);
- false ->
- Acc;
- undefined ->
- Acc
- end,
+ case ets:lookup(C#common.mod_tab, ModName) of
+ [M2] when M2#mod.app_name=:=A#app.name ->
+ %% print(ModName, file, "Maybe Prop ~p -> ~p\n",
+ %% [M2, M2#mod.is_included]),
+ %% print(ModName, filename, "Maybe Prop ~p -> ~p\n",
+ %% [M2, M2#mod.is_included]),
+ case M2#mod.is_included of
+ true ->
+ %% Propagate include mark
+ mod_mark_is_included(C,Sys,ModName,M2#mod.uses_mods,Acc);
+ false ->
+ Acc;
+ undefined ->
+ Acc
+ end;
+ [_] ->
+ %% This module is currently used from a different application
+ %% Ignore
+ Acc
+ end,
mod_propagate_is_included(C, Sys, A, Mods, Acc2);
mod_propagate_is_included(_C, _Sys, _A, [], Acc) ->
Acc.
@@ -740,9 +792,10 @@ mod_propagate_is_used_by(C, [#mod{name = ModName} | Mods]) ->
mod_propagate_is_used_by(_C, []) ->
ok.
-read_apps(C, Sys, [#app{mods = Mods, is_included = IsIncl} = A | Apps], Acc) ->
- {Mods2, IsIncl2} = read_apps(C, Sys, A, Mods, [], IsIncl),
- Status =
+app_recap_dependencies(C, Sys, [#app{mods = Mods, is_included = IsIncl} = A | Apps], Acc, Status) ->
+ {Mods2, IsIncl2, Status2} =
+ mod_recap_dependencies(C, Sys, A, Mods, [], IsIncl, Status),
+ AppStatus =
case lists:keymember(missing, #mod.status, Mods2) of
true -> missing;
false -> ok
@@ -759,34 +812,52 @@ read_apps(C, Sys, [#app{mods = Mods, is_included = IsIncl} = A | Apps], Acc) ->
UsedByApps2 = lists:usort(UsedByApps),
A2 = A#app{mods = Mods2,
- status = Status,
+ status = AppStatus,
uses_mods = UsesMods2,
used_by_mods = UsedByMods2,
uses_apps = UsesApps2,
used_by_apps = UsedByApps2,
is_included = IsIncl2},
- read_apps(C, Sys, Apps, [A2 | Acc]);
-read_apps(_C, _Sys, [], Acc) ->
- lists:reverse(Acc).
-
-read_apps(C, Sys, A, [#mod{name = ModName} | Mods], Acc, IsIncl) ->
- [M2] = ets:lookup(C#common.mod_tab, ModName),
- Status = do_get_status(M2),
- %% print(M2#mod.name, hipe, "status -> ~p\n", [Status]),
- {IsIncl2, M3} =
- case M2#mod.is_included of
- true ->
- UsedByMods =
- [N || {_, N} <- ets:lookup(C#common.mod_used_by_tab,
- ModName)],
- {true, M2#mod{status = Status, used_by_mods = UsedByMods}};
- _ ->
- {IsIncl, M2#mod{status = Status, used_by_mods = []}}
- end,
- ets:insert(C#common.mod_tab, M3),
- read_apps(C, Sys, A, Mods, [M3 | Acc], IsIncl2);
-read_apps(_C, _Sys, _A, [], Acc, IsIncl) ->
- {lists:reverse(Acc), IsIncl}.
+ ets:insert(C#common.app_tab,A2),
+ app_recap_dependencies(C, Sys, Apps, [A2 | Acc], Status2);
+app_recap_dependencies(_C, _Sys, [], Acc, Status) ->
+ {lists:reverse(Acc), Status}.
+
+mod_recap_dependencies(C, Sys, A, [#mod{name = ModName}=M1 | Mods], Acc, IsIncl, Status) ->
+ case ets:lookup(C#common.mod_tab, ModName) of
+ [M2] when M2#mod.app_name=:=A#app.name ->
+ ModStatus = do_get_status(M2),
+ %% print(M2#mod.name, hipe, "status -> ~p\n", [ModStatus]),
+ {IsIncl2, M3} =
+ case M2#mod.is_included of
+ true ->
+ UsedByMods =
+ [N || {_, N} <- ets:lookup(C#common.mod_used_by_tab,
+ ModName)],
+ {true, M2#mod{status = ModStatus, used_by_mods = UsedByMods}};
+ _ ->
+ {IsIncl, M2#mod{status = ModStatus, used_by_mods = []}}
+ end,
+ ets:insert(C#common.mod_tab, M3),
+ mod_recap_dependencies(C, Sys, A, Mods, [M3 | Acc], IsIncl2, Status);
+ [_] when A#app.is_included==false; M1#mod.incl_cond==exclude ->
+ %% App is explicitely excluded so it is ok that the module
+ %% record does not exist for this module in this
+ %% application.
+ mod_recap_dependencies(C, Sys, A, Mods, [M1 | Acc], IsIncl, Status);
+ [M2] ->
+ %% A module is potensially included by multiple
+ %% applications. This is not allowed!
+ Error =
+ lists:concat(
+ ["Module ",ModName,
+ " potentially included by two different applications: ",
+ A#app.name, " and ", M2#mod.app_name, "."]),
+ Status2 = reltool_utils:return_first_error(Status,Error),
+ mod_recap_dependencies(C, Sys, A, Mods, [M1 | Acc], IsIncl, Status2)
+ end;
+mod_recap_dependencies(_C, _Sys, _A, [], Acc, IsIncl, Status) ->
+ {lists:reverse(Acc), IsIncl, Status}.
do_get_status(M) ->
if
diff --git a/lib/reltool/src/reltool_sys_win.erl b/lib/reltool/src/reltool_sys_win.erl
index dbb8e32aa2..76c064f1e7 100644
--- a/lib/reltool/src/reltool_sys_win.erl
+++ b/lib/reltool/src/reltool_sys_win.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2009-2010. All Rights Reserved.
+%% 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
@@ -1092,17 +1092,23 @@ move_app(S, {_ItemNo, AppBase}, Action) ->
OldApp#app{incl_cond = AppCond}.
do_set_app(#state{server_pid = ServerPid, app_wins = AppWins} = S, NewApp) ->
- {ok, AnalysedApp, Warnings} = reltool_server:set_app(ServerPid, NewApp),
+ Result = reltool_server:set_app(ServerPid, NewApp),
[ok = reltool_app_win:refresh(AW#app_win.pid) || AW <- AppWins],
S2 = redraw_apps(S),
- case Warnings of
- [] ->
- ignore;
- _ ->
- Msg = lists:flatten([[W, $\n] || W <- Warnings]),
- display_message(Msg, ?wxICON_WARNING)
- end,
- {ok, AnalysedApp, S2}.
+ ReturnApp =
+ case Result of
+ {ok, AnalysedApp, []} ->
+ AnalysedApp;
+ {ok, AnalysedApp, Warnings} ->
+ Msg = lists:flatten([[W, $\n] || W <- Warnings]),
+ display_message(Msg, ?wxICON_WARNING),
+ AnalysedApp;
+ {error, Reason} ->
+ display_message(Reason, ?wxICON_ERROR),
+ {ok,OldApp} = reltool_server:get_app(ServerPid, NewApp#app.name),
+ OldApp
+ end,
+ {ok, ReturnApp, S2}.
redraw_apps(#state{server_pid = ServerPid,
source = SourceCtrl,
diff --git a/lib/reltool/test/Makefile b/lib/reltool/test/Makefile
index 62fe05238b..767454b66a 100644
--- a/lib/reltool/test/Makefile
+++ b/lib/reltool/test/Makefile
@@ -76,8 +76,8 @@ release_tests_spec: opt
$(INSTALL_DATA) reltool.spec reltool.cover $(ERL_FILES) $(HRL_FILES) $(RELSYSDIR)
$(INSTALL_SCRIPT) rtt $(INSTALL_PROGS) $(RELSYSDIR)
$(INSTALL_DATA) $(INSTALL_PROGS) $(RELSYSDIR)
-# chmod -R u+w $(RELSYSDIR)
-# @tar cf - *_SUITE_data | (cd $(RELSYSDIR); tar xf -)
+ chmod -R u+w $(RELSYSDIR)
+ @tar cf - *_SUITE_data | (cd $(RELSYSDIR); tar xf -)
release_docs_spec:
diff --git a/lib/reltool/test/reltool_server_SUITE.erl b/lib/reltool/test/reltool_server_SUITE.erl
index b77560db94..9ed79e8c95 100644
--- a/lib/reltool/test/reltool_server_SUITE.erl
+++ b/lib/reltool/test/reltool_server_SUITE.erl
@@ -25,6 +25,7 @@
-compile(export_all).
-include("reltool_test_lib.hrl").
+-include_lib("common_test/include/ct.hrl").
-define(NODE_NAME, '__RELTOOL__TEMPORARY_TEST__NODE__').
-define(WORK_DIR, "reltool_work_dir").
@@ -53,7 +54,7 @@ all() ->
[start_server, set_config, create_release,
create_script, create_target, create_embedded,
create_standalone, create_old_target,
- otp_9135].
+ otp_9135, otp_9229_exclude_app, otp_9229_exclude_mod].
groups() ->
[].
@@ -361,6 +362,114 @@ create_old_target(_Config) ->
ok.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% OTP-9229 - handle duplicated module names, i.e. same module name
+%% exists in two applications.
+
+%% Include on app, exclude the other
+otp_9229_exclude_app(Config) ->
+ DataDir = ?config(data_dir,Config),
+ LibDir = filename:join(DataDir,"otp_9229"),
+
+ %% Configure the server
+ ExclApp =
+ {sys,
+ [
+ {root_dir, code:root_dir()},
+ {lib_dirs, [LibDir]},
+ {incl_cond,exclude},
+ {app,x,[{incl_cond,include}]},
+ {app,y,[{incl_cond,exclude}]},
+ {app,kernel,[{incl_cond,include}]},
+ {app,stdlib,[{incl_cond,include}]},
+ {app,sasl,[{incl_cond,include}]}
+ ]},
+
+ %% Generate target file
+ TargetDir = filename:join([?WORK_DIR, "target_dupl_mod_excl_app"]),
+ ?m(ok, reltool_utils:recursive_delete(TargetDir)),
+ ?m(ok, file:make_dir(TargetDir)),
+ ?log("SPEC: ~p\n", [reltool:get_target_spec([{config, ExclApp}])]),
+ {ok,["Module mylib exists in applications x and y. Using module from application x."]} = reltool:get_status([{config, ExclApp}]),
+ ?m(ok, reltool:create_target([{config, ExclApp}], TargetDir)),
+
+ Erl = filename:join([TargetDir, "bin", "erl"]),
+ {ok, Node} = ?msym({ok, _}, start_node(?NODE_NAME, Erl)),
+
+ AbsTargetDir = filename:absname(TargetDir),
+ XArchive = "x-1.0.ez",
+ AbsXArchive = filename:join([AbsTargetDir,lib,XArchive]),
+ XEbin = ["ebin","x-1.0",XArchive],
+ YArchive = "y-1.0.ez",
+ AbsYArchive = filename:join([AbsTargetDir,lib,YArchive]),
+
+ ?m(true, filelib:is_file(AbsXArchive)),
+ ?m(XEbin, mod_path(Node,x)),
+ ?m(XEbin, mod_path(Node,mylib)),
+ ?m(false, filelib:is_file(AbsYArchive)),
+ ?m(non_existing, mod_path(Node,y)),
+
+ ?msym(ok, stop_node(Node)),
+
+ ok.
+
+%% Include both apps, but exclude common module from one app
+otp_9229_exclude_mod(Config) ->
+ DataDir = ?config(data_dir,Config),
+ LibDir = filename:join(DataDir,"otp_9229"),
+
+ %% Configure the server
+ ExclMod =
+ {sys,
+ [
+ {root_dir, code:root_dir()},
+ {lib_dirs, [LibDir]},
+ {incl_cond,exclude},
+ {app,x,[{incl_cond,include}]},
+ {app,y,[{incl_cond,include},{mod, mylib,[{incl_cond,exclude}]}]},
+ {app,kernel,[{incl_cond,include}]},
+ {app,stdlib,[{incl_cond,include}]},
+ {app,sasl,[{incl_cond,include}]}
+ ]},
+
+ %% Generate target file
+ TargetDir = filename:join([?WORK_DIR, "target_dupl_mod_excl_mod"]),
+ ?m(ok, reltool_utils:recursive_delete(TargetDir)),
+ ?m(ok, file:make_dir(TargetDir)),
+ ?log("SPEC: ~p\n", [reltool:get_target_spec([{config, ExclMod}])]),
+ {ok,["Module mylib exists in applications x and y. Using module from application x."]} = reltool:get_status([{config, ExclMod}]),
+ ?m(ok, reltool:create_target([{config, ExclMod}], TargetDir)),
+
+ Erl = filename:join([TargetDir, "bin", "erl"]),
+ {ok, Node} = ?msym({ok, _}, start_node(?NODE_NAME, Erl)),
+
+ AbsTargetDir = filename:absname(TargetDir),
+ XArchive = "x-1.0.ez",
+ AbsXArchive = filename:join([AbsTargetDir,lib,XArchive]),
+ XEbin = ["ebin","x-1.0",XArchive],
+ YArchive = "y-1.0.ez",
+ AbsYArchive = filename:join([AbsTargetDir,lib,YArchive]),
+ YEbin = ["ebin","y-1.0",YArchive],
+
+ ?m(true, filelib:is_file(AbsXArchive)),
+ ?m(XEbin, mod_path(Node,x)),
+ ?m(XEbin, mod_path(Node,mylib)),
+ ?m(true, filelib:is_file(AbsYArchive)),
+ ?m(YEbin, mod_path(Node,y)),
+
+ %% Remove path to XEbin and check that mylib is not located in YEbin
+ Mylib = rpc:call(Node,code,which,[mylib]),
+ rpc:call(Node,code,del_path,[filename:dirname(Mylib)]),
+ ?m(non_existing, mod_path(Node,mylib)),
+
+ ?msym(ok, stop_node(Node)),
+
+ ok.
+
+
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Library functions
erl_libs() ->
@@ -407,6 +516,20 @@ os_cmd(Cmd) when is_list(Cmd) ->
end
end.
+%% Returns the location (directory) of the given module. Split,
+%% reverted and relative to the lib dir.
+mod_path(Node,Mod) ->
+ case rpc:call(Node,code,which,[Mod]) of
+ Path when is_list(Path) ->
+ lists:takewhile(
+ fun("lib") -> false;
+ (_) -> true
+ end,
+ lists:reverse(filename:split(filename:dirname(Path))));
+ Other ->
+ Other
+ end.
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Node handling
diff --git a/lib/reltool/test/reltool_server_SUITE_data/Makefile.src b/lib/reltool/test/reltool_server_SUITE_data/Makefile.src
new file mode 100644
index 0000000000..049e8dd6cc
--- /dev/null
+++ b/lib/reltool/test/reltool_server_SUITE_data/Makefile.src
@@ -0,0 +1,19 @@
+EFLAGS=+debug_info
+
+OTP9229= \
+ otp_9229/x-1.0/ebin/x.@EMULATOR@ \
+ otp_9229/x-1.0/ebin/mylib.@EMULATOR@ \
+ otp_9229/y-1.0/ebin/y.@EMULATOR@ \
+ otp_9229/y-1.0/ebin/mylib.@EMULATOR@
+
+
+all: $(OTP9229)
+
+otp_9229/x-1.0/ebin/x.@EMULATOR@: otp_9229/x-1.0/src/x.erl
+ erlc $(EFLAGS) -ootp_9229/x-1.0/ebin otp_9229/x-1.0/src/x.erl
+otp_9229/x-1.0/ebin/mylib.@EMULATOR@: otp_9229/x-1.0/src/mylib.erl
+ erlc $(EFLAGS) -ootp_9229/x-1.0/ebin otp_9229/x-1.0/src/mylib.erl
+otp_9229/y-1.0/ebin/y.@EMULATOR@: otp_9229/y-1.0/src/y.erl
+ erlc $(EFLAGS) -ootp_9229/y-1.0/ebin otp_9229/y-1.0/src/y.erl
+otp_9229/y-1.0/ebin/mylib.@EMULATOR@: otp_9229/y-1.0/src/mylib.erl
+ erlc $(EFLAGS) -ootp_9229/y-1.0/ebin otp_9229/y-1.0/src/mylib.erl
diff --git a/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/ebin/x.app b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/ebin/x.app
new file mode 100644
index 0000000000..e597704b19
--- /dev/null
+++ b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/ebin/x.app
@@ -0,0 +1,7 @@
+%% -*- erlang -*-
+{application, x,
+ [{description, "X CXC 138 11"},
+ {vsn, "1.0"},
+ {modules, [x, mylib]},
+ {registered, []},
+ {applications, [kernel, stdlib]}]}.
diff --git a/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/mylib.erl b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/mylib.erl
new file mode 100644
index 0000000000..c8603d1a8e
--- /dev/null
+++ b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/mylib.erl
@@ -0,0 +1,4 @@
+-module(mylib).
+-export([foo/0]).
+
+foo() -> erlang:time().
diff --git a/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/x.erl b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/x.erl
new file mode 100644
index 0000000000..17ff84f08f
--- /dev/null
+++ b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/x-1.0/src/x.erl
@@ -0,0 +1,4 @@
+-module(x).
+-export([x/0]).
+
+x() ->mylib:foo().
diff --git a/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/ebin/y.app b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/ebin/y.app
new file mode 100644
index 0000000000..5b327862e3
--- /dev/null
+++ b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/ebin/y.app
@@ -0,0 +1,7 @@
+%% -*- erlang -*-
+{application, y,
+ [{description, "Y CXC 138 11"},
+ {vsn, "1.0"},
+ {modules, [y, mylib]},
+ {registered, []},
+ {applications, [kernel, stdlib]}]}.
diff --git a/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/mylib.erl b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/mylib.erl
new file mode 100644
index 0000000000..c8603d1a8e
--- /dev/null
+++ b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/mylib.erl
@@ -0,0 +1,4 @@
+-module(mylib).
+-export([foo/0]).
+
+foo() -> erlang:time().
diff --git a/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/y.erl b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/y.erl
new file mode 100644
index 0000000000..342e7da7d5
--- /dev/null
+++ b/lib/reltool/test/reltool_server_SUITE_data/otp_9229/y-1.0/src/y.erl
@@ -0,0 +1,4 @@
+-module(y).
+-export([y/0]).
+
+y() ->mylib:foo().
diff --git a/lib/runtime_tools/doc/src/notes.xml b/lib/runtime_tools/doc/src/notes.xml
index b27a3a0996..599be62241 100644
--- a/lib/runtime_tools/doc/src/notes.xml
+++ b/lib/runtime_tools/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/sasl/Makefile b/lib/sasl/Makefile
index 2affcf1e40..4073e5af85 100644
--- a/lib/sasl/Makefile
+++ b/lib/sasl/Makefile
@@ -1,7 +1,7 @@
#
# %CopyrightBegin%
#
-# Copyright Ericsson AB 1996-2009. All Rights Reserved.
+# Copyright Ericsson AB 1996-2010. All Rights Reserved.
#
# The contents of this file are subject to the Erlang Public License,
# Version 1.1, (the "License"); you may not use this file except in
@@ -23,7 +23,7 @@ include $(ERL_TOP)/make/$(TARGET)/otp.mk
# Macros
#
-SUB_DIRECTORIES = src doc/src
+SUB_DIRECTORIES = src doc/src examples/src
include vsn.mk
VSN = $(SASL_VSN)
diff --git a/lib/sasl/doc/src/notes.xml b/lib/sasl/doc/src/notes.xml
index 7941e371a0..73c4825458 100644
--- a/lib/sasl/doc/src/notes.xml
+++ b/lib/sasl/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/sasl/examples/ebin/.gitignore b/lib/sasl/examples/ebin/.gitignore
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/lib/sasl/examples/ebin/.gitignore
diff --git a/lib/sasl/examples/src/Makefile b/lib/sasl/examples/src/Makefile
new file mode 100644
index 0000000000..4a4e04a536
--- /dev/null
+++ b/lib/sasl/examples/src/Makefile
@@ -0,0 +1,78 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2010. 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%
+#
+
+#
+
+include $(ERL_TOP)/make/target.mk
+include $(ERL_TOP)/make/$(TARGET)/otp.mk
+
+# ----------------------------------------------------
+# Application version
+# ----------------------------------------------------
+include ../../vsn.mk
+VSN=$(SASL_VSN)
+
+# ----------------------------------------------------
+# Release directory specification
+# ----------------------------------------------------
+RELSYSDIR = $(RELEASE_PATH)/lib/sasl-$(VSN)
+
+# ----------------------------------------------------
+# Common Macros
+# ----------------------------------------------------
+EXTRA_ERLC_FLAGS = +warn_unused_vars
+ERL_COMPILE_FLAGS += $(EXTRA_ERLC_FLAGS)
+
+
+MODULES = target_system
+
+ERL_FILES= $(MODULES:%=%.erl)
+
+TARGET_FILES= $(MODULES:%=$(EBIN)/%.$(EMULATOR))
+
+# ----------------------------------------------------
+# Targets
+# ----------------------------------------------------
+
+debug opt: $(TARGET_FILES)
+
+clean:
+ rm -fr $(TARGET_FILES) *~ *.beam
+
+docs:
+
+# ----------------------------------------------------
+# Release Target
+# ----------------------------------------------------
+include $(ERL_TOP)/make/otp_release_targets.mk
+
+release_spec: opt
+ $(INSTALL_DIR) $(RELSYSDIR)/examples/src
+ $(INSTALL_DIR) $(RELSYSDIR)/examples/ebin
+ (cd ..; tar cf - src ebin | (cd $(RELSYSDIR)/examples; tar xf -))
+ chmod -f -R ug+w $(RELSYSDIR)/examples
+
+release_docs_spec:
+
+
+
+
+
+
+
diff --git a/lib/sasl/examples/src/target_system.erl b/lib/sasl/examples/src/target_system.erl
new file mode 100644
index 0000000000..0e1e0b2324
--- /dev/null
+++ b/lib/sasl/examples/src/target_system.erl
@@ -0,0 +1,259 @@
+%%
+%% %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%
+%%
+-module(target_system).
+-export([create/1, create/2, install/2]).
+
+%% Note: RelFileName below is the *stem* without trailing .rel,
+%% .script etc.
+%%
+
+%% create(RelFileName)
+%%
+create(RelFileName) ->
+ create(RelFileName,[]).
+
+create(RelFileName,SystoolsOpts) ->
+ RelFile = RelFileName ++ ".rel",
+ Dir = filename:dirname(RelFileName),
+ PlainRelFileName = filename:join(Dir,"plain"),
+ PlainRelFile = PlainRelFileName ++ ".rel",
+ io:fwrite("Reading file: ~p ...~n", [RelFile]),
+ {ok, [RelSpec]} = file:consult(RelFile),
+ io:fwrite("Creating file: ~p from ~p ...~n",
+ [PlainRelFile, RelFile]),
+ {release,
+ {RelName, RelVsn},
+ {erts, ErtsVsn},
+ AppVsns} = RelSpec,
+ PlainRelSpec = {release,
+ {RelName, RelVsn},
+ {erts, ErtsVsn},
+ lists:filter(fun({kernel, _}) ->
+ true;
+ ({stdlib, _}) ->
+ true;
+ (_) ->
+ false
+ end, AppVsns)
+ },
+ {ok, Fd} = file:open(PlainRelFile, [write]),
+ io:fwrite(Fd, "~p.~n", [PlainRelSpec]),
+ file:close(Fd),
+
+ io:fwrite("Making \"~s.script\" and \"~s.boot\" files ...~n",
+ [PlainRelFileName,PlainRelFileName]),
+ make_script(PlainRelFileName,SystoolsOpts),
+
+ io:fwrite("Making \"~s.script\" and \"~s.boot\" files ...~n",
+ [RelFileName, RelFileName]),
+ make_script(RelFileName,SystoolsOpts),
+
+ TarFileName = filename:join(Dir,RelFileName ++ ".tar.gz"),
+ io:fwrite("Creating tar file ~p ...~n", [TarFileName]),
+ make_tar(RelFileName,SystoolsOpts),
+
+ TmpDir = filename:join(Dir,"tmp"),
+ io:fwrite("Creating directory ~p ...~n",[TmpDir]),
+ file:make_dir(TmpDir),
+
+ io:fwrite("Extracting ~p into directory ~p ...~n", [TarFileName,TmpDir]),
+ extract_tar(TarFileName, TmpDir),
+
+ TmpBinDir = filename:join([TmpDir, "bin"]),
+ ErtsBinDir = filename:join([TmpDir, "erts-" ++ ErtsVsn, "bin"]),
+ io:fwrite("Deleting \"erl\" and \"start\" in directory ~p ...~n",
+ [ErtsBinDir]),
+ file:delete(filename:join([ErtsBinDir, "erl"])),
+ file:delete(filename:join([ErtsBinDir, "start"])),
+
+ io:fwrite("Creating temporary directory ~p ...~n", [TmpBinDir]),
+ file:make_dir(TmpBinDir),
+
+ io:fwrite("Copying file \"~s.boot\" to ~p ...~n",
+ [PlainRelFileName, filename:join([TmpBinDir, "start.boot"])]),
+ copy_file(PlainRelFileName++".boot",filename:join([TmpBinDir, "start.boot"])),
+
+ io:fwrite("Copying files \"epmd\", \"run_erl\" and \"to_erl\" from \n"
+ "~p to ~p ...~n",
+ [ErtsBinDir, TmpBinDir]),
+ copy_file(filename:join([ErtsBinDir, "epmd"]),
+ filename:join([TmpBinDir, "epmd"]), [preserve]),
+ copy_file(filename:join([ErtsBinDir, "run_erl"]),
+ filename:join([TmpBinDir, "run_erl"]), [preserve]),
+ copy_file(filename:join([ErtsBinDir, "to_erl"]),
+ filename:join([TmpBinDir, "to_erl"]), [preserve]),
+
+ StartErlDataFile = filename:join([TmpDir, "releases", "start_erl.data"]),
+ io:fwrite("Creating ~p ...~n", [StartErlDataFile]),
+ StartErlData = io_lib:fwrite("~s ~s~n", [ErtsVsn, RelVsn]),
+ write_file(StartErlDataFile, StartErlData),
+
+ io:fwrite("Recreating tar file ~p from contents in directory ~p ...~n",
+ [TarFileName,TmpDir]),
+ {ok, Tar} = erl_tar:open(TarFileName, [write, compressed]),
+ %% {ok, Cwd} = file:get_cwd(),
+ %% file:set_cwd("tmp"),
+ ErtsDir = "erts-"++ErtsVsn,
+ erl_tar:add(Tar, filename:join(TmpDir,"bin"), "bin", []),
+ erl_tar:add(Tar, filename:join(TmpDir,ErtsDir), ErtsDir, []),
+ erl_tar:add(Tar, filename:join(TmpDir,"releases"), "releases", []),
+ erl_tar:add(Tar, filename:join(TmpDir,"lib"), "lib", []),
+ erl_tar:close(Tar),
+ %% file:set_cwd(Cwd),
+ io:fwrite("Removing directory ~p ...~n",[TmpDir]),
+ remove_dir_tree(TmpDir),
+ ok.
+
+
+install(RelFileName, RootDir) ->
+ TarFile = RelFileName ++ ".tar.gz",
+ io:fwrite("Extracting ~p ...~n", [TarFile]),
+ extract_tar(TarFile, RootDir),
+ StartErlDataFile = filename:join([RootDir, "releases", "start_erl.data"]),
+ {ok, StartErlData} = read_txt_file(StartErlDataFile),
+ [ErlVsn, _RelVsn| _] = string:tokens(StartErlData, " \n"),
+ ErtsBinDir = filename:join([RootDir, "erts-" ++ ErlVsn, "bin"]),
+ BinDir = filename:join([RootDir, "bin"]),
+ io:fwrite("Substituting in erl.src, start.src and start_erl.src to\n"
+ "form erl, start and start_erl ...\n"),
+ subst_src_scripts(["erl", "start", "start_erl"], ErtsBinDir, BinDir,
+ [{"FINAL_ROOTDIR", RootDir}, {"EMU", "beam"}],
+ [preserve]),
+ io:fwrite("Creating the RELEASES file ...\n"),
+ create_RELEASES(RootDir,
+ filename:join([RootDir, "releases", RelFileName])).
+
+%% LOCALS
+
+%% make_script(RelFileName,Opts)
+%%
+make_script(RelFileName,Opts) ->
+ systools:make_script(RelFileName, [no_module_tests,
+ {outdir,filename:dirname(RelFileName)}
+ |Opts]).
+
+%% make_tar(RelFileName,Opts)
+%%
+make_tar(RelFileName,Opts) ->
+ RootDir = code:root_dir(),
+ systools:make_tar(RelFileName, [{erts, RootDir},
+ {outdir,filename:dirname(RelFileName)}
+ |Opts]).
+
+%% extract_tar(TarFile, DestDir)
+%%
+extract_tar(TarFile, DestDir) ->
+ erl_tar:extract(TarFile, [{cwd, DestDir}, compressed]).
+
+create_RELEASES(DestDir, RelFileName) ->
+ release_handler:create_RELEASES(DestDir, RelFileName ++ ".rel").
+
+subst_src_scripts(Scripts, SrcDir, DestDir, Vars, Opts) ->
+ lists:foreach(fun(Script) ->
+ subst_src_script(Script, SrcDir, DestDir,
+ Vars, Opts)
+ end, Scripts).
+
+subst_src_script(Script, SrcDir, DestDir, Vars, Opts) ->
+ subst_file(filename:join([SrcDir, Script ++ ".src"]),
+ filename:join([DestDir, Script]),
+ Vars, Opts).
+
+subst_file(Src, Dest, Vars, Opts) ->
+ {ok, Conts} = read_txt_file(Src),
+ NConts = subst(Conts, Vars),
+ write_file(Dest, NConts),
+ case lists:member(preserve, Opts) of
+ true ->
+ {ok, FileInfo} = file:read_file_info(Src),
+ file:write_file_info(Dest, FileInfo);
+ false ->
+ ok
+ end.
+
+%% subst(Str, Vars)
+%% Vars = [{Var, Val}]
+%% Var = Val = string()
+%% Substitute all occurrences of %Var% for Val in Str, using the list
+%% of variables in Vars.
+%%
+subst(Str, Vars) ->
+ subst(Str, Vars, []).
+
+subst([$%, C| Rest], Vars, Result) when $A =< C, C =< $Z ->
+ subst_var([C| Rest], Vars, Result, []);
+subst([$%, C| Rest], Vars, Result) when $a =< C, C =< $z ->
+ subst_var([C| Rest], Vars, Result, []);
+subst([$%, C| Rest], Vars, Result) when C == $_ ->
+ subst_var([C| Rest], Vars, Result, []);
+subst([C| Rest], Vars, Result) ->
+ subst(Rest, Vars, [C| Result]);
+subst([], _Vars, Result) ->
+ lists:reverse(Result).
+
+subst_var([$%| Rest], Vars, Result, VarAcc) ->
+ Key = lists:reverse(VarAcc),
+ case lists:keysearch(Key, 1, Vars) of
+ {value, {Key, Value}} ->
+ subst(Rest, Vars, lists:reverse(Value, Result));
+ false ->
+ subst(Rest, Vars, [$%| VarAcc ++ [$%| Result]])
+ end;
+subst_var([C| Rest], Vars, Result, VarAcc) ->
+ subst_var(Rest, Vars, Result, [C| VarAcc]);
+subst_var([], Vars, Result, VarAcc) ->
+ subst([], Vars, [VarAcc ++ [$%| Result]]).
+
+copy_file(Src, Dest) ->
+ copy_file(Src, Dest, []).
+
+copy_file(Src, Dest, Opts) ->
+ {ok,_} = file:copy(Src, Dest),
+ case lists:member(preserve, Opts) of
+ true ->
+ {ok, FileInfo} = file:read_file_info(Src),
+ file:write_file_info(Dest, FileInfo);
+ false ->
+ ok
+ end.
+
+write_file(FName, Conts) ->
+ {ok, Fd} = file:open(FName, [write]),
+ file:write(Fd, Conts),
+ file:close(Fd).
+
+read_txt_file(File) ->
+ {ok, Bin} = file:read_file(File),
+ {ok, binary_to_list(Bin)}.
+
+remove_dir_tree(Dir) ->
+ remove_all_files(".", [Dir]).
+
+remove_all_files(Dir, Files) ->
+ lists:foreach(fun(File) ->
+ FilePath = filename:join([Dir, File]),
+ case filelib:is_dir(FilePath) of
+ true ->
+ {ok, DirFiles} = file:list_dir(FilePath),
+ remove_all_files(FilePath, DirFiles),
+ file:del_dir(FilePath);
+ _ ->
+ file:delete(FilePath)
+ end
+ end, Files).
diff --git a/lib/sasl/src/rb.erl b/lib/sasl/src/rb.erl
index 13753565d8..8004ef2c5a 100644
--- a/lib/sasl/src/rb.erl
+++ b/lib/sasl/src/rb.erl
@@ -53,8 +53,7 @@ start_link(Options) ->
gen_server:start_link({local, rb_server}, rb, Options, []).
stop() ->
- call(stop),
- supervisor:delete_child(sasl_sup, rb_server).
+ supervisor:terminate_child(sasl_sup, rb_server).
rescan() -> rescan([]).
rescan(Options) ->
@@ -205,8 +204,6 @@ handle_call({rescan, Options}, _From, State) ->
NewState = State#state{data = Data, max = Max, type = Type,
device = Device, abort = Abort, log = Log1},
{reply, ok, NewState};
-handle_call(stop, _From, State) ->
- {stop, normal, stopped, State};
handle_call(_, _From, #state{data = undefined}) ->
{reply, {error, no_data}, #state{}};
handle_call({list, Type}, _From, State) ->
@@ -312,11 +309,14 @@ scan_files(RptDir, Max, Type) ->
{ok, Fd} ->
case catch file:read(Fd, 1) of
{ok, [LastWritten]} ->
+ file:close(Fd),
Files = make_file_list(RptDir, LastWritten),
scan_files(RptDir, Files, Max, Type);
- _ -> exit("cannot read the index file")
+ _X ->
+ file:close(Fd),
+ exit("cannot read the index file")
end;
- _ -> exit("cannot read the index file")
+ _X -> exit("cannot read the index file")
end.
make_file_list(Dir, FirstFileNo) ->
@@ -789,7 +789,7 @@ filter_report([{Key, RegExp, re}|T], Msg) ->
filter_report([{Key, RegExp, re, no}|T], Msg) ->
case proplists:get_value(Key, Msg) of
undefined ->
- false;
+ true;
Value ->
Subject = lists:flatten(io_lib:format("~p",[Value])),
case run_re(Subject, RegExp) of
diff --git a/lib/sasl/test/.gitignore b/lib/sasl/test/.gitignore
new file mode 100644
index 0000000000..76e706b874
--- /dev/null
+++ b/lib/sasl/test/.gitignore
@@ -0,0 +1,5 @@
+#
+# Don't ignore *.beam files in any sub-directory.
+#
+
+!*.beam
diff --git a/lib/sasl/test/Makefile b/lib/sasl/test/Makefile
new file mode 100644
index 0000000000..ad08c8136b
--- /dev/null
+++ b/lib/sasl/test/Makefile
@@ -0,0 +1,91 @@
+#
+# %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%
+#
+include $(ERL_TOP)/make/target.mk
+include $(ERL_TOP)/make/$(TARGET)/otp.mk
+
+# ----------------------------------------------------
+# Target Specs
+# ----------------------------------------------------
+
+MODULES= \
+ sasl_SUITE \
+ alarm_handler_SUITE \
+ installer \
+ release_handler_SUITE \
+ systools_SUITE \
+ systools_rc_SUITE \
+ overload_SUITE \
+ rb_SUITE
+
+ERL_FILES= $(MODULES:%=%.erl)
+
+TARGET_FILES= $(MODULES:%=$(EBIN)/%.$(EMULATOR))
+INSTALL_PROGS= $(TARGET_FILES)
+
+EMAKEFILE=Emakefile
+
+# ----------------------------------------------------
+# Release directory specification
+# ----------------------------------------------------
+RELSYSDIR = $(RELEASE_PATH)/sasl_test
+
+# ----------------------------------------------------
+# FLAGS
+# ----------------------------------------------------
+ERL_MAKE_FLAGS +=
+ERL_COMPILE_FLAGS += -I$(ERL_TOP)/lib/test_server/include \
+ -I$(ERL_TOP)/lib/sasl/src
+
+EBIN = .
+
+# ----------------------------------------------------
+# Targets
+# ----------------------------------------------------
+
+make_emakefile:
+ $(ERL_TOP)/make/make_emakefile $(ERL_COMPILE_FLAGS) -o$(EBIN) '*_SUITE_make'\
+ > $(EMAKEFILE)
+ $(ERL_TOP)/make/make_emakefile $(ERL_COMPILE_FLAGS) -o$(EBIN) $(MODULES)\
+ >> $(EMAKEFILE)
+
+tests debug opt: make_emakefile
+ erl $(ERL_MAKE_FLAGS) -make
+
+clean:
+ rm -f $(EMAKEFILE)
+ rm -f $(TARGET_FILES)
+ rm -f core
+
+docs:
+
+# ----------------------------------------------------
+# Release Target
+# ----------------------------------------------------
+include $(ERL_TOP)/make/otp_release_targets.mk
+
+release_spec: opt
+
+release_tests_spec: make_emakefile
+ $(INSTALL_DIR) $(RELSYSDIR)
+ $(INSTALL_DATA) $(ERL_FILES) $(RELSYSDIR)
+ $(INSTALL_DATA) sasl.spec sasl.cover $(EMAKEFILE) $(RELSYSDIR)
+ chmod -f -R u+w $(RELSYSDIR)
+ @tar cfh - *_SUITE_data | (cd $(RELSYSDIR); tar xf -)
+
+release_docs_spec:
diff --git a/lib/sasl/test/alarm_handler_SUITE.erl b/lib/sasl/test/alarm_handler_SUITE.erl
new file mode 100644
index 0000000000..a98e8c9c67
--- /dev/null
+++ b/lib/sasl/test/alarm_handler_SUITE.erl
@@ -0,0 +1,179 @@
+%%
+%% %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%
+%%
+-module(alarm_handler_SUITE).
+
+-include_lib("test_server/include/test_server.hrl").
+
+%%-----------------------------------------------------------------
+%% We will add an own alarm handler in order to verify that the
+%% alarm_handler deliver the expected events.
+%%-----------------------------------------------------------------
+
+-export([init_per_suite/1, end_per_suite/1, all/0,groups/0,
+ init_per_group/2,end_per_group/2,
+ set_alarm/1, clear_alarm/1, swap/1]).
+
+-export([init/1, handle_event/2, handle_call/2, handle_info/2,
+ terminate/2]).
+
+
+init_per_suite(Config) ->
+ application:start(sasl),
+ Config.
+
+end_per_suite(_Config) ->
+ ok.
+
+all() ->
+ [set_alarm, clear_alarm, swap].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+
+%%-----------------------------------------------------------------
+
+set_alarm(suite) -> [];
+set_alarm(Config) when is_list(Config) ->
+ ?line gen_event:add_handler(alarm_handler, ?MODULE, self()),
+ Alarm1 = {alarm1, "this is the alarm"},
+ Alarm2 = {"alarm2", this_is_the_alarm},
+ Alarm3 = {{alarm3}, {this_is,"the_alarm"}},
+ ?line ok = alarm_handler:set_alarm(Alarm1),
+ reported(set_alarm, Alarm1),
+ ?line ok = alarm_handler:set_alarm(Alarm2),
+ reported(set_alarm, Alarm2),
+ ?line ok = alarm_handler:set_alarm(Alarm3),
+ reported(set_alarm, Alarm3),
+
+ ?line [Alarm3,Alarm2,Alarm1] = alarm_handler:get_alarms(),
+ alarm_handler:clear_alarm(alarm1),
+ alarm_handler:clear_alarm("alarm2"),
+ alarm_handler:clear_alarm({alarm3}),
+ ?line [] = alarm_handler:get_alarms(),
+
+ test_server:messages_get(),
+ ?line my_yes = gen_event:delete_handler(alarm_handler, ?MODULE, []),
+ ok.
+
+%%-----------------------------------------------------------------
+
+clear_alarm(suite) -> [];
+clear_alarm(Config) when is_list(Config) ->
+ ?line gen_event:add_handler(alarm_handler, ?MODULE, self()),
+ Alarm1 = {alarm1, "this is the alarm"},
+ Alarm2 = {"alarm2", this_is_the_alarm},
+ Alarm3 = {{alarm3}, {this_is,"the_alarm"}},
+ alarm_handler:set_alarm(Alarm1),
+ alarm_handler:set_alarm(Alarm2),
+ alarm_handler:set_alarm(Alarm3),
+ test_server:messages_get(),
+
+ ?line ok = alarm_handler:clear_alarm(alarm1),
+ reported(clear_alarm, alarm1),
+ ?line ok = alarm_handler:clear_alarm("alarm2"),
+ reported(clear_alarm, "alarm2"),
+ ?line ok = alarm_handler:clear_alarm({alarm3}),
+ reported(clear_alarm, {alarm3}),
+ ?line [] = alarm_handler:get_alarms(),
+
+ ?line my_yes = gen_event:delete_handler(alarm_handler, ?MODULE, []),
+ ok.
+
+%%-----------------------------------------------------------------
+
+swap(suite) -> [];
+swap(Config) when is_list(Config) ->
+ ?line Alarm1 = {alarm1, "this is the alarm"},
+ ?line Alarm2 = {"alarm2", this_is_the_alarm},
+ ?line Alarm3 = {{alarm3}, {this_is,"the_alarm"}},
+ ?line alarm_handler:set_alarm(Alarm1),
+ ?line alarm_handler:set_alarm(Alarm2),
+ ?line alarm_handler:set_alarm(Alarm3),
+
+ ?line foo,
+ case gen_event:which_handlers(alarm_handler) of
+ [alarm_handler] ->
+ ?line ok = gen_event:swap_handler(alarm_handler,
+ {alarm_handler, swap},
+ {?MODULE, self()}),
+ ?line [?MODULE] = gen_event:which_handlers(alarm_handler),
+ Alarms = [Alarm3, Alarm2, Alarm1],
+ reported(swap_alarms, Alarms),
+
+ %% get_alarms is only valid with the default handler installed.
+ ?line {error, _} = alarm_handler:get_alarms(),
+
+ ?line my_yes = gen_event:delete_handler(alarm_handler,
+ ?MODULE, []),
+ ?line gen_event:add_handler(alarm_handler, alarm_handler, []),
+ ok;
+ _ ->
+ alarm_handler:clear_alarm(alarm1),
+ alarm_handler:clear_alarm("alarm2"),
+ alarm_handler:clear_alarm({alarm3}),
+ ok
+ end.
+
+%%-----------------------------------------------------------------
+%% Check that the alarm has been received.
+%%-----------------------------------------------------------------
+reported(Tag, Data) ->
+ receive
+ {Tag, Data} ->
+ test_server:messages_get(),
+ ok
+ after 1000 ->
+ test_server:fail(no_alarm_received)
+ end.
+
+%%-----------------------------------------------------------------
+%% The error_logger handler (gen_event behaviour).
+%% Sends a notification to the Tester process about the events
+%% generated by the Tester process.
+%%-----------------------------------------------------------------
+init(Tester) when is_pid(Tester) ->
+ {ok, Tester};
+init({Tester, {alarm_handler,Alarms}}) -> % Swap from default handler.
+ Tester ! {swap_alarms, Alarms},
+ {ok, Tester}.
+
+handle_event({set_alarm, Alarm}, Tester) ->
+ Tester ! {set_alarm, Alarm},
+ {ok, Tester};
+handle_event({clear_alarm, AlarmId}, Tester) ->
+ Tester ! {clear_alarm, AlarmId},
+ {ok, Tester};
+handle_event(_Event, Tester) ->
+ {ok, Tester}.
+
+handle_info(_, Tester) ->
+ {ok, Tester}.
+
+handle_call(_Query, Tester) -> {ok, {error, bad_query}, Tester}.
+
+terminate(_Reason, _Tester) ->
+ my_yes.
diff --git a/lib/sasl/test/installer.erl b/lib/sasl/test/installer.erl
new file mode 100644
index 0000000000..a114c4b5c9
--- /dev/null
+++ b/lib/sasl/test/installer.erl
@@ -0,0 +1,778 @@
+%%
+%% %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%
+%%
+
+-module(installer).
+
+%%-compile(export_all).
+-export([install_1/2]).
+-export([install_2/1]).
+-export([install_3/2]).
+-export([install_3a/1]).
+-export([install_4/1]).
+-export([install_5/1]).
+-export([install_5a/1]).
+-export([install_6/1]).
+-export([install_7/1]).
+-export([install_8/1]).
+-export([install_9/1]).
+-export([install_10/1]).
+-export([install_11/1]).
+-export([client1_1/4]).
+-export([client2/3]).
+-export([stop/1]).
+-export([unpack_p1h/2]).
+-export([permanent_p1h/1]).
+-export([reg_proc/1]).
+-export([registered_loop/1]).
+
+-define(print(List), {rh_print, TestNode} ! {print, {?MODULE, ?LINE}, List}).
+-define(print_line(Line,List), {rh_print, TestNode} ! {print, {?MODULE, Line}, List}).
+-define(fail(Term), exit({?MODULE, ?LINE, Term})).
+-define(fail_line(Line,Term), exit({?MODULE, Line, Term})).
+
+-define(check_release(Vsn,Status,Apps),
+ check_release(TestNode,node(),Vsn,Status,Apps,?LINE)).
+-define(check_release_client(Node,Vsn,Status,Apps),
+ check_release(TestNode,Node,Vsn,Status,Apps,?LINE)).
+
+-define(check_running_app(App,Vsn),
+ check_running_app(TestNode,node(),App,Vsn,?LINE)).
+-define(check_running_app_client(Node,App,Vsn),
+ check_running_app(TestNode,Node,App,Vsn,?LINE)).
+
+
+install_1(TestNode,PrivDir) ->
+ ?print([TestNode]),
+ ?print(["install_1 start"]),
+
+ % Unpack and install P1H
+ {ok, "P1H"} = unpack_release(PrivDir,"rel1"),
+ ?print(["unpack_release P1H ok"]),
+ ?check_release("P1H",unpacked,["a-1.0"]),
+ {ok,"P1G",[new_appl]} = release_handler:install_release("P1H"),
+ ?print(["install_release P1H ok"]),
+ ?check_release("P1H",current,["a-1.0"]),
+ ?check_running_app(a,"1.0"),
+ X = a:a(),
+ ?print(["X", X]),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+ ?print(["install_1 end OK"]),
+ ok.
+ % release_handler_SUITE will reboot this node now!
+
+install_2(TestNode) ->
+ ?print(["install_2 start"]),
+
+ % Check that P1H is still unpacked, install it and make_permanent
+ ?check_release("P1H",unpacked,["a-1.0"]),
+ ?print(["install_2 P1H unpacked"]),
+ {ok,"P1G",[new_appl]} = release_handler:install_release("P1H"),
+ ?print(["install_2 install_release ok"]),
+ ?check_release("P1H",current,["a-1.0"]),
+ ?check_running_app(a,"1.0"),
+ ok = release_handler:make_permanent("P1H").
+ % release_handler_SUITE will reboot this node now!
+
+install_3(TestNode,PrivDir) ->
+ ?print(["install_3 start"]),
+
+ % Check that P1H is permanent
+ ?check_release("P1H",permanent,["a-1.0"]),
+ X = a:a(),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+
+ % Unpack and install P1I
+ {ok, "P1I"} = unpack_release(PrivDir,"rel2"),
+ ?print(["install_3 unpack_release P1I ok"]),
+ ?check_release("P1I",unpacked,["a-1.1"]),
+ {ok,"P1H",[{extra, gott}]} = release_handler:check_install_release("P1I"),
+ {error,_} = release_handler:check_install_release("P1J"),
+ {ok,"P1H",[{extra, gott}]} = release_handler:install_release("P1I"),
+ ?print(["install_3 install_release P1I ok"]),
+ ?check_release("P1I",current,["a-1.1"]),
+ ?check_running_app(a,"1.1"),
+ X2 = a:a(),
+ {key2, newval2} = lists:keyfind(key2, 1, X2),
+ {key1, val1} = lists:keyfind(key1, 1, X2),
+ {ok, bval} = a:b(),
+
+ % Unpack and install P2A
+ {ok, "P2A"} = unpack_release(PrivDir,"rel3"),
+ ?print(["install_3 unpack_release P2A ok"]),
+ ?check_release("P2A",unpacked,["a-1.1"]),
+ {ok, "P1I", [new_emu]} = release_handler:check_install_release("P2A"),
+ ok = release_handler:make_permanent("P1I"),
+ ?print(["install_3 make_permanent P1I ok"]),
+ ?check_release("P1I",permanent,["a-1.1"]),
+ ok.
+
+install_3a(TestNode) ->
+ {ok, "P1I", [new_emu]} = release_handler:install_release("P2A"),
+ %% Node is rebooted by the release_handler:install_release
+ %% (init:reboot) because P2A includes a new erts vsn and the relup
+ %% file contains a 'restart_new_emulator' instruction.
+ ?print(["install_3 P2A installed"]),
+ ok.
+
+
+
+install_4(TestNode) ->
+ ?print(["install_4 start"]),
+
+ % Check that P2A is in use.
+ ?check_release("P2A",current,["a-1.1"]),
+ ?check_running_app(a,"1.1"),
+ X = a:a(),
+ {key2, newval2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+ {ok, bval} = a:b(),
+ ok.
+ % release_handler_SUITE will reboot this node now!
+
+install_5(TestNode) ->
+ ?print(["install_5 start"]),
+
+ % Check that P1I is used
+ {ok, "P1I", [new_emu]} = release_handler:check_install_release("P2A"),
+ ok.
+
+install_5a(TestNode) ->
+ % Install P2A again
+ {ok, "P1I", [new_emu]} = release_handler:install_release("P2A"),
+ %% Node is rebooted by the release_handler:install_release
+ %% (init:reboot) because P2A includes a new erts vsn and the relup
+ %% file contains a 'restart_new_emulator' instruction.
+ ?print(["install_5 P2A installed"]),
+ ok.
+
+install_6(TestNode) ->
+ ?print(["install_6 start"]),
+
+ % Check that P2A is used
+ ?check_release("P2A",current,["a-1.1"]),
+ ?check_running_app(a,"1.1"),
+ X = a:a(),
+ {key2, newval2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+ {ok, bval} = a:b(),
+ ok = release_handler:make_permanent("P2A").
+ % release_handler_SUITE will reboot this node now!
+
+
+install_7(TestNode) ->
+ ?print(["install_7 start"]),
+
+ % Check that P2A is used
+ ?check_release("P2A",permanent,["a-1.1"]),
+
+ % Install old P1H
+ ok = release_handler:reboot_old_release("P1H"),
+ ok.
+
+install_8(TestNode) ->
+ ?print(["install_8 start"]),
+
+ % Check that P1H is permanent
+ ?check_release("P1H",permanent,["a-1.0"]),
+ X = a:a(),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+
+ %% Remove P1I and P2A and check that a-1.1 and erts-<latest> are removed
+ ok = release_handler:remove_release("P2A"),
+ ok = release_handler:remove_release("P1I"),
+ {ok, Libs} = file:list_dir(code:lib_dir()),
+ {_,_,StdlibVsn} = lists:keyfind(stdlib,1,application:which_applications()),
+ true = lists:member("stdlib-"++StdlibVsn, Libs),
+ true = lists:member("a-1.0", Libs),
+ false = lists:member("a-1.1", Libs),
+ {ok, Dirs} = file:list_dir(code:root_dir()),
+ ["erts-4.4"] = lists:filter(fun(Dir) -> lists:prefix("erts-",Dir) end, Dirs),
+ ok.
+ % release_handler_SUITE will reboot this node now!
+
+install_9(TestNode) ->
+ ?print(["install_9 start"]),
+
+ % Check that P1H is permanent
+ ?check_release("P1H",permanent,["a-1.0"]),
+ X = a:a(),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+
+ % Install old P1G
+ ok = release_handler:reboot_old_release("P1G"),
+ ok.
+
+install_10(TestNode) ->
+ ?print(["install_10 start"]),
+
+ % Check that P1G is permanent
+ ?check_release("P1G",permanent,[]),
+ ?check_release("P1H",old,["a-1.0"]),
+
+ %% Remove P1H and check that both versions of application a is removed
+ ok = release_handler:remove_release("P1H"),
+ {ok, Libs} = file:list_dir(code:lib_dir()),
+ {_,_,StdlibVsn} = lists:keyfind(stdlib,1,application:which_applications()),
+ true = lists:member("stdlib-"++StdlibVsn, Libs),
+ false = lists:member("a-1.0", Libs),
+ false = lists:member("a-1.1", Libs),
+ ok.
+ % release_handler_SUITE will reboot this node now!
+
+install_11(TestNode) ->
+ ?print(["install_11 start"]),
+
+ % Check that P1G is permanent
+ ?check_release("P1G",permanent,[]),
+ ok.
+
+
+
+%%-----------------------------------------------------------------
+%% This test starts a client node which uses this node as master
+%% for the release_handler.
+%% The client node runs all tests as in installer/1 test case.
+%% Thus, the client node will be rebooted several times.
+%% The to_erl /tmp/NODENAME@HOSTNAME/ command can be used to connect
+%% to the client node.
+%% run_erl logs for the client can be found in the directory:
+%% code:root_dir() ++ "/clients/type1/NODENAME@HOSTNAME/log
+%%-----------------------------------------------------------------
+
+
+client1_1(TestNode,PrivDir,MasterDir,ClientSname) ->
+ TestHost = test_host(),
+ ?print(["client1_1 start"]),
+
+ {ok,IP} = inet:getaddr(TestHost,inet),
+ erl_boot_server:start([IP]),
+
+ ok = net_kernel:monitor_nodes(true),
+ Node = start_client(TestNode,ClientSname),
+ trace_disallowed_calls(Node),
+
+ %% Check env var for SASL on client node
+ SaslEnv = rpc:call(Node, application, get_all_env, [sasl]),
+ {_,CliDir} = lists:keyfind(client_directory,1,SaslEnv),
+ {_,[Master]} = lists:keyfind(masters,1,SaslEnv),
+ {_,StartCli} = lists:keyfind(start_prg,1,SaslEnv),
+ Root = code:root_dir(),
+ true = (CliDir =:= filename:join([Root,"clients","type1",Node])),
+ true = (StartCli =:= filename:join([CliDir,"bin","start"])),
+ true = (Master =:= node()),
+
+ %% Unpack P1H on master
+ {ok, "P1H"} = unpack_release(PrivDir,"rel1"),
+
+ %% Unpack and install P1H on client
+ P1HDir = filename:join([Root, "releases", "P1H"]),
+
+ %% The AppDirs argument (last arg to set_unpacked) below is really
+ %% not necessary, it could just be [] since the path is the same
+ %% as default. But it is given here in order to force hitting the
+ %% release_handler:check_path function so it can be checked that
+ %% it does not use file:read_file_info on the client node, see
+ %% trace_disallowed_calls/1 and check_disallowed_calls/0 below.
+ %% (OTP-9142)
+ {ok, "P1H"} = rpc:call(Node, release_handler, set_unpacked,
+ [filename:join(P1HDir, "rel1.rel"),
+ [{a,"1.0",filename:join(MasterDir,lib)}]]),
+
+ ?check_release_client(Node,"P1H",unpacked,["a-1.0"]),
+
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P1H", filename:join(P1HDir, "start.boot")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P1H", filename:join(P1HDir, "sys.config")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P1H", filename:join(P1HDir, "relup")]),
+ ?print([{release_handler_state, Node},
+ rpc:call(Node, sys, get_status, [release_handler])]),
+
+ {ok,"P1G",[new_appl]} =
+ rpc:call(Node, release_handler, check_install_release, ["P1H"]),
+
+ {ok,"P1G",[new_appl]} =
+ rpc:call(Node, release_handler, install_release, ["P1H"]),
+
+ Apps = rpc:call(Node, application, which_applications, []),
+ {a,"A CXC 138 11","1.0"} = lists:keyfind(a, 1, Apps),
+ X = rpc:call(Node, a, a, []),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+
+ check_disallowed_calls(),
+ reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_2(TestNode,PrivDir,Node).
+
+client1_2(TestNode,PrivDir,Node) ->
+ ?print(["client1_2 start"]),
+
+ %% Check that P1H is still unpacked, install it and make_permanent
+ ?check_release_client(Node,"P1H",unpacked,["a-1.0"]),
+
+ {ok,"P1G",[new_appl]} =
+ rpc:call(Node, release_handler, install_release, ["P1H"]),
+ ?check_release_client(Node,"P1H",current,["a-1.0"]),
+ ?check_running_app_client(Node,a,"1.0"),
+
+ ok = rpc:call(Node, release_handler, make_permanent, ["P1H"]),
+
+ check_disallowed_calls(),
+ reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_3(TestNode,PrivDir,Node).
+
+client1_3(TestNode,PrivDir,Node) ->
+ ?print(["client1_3 start"]),
+
+ %% Check that P1H is permanent
+ ?check_release_client(Node,"P1H",permanent,["a-1.0"]),
+ X = rpc:call(Node, a, a, []),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+
+ %% Unpack P1I on master
+ {ok, "P1I"} = unpack_release(PrivDir,"rel2"),
+
+ MasterRoot = code:root_dir(),
+
+ %% Unpack and install P1I on client
+ P1IDir = filename:join([MasterRoot, "releases", "P1I"]),
+ {ok, "P1I"} = rpc:call(Node, release_handler, set_unpacked,
+ [filename:join(P1IDir, "rel2.rel"),[]]),
+
+ ?check_release_client(Node,"P1I",unpacked,["a-1.1"]),
+
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P1I", filename:join(P1IDir, "start.boot")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P1I", filename:join(P1IDir, "sys.config")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P1I", filename:join(P1IDir, "relup")]),
+
+ {ok,"P1H",[{extra, gott}]} =
+ rpc:call(Node, release_handler, check_install_release, ["P1I"]),
+ {error,_} = rpc:call(Node, release_handler, check_install_release, ["P1J"]),
+ {ok,"P1H",[{extra, gott}]} =
+ rpc:call(Node, release_handler, install_release, ["P1I"]),
+
+ ?check_running_app_client(Node,a,"1.1"),
+ X2 = rpc:call(Node, a, a, []),
+ {key2, newval2} = lists:keyfind(key2, 1, X2),
+ {key1, val1} = lists:keyfind(key1, 1, X2),
+ {ok, bval} = rpc:call(Node, a, b, []),
+
+ %% Unpack P2A on master
+ {ok, "P2A"} = unpack_release(PrivDir,"rel3"),
+
+ %% Unpack and install P2A on client
+ P2ADir = filename:join([MasterRoot, "releases", "P2A"]),
+ {ok, "P2A"} =
+ rpc:call(Node, release_handler, set_unpacked,
+ [filename:join(P2ADir, "rel3.rel"),[]]),
+
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P2A", filename:join(P2ADir, "start.boot")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P2A", filename:join(P2ADir, "sys.config")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ ["P2A", filename:join(P2ADir, "relup")]),
+
+ {ok, "P1I", [new_emu]} =
+ rpc:call(Node, release_handler, check_install_release, ["P2A"]),
+ ok = rpc:call(Node, release_handler, make_permanent, ["P1I"]),
+ ?check_release_client(Node,"P1I",permanent,["a-1.1"]),
+
+ %% since the install_release below reboot the node...
+ check_disallowed_calls(),
+ cover_client(TestNode,Node,stop_cover),
+
+ {ok, "P1I", [new_emu]} =
+ rpc:call(Node, release_handler, install_release, ["P2A"]),
+ %% Reboots the client !
+
+ check_reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_4(TestNode,Node).
+
+client1_4(TestNode,Node) ->
+ ?print(["client1_4 start"]),
+
+ %% Check that P2A is in use.
+ ?check_release_client(Node,"P2A",current,["a-1.1"]),
+ ?check_running_app_client(Node,a,"1.1"),
+ X = rpc:call(Node, a, a, []),
+ {key2, newval2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+ {ok, bval} = rpc:call(Node, a, b, []),
+
+ %% Reboot from P1I
+ check_disallowed_calls(),
+ reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_5(TestNode,Node).
+
+client1_5(TestNode,Node) ->
+ ?print(["client1_5 start"]),
+
+ %% Check that P1I is used
+ {ok, "P1I", [new_emu]} =
+ rpc:call(Node, release_handler, check_install_release, ["P2A"]),
+
+ %% since the install_release below will reboot the node...
+ check_disallowed_calls(),
+ cover_client(TestNode,Node,stop_cover),
+
+ %% Install P2A again
+ {ok, "P1I", [new_emu]} =
+ rpc:call(Node, release_handler, install_release, ["P2A"]),
+
+ %% We are rebooted again.
+ check_reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_6(TestNode,Node).
+
+client1_6(TestNode,Node) ->
+ ?print(["client1_6 start"]),
+
+ %% Check that P2A is used
+ ?check_release_client(Node,"P2A",current,["a-1.1"]),
+ ?check_running_app_client(Node,a,"1.1"),
+ X = rpc:call(Node, a, a, []),
+ {key2, newval2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+ {ok, bval} = rpc:call(Node, a, b, []),
+
+ %% Make P2A permanent
+ ok = rpc:call(Node, release_handler, make_permanent, ["P2A"]),
+
+ %% Reboot from P2A
+ check_disallowed_calls(),
+ reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_7(TestNode,Node).
+
+client1_7(TestNode,Node) ->
+ ?print(["client1_7 start"]),
+
+ %% Check that P2A is used
+ ?check_release_client(Node,"P2A",permanent,["a-1.1"]),
+
+ %% since the reboot_old_release below will reboot the node
+ check_disallowed_calls(),
+ cover_client(TestNode,Node,stop_cover),
+
+ %% Install old P1H
+ rpc:call(Node, release_handler, reboot_old_release, ["P1H"]),
+ %% We are rebooted.
+ check_reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_8(TestNode,Node).
+
+client1_8(TestNode,Node) ->
+ ?print(["client1_8 start"]),
+
+ %% Check that P1H is permanent
+ ?check_release_client(Node,"P1H",permanent,["a-1.0"]),
+ X = rpc:call(Node, a, a, []),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+
+ %% Remove P1I and P2I from client
+ ok = rpc:call(Node, release_handler, set_removed, ["P2A"]),
+ ok = rpc:call(Node, release_handler, set_removed, ["P1I"]),
+
+ check_disallowed_calls(),
+ reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_9(TestNode,Node).
+
+client1_9(TestNode,Node) ->
+ ?print(["client1_9 start"]),
+
+ %% Check that P2A and P1I does not exists and that PiH is permanent.
+ Rels = rpc:call(Node, release_handler, which_releases, []),
+ false = lists:keysearch("P2A", 2, Rels),
+ false = lists:keysearch("P1I", 2, Rels),
+ ?check_release_client(Node,"P1H",permanent,["a-1.0"]),
+ X = rpc:call(Node, a, a, []),
+ {key2, val2} = lists:keyfind(key2, 1, X),
+ {key1, val1} = lists:keyfind(key1, 1, X),
+
+ %% since the reboot_old_release below will reboot the node
+ check_disallowed_calls(),
+ cover_client(TestNode,Node,stop_cover),
+
+ %% Install old P1G
+ rpc:call(Node, release_handler, reboot_old_release, ["P1G"]),
+ %% We are rebooted.
+ check_reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_10(TestNode,Node).
+
+client1_10(TestNode,Node) ->
+ ?print(["client1_10 start"]),
+
+ %% Check that P1G is permanent
+ ?check_release_client(Node,"P1G",permanent,[]),
+ ?check_release_client(Node,"P1H",old,["a-1.0"]),
+ {error,client_node} = rpc:call(Node,release_handler,remove_release,["P1H"]),
+ ok = rpc:call(Node, release_handler, set_removed, ["P1H"]),
+
+ check_disallowed_calls(),
+ reboot(TestNode,Node),
+ trace_disallowed_calls(Node),
+
+ client1_11(TestNode,Node).
+
+client1_11(TestNode,Node) ->
+ ?print(["client1_11 start"]),
+
+ %% Check that P1G is permanent
+ ?check_release_client(Node,"P1G",permanent,[]),
+
+ check_disallowed_calls(),
+ stop_client(TestNode,Node), %% TEST IS OK !!
+ net_kernel:monitor_nodes(false),
+
+ ok = release_handler:remove_release("P2A"),
+ ok = release_handler:remove_release("P1I"),
+ ok = release_handler:remove_release("P1H"),
+ ok.
+
+%% Start tracing of the file module on the client node. This module
+%% shall never be called, since
+%% 1) the node is a client from the release_handler's point of view,
+%% so all file access should be done via rpc calls to the master
+%% 2) it is started with erl_prim_loader loader set to 'inet' so all
+%% code loading should be done via the inet to the master
+%% (OTP-9142)
+%% This function is called each time the client node is started and to
+%% check if a call has been made, call check_disallowed_node/0
+trace_disallowed_calls(Node) ->
+ MasterProc = self(),
+ rpc:call(Node,dbg,tracer,[process,{fun(T,_) -> MasterProc ! T end,[]}]),
+ rpc:call(Node,dbg,p,[all,call]),
+ rpc:call(Node,dbg,tp,[file,[]]).
+
+check_disallowed_calls() ->
+ receive
+ Trace when element(1,Trace)==trace ->
+ exit({disallowed_function_call,Trace})
+ after 0 ->
+ ok
+ end.
+
+start_client(TestNode,Client) ->
+ {Start, Node} = do_start_client(Client,test_host()),
+ Cmd = lists:concat(["env NODENAME=",Client," ",
+ filename:join(code:root_dir(), Start)]),
+ ?print([{start_client,Client},Cmd]),
+ Res = os:cmd(Cmd),
+ ?print([{start_client,result},Res]),
+ receive
+ {nodeup, Node} ->
+ wait_started(TestNode,Node)
+ after 30000 ->
+ ?print([{start_client,failed,Node},net_adm:ping(Node)]),
+ ?fail({"can not start", Node})
+ end.
+
+do_start_client(Client, Host) ->
+ Node = list_to_atom(lists:concat([Client,"@",Host])),
+ Start = filename:join(["clients", "type1", Node, "bin", "start"]),
+ {Start, Node}.
+
+reboot(TestNode,Node) ->
+ cover_client(TestNode,Node,stop_cover),
+ rpc:call(Node, init, reboot, []),
+ check_reboot(TestNode,Node).
+
+%% This way of checking that the node is rebooted will only work if
+%% the nodes are automatically re-connected after the reboot. This
+%% happens for master/client (when sasl is started on the client).
+check_reboot(TestNode,Node) ->
+ receive
+ {nodedown, Node} ->
+ receive
+ {nodeup, Node} -> wait_started(TestNode,Node)
+ after 30000 ->
+ ?fail({Node, "not rebooted",net_adm:ping(Node)})
+ end
+ after 30000 ->
+ ?fail({Node, "not closing down",net_adm:ping(Node)})
+ end.
+
+stop_client(TestNode,Node) ->
+ cover_client(TestNode,Node,stop_cover),
+ rpc:call(Node, init, stop, []),
+ receive
+ {nodedown, Node} -> ok
+ after 30000 ->
+ ?fail({Node, "not stopping"})
+ end.
+
+wait_started(TestNode,Node) ->
+ case rpc:call(Node, init, get_status, []) of
+ {started, _} ->
+ cover_client(TestNode,Node,start_cover),
+ Node;
+ _ ->
+ timer:sleep(1000),
+ wait_started(TestNode,Node)
+ end.
+
+cover_client(TestNode,Node,Func) ->
+ R = rpc:call(TestNode,release_handler_SUITE,Func,[Node]),
+ ?print([{Func,Node,R}]).
+
+
+%%-----------------------------------------------------------------
+%% This test starts a client node which uses this node as master
+%% for the release_handler.
+%% The client node has the name cli2@HOSTNAME.
+%% The client node is not allowed to do ANY release updates
+%% as it also have another (non-existing) master node.
+%%
+%% The to_erl /tmp/cli2@HOSTNAME/ command can be used to connect
+%% to the client node.
+%% run_erl logs for the client can be found in the directory:
+%% code:root_dir() ++ "/clients/type1/cli2@HOSTNAME/log
+%%-----------------------------------------------------------------
+client2(TestNode,PrivDir,ClientSname) ->
+ TestHost = test_host(),
+ ?print(["client2 start"]),
+
+ %% Clean up if previous test case failed
+ release_handler:remove_release("P1H"),
+
+ ok = net_kernel:monitor_nodes(true),
+ Node = start_client(TestNode,ClientSname),
+
+ %% Check env var for SASL on client node
+ ?print([{sasl_env, Node}, rpc:call(Node, application, get_all_env, [sasl])]),
+ SaslEnv = rpc:call(Node, application, get_all_env, [sasl]),
+ {_,CliDir} = lists:keyfind(client_directory,1,SaslEnv),
+ {_,[Master,Master2]} = lists:keyfind(masters,1,SaslEnv),
+ {_,StartCli} = lists:keyfind(start_prg,1,SaslEnv),
+ Root = code:root_dir(),
+ true = (CliDir =:= filename:join([Root,"clients","type1",Node])),
+ true = (StartCli =:= filename:join([CliDir,"bin","start"])),
+ true = (Master =:= node()),
+ true = (Master2 =:= list_to_atom("master2@"++TestHost)),
+
+ {ok, "P1H"} = unpack_release(PrivDir,"rel1"),
+
+ {error,{bad_masters,[Master2]}} =
+ rpc:call(Node, release_handler, set_unpacked,
+ [filename:join([Root, "releases", "P1H", "rel1.rel"]),[]]),
+
+ {error,{no_such_release,"P1H"}} =
+ rpc:call(Node, release_handler, check_install_release, ["P1H"]),
+
+ stop_client(TestNode,Node), %% TEST IS OK !!
+ net_kernel:monitor_nodes(false),
+
+ release_handler:remove_release("P1H"),
+ ok.
+
+
+stop(Now) ->
+ %% The timestamp is only used for debugging. It is printed by
+ %% release_handler_SUITE also.
+ R = init:stop(),
+ erlang:display({init_stop,Now,R}),
+ R.
+
+unpack_p1h(TestNode,PrivDir) ->
+ {ok, "P1H"} = unpack_release(PrivDir,"rel1"),
+ ?check_release("P1H",unpacked,["a-1.0"]),
+ ok.
+
+permanent_p1h(TestNode) ->
+ ?check_release("P1H",unpacked,["a-1.0"]),
+ {ok,"P1G",[new_appl]} = release_handler:install_release("P1H"),
+ ?check_release("P1H",current,["a-1.0"]),
+ ok = release_handler:make_permanent("P1H"),
+ ?check_release("P1H",permanent,["a-1.0"]),
+ ok.
+
+
+reg_proc(Name) ->
+ catch unregister(Name),
+ Pid = spawn_link(?MODULE, registered_loop, [Name]),
+ global:register_name(Name, Pid),
+ ok.
+
+registered_loop(_Name) ->
+ receive
+ kill ->
+ exit(killed)
+ end.
+
+check_release(TestNode,Node,Vsn,Status,Apps,Line) ->
+ case rpc:call(Node,release_handler,which_releases,[]) of
+ {badrpc,_}=Error ->
+ ?fail_line(Line,{check_release,Node,Vsn,Status,Error});
+ Rels ->
+ ?print_line(Line,["check_release:", Rels]),
+ {"SASL-test", Vsn, Libs, Status} = lists:keyfind(Vsn, 2, Rels),
+ true = lists:all(fun(App) -> lists:member(App,Libs) end,Apps),
+ ok
+ end.
+
+check_running_app(TestNode,Node,App,Vsn,Line) ->
+ case rpc:call(Node,application,which_applications,[]) of
+ {badrpc,_}=Error ->
+ ?fail_line(Line,{check_running_app,Node,App,Vsn,Error});
+ Apps ->
+ ?print_line(Line,["check_running_app:", Apps]),
+ {App, _, Vsn} = lists:keyfind(a, 1, Apps),
+ ok
+ end.
+
+test_host() ->
+ {ok,Host} = inet:gethostname(),
+ Host.
+
+unpack_release(PrivDir,Rel) ->
+ copy(filename:join([PrivDir,Rel,Rel++".tar.gz"]),
+ filename:join(code:root_dir(),releases)),
+ release_handler:unpack_release(Rel).
+
+copy(Src, DestDir) ->
+ Dest = filename:join(DestDir, filename:basename(Src)),
+ {ok,_} = file:copy(Src, Dest),
+ ok.
+
diff --git a/lib/sasl/test/overload_SUITE.erl b/lib/sasl/test/overload_SUITE.erl
new file mode 100644
index 0000000000..92b1aaed6e
--- /dev/null
+++ b/lib/sasl/test/overload_SUITE.erl
@@ -0,0 +1,175 @@
+%%
+%% %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%
+%%
+
+-module(overload_SUITE).
+-include("test_server.hrl").
+
+-compile(export_all).
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() -> [info, set_config_data, set_env_vars, request, timeout].
+all(suite) -> all().
+
+init_per_testcase(_Case,Config) ->
+ restart_sasl(),
+ Config.
+
+end_per_testcase(Case,Config) ->
+ try apply(?MODULE,Case,[cleanup,Config])
+ catch error:undef -> ok
+ end,
+ ok.
+
+%%%-----------------------------------------------------------------
+info(suite) -> [];
+info(_Config) ->
+ ?line Info = overload:get_overload_info(),
+ ?line [{total_intensity,0.0},
+ {accept_intensity,0.0},
+ {max_intensity,0.8},
+ {weight,0.1},
+ {total_requests,0},
+ {accepted_requests,0}] = Info.
+
+%%%-----------------------------------------------------------------
+set_config_data(suite) -> [];
+set_config_data(_Config) ->
+ ?line InfoDefault = overload:get_overload_info(),
+ ?line ok = check_info(0.8,0.1,InfoDefault),
+ ?line ok = overload:set_config_data(0.5,0.4),
+ ?line Info1 = overload:get_overload_info(),
+ ?line ok = check_info(0.5,0.4,Info1),
+ ok.
+
+%%%-----------------------------------------------------------------
+set_env_vars(suite) -> [];
+set_env_vars(_Config) ->
+ ?line InfoDefault = overload:get_overload_info(),
+ ?line ok = check_info(0.8,0.1,InfoDefault),
+ ?line ok = application:set_env(sasl,overload_max_intensity,0.5),
+ ?line ok = application:set_env(sasl,overload_weight,0.4),
+ ?line ok = application:stop(sasl),
+ ?line ok = application:start(sasl),
+ ?line Info1 = overload:get_overload_info(),
+ ?line ok = check_info(0.5,0.4,Info1),
+ ok.
+set_env_vars(cleanup,_Config) ->
+ application:unset_env(sasl,overload_max_intensity),
+ application:unset_env(sasl,overload_weight),
+ ok.
+
+%%%-----------------------------------------------------------------
+request(suite) -> [];
+request(_Config) ->
+ %% Find number of request that can be done with default settings
+ %% and no delay
+ ?line overload:set_config_data(0.8, 0.1),
+ ?line NDefault = do_many_requests(0),
+ ?line restart_sasl(),
+ ?line ?t:format("NDefault: ~p",[NDefault]),
+
+ %% Check that the number of requests increases when max_intensity
+ %% increases
+ ?line overload:set_config_data(2, 0.1),
+ ?line NLargeMI = do_many_requests(0),
+ ?line restart_sasl(),
+ ?line ?t:format("NLargeMI: ~p",[NLargeMI]),
+ ?line true = NLargeMI > NDefault,
+
+ %% Check that the number of requests decreases when weight
+ %% increases
+ ?line overload:set_config_data(0.8, 1),
+ ?line NLargeWeight = do_many_requests(0),
+ ?line restart_sasl(),
+ ?line ?t:format("NLargeWeight: ~p",[NLargeWeight]),
+ ?line true = NLargeWeight < NDefault,
+
+ %% Check that number of requests increases when delay between
+ %% requests increases.
+ %% (Keeping same config and comparing to large weight in order to
+ %% minimize the time needed for this case.)
+ ?line overload:set_config_data(0.8, 1),
+ ?line NLargeTime = do_many_requests(500),
+ ?line restart_sasl(),
+ ?line ?t:format("NLargeTime: ~p",[NLargeTime]),
+ ?line true = NLargeTime > NLargeWeight,
+ ok.
+
+%%%-----------------------------------------------------------------
+timeout(suite) -> [];
+timeout(_Config) ->
+ ?line overload:set_config_data(0.8, 1),
+ ?line _N = do_many_requests(0),
+
+ %% Check that the overload alarm is raised
+ ?line [{overload,_}] = alarm_handler:get_alarms(),
+
+ %% Fake a clear timeout in overload.erl and check that, since it
+ %% came very soon after the overload situation, the alarm is not
+ %% cleared
+ ?line overload ! timeout,
+ ?line timer:sleep(1000),
+ ?line [{overload,_}] = alarm_handler:get_alarms(),
+
+ %% A bit later, try again and check that this time the alarm is
+ %% cleared
+ ?line overload ! timeout,
+ ?line timer:sleep(1000),
+ ?line [] = alarm_handler:get_alarms(),
+
+ ok.
+
+
+%%%-----------------------------------------------------------------
+%%% INTERNAL FUNCTIONS
+
+%%%-----------------------------------------------------------------
+%%% Call overload:request/0 up to 30 times with the given time delay
+%%% between. Stop when 'reject' is returned.
+do_many_requests(T) ->
+ 30 - do_requests(30,T).
+
+do_requests(0,_) ->
+ ?t:fail(never_rejected);
+do_requests(N,T) ->
+ case overload:request() of
+ accept ->
+ timer:sleep(T),
+ do_requests(N-1,T);
+ reject ->
+ N
+ end.
+
+%%%-----------------------------------------------------------------
+%%% Restart the sasl application
+restart_sasl() ->
+ application:stop(sasl),
+ application:start(sasl),
+ ok.
+
+%%%-----------------------------------------------------------------
+%%% Check that max_intensity and weight is set as expected
+check_info(MI,W,Info) ->
+ case {lists:keyfind(max_intensity,1,Info), lists:keyfind(weight,1,Info)} of
+ {{_,MI},{_,W}} -> ok;
+ _ -> ?t:fail({unexpected_info,MI,W,Info})
+ end.
+
+
diff --git a/lib/sasl/test/rb_SUITE.erl b/lib/sasl/test/rb_SUITE.erl
new file mode 100644
index 0000000000..b53c382609
--- /dev/null
+++ b/lib/sasl/test/rb_SUITE.erl
@@ -0,0 +1,606 @@
+%%
+%% %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%
+%%
+
+-module(rb_SUITE).
+-include("test_server.hrl").
+
+-compile(export_all).
+
+-define(SUP,rb_SUITE_sup).
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+all() ->
+ no_group_cases() ++ [{group,running_error_logger}].
+
+no_group_cases() ->
+ [help,
+ start_error_stop].
+
+groups() ->
+ [{running_error_logger,[shuffle],[show,
+ list,
+ rescan,
+ start_stop_log,
+ grep,
+ filter_filter,
+ filter_date,
+ filter_filter_and_date,
+ filter_re_no
+ ]}].
+
+
+all(suite) ->
+ no_group_cases() ++
+ [{conf,
+ install_mf_h,
+ element(3,lists:keyfind(running_error_logger,1,groups())),
+ remove_mf_h}
+ ].
+
+
+init_per_suite(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line RbDir = filename:join(PrivDir,rb),
+ ?line ok = file:make_dir(RbDir),
+ NewConfig = [{rb_dir,RbDir}|Config],
+ reset_sasl(NewConfig),
+ NewConfig.
+
+end_per_suite(_Config) ->
+ ok.
+
+init_per_group(running_error_logger,Config) ->
+ install_mf_h(Config).
+
+end_per_group(running_error_logger,Config) ->
+ remove_mf_h(Config).
+
+init_per_testcase(_Case,Config) ->
+ case whereis(?SUP) of
+ undefined -> ok;
+ Pid -> kill(Pid)
+ end,
+ empty_error_logs(Config),
+ Config.
+
+kill(Pid) ->
+ Ref = erlang:monitor(process,Pid),
+ exit(Pid,kill),
+ receive {'DOWN', Ref, process, Pid, _Info} -> ok end.
+
+end_per_testcase(Case,Config) ->
+ try apply(?MODULE,Case,[cleanup,Config])
+ catch error:undef -> ok
+ end,
+ ok.
+
+
+%%%-----------------------------------------------------------------
+
+help() -> help(suite).
+help(suite) -> [];
+help(_Config) ->
+ ?line Help = capture(fun() -> rb:h() end),
+ ?line "Report Browser Tool - usage" = hd(Help),
+ ?line "rb:stop - stop the rb_server" = lists:last(Help),
+ ok.
+
+
+start_error_stop() -> start_error_stop(suite).
+start_error_stop(suite) -> [];
+start_error_stop(Config) ->
+ ?line RbDir = ?config(rb_dir,Config),
+
+ ?line {error,{"cannot locate report directory",_}} = rb:start(),
+
+
+ ?line ok = application:set_env(sasl,error_logger_mf_dir,"invaliddir"),
+ ?line ok = application:set_env(sasl,error_logger_mf_maxbytes,1000),
+ ?line ok = application:set_env(sasl,error_logger_mf_maxfiles,2),
+ ?line restart_sasl(),
+ ?line {error,{"cannot read the index file",_}} = rb:start(),
+ ?line ok = application:set_env(sasl,error_logger_mf_dir,RbDir),
+ ?line restart_sasl(),
+ ?line {ok,_} = rb:start(),
+
+ ?line ok = rb:stop(),
+ ok.
+
+
+%% start_opts(suite) -> [];
+%% start_opts(Config) ->
+%% PrivDir = ?config(priv_dir,Config),
+%% RbDir = filename:join(PrivDir,rb_opts),
+%% ok = file:make_dir(RbDir),
+
+
+install_mf_h(Config) ->
+ ?line RbDir = ?config(rb_dir,Config),
+ ?line ok = application:set_env(sasl,error_logger_mf_dir,RbDir),
+ ?line ok = application:set_env(sasl,error_logger_mf_maxbytes,5000),
+ ?line ok = application:set_env(sasl,error_logger_mf_maxfiles,2),
+ ?line restart_sasl(),
+ Config.
+
+remove_mf_h(_Config) ->
+ ok.
+
+
+
+show() -> show(suite).
+show(suite) -> [];
+show(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+ %% Insert some reports in the error log and start rb
+ init_error_logs(),
+ ?line ok = start_rb(OutFile),
+
+ %% Show all reports
+ ?line All = check_report(fun() -> rb:show() end,OutFile),
+
+ %% Show by number
+ ?line [{_,First}] = check_report(fun() -> rb:show(1) end,OutFile),
+ ?line {1,First} = lists:keyfind(1,1,All),
+
+ %% Show by type
+ ?line [{_,CR}] = check_report(fun() -> rb:show(crash_report) end,OutFile),
+ ?line true = contains(CR,"rb_test_crash"),
+ ?line [{_,EC},{_,EM}] = check_report(fun() -> rb:show(error) end,OutFile),
+ ?line true = contains(EC,"rb_test_crash"),
+ ?line true = contains(EM,"rb_test_error_msg"),
+ ?line [{_,ER}] = check_report(fun() -> rb:show(error_report) end,OutFile),
+ ?line true = contains(ER,"rb_test_error"),
+ ?line [{_,IR}] = check_report(fun() -> rb:show(info_report) end,OutFile),
+ ?line true = contains(IR,"rb_test_info"),
+ ?line [{_,IM}] = check_report(fun() -> rb:show(info_msg) end,OutFile),
+ ?line true = contains(IM,"rb_test_info_msg"),
+ ?line [_|_] = check_report(fun() -> rb:show(progress) end,OutFile),
+ ?line [{_,SR}] = check_report(fun() -> rb:show(supervisor_report) end,
+ OutFile),
+ ?line true = contains(SR,"child_terminated"),
+ ?line true = contains(SR,"{rb_SUITE,rb_test_crash}"),
+
+ ok.
+
+list() -> list(suite).
+list(suite) -> [];
+list(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+ %% Insert some reports in the error log and start rb
+ init_error_logs(),
+ ?line ok = start_rb(OutFile),
+
+ ?line All = capture(fun() -> rb:list() end),
+ ?line [{crash_report,[_]=CR},
+ {error,[_,_]=EM},
+ {error_report,[_]=ER},
+ {info_msg,[_]=IM},
+ {info_report,[_]=IR},
+ {progress,[_|_]=P},
+ {supervisor_report,[_]=SR}] = sort_list(All),
+
+ ?line [{crash_report,CR}] =
+ sort_list(capture(fun() -> rb:list(crash_report) end)),
+ ?line [{error,EM}] =
+ sort_list(capture(fun() -> rb:list(error) end)),
+ ?line [{error_report,ER}] =
+ sort_list(capture(fun() -> rb:list(error_report) end)),
+ ?line [{info_msg,IM}] =
+ sort_list(capture(fun() -> rb:list(info_msg) end)),
+ ?line [{info_report,IR}] =
+ sort_list(capture(fun() -> rb:list(info_report) end)),
+ ?line [{progress,P}] =
+ sort_list(capture(fun() -> rb:list(progress) end)),
+ ?line [{supervisor_report,SR}] =
+ sort_list(capture(fun() -> rb:list(supervisor_report) end)),
+
+ ok.
+
+
+grep() -> grep(suite).
+grep(suite) -> [];
+grep(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+ %% Insert some reports in the error log and start rb
+ init_error_logs(),
+ ?line ok = start_rb(OutFile),
+
+ ?line [{_,S},
+ {_,CR},
+ {_,EC},
+ {_,IM},
+ {_,IR},
+ {_,EM},
+ {_,ER}]= check_report(fun() -> rb:grep("rb_test_") end,OutFile),
+ ?line true = contains(S, "rb_test_crash"),
+ ?line true = contains(CR, "rb_test_crash"),
+ ?line true = contains(EC, "rb_test_crash"),
+ ?line true = contains(IM, "rb_test_info_msg"),
+ ?line true = contains(IR, "rb_test_info"),
+ ?line true = contains(EM, "rb_test_error_msg"),
+ ?line true = contains(ER, "rb_test_error"),
+ ok.
+
+
+filter_filter() -> filter_filter(suite).
+filter_filter(suite) -> [];
+filter_filter(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+ %% Insert some reports in the error log and start rb
+ init_error_logs(),
+ ?line ok = start_rb(OutFile),
+
+ ?line All = check_report(fun() -> rb:show() end,OutFile),
+
+ ?line ER = [_] = rb_filter([{rb_SUITE,rb_test_error}],OutFile),
+ ?line [] = rb_filter([{rb_SUITE,rb_test}],OutFile),
+ ?line _E = [_,_] = rb_filter([{rb_SUITE,"rb_test",re}],OutFile),
+ ?line AllButER = rb_filter([{rb_SUITE,rb_test_error,no}],OutFile),
+
+ {_,AllRep} = lists:unzip(All),
+ {_,ERRep} = lists:unzip(ER),
+ {_,AllButERRep} = lists:unzip(AllButER),
+ ?line AllButERRep = AllRep -- ERRep,
+
+ ok.
+
+filter_date() -> filter_date(suite).
+filter_date(suite) -> [];
+filter_date(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+
+ %% Insert some reports in the error log and start rb
+ init_error_logs(),
+ Between1 = calendar:local_time(),
+ timer:sleep(1000),
+ Between2 = calendar:local_time(),
+ ?line ok = start_rb(OutFile),
+
+ ?line All = check_report(fun() -> rb:show() end,OutFile),
+
+ Before = calendar:gregorian_seconds_to_datetime(
+ calendar:datetime_to_gregorian_seconds(calendar:local_time()) - 10),
+ After = calendar:gregorian_seconds_to_datetime(
+ calendar:datetime_to_gregorian_seconds(calendar:local_time()) + 1),
+
+ ?line All = rb_filter([],{Before,from},OutFile),
+ ?line All = rb_filter([],{After,to},OutFile),
+ ?line [] = rb_filter([],{Before,to},OutFile),
+ ?line [] = rb_filter([],{After,from},OutFile),
+ ?line All = rb_filter([],{Before,After},OutFile),
+
+ %%?t:format("~p~n",[All]),
+ ?line AllButLast = [{N-1,R} || {N,R} <- tl(All)],
+ ?line AllButLast = rb_filter([],{Before,Between1},OutFile),
+
+ ?line Last = hd(All),
+ ?line [Last] = rb_filter([],{Between2,After},OutFile),
+
+ ok.
+
+filter_filter_and_date() -> filter_filter_and_date(suite).
+filter_filter_and_date(suite) -> [];
+filter_filter_and_date(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+
+ %% Insert some reports in the error log and start rb
+ init_error_logs(),
+ Between1 = calendar:local_time(),
+ timer:sleep(1000),
+ Between2 = calendar:local_time(),
+ ?line error_logger:error_report([{rb_SUITE,rb_test_filter}]),
+ ?line ok = start_rb(OutFile),
+
+ Before = calendar:gregorian_seconds_to_datetime(
+ calendar:datetime_to_gregorian_seconds(calendar:local_time()) - 10),
+ After = calendar:gregorian_seconds_to_datetime(
+ calendar:datetime_to_gregorian_seconds(calendar:local_time()) + 1),
+
+ ?line All = check_report(fun() -> rb:show() end,OutFile),
+ ?line Last = hd(All),
+
+ ?line [_,_,_] = rb_filter([{rb_SUITE,"rb_test",re}],{Before,After},OutFile),
+ ?line [_,_] = rb_filter([{rb_SUITE,"rb_test",re}],{Before,Between1},OutFile),
+ ?line [_] = rb_filter([{rb_SUITE,"rb_test",re}],{Between2,After},OutFile),
+ ?line [_] = rb_filter([{rb_SUITE,rb_test_filter}],{Before,After},OutFile),
+ ?line [] = rb_filter([{rb_SUITE,rb_test_filter}],{Before,Between1},OutFile),
+ ?line [Last] = rb_filter([{rb_SUITE,rb_test_filter,no}],{Between2,After},OutFile),
+ ?line {_,Str} = Last,
+ ?line false = contains(Str,"rb_test_filter"),
+
+ ok.
+
+
+filter_re_no() -> filter_re_no(suite).
+filter_re_no(suite) -> [];
+filter_re_no(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+ %% Insert some reports in the error log and start rb
+ init_error_logs(),
+ ?line ok = start_rb(OutFile),
+
+ ?line All = check_report(fun() -> rb:show() end,OutFile),
+
+ ?line E = [_,_] = rb_filter([{rb_SUITE,"rb_test",re}],OutFile),
+ ?line AllButE = rb_filter([{rb_SUITE,"rb_test",re,no}],OutFile),
+
+ {_,AllRep} = lists:unzip(All),
+ {_,ERep} = lists:unzip(E),
+ {_,AllButERep} = lists:unzip(AllButE),
+ ?line AllButERep = AllRep -- ERep,
+
+ ok.
+
+
+rescan() -> rescan(suite).
+rescan(suite) -> [];
+rescan(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+
+ %% Start rb
+ ?line ok = start_rb(OutFile),
+
+ %% Insert one more report and check that the list is longer. Note
+ %% that there might be two more reports, since the progress report
+ %% from starting rb_server might not be included before the rescan.
+ ?line AllBefore = capture(fun() -> rb:list() end),
+ ?line error_logger:error_report([{rb_SUITE,rb_test_rescan}]),
+ ?line ok = rb:rescan(),
+ ?line AllAfter = capture(fun() -> rb:list() end),
+ ?line Diff = length(AllAfter) - length(AllBefore),
+ ?line true = (Diff >= 1),
+
+ ok.
+
+
+start_stop_log() -> start_stop_log(suite).
+start_stop_log(suite) -> [];
+start_stop_log(Config) ->
+ ?line PrivDir = ?config(priv_dir,Config),
+ ?line OutFile = filename:join(PrivDir,"rb_SUITE_log.txt"),
+ ?line ok = file:write_file(OutFile,[]),
+
+ %% Start rb and check that show is printed to standard_io
+ ?line ok = start_rb(),
+ ?line StdioResult = [_|_] = capture(fun() -> rb:show(1) end),
+ ?line {ok,<<>>} = file:read_file(OutFile),
+
+ %% Start log and check that show is printed to log and not to standad_io
+ ?line ok = rb:start_log(OutFile),
+ ?line [] = capture(fun() -> rb:show(1) end),
+ ?line {ok,Bin} = file:read_file(OutFile),
+ ?line true = (Bin =/= <<>>),
+
+ %% Stop log and check that show is printed to standard_io and not to log
+ ?line ok = rb:stop_log(),
+ ?line ok = file:write_file(OutFile,[]),
+ ?line StdioResult = capture(fun() -> rb:show(1) end),
+ ?line {ok,<<>>} = file:read_file(OutFile),
+
+ %% Test that standard_io is used if log file can not be opened
+ ?line ok = rb:start_log(filename:join(nonexistingdir,"newfile.txt")),
+ ?line StdioResult = capture(fun() -> rb:show(1) end),
+ ?line {ok,<<>>} = file:read_file(OutFile),
+
+ ok.
+
+
+%%%-----------------------------------------------------------------
+%%% INTERNAL FUNCTIONS
+
+restart_sasl() ->
+ application:stop(sasl),
+ ok = application:start(sasl),
+ wait_for_sasl().
+
+reset_sasl(Config) ->
+ application:unset_env(sasl,error_logger_mf_dir),
+ application:unset_env(sasl,error_logger_mf_maxbytes),
+ application:unset_env(sasl,error_logger_mf_maxfiles),
+ empty_error_logs(Config).
+
+empty_error_logs(Config) ->
+ application:stop(sasl),
+ catch delete_content(?config(rb_dir, Config)),
+ ok = application:start(sasl),
+ wait_for_sasl().
+
+wait_for_sasl() ->
+ wait_for_sasl(50).
+wait_for_sasl(0) ->
+ ?t:fail("sasl application did not start within 5 seconds");
+wait_for_sasl(N) ->
+ case lists:keymember(sasl,1,application:which_applications()) of
+ true ->
+ ok;
+ false ->
+ timer:sleep(100),
+ wait_for_sasl(N-1)
+ end.
+
+start_rb(OutFile) ->
+ do_start_rb([{start_log,OutFile}]).
+start_rb() ->
+ do_start_rb([]).
+
+do_start_rb(Opts) ->
+ {ok,Pid} = rb:start(Opts),
+
+ %% Wait for process to started, then wait a little bit more
+ sys:get_status(Pid),
+ timer:sleep(500),
+
+ %% Make sure printouts (e.g. from rb:list(), come to the test log,
+ %% and that they can be captured.
+ group_leader(group_leader(),Pid),
+ ok.
+
+
+delete_tree(Dir) ->
+ case filelib:is_dir(Dir) of
+ true ->
+ delete_content(Dir),
+ file:del_dir(Dir);
+ false ->
+ ok = file:delete(Dir)
+ end.
+
+delete_content(Dir) ->
+ {ok,Files} = file:list_dir(Dir),
+ lists:foreach(fun(File) -> delete_tree(filename:join(Dir,File)) end,
+ Files).
+
+init_error_logs() ->
+ ?line error_logger:error_report([{rb_SUITE,rb_test_error}]),
+ ?line error_logger:error_msg("rb_test_error_msg"),
+ ?line error_logger:info_report([{rb_SUITE,rb_test_info}]),
+ ?line error_logger:info_msg("rb_test_info_msg"),
+ ?line _Pid = start(),
+ ?line Ref = erlang:monitor(process,?MODULE),
+ ?line gen_server:cast(?MODULE,crash),
+ ?line receive {'DOWN',Ref,process,_,{rb_SUITE,rb_test_crash}} -> ok
+ after 2000 ->
+ ?t:format("Got: ~p~n",[process_info(self(),messages)]),
+ ?t:fail("rb_SUITE server never died")
+ end,
+ ?line erlang:demonitor(Ref),
+ ?line wait_for_server(),
+ ok.
+
+wait_for_server() ->
+ case whereis(?MODULE) of
+ undefined ->
+ wait_for_server();
+ Pid ->
+ timer:sleep(100), % allow the supervisor report to be written
+ Pid
+ end.
+
+capture(Fun) ->
+ ?t:capture_start(),
+ ok = Fun(),
+ timer:sleep(1000),
+ ?t:capture_stop(),
+ string:tokens(lists:append(?t:capture_get()),"\n").
+
+
+rb_filter(Filter,OutFile) ->
+ check_report(fun() -> rb:filter(Filter) end, OutFile).
+rb_filter(Filter,Dates,OutFile) ->
+ check_report(fun() -> rb:filter(Filter,Dates) end, OutFile).
+
+
+%% This function first empties the given report file, then executes
+%% the fun and returns a list of {N,Report}, where Report is a report
+%% read from the file and N is an integer. The newest report has the
+%% lowest number.
+%% If the fun was a call to rb:show() (i.e. with no arguments), then
+%% the numbering (N) will be the same as rb's own numbering (as shown
+%% by rb:list()).
+check_report(Fun,File) ->
+ file:delete(File),
+ rb:rescan([{start_log,File}]),
+ ok = Fun(),
+ {ok,Bin} = file:read_file(File),
+ Reports = split_reports(binary_to_list(Bin),[],[]),
+ lists:zip(lists:seq(1,length(Reports)),Reports).
+
+-define(report_header_line,"\n===============================================================================\n").
+split_reports([],Report,Reports) ->
+ add_report(Report,Reports);
+split_reports(Text,Report,Reports) ->
+ case Text of
+ ?report_header_line++Rest ->
+ {Heading,PrevReport} = lists:splitwith(fun($\n) -> false;
+ (_) -> true
+ end,
+ Report),
+ split_reports(Rest,
+ ?report_header_line++Heading,
+ add_report(PrevReport,Reports));
+ [Ch|Rest] ->
+ split_reports(Rest,[Ch|Report],Reports)
+ end.
+
+add_report(Report,Reports) ->
+ case string:strip(Report,both,$\n) of
+ [] -> Reports;
+ Report1 -> [lists:reverse(Report1)|Reports]
+ end.
+
+%% Returns true if Substr is a substring of Str.
+contains(Str,Substr) ->
+ 0 =/= string:str(Str,Substr).
+
+%% Sort the result of rb_list after report type
+sort_list(List) ->
+ sort_list(List,dict:new()).
+sort_list([H|T],D) ->
+ case re:run(H,"\s+[0-9]+\s+([a-z_]+)",[{capture,all_but_first,list}]) of
+ nomatch ->
+ sort_list(T,D);
+ {match,[TypeStr]} ->
+ sort_list(T,dict:append(list_to_atom(TypeStr),H,D))
+ end;
+sort_list([],D) ->
+ lists:sort(dict:to_list(D)).
+
+
+%%%-----------------------------------------------------------------
+%%% A dummy supervisor and gen_server used for creating crash- and
+%%% supervisor reports
+start() ->
+ {ok,Pid} =
+ supervisor:start_link({local, ?SUP}, ?MODULE, i_am_supervisor),
+ unlink(Pid),
+ Pid.
+start_server() ->
+ gen_server:start_link({local, ?MODULE}, ?MODULE, i_am_server, []).
+init(i_am_server) ->
+ {ok, state};
+init(i_am_supervisor) ->
+ AChild = {?SUP,{?MODULE,start_server,[]},
+ permanent,2000,worker,[?MODULE]},
+ {ok,{{one_for_all,1,1}, [AChild]}}.
+handle_call(_Request, _From, State) ->
+ Reply = ok,
+ {reply, Reply, State}.
+handle_cast(crash, State) ->
+ exit({rb_SUITE,rb_test_crash}),
+ {noreply, State}.
+handle_info(_Info, State) ->
+ {noreply, State}.
+terminate(_Reason, _State) ->
+ ok.
+
diff --git a/lib/sasl/test/release_handler_SUITE.erl b/lib/sasl/test/release_handler_SUITE.erl
new file mode 100644
index 0000000000..efa775f344
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE.erl
@@ -0,0 +1,1651 @@
+%%
+%% %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%
+%%
+-module(release_handler_SUITE).
+
+-include_lib("common_test/include/ct.hrl").
+
+-compile(export_all).
+
+% Default timetrap timeout (set in init_per_testcase).
+%-define(default_timeout, ?t:minutes(40)).
+-define(default_timeout, ?t:minutes(10)).
+
+suite() ->
+ [{ct_hooks, [ts_install_cth]}].
+
+init_per_suite(Config) ->
+ application:start(sasl),
+ Config.
+
+end_per_suite(_Config) ->
+ ok.
+
+all() ->
+ case os:type() of
+ {unix, _} -> unix_cases();
+ {win32, _} -> win32_cases()
+ end.
+
+unix_cases() ->
+ RunErl = filename:join([code:root_dir(),"bin","run_erl"]),
+ RunErlCases = case filelib:is_file(RunErl) of
+ true -> [{group, release}];
+ false -> [no_run_erl]
+ end,
+ [target_system] ++ RunErlCases ++ cases().
+
+win32_cases() ->
+ cases().
+
+%% Cases that can be run on all platforms
+cases() ->
+ [otp_2740, otp_2760, otp_5761, instructions, eval_appup].
+
+groups() ->
+ [{release,[],
+ [
+ {group,release_single},
+ {group,release_gg}
+ ]},
+ {release_single,[],
+ [
+ upgrade,
+ client1,
+ client2
+ ]},
+ {release_gg,[],
+ [
+ upgrade_gg
+ ]}].
+
+%% {group,release}
+%% Top group for all cases using run_erl
+init_per_group(release, Config) ->
+ Dog = ?t:timetrap(?default_timeout),
+ P1gInstall = filename:join(priv_dir(Config),p1g_install),
+ ok = do_create_p1g(Config,P1gInstall),
+ ok = create_p1h(Config),
+ ?t:timetrap_cancel(Dog);
+
+%% {group,release_single}
+%% Subgroup of {group,release}, contains all cases that are not
+%% related to global_group
+init_per_group(release_single, Config) ->
+ Dog = ?t:timetrap(?default_timeout),
+
+ %% Create some more releases to upgrade to
+ ok = create_p1i(Config),
+ ok = create_p2a(Config),
+
+ ?t:timetrap_cancel(Dog);
+
+%% {group,release_gg}
+%% Subgroup of {group,release}. global_group tests.
+init_per_group(release_gg, Config0) ->
+ Config = [{sname_prefix,release_gg}|Config0],
+
+ PrivDir = priv_dir(Config),
+ Dog = ?t:timetrap(?default_timeout),
+
+ reg_print_proc(), %% starts a printer process on this node
+
+ Snames = [Gg1Sname,Gg2Sname,Gg3Sname,Gg4Sname,Gg5Sname,Gg6Sname] =
+ gg_node_snames(Config),
+
+ %% kill all possible nodes which are to be used
+ ok = stop_nodes([node_name(Sname) || Sname <- Snames]),
+
+ %% For gg1, gg3, gg4 and gg5: create a target system running
+ %% P1G, and with P1H unpacked.
+ %% For gg2 and gg6: create a target system running P1H.
+ %% Use gg2 for unpacking and permanenting P1H.
+ ok = copy_installed(Config,p1g_install,[Gg2Sname]),
+ InstallNode = unpack_p1h(Config,Gg2Sname),
+ ok = copy_installed(Config,Gg2Sname,[Gg1Sname,Gg3Sname,Gg4Sname,Gg5Sname]),
+ ok = permanent_p1h(InstallNode),
+ ok = stop_nodes([InstallNode]),
+ ok = copy_installed(Config,Gg2Sname,[Gg6Sname]),
+
+ %% Replace the sys.config files
+ %% The reason for not creating the releases with these configs in
+ %% the first place (create_p1g, create_p1h) is that then the
+ %% InstallNode (gg2) will be very slow started since it will try
+ %% to synch with the other nodes in the global group.
+ %% Also, the rpc call for installing the P1H release (in
+ %% permanent_p1h/1) would return {rpc,nodedown} due to change of
+ %% global groups.
+ lists:foreach(
+ fun(Sname) ->
+ ReleasesDir = filename:join([PrivDir,Sname,"releases"]),
+ write_term_file(filename:join([ReleasesDir,"P1G","sys.config"]),
+ gg_config([Gg1Sname,Gg3Sname,Gg4Sname,Gg5Sname])),
+ write_term_file(filename:join([ReleasesDir,"P1H","sys.config"]),
+ gg_config([Gg1Sname,Gg2Sname,Gg4Sname,
+ Gg5Sname,Gg6Sname]))
+ end,
+ Snames),
+
+ ?t:timetrap_cancel(Dog),
+ [{snames,Snames}|Config].
+
+
+end_per_group(release, Config) ->
+ Dog = ?t:timetrap(?default_timeout),
+ stop_print_proc(),
+ delete_release(Config),
+ ?t:timetrap_cancel(Dog),
+ Config;
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+init_per_testcase(Case, Config0) ->
+ Dog = test_server:timetrap(?default_timeout),
+ Config = [{sname_prefix,Case},{watchdog, Dog}|Config0],
+ try apply(?MODULE,Case,[cleanup,Config])
+ catch error:undef -> ok
+ end,
+ ?t:format("~n======= init_per_testcase done =======~n",[]),
+ Config.
+
+end_per_testcase(Case, Config) ->
+ ?t:format("~n======= start end_per_testcase =======~n",[]),
+ Dog=?config(watchdog, Config),
+ test_server:timetrap_cancel(Dog),
+
+ %% DEBUG
+ case ?config(tc_status,Config) of
+ ok ->
+ ok;
+ _Fail ->
+ %% save logs from master and client nodes
+ PrivDir = priv_dir(Config),
+ SaveDir = filename:join(PrivDir,save),
+ FailDir = filename:join(SaveDir,lists:concat(["failed-",Case])),
+ ok = filelib:ensure_dir(filename:join(FailDir,"*")),
+
+ LogDirs = filelib:wildcard(filename:join([PrivDir,"*",log])),
+
+ lists:foreach(
+ fun(LogDir) ->
+ ["log",Sname|_] = lists:reverse(filename:split(LogDir)),
+ copy_tree(Config,LogDir,Sname,FailDir)
+ end,
+ LogDirs),
+
+ case filelib:is_file("sasl_erl_crash.dump") of
+ true ->
+ copy_file("sasl_erl_crash.dump",FailDir);
+ _ ->
+ ok
+ end
+
+ end,
+ %% End DEBUG
+
+ %% Remove any remaining sasl_erl_crash.dump
+ %% These can occur when a new master@<host> is started, before
+ %% the old usage of the name is unregistered, causing the node to
+ %% terminate. (This has no effect on the test case, as the node is
+ %% immediately restarted by heart and the test cases wait until
+ %% the node is actually up and running -- see wait_nodes_up/2)
+ file:delete("sasl_erl_crash.dump"),
+
+ try apply(?MODULE,Case,[cleanup,Config])
+ catch error:undef -> ok
+ end,
+ ok.
+
+gg_node_snames(Config) ->
+ [tc_sname(Config,X) || X <- [gg1,gg2,gg3,gg4,gg5,gg6]].
+
+
+%%%-----------------------------------------------------------------
+%%% TEST CASES
+
+
+%% Executed instead of release group when no run_erl program exists
+no_run_erl(Config) when is_list(Config) ->
+ {comment, "No run_erl program"}.
+
+
+
+%% Test upgrade and downgrade of erts
+upgrade(Conf) when is_list(Conf) ->
+ reg_print_proc(), %% starts a printer process on test_server node
+ ?t:format("upgrade ~p~n",[reg_print_proc]),
+ PrivDir = priv_dir(Conf),
+ Sname = tc_sname(Conf), % nodename for use in this testcase
+
+ %% Copy the P1G release to a directory for use in this testcase
+ ok = copy_installed(Conf,p1g_install,[Sname]),
+
+ %% start the test node
+ [TestNode] = start_nodes(Conf,[Sname],"upgrade start"),
+
+ %% unpack and install P1H
+ ok = rpc_inst(TestNode, install_1, [PrivDir]),
+ stop_cover(TestNode),
+ reboot_and_wait(TestNode,"install_1"),
+
+ %% reinstall P1H and make it permanent
+ ok = rpc_inst(TestNode, install_2, []),
+ stop_cover(TestNode),
+ reboot_and_wait(TestNode,"install_2",[a]),
+
+ %% check that P1H is permanent, unpack and install P1I, unpack and install P2A
+ TestNodeInit1 = rpc:call(TestNode,erlang,whereis,[init]),
+ ok = rpc_inst(TestNode, install_3, [PrivDir]),
+ stop_cover(TestNode),
+ ok = rpc_inst(TestNode, install_3a, []),
+ wait_nodes_up([{TestNode,TestNodeInit1}],"install_3",[a]),
+
+ %% check that P2A is used, reboot from P1I
+ ok = rpc_inst(TestNode, install_4, []),
+ stop_cover(TestNode),
+ reboot_and_wait(TestNode,"install_4",[a]),
+
+ %% check that P1I, reinstall P2A
+ TestNodeInit2 = rpc:call(TestNode,erlang,whereis,[init]),
+ ok = rpc_inst(TestNode, install_5, []),
+ stop_cover(TestNode),
+ ok = rpc_inst(TestNode, install_5a, []),
+ wait_nodes_up([{TestNode,TestNodeInit2}],"install_5",[a]),
+
+ %% check that P2A is used, make P2A permanent
+ ok = rpc_inst(TestNode, install_6, []),
+ stop_cover(TestNode),
+ reboot_and_wait(TestNode,"install_6",[a]),
+
+ %% check that P2A is permanent, install old P1H
+ TestNodeInit3 = rpc:call(TestNode,erlang,whereis,[init]),
+ stop_cover(TestNode),
+ ok = rpc_inst(TestNode, install_7, []),
+ wait_nodes_up([{TestNode,TestNodeInit3}],"install_7",[a]),
+
+ %% check that P1H is permanent, remove P1I and P2A
+ ok = rpc_inst(TestNode, install_8, []),
+ stop_cover(TestNode),
+ reboot_and_wait(TestNode,"install_8",[a]),
+
+ %% check that P1H is permanent, reboot old P1G
+ TestNodeInit4 = rpc:call(TestNode,erlang,whereis,[init]),
+ stop_cover(TestNode),
+ ok = rpc_inst(TestNode, install_9, []),
+ wait_nodes_up([{TestNode,TestNodeInit4}],"install_9"),
+
+ %% check that P1G is permanent, remove P1H
+ ok = rpc_inst(TestNode, install_10, []),
+ stop_cover(TestNode),
+ reboot_and_wait(TestNode,"install_10"),
+
+ %% check that P1G is permanent
+ ok = rpc_inst(TestNode, install_11, []),
+
+ ok.
+
+upgrade(cleanup,Config) ->
+ TestNode = tc_full_node_name(Config),
+ ok = stop_nodes([TestNode]).
+
+reboot_and_wait(Node,Tag) ->
+ reboot_and_wait(Node,Tag,[]).
+
+reboot_and_wait(Node,Tag,Apps) ->
+ InitPid = rpc:call(Node,erlang,whereis,[init]),
+ ok = rpc:call(Node,init,reboot,[]),
+ wait_nodes_up([{Node,InitPid}],Tag,Apps).
+
+
+%% Test upgrade and downgrade of erts, diskless
+client1(Conf) when is_list(Conf) ->
+ reg_print_proc(), %% starts a printer process on test_server node
+ PrivDir = priv_dir(Conf),
+ Master = tc_sname(Conf,master),
+ Client = tc_sname(Conf,client),
+ MasterDir = filename:join(PrivDir,Master),
+
+ %% Copy the P1G release to a directory for use in this testcase
+ ok = copy_installed(Conf,p1g_install,[Master]),
+ ok = copy_client(Conf,Master,Client,"start_cli1"),
+
+ %% start the master node
+ [TestNode] = start_nodes(Conf,[Master],"client1"),
+
+ ok = rpc_inst(TestNode, client1_1, [PrivDir,MasterDir,Client]),
+
+ ok.
+
+client1(cleanup,Config) ->
+ MasterNode = tc_full_node_name(Config,master),
+ ClientNode = tc_full_node_name(Config,client),
+ ok = stop_nodes([MasterNode,ClientNode]).
+
+
+
+%% Test diskless release handling when illegal master node
+client2(Conf) when is_list(Conf) ->
+ reg_print_proc(), %% starts a printer process on test_server node
+ PrivDir = priv_dir(Conf),
+ Master = tc_sname(Conf,master),
+ Client = tc_sname(Conf,client),
+
+ %% Copy the P1G release to a directory for use in this testcase
+ ok = copy_installed(Conf,p1g_install,[Master]),
+ ok = copy_client(Conf,Master,Client,"start_cli2"),
+
+ %% start the master node
+ [TestNode] = start_nodes(Conf,[Master],"client2"),
+
+ ok = rpc_inst(TestNode, client2, [PrivDir,Client]),
+
+ ok.
+
+client2(cleanup,Config) ->
+ MasterNode = tc_full_node_name(Config,master),
+ ClientNode = tc_full_node_name(Config,client),
+ ok = stop_nodes([MasterNode,ClientNode]).
+
+
+
+%% Test instructions _not_ tested by the installer module.
+instructions(Conf) when is_list(Conf) ->
+ DataDir = ?config(data_dir, Conf),
+
+ Dir = filename:join(DataDir, "c"),
+ true = code:add_path(Dir),
+ check_bstate("no", []),
+ ok = application:start(c),
+ ok = wait_for(bb),
+ check_bstate("first", []),
+ FirstBB = whereis(bb),
+
+ case whereis(cc) of
+ Pid when is_pid(Pid) -> ok;
+ _ -> ?t:fail("cc not started")
+ end,
+
+ %% Stop and start cc process
+ S1 = [point_of_no_return,
+ {stop, [aa]},
+ {apply, {?MODULE, no_cc, []}},
+ {start, [aa]}],
+ {ok, _} = release_handler_1:eval_script(S1, [], []),
+
+ case whereis(cc) of
+ Pid2 when is_pid(Pid2) -> ok;
+ _ -> ?t:fail("cc not started")
+ end,
+
+ %% Make bb run old version of b.
+ S2 = [point_of_no_return,
+ {remove, {b, soft_purge, soft_purge}}],
+ {ok, [{b, soft_purge}]} = release_handler_1:eval_script(S2, [], []),
+ check_bstate("first", [FirstBB]),
+
+ false = code:is_loaded(b),
+ {error,{old_processes,b}} = release_handler_1:eval_script(S2,[],[]),
+ check_bstate("first", [FirstBB]),
+
+ %% Let supervisor restart bb with new code
+ S3 = [point_of_no_return,
+ {purge, [b]}],
+ {ok, []} = release_handler_1:eval_script(S3, [], []),
+ ok = wait_for(bb),
+ check_bstate("second", []),
+ SecondBB = whereis(bb),
+
+ if
+ SecondBB =:= FirstBB -> ?t:fail("bb not killed");
+ true -> ok
+ end,
+
+ %% Restart bb yet another time
+ ok = application:stop(c),
+ ok = application:start(c),
+ ok = wait_for(bb),
+ check_bstate("third", []),
+ ThirdBB = whereis(bb),
+
+ case ThirdBB of
+ _ when is_pid(ThirdBB) -> ok;
+ undefined -> ?t:fail("bb not started")
+ end,
+
+ %% Make bb run old version of b.
+ %%c:l(b),
+ check_bstate("third", []),
+ false = code:purge(b),
+ check_bstate("third", []),
+ {module,b} = code:load_file(b),
+ check_bstate("third", [ThirdBB]),
+
+ %% Let supervisor restart bb yet another time
+ S4 = [point_of_no_return,
+ {remove, {b, brutal_purge, soft_purge}}],
+ {ok, HopefullyEmpty} = release_handler_1:eval_script(S4, [], []),
+ ok = wait_for(bb),
+ FourthBB = whereis(bb),
+
+ case HopefullyEmpty of
+ [{b, soft_purge}] ->
+ %% The process managed to start between purge and delete
+ check_bstate("fourth", [FourthBB]);
+ [] ->
+ %% The process started after delete
+ check_bstate("fourth", [])
+ end,
+
+ application:stop(c),
+ check_bstate("no", []),
+ ok.
+
+instructions(cleanup,Conf) ->
+ application:stop(c),
+ really_del_code([aa,b,c_sup]),
+ code:del_path(filename:join(?config(data_dir,Conf), "c")),
+ ok.
+
+really_del_code(Mods) ->
+ lists:foreach(fun(Mod) ->
+ code:purge(Mod), % remove old code
+ code:delete(Mod),% make current code old
+ code:purge(Mod) % remove old code
+ end,
+ Mods).
+
+check_bstate(Slogan,ExpectedProcs) ->
+ BB = whereis(bb),
+ ActualProcs = lists:sort([P || P <- processes(),
+ erlang:check_process_code(P, b)]),
+ ExpectedProcs2 = lists:sort(ExpectedProcs),
+ ?t:format("check_bstate:~n~p~n~p~n",
+ [{"bb process", Slogan, BB},
+ {"Processes running old b code", ActualProcs}]),
+ if
+ Slogan =:= "no", BB =/= undefined ->
+ ?t:fail("instructions failed; process bb is running");
+ Slogan =/= "no", BB =:= undefined ->
+ ?t:fail("instructions failed; process bb is not running");
+ ExpectedProcs2 =:= [], ActualProcs =/= ExpectedProcs2 ->
+ ?t:fail("instructions failed; old b processes are running");
+ ActualProcs =/= ExpectedProcs2 ->
+ ?t:fail("instructions failed; wrong number of old b processes are running");
+ true ->
+ ok
+ end.
+
+wait_for(Name) ->
+ case whereis(Name) of
+ undefined ->
+ timer:sleep(100),
+ wait_for(Name);
+ Pid when is_pid(Pid) ->
+ ok
+ end.
+
+no_cc() ->
+ case whereis(cc) of
+ Pid when is_pid(Pid) -> ?t:fail("cc not stopped");
+ _ -> ok
+ end.
+
+
+
+%%%-----------------------------------------------------------------
+%%% Testing of reported bugs and other tickets.
+%%%-----------------------------------------------------------------
+
+%%-----------------------------------------------------------------
+%% Ticket: OTP-2740
+%% Slogan: vsn not numeric doesn't work so good in release_handling
+%%-----------------------------------------------------------------
+%% Test vsn.
+otp_2740(Conf) ->
+ DataDir = ?config(data_dir, Conf),
+ Dir = filename:join(DataDir, "otp_2740"),
+ true = code:add_path(Dir),
+
+ {module, vsn_numeric} = c:l(vsn_numeric),
+ {module, vsn_tuple} = c:l(vsn_tuple),
+ {module, vsn_list} = c:l(vsn_list),
+ {module, vsn_atom} = c:l(vsn_atom),
+ {module, vsn_string} = c:l(vsn_string),
+
+ 231894 = release_handler_1:get_current_vsn(vsn_numeric),
+ {tuple,["of",terms]} = release_handler_1:get_current_vsn(vsn_tuple),
+ [list,"of",{some,terms}] = release_handler_1:get_current_vsn(vsn_list),
+ atom = release_handler_1:get_current_vsn(vsn_atom),
+ "a string" = release_handler_1:get_current_vsn(vsn_string),
+
+ true = code:del_path(Dir),
+ ok.
+
+%%-----------------------------------------------------------------
+%% Ticket: OTP-2760
+%% Slogan: when an application is removed from a node it is not unloaded
+%%-----------------------------------------------------------------
+%% Test that when an application is removed from a node it is also unloaded.
+otp_2760(Conf) ->
+ PrivDir = priv_dir(Conf),
+ Dir = filename:join(PrivDir,"otp_2760"),
+ DataDir = ?config(data_dir,Conf),
+ LibDir = filename:join([DataDir,app1_app2,lib1]),
+
+ Rel1 = create_and_install_fake_first_release(Dir,[{app1,"1.0",LibDir}]),
+ Rel2 = create_fake_upgrade_release(Dir,"after",[],{Rel1,Rel1,[LibDir]}),
+ Rel2Dir = filename:dirname(Rel2),
+
+ %% Start a node with Rel1.boot and check that the app1 module is loaded
+ {ok, Node} = t_start_node(otp_2760, Rel1, []),
+ {file, _} = rpc:call(Node, code, is_loaded, [app1]),
+
+ %% Execute the relup script and check that app1 is unloaded
+ {ok, [{"after", [{_Rel1Vsn, _Descr, Script}], _}]} =
+ file:consult(filename:join(Rel2Dir, "relup")),
+ {ok, []} = rpc:call(Node, release_handler_1, eval_script,
+ [Script, [], []]),
+ false = rpc:call(Node, code, is_loaded, [app1]),
+
+ true = stop_node(Node),
+ ok.
+
+%% Test upgrade using other filesystem than the defined in OTP and
+%% option {update_paths, true}
+otp_5761(Conf) when is_list(Conf) ->
+
+ %% In the following test case, the release upgrade is somewhat
+ %% simplified (since it is not this procedure in itself we want to
+ %% test, but that application code directories are set correctly.)
+ %% Existing Erlang release is used as base, instead of creating
+ %% a new one.
+
+ %% Set some paths
+ PrivDir = priv_dir(Conf),
+ Dir = filename:join(PrivDir,"otp_5761"),
+ RelDir = filename:join(?config(data_dir, Conf), "app1_app2"),
+ LibDir1 = filename:join(RelDir, "lib1"),
+ LibDir2 = filename:join(RelDir, "lib2"),
+
+ %% Create the releases
+ Rel1 = create_and_install_fake_first_release(Dir,
+ [{app1,"1.0",LibDir1},
+ {app2,"1.0",LibDir1}]),
+ Rel2 = create_fake_upgrade_release(Dir,
+ "2",
+ [{app1,"2.0",LibDir2},
+ {app2,"1.0",LibDir2}],
+ {Rel1,Rel1,[LibDir1]}),
+ Rel1Dir = filename:dirname(Rel1),
+ Rel2Dir = filename:dirname(Rel2),
+
+ %% Start a slave node
+ {ok, Node} = t_start_node(otp_5761, Rel1, filename:join(Rel1Dir,"sys.config")),
+
+ %% Bind some variable names that will be used in patternmatching below
+ App11Dir = filename:join([LibDir1, "app1-1.0"]),
+ App12Dir = filename:join([LibDir2, "app1-2.0"]),
+ App2aDir = filename:join([LibDir1, "app2-1.0"]),
+ App2bDir = filename:join([LibDir2, "app2-1.0"]),
+
+ %% Make sure correct code paths are used
+ App11Dir = rpc:call(Node, code, lib_dir, [app1]),
+ App2aDir = rpc:call(Node, code, lib_dir, [app2]),
+
+ %% Unpack rel2 (make sure it does not work if an AppDir is bad)
+ LibDir3 = filename:join(RelDir, "lib3"),
+ {error, {no_such_directory, _}} =
+ rpc:call(Node, release_handler, set_unpacked,
+ [Rel2++".rel", [{app1,"2.0",LibDir2}, {app2,"1.0",LibDir3}]]),
+ {ok, RelVsn2} =
+ rpc:call(Node, release_handler, set_unpacked,
+ [Rel2++".rel", [{app1,"2.0",LibDir2}, {app2,"1.0",LibDir2}]]),
+ ok = rpc:call(Node, release_handler, install_file,
+ [RelVsn2, filename:join(Rel2Dir, "relup")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ [RelVsn2, filename:join(Rel2Dir, "start.boot")]),
+ ok = rpc:call(Node, release_handler, install_file,
+ [RelVsn2, filename:join(Rel2Dir, "sys.config")]),
+
+ %% Install RelVsn2 without {update_paths, true} option
+ {ok, RelVsn1, []} =
+ rpc:call(Node, release_handler, install_release, [RelVsn2]),
+ App12Dir = rpc:call(Node, code, lib_dir, [app1]),
+ App2aDir = rpc:call(Node, code, lib_dir, [app2]),
+
+ %% Install RelVsn1 again
+ {ok, RelVsn1, []} =
+ rpc:call(Node, release_handler, install_release, [RelVsn1]),
+
+ %% Install RelVsn2 with {update_paths, true} option
+ {ok, RelVsn1, []} =
+ rpc:call(Node, release_handler, install_release,
+ [RelVsn2, [{update_paths, true}]]),
+ App12Dir = rpc:call(Node, code, lib_dir, [app1]),
+ App2bDir = rpc:call(Node, code, lib_dir, [app2]),
+
+ %% Install RelVsn1 again
+ {ok, RelVsn1, []} =
+ rpc:call(Node, release_handler, install_release,
+ [RelVsn1, [{update_paths, true}]]),
+ App11Dir = rpc:call(Node, code, lib_dir, [app1]),
+ App2aDir = rpc:call(Node, code, lib_dir, [app2]),
+
+ %% Stop the slave node
+ true = stop_node(Node),
+ ok.
+
+%% Test upgrade and downgrade of applications
+eval_appup(Conf) when is_list(Conf) ->
+
+ %% OTP-6162
+ %% Create an ETS table which is updated by app1 if there is any
+ %% change made to the application configuration parameter 'var'
+ %% (see config_change/3 in myrel/lib1|2/app1-1|2.0/src/app1.erl)
+ ets:new(otp_6162, [set, public, named_table]),
+
+ %% Set some paths
+ RelDir = filename:join(?config(data_dir, Conf), "app1_app2"),
+ App11Dir = filename:join([RelDir, "lib1", "app1-1.0"]),
+ App12Dir = filename:join([RelDir, "lib2", "app1-2.0"]),
+ EbinDir = filename:join(App11Dir, "ebin"),
+
+ %% Start app1-1.0
+ code:add_patha(EbinDir),
+ ok = application:start(app1),
+ App11Dir = code:lib_dir(app1),
+ ok = gen_server:call(harry, error),
+
+ %% Upgrade to app1-2.0
+ {ok, []} = release_handler:upgrade_app(app1, App12Dir),
+ App12Dir = code:lib_dir(app1),
+ error = gen_server:call(harry, error),
+
+ %% OTP-6162
+ %% Value of config parameter 'var' should now be 'val2'
+ %% (see myrel/lib2/app1-2.0/ebin/app1.app)
+ [{var,val2}] = ets:lookup(otp_6162, var),
+
+ %% Downgrade to app1-1.0
+ {ok, []} = release_handler:downgrade_app(app1,"1.0",App11Dir),
+ App11Dir = code:lib_dir(app1),
+ ok = gen_server:call(harry, error),
+
+ %% OTP-6162
+ %% Value of config parameter 'var' should now be 'val1'
+ %% (see myrel/lib1/app1-1.0/ebin/app1.app)
+ [{var,val1}] = ets:lookup(otp_6162, var),
+
+ ok = application:stop(app1),
+ ok = application:unload(app1),
+
+ true = code:del_path(EbinDir),
+ ok.
+
+
+%% Test the example/target_system.erl module
+target_system(Conf) when is_list(Conf) ->
+ PrivDir = priv_dir(Conf),
+ DataDir = ?config(data_dir,Conf),
+
+ TargetCreateDir = filename:join([PrivDir,"target_system","create"]),
+ TargetInstallDir = filename:join([PrivDir,"target_system","install"]),
+
+ ok = filelib:ensure_dir(filename:join(TargetCreateDir,"xx")),
+ ok = filelib:ensure_dir(filename:join(TargetInstallDir,"xx")),
+
+
+ %% Create the .rel file
+ ErtsVsn = erlang:system_info(version),
+ RelName = filename:join(TargetCreateDir,"ts-1.0"),
+ RelFile = RelName++".rel",
+ RelVsn = "R1A",
+ create_rel_file(RelFile,RelName,RelVsn,ErtsVsn,[{a, "1.0"}]),
+
+ %% Build the target_system module
+ ExamplesEbin = filename:join([code:lib_dir(sasl),examples,ebin]),
+ TSPath =
+ case filelib:is_file(filename:join(ExamplesEbin,"target_system.beam")) of
+ true ->
+ ExamplesEbin;
+ false ->
+ {ok,_} =
+ compile:file(filename:join(DataDir,"target_system.erl"),
+ [{outdir,TargetCreateDir}]),
+ TargetCreateDir
+ end,
+ code:add_path(TSPath),
+
+ %% Create the release
+ target_system:create(RelName,[{path,[filename:join([DataDir,
+ lib,
+ "a-1.0",
+ ebin])]}]),
+
+ %% Install the release
+ target_system:install(RelName,TargetInstallDir),
+
+ code:del_path(TSPath),
+
+ %% Check that all files exist in installation
+ true = filelib:is_dir(filename:join(TargetInstallDir,"erts-"++ErtsVsn)),
+ LibDir = filename:join(TargetInstallDir,lib),
+ {ok,KernelVsn} = application:get_key(kernel,vsn),
+ {ok,StdlibVsn} = application:get_key(stdlib,vsn),
+ {ok,SaslVsn} = application:get_key(sasl,vsn),
+ true = filelib:is_dir(filename:join(LibDir,"kernel-"++KernelVsn)),
+ true = filelib:is_dir(filename:join(LibDir,"stdlib-"++StdlibVsn)),
+ true = filelib:is_dir(filename:join(LibDir,"sasl-"++SaslVsn)),
+ true = filelib:is_dir(filename:join(LibDir,"a-1.0")),
+ RelDir = filename:join(TargetInstallDir,releases),
+ true = filelib:is_regular(filename:join(RelDir,"RELEASES")),
+ true = filelib:is_regular(filename:join(RelDir,"start_erl.data")),
+ true = filelib:is_regular(filename:join(RelDir,
+ filename:basename(RelFile))),
+ true = filelib:is_dir(filename:join(RelDir,RelVsn)),
+ true = filelib:is_regular(filename:join([RelDir,RelVsn,"start.boot"])),
+ BinDir = filename:join(TargetInstallDir,bin),
+ true = filelib:is_regular(filename:join(BinDir,"start.boot")),
+ true = filelib:is_regular(filename:join(BinDir,erl)),
+ true = filelib:is_regular(filename:join(BinDir,start_erl)),
+ true = filelib:is_regular(filename:join(BinDir,start)),
+ true = filelib:is_regular(filename:join(BinDir,epmd)),
+ true = filelib:is_regular(filename:join(BinDir,run_erl)),
+ true = filelib:is_regular(filename:join(BinDir,to_erl)),
+
+ %% Check content of files
+ {ok,SED} = file:read_file(filename:join(RelDir,"start_erl.data")),
+ [ErtsVsn,RelVsn] = string:tokens(binary_to_list(SED),"\s\n"),
+ ok.
+
+
+
+%%%=================================================================
+%%% Testing global groups.
+%%%=================================================================
+
+%% This test case involves P1G and P1H with the sys.config as
+%% specified in gg_config/1. The test case checks that the global
+%% group information is correct before and after the upgrade and also
+%% after terminating one of the nodes. The flow is as follows:
+%% 1. Start all four nodes of global group gg1 with P1G
+%% 2. Terminate one of the nodes, and upgrade the others to P1H. P1H
+%% config adds to more nodes to the global group.
+%% 3. Start the two remaining nodes with P1H
+upgrade_gg(Conf) ->
+ [Gg1Sname,Gg2Sname,Gg3Sname,Gg4Sname,Gg5Sname,Gg6Sname] =
+ ?config(snames,Conf),
+
+ %% start gg1, gg3, gg4, gg5 and check that global group info is ok
+ Nodes1 = [Gg1,Gg3,Gg4,Gg5] =
+ start_nodes(Conf,[Gg1Sname,Gg3Sname,Gg4Sname,Gg5Sname],"upgrade_gg"),
+
+ %% Give some time to synch nodes, then check global group info.
+ timer:sleep(1000),
+ [check_gg_info(Node,Nodes1,[],Nodes1--[Node]) || Node <- Nodes1],
+
+ %% register a process on each of the nodes
+ ok = rpc:call(Gg1, installer, reg_proc, [reg1]),
+ ok = rpc:call(Gg3, installer, reg_proc, [reg3]),
+ ok = rpc:call(Gg4, installer, reg_proc, [reg4]),
+ ok = rpc:call(Gg5, installer, reg_proc, [reg5]),
+ are_names_reg_gg(Gg1, [reg1, reg3, reg4, reg5]),
+
+ %% Stop gg3, then upgrade gg1, gg4 and gg5 to P1H
+ ok = stop_nodes([Gg3]),
+
+ ok = install_release_changed_gg(Gg1,"P1H"),
+ ok = install_release_changed_gg(Gg4,"P1H"),
+ ok = install_release_changed_gg(Gg5,"P1H"),
+
+ %% Check global group info
+ Gg2 = node_name(Gg2Sname),
+ Gg6 = node_name(Gg6Sname),
+ Nodes2 = [Gg1,Gg4,Gg5],
+ [check_gg_info(Node,Nodes2,[Gg2,Gg6],Nodes2--[Node]) || Node <- Nodes2],
+
+ %% start gg2 and gg6
+ [Gg2,Gg6] = start_nodes(Conf,[Gg2Sname,Gg6Sname],"upgrade_gg start gg2/gg6"),
+
+ %% reg proc on each of the nodes
+ ok = rpc:call(Gg2, installer, reg_proc, [reg2]),
+ ok = rpc:call(Gg6, installer, reg_proc, [reg6]),
+ are_names_reg_gg(Gg1, [reg1, reg2, reg4, reg5, reg6]),
+
+ %% Check global group info
+ Nodes3 = [Gg1,Gg2,Gg4,Gg5,Gg6],
+ [check_gg_info(Node,Nodes3,[],Nodes3--[Node]) || Node <- Nodes3],
+
+ ok.
+
+upgrade_gg(cleanup,Config) ->
+ Snames = ?config(snames,Config),
+ NodeNames = [node_name(Sname) || Sname <- Snames],
+ ok = stop_nodes(NodeNames).
+
+
+
+
+%%%=================================================================
+%%% Misceleaneous functions
+%%%=================================================================
+stop_nodes(Nodes) ->
+ ?t:format("Stopping nodes: ~p~n",[Nodes]),
+ Running =
+ lists:foldl(fun(Node,Acc) ->
+ Now = now(),
+ stop_cover(Node),
+ case rpc:call(Node,installer,stop,[Now]) of
+ {badrpc,nodedown} ->
+ Acc;
+ Other ->
+ ?t:format("Stop ~p(~p): ~p~n",
+ [Node,Now,Other]),
+ [Node|Acc]
+ end
+ end, [], Nodes),
+ wait_nodes_down(Running).
+
+
+wait_nodes_down(Nodes) ->
+ ?t:format( "wait_nodes_down ~p:",[Nodes]),
+ wait_nodes_down(Nodes, 30).
+
+wait_nodes_down(Nodes, 0) ->
+ test_server:fail({error, {"could not kill nodes", Nodes}});
+wait_nodes_down(Nodes, N) ->
+ Fun = fun(Node, A) ->
+ case net_adm:ping(Node) of
+ pong ->
+ ?t:format( " net_adm:ping(~p) = pong", [Node]),
+ [Node|A];
+ pang ->
+ ?t:format( " net_adm:ping(~p) = pang", [Node]),
+ A
+ end
+ end,
+ Pang = lists:foldl(Fun, [], Nodes),
+ case Pang of
+ [] ->
+ ?t:format("",[]),
+ ok;
+ _ ->
+ timer:sleep(1000),
+ wait_nodes_down(Pang, N-1)
+ end.
+
+
+
+wait_nodes_up(Nodes, Tag) ->
+ wait_nodes_up(Nodes, Tag, []).
+
+wait_nodes_up(Nodes0, Tag, Apps) ->
+ ?t:format("wait_nodes_up(~p, ~p, ~p):",[Nodes0, Tag, Apps]),
+ Nodes = fix_nodes(Nodes0),
+ wait_nodes_up(Nodes, Tag, lists:umerge(Apps,[kernel,stdlib,sasl]), 30).
+
+fix_nodes([{Node,InitPid}|Nodes]) ->
+ [{Node,InitPid} | fix_nodes(Nodes)];
+fix_nodes([Node|Nodes]) ->
+ [{Node,fake_init_pid} | fix_nodes(Nodes)];
+fix_nodes([]) ->
+ [].
+
+wait_nodes_up(Nodes, Tag, Apps, 0) ->
+ test_server:fail({error, {"nodes not started", Nodes, Tag, Apps}});
+wait_nodes_up(Nodes, Tag, Apps, N) ->
+ Fun =
+ fun(NodeInfo={Node,OldInitPid}, A) ->
+ case rpc:call(Node, application, which_applications, []) of
+ {badrpc, nodedown} ->
+ ?t:format( " ~p = {badarg, nodedown}",[Node]),
+ [NodeInfo | A];
+ List when is_list(List)->
+ ?t:format( " ~p = [~p]",[Node, List]),
+ case lists:all(fun(App) ->
+ lists:keymember(App,1,List)
+ end, Apps) of
+ true ->
+ case rpc:call(Node,erlang,whereis,[init]) of
+ OldInitPid ->
+ [NodeInfo | A];
+ _ ->
+ start_cover(Node),
+ A
+ end;
+ false ->
+ [NodeInfo | A]
+ end
+ end
+ end,
+ Pang = lists:foldl(Fun,[],Nodes),
+ case Pang of
+ [] ->
+ ?t:format("",[]),
+ ok;
+ _ ->
+ timer:sleep(1000),
+ wait_nodes_up(Pang, Tag, Apps, N-1)
+ end.
+
+
+
+
+are_names_reg_gg(Node, Names) ->
+ ?t:format( "are_names_reg_gg ~p~n",[Names]),
+ are_names_reg_gg(Node, Names, 30).
+
+are_names_reg_gg(Node, Names, N) ->
+ case lists:sort(rpc:call(Node, global, registered_names, [])) of
+ Names ->
+ ok;
+ Regs when N > 0 ->
+ timer:sleep(1000),
+ ?t:format( "are_names_reg_gg Regs ~p~n",[Regs]),
+ are_names_reg_gg(Node, Names, N-1);
+ Regs ->
+ ?t:fail({error, {"Names not registered",
+ {{"should :", Names},
+ {"was :", Regs}}}})
+ end.
+
+
+
+t_start_node(Name, Boot, SysConfig) ->
+ Args =
+ case Boot of
+ [] -> [];
+ _ -> " -boot " ++ Boot
+ end ++
+ case SysConfig of
+ [] -> [];
+ _ -> " -config " ++ SysConfig
+ end,
+ test_server:start_node(Name, slave, [{args, Args}]).
+
+stop_node(Node) ->
+ ?t:stop_node(Node).
+
+
+copy_client(Conf,Master,Sname,StartScript) ->
+ io:format("copy_client(Conf)"),
+
+ DataDir = ?config(data_dir, Conf),
+ MasterDir = filename:join(priv_dir(Conf),Master),
+
+ {ok,Host} = inet:gethostname(),
+ {ok,IpTuple} = inet:getaddr(Host,inet),
+ IpAddr = inet_parse:ntoa(IpTuple),
+
+ CliNode = node_name(Sname),
+
+ Cli = filename:join([MasterDir, "clients", "type1", CliNode]),
+ ok = filelib:ensure_dir(filename:join([Cli,"bin","."])),
+ ok = filelib:ensure_dir(filename:join([Cli,"releases","."])),
+ ok = filelib:ensure_dir(filename:join([Cli,"log","."])),
+
+ P1GOrig = filename:join([MasterDir, "releases", "P1G"]),
+ ok = copy_tree(Conf,P1GOrig,filename:join(Cli,"releases")),
+
+ ok = subst_file(filename:join([DataDir, "clients", StartScript]),
+ filename:join([Cli,"bin","start"]),
+ [{"ROOT",MasterDir},
+ {"MASTER",atom_to_list(Master)},
+ {"IPADDR",IpAddr}],
+ [{chmod,8#0755}]),
+
+ StartErlData = filename:join([MasterDir, "releases", "start_erl.data"]),
+ CliRelDir = filename:join([Cli, "releases"]),
+ copy_file(StartErlData, CliRelDir),
+
+ RR = filename:join([MasterDir, "releases", "RELEASES"]),
+ copy_file(RR, CliRelDir),
+
+ ok.
+
+
+delete_release(Conf) ->
+ PrivDir = priv_dir(Conf),
+
+ {ok, OrigWd} = file:get_cwd(),
+
+ ok = file:set_cwd(PrivDir),
+ ?t:format("======== current dir ~p~n",[PrivDir]),
+ {ok, Dirs} = file:list_dir(PrivDir),
+ ?t:format("======== deleting ~p~n",[Dirs]),
+
+ ok = delete_release_os(Dirs),
+ ?t:format("======== remaining ~p~n",[file:list_dir(PrivDir)]),
+ ok = file:set_cwd(OrigWd),
+ ok.
+
+
+delete_release_os(Dirs) ->
+ case os:type() of
+ {unix, _} ->
+ delete_release_unix(Dirs);
+ {win32, _} ->
+ delete_release_win32(Dirs);
+ Os ->
+ test_server:fail({error, {not_yet_implemented_os, Os}})
+ end.
+
+
+delete_release_unix([]) ->
+ ok;
+delete_release_unix(["save"|Dirs]) ->
+ delete_release_unix(Dirs);
+delete_release_unix([Dir|Dirs]) ->
+ Rm = string:concat("rm -rf ", Dir),
+ ?t:format("============== COMMAND ~p~n",[Rm]),
+ case file:list_dir(Dir) of
+ {error, enotdir} ->
+ ok;
+ X ->
+ ?t:format("------- Dir ~p~n ~p~n",[Dir, X])
+ end,
+ case os:cmd(Rm) of
+ [] ->
+ ?t:format("------- Result of COMMAND ~p~n",[ok]);
+ Y ->
+ ?t:format("!!!!!!! delete ERROR Dir ~p Error ~p~n",[Dir, Y]),
+ ?t:format("------- ls -al ~p~n",[os:cmd("ls -al " ++ Dir)])
+ end,
+
+ delete_release_unix(Dirs).
+
+delete_release_win32([]) ->
+ ok;
+delete_release_win32(["save"|Dirs]) ->
+ delete_release_win32(Dirs);
+delete_release_win32([Dir|Dirs]) ->
+ Rm = string:concat("rmdir /s ", Dir),
+ [] = os:cmd(Rm),
+ delete_release_win32(Dirs).
+
+
+node_name(Sname) when is_atom(Sname) ->
+ {ok,Host} = inet:gethostname(),
+ list_to_atom(atom_to_list(Sname) ++ "@" ++ Host).
+
+copy_file(Src, Dest) ->
+ copy_file(Src, Dest, []).
+copy_file(Src, Dest, Opts) ->
+ case file:copy(Src,Dest) of
+ {ok,_} ->
+ preserve(Src,Dest,Opts),
+ chmod(Dest,Opts),
+ ok;
+ {error,eisdir} ->
+ NewDest = filename:join(Dest, filename:basename(Src)),
+ case file:copy(Src,NewDest) of
+ {ok,_} ->
+ preserve(Src,NewDest,Opts),
+ chmod(NewDest,Opts);
+ {error,Reason} ->
+ copy_error(Src,Dest,Reason)
+ end;
+ {error,Reason} ->
+ copy_error(Src,Dest,Reason)
+ end.
+
+preserve(Src,Dest,Opts) ->
+ case lists:member(preserve, Opts) of
+ true ->
+ {ok, FileInfo} = file:read_file_info(Src),
+ ok = file:write_file_info(Dest, FileInfo);
+ false ->
+ ok
+ end.
+
+chmod(Dest,Opts) ->
+ case lists:keyfind(chmod,1,Opts) of
+ {chmod,Mode} ->
+ ok = file:change_mode(Dest, Mode);
+ false ->
+ ok
+ end.
+
+
+
+copy_error(Src, Dest, Reason) ->
+ io:format("Copy ~s to ~s failed: ~s\n",
+ [Src,Dest,file:format_error(Reason)]),
+ ?t:fail(file_copy_failed).
+
+copy_tree(Conf, Src, DestDir) ->
+ case catch copy_tree(Conf, Src, filename:basename(Src), DestDir) of
+ ok ->
+ ok;
+ {'EXIT', {{badmatch,Error},_Stack}} ->
+ %% Most probably, an erl_tar call has failed.
+ %% Known to happen on some platforms (symbolic_link_too_long)
+ Error;
+ {'EXIT', Reason} ->
+ {error, Reason}
+ end.
+
+copy_tree(Conf, Src, NewName, DestDir) ->
+ PrivDir = priv_dir(Conf),
+ TempTarName = filename:join(PrivDir, "temp_tar_file.tar"),
+ %% Not compressing tar file here since that would increase test
+ %% suite time by almost 100%, and the tar file is deleted
+ %% imediately anyway.
+ {ok,Tar} = erl_tar:open(TempTarName, [write]),
+ ok = erl_tar:add(Tar, Src, NewName, []),
+ ok = erl_tar:close(Tar),
+ ok = erl_tar:extract(TempTarName, [{cwd,DestDir}]),
+ ok = file:delete(TempTarName),
+ ok.
+
+%% subst_file(Src, Dest, Vars)
+%% Src = Dest = string(), filename and path
+%% Vars = [{Var, Val}]
+%% Var = Val = string()
+%% Substitute all occurrences of %Var% for Val in Src, using the list
+%% of variables in Vars. Result is written to Dest.
+%%
+subst_file(Src, Dest, Vars) ->
+ subst_file(Src, Dest, Vars, []).
+subst_file(Src, Dest, Vars, Opts) ->
+ {ok, Bin} = file:read_file(Src),
+ Conts = binary_to_list(Bin),
+ NConts = subst(Conts, Vars),
+ ok = file:write_file(Dest, NConts),
+ preserve(Src,Dest,Opts),
+ chmod(Dest,Opts).
+
+subst(Str, Vars) ->
+ subst(Str, Vars, []).
+
+subst([$%, C| Rest], Vars, Result) when $A =< C, C =< $Z ->
+ subst_var([C| Rest], Vars, Result, []);
+subst([$%, C| Rest], Vars, Result) when $a =< C, C =< $z ->
+ subst_var([C| Rest], Vars, Result, []);
+subst([$%, C| Rest], Vars, Result) when C == $_ ->
+ subst_var([C| Rest], Vars, Result, []);
+subst([C| Rest], Vars, Result) ->
+ subst(Rest, Vars, [C| Result]);
+subst([], _Vars, Result) ->
+ lists:reverse(Result).
+
+subst_var([$%| Rest], Vars, Result, VarAcc) ->
+ Key = lists:reverse(VarAcc),
+ case lists:keysearch(Key, 1, Vars) of
+ {value, {Key, Value}} ->
+ subst(Rest, Vars, lists:reverse(Value, Result));
+ false ->
+ subst(Rest, Vars, [$%| VarAcc ++ [$%| Result]])
+ end;
+subst_var([C| Rest], Vars, Result, VarAcc) ->
+ subst_var(Rest, Vars, Result, [C| VarAcc]);
+subst_var([], Vars, Result, VarAcc) ->
+ subst([], Vars, [VarAcc ++ [$%| Result]]).
+
+
+priv_dir(Conf) ->
+ filename:absname(?config(priv_dir, Conf)). % Get rid of trailing slash
+
+latest_version(Dir) ->
+ List = filelib:wildcard(Dir ++ "*"),
+ lists:last(lists:sort(List)).
+
+%% A printer process which receives messages from other nodes and
+%% prints in the log
+reg_print_proc() ->
+ catch unregister(rh_print),
+ Pid = spawn_link(?MODULE, rh_print, []),
+ register(rh_print, Pid),
+ ok.
+
+rh_print() ->
+ receive
+ {print, {Module,Line}, [H|T]} ->
+ ?t:format("=== ~p:~p - ~p",[Module,Line,H]),
+ lists:foreach(fun(Term) -> ?t:format(" ~p",[Term]) end, T),
+ ?t:format("",[]),
+ rh_print();
+ kill ->
+ exit(normal)
+ end.
+
+stop_print_proc() ->
+ case whereis(rh_print) of %%removes the printer process
+ undefined ->
+ ok;
+ Pid when is_pid(Pid) ->
+ rh_print ! kill
+ end.
+
+%% Create the first target release, vsn P1G. This release is used for
+%% all test cases in {group,release}
+create_p1g(Conf,Sname) ->
+ do_create_p1g(Conf,filename:join(priv_dir(Conf),Sname)).
+
+do_create_p1g(Conf,TargetDir) ->
+ PrivDir = priv_dir(Conf),
+ DataDir = ?config(data_dir,Conf),
+ ErtsVsn = "4.4",
+ ErtsDir = "erts-"++ErtsVsn,
+
+ %% Create dirs
+ BinDir = filename:join(TargetDir,bin),
+ ReleasesDir = filename:join(TargetDir,releases),
+ LogDir = filename:join(TargetDir,log),
+ ok = filelib:ensure_dir(filename:join(BinDir,"*")),
+ ok = filelib:ensure_dir(filename:join(ReleasesDir,"*")),
+ ok = filelib:ensure_dir(filename:join(LogDir,"*")),
+
+ %% Copy stuff
+ ErtsLatest = latest_version(filename:join(code:root_dir(),"erts")),
+ ok = copy_tree(Conf, ErtsLatest, ErtsDir, TargetDir),
+ ErtsBinDir = filename:join([TargetDir,ErtsDir,bin]),
+ copy_file(filename:join([ErtsBinDir, "epmd"]), BinDir, [preserve]),
+ copy_file(filename:join([ErtsBinDir, "run_erl"]), BinDir, [preserve]),
+ copy_file(filename:join([ErtsBinDir, "to_erl"]), BinDir, [preserve]),
+
+ copy_file(filename:join(DataDir, "../installer.beam"),
+ filename:join([DataDir,lib,"installer-1.0",ebin])),
+
+ %% Create .rel, .script and .boot files
+ RelName = "rel0",
+ RelVsn = "P1G",
+ RelDir = filename:join(PrivDir,RelName),
+ RelFileName = filename:join(RelDir,RelName),
+ RelFile = RelFileName ++ ".rel",
+ ok = filelib:ensure_dir(RelFile),
+ LibPath = filename:join([DataDir,lib,"*",ebin]),
+
+ TarFile = create_basic_release(RelFile, RelVsn, {ErtsVsn,false},
+ LibPath, [], [], [], []),
+
+ %% Extract tar file in target directory (i.e. same directory as erts etc.)
+ ok = erl_tar:extract(TarFile, [{cwd, TargetDir}, compressed]),
+
+ %% Create start_erl.data
+ StartErlDataFile = filename:join([ReleasesDir, "start_erl.data"]),
+ StartErlData = io_lib:fwrite("~s ~s~n", [ErtsVsn, RelVsn]),
+ ok = file:write_file(StartErlDataFile, StartErlData),
+
+ %% Create RELEASES
+ ok = release_handler:create_RELEASES(TargetDir,ReleasesDir,RelFile,[]),
+
+ %% Create start_erl
+ ok = subst_file(filename:join([ErtsBinDir,"start_erl.src"]),
+ filename:join([BinDir,"start_erl"]),
+ [{"EMU","beam"}],
+ [{chmod,8#0755}]),
+
+ %% Create start script
+ %% Using a customized start script from DataDir where some options
+ %% (heart and nodename) are added compared to the start.src in the
+ %% erlang distribution.
+ ok = subst_file(filename:join(DataDir, "start"),
+ filename:join([BinDir, "start"]),
+ [{"ROOT",TargetDir}],
+ [preserve]),
+ ok.
+
+%% Create version P1H - which is P1G + a-1.0
+%% Must have run create_p1g first!!
+create_p1h(Conf) ->
+ create_upgrade_release(Conf,"rel1","P1H",{"4.4",false},[{a,"1.0"}],
+ [{a,[{key2,val2}]}],{"rel0",[new_appl]}).
+
+%% Create version P1I - which is P1H, but with application a upgraded to a-1.1
+%% Must have run create_p1h first!!
+create_p1i(Conf) ->
+ create_upgrade_release(Conf,"rel2","P1I",{"4.4",false},[{a,"1.1"}],
+ [{a,[{key2,newval2}]}],
+ {"rel1",[{extra,gott}]}).
+
+%% Create version P2A - which is P1I, but with erts-<latest>
+%% Must have run create_p1i first!!
+create_p2a(Conf) ->
+ ErtsVsn = erlang:system_info(version),
+ create_upgrade_release(Conf,"rel3","P2A",{ErtsVsn,code:root_dir()},
+ [{a,"1.1"}],[{a,[{key2,newval2}]}],
+ {"rel2",[new_emu]}).
+
+%% Create a release tar package which can be installed on top of P1G
+create_upgrade_release(Conf,RelName,RelVsn,Erts,Apps,Config,{UpFromName,Descr}) ->
+ PrivDir = priv_dir(Conf),
+ DataDir = ?config(data_dir,Conf),
+
+ RelDir = filename:join(PrivDir,RelName),
+ RelFileName = filename:join(RelDir,RelName),
+ RelFile = RelFileName ++ ".rel",
+ ok = filelib:ensure_dir(RelFile),
+ LibPath = filename:join([DataDir,lib,"*",ebin]),
+
+ UpFrom = [{filename:join([PrivDir,UpFromName,UpFromName]),Descr}],
+
+ create_basic_release(RelFile, RelVsn, Erts, LibPath,
+ Apps, Config, UpFrom, []),
+ ok.
+
+%% Create .rel, .script, .boot, sys.config and tar
+create_basic_release(RelFile,RelVsn,{ErtsVsn,ErtsDir},LibPath,ExtraApps,Config,UpFrom,DownTo) ->
+ RelDir = filename:dirname(RelFile),
+ RelFileName = filename:rootname(RelFile),
+
+ %% Create .rel file
+ create_installer_rel_file(RelFile,RelVsn,ErtsVsn,ExtraApps),
+
+ %% Generate .script and .boot
+ ok = systools:make_script(RelFileName,
+ [{path,[LibPath]},
+ {outdir,RelDir}]),
+
+ %% Generate relup
+ ok = systools:make_relup(RelFileName,UpFrom,DownTo,[{path,[LibPath]},
+ {outdir,RelDir}]),
+
+ %% Create sys.config
+ ok = write_term_file(filename:join(RelDir,"sys.config"),Config),
+
+
+ %% Create tar file (i.e. collect all lib/app-*/* and system files)
+ ok = systools:make_tar(RelFileName,
+ [{path,[LibPath]},
+ {outdir,RelDir} |
+ case ErtsDir of
+ false -> [];
+ _ -> [{erts,ErtsDir}]
+ end]),
+
+ RelFileName ++ ".tar.gz".
+
+%% Create a .rel file
+create_installer_rel_file(RelFile,RelVsn,ErtsVsn,ExtraApps) ->
+ create_rel_file(RelFile,"SASL-test",RelVsn,ErtsVsn,
+ [{installer,"1.0"}|ExtraApps]).
+
+create_rel_file(RelFile,RelName,RelVsn,ErtsVsn,ExtraApps) ->
+ {ok,KernelVsn} = application:get_key(kernel,vsn),
+ {ok,StdlibVsn} = application:get_key(stdlib,vsn),
+ {ok,SaslVsn} = application:get_key(sasl,vsn),
+ application:load(tools),
+ {ok,ToolsVsn} = application:get_key(tools,vsn),
+ application:load(runtime_tools),
+ {ok,RuntimeToolsVsn} = application:get_key(runtime_tools,vsn),
+
+ RelFileContent = {release,
+ {RelName, RelVsn},
+ {erts, ErtsVsn},
+ [{kernel, KernelVsn},
+ {stdlib, StdlibVsn},
+ {sasl, SaslVsn},
+ {runtime_tools, RuntimeToolsVsn},
+ {tools, ToolsVsn} |
+ ExtraApps]},
+ ok = write_term_file(RelFile,RelFileContent).
+
+%% Insert a term in a file, which can be read with file:consult/1.
+write_term_file(File,Term) ->
+ ok = file:write_file(File,io_lib:format("~p.~n",[Term])).
+
+
+%% Check that global group info is correct
+check_gg_info(Node,OtherAlive,OtherDead,Synced) ->
+ GGI = rpc:call(Node, global_group, info, []),
+ GI = rpc:call(Node, global, info,[]),
+ try do_check_gg_info(OtherAlive,OtherDead,Synced,GGI,GI)
+ catch _:E ->
+ ?t:format("~ncheck_gg_info failed for ~p: ~p~nwhen GGI was: ~p~n"
+ "and GI was: ~p~n",
+ [Node,E,GGI,GI]),
+ ?t:fail("check_gg_info failed")
+ end.
+
+do_check_gg_info(OtherAlive,OtherDead,Synced,GGI,GI) ->
+ {_,gg1} = lists:keyfind(own_group_name,1,GGI),
+ {_,synced} = lists:keyfind(state,1,GGI),
+ {_,AllNodes} = lists:keyfind(own_group_nodes,1,GGI),
+ true = lists:sort(AllNodes) =:= lists:sort(OtherAlive++OtherDead),
+ {_,[]} = lists:keyfind(sync_error,1,GGI),
+ {_,[{gg2,[_,_]}]} = lists:keyfind(other_groups,1,GGI),
+
+ %% There is a known bug in global_group (OTP-9177) which causes
+ %% the following to fail every now and then:
+ %% {_,SyncedNodes} = lists:keyfind(synced_nodes,1,GGI),
+ %% true = lists:sort(SyncedNodes) =:= lists:sort(Synced),
+ %% {_,NoContact} = lists:keyfind(no_contact,1,GGI),
+ %% true = lists:sort(NoContact) =:= lists:sort(OtherDead),
+
+ %% Therefore we use global:info instead for this part
+ {state,_,_,SyncedNodes,_,_,_,_,_,_,_} = GI,
+ true = lists:sort(SyncedNodes) =:= lists:sort(Synced),
+
+ %% .. and we only check that all OtherDead are listed as
+ %% no_contact (due to th bug there might be more nodes in this
+ %% list)
+ {_,NoContact} = lists:keyfind(no_contact,1,GGI),
+ true =
+ lists:sort(OtherDead) =:=
+ lists:sort([NC || NC <- NoContact,lists:member(NC,OtherDead)]),
+
+ ok.
+
+%% Return the configuration (to be inserted in sys.config) for global group tests
+gg_config(Snames) ->
+ Nodes = [node_name(Sname) || Sname <- Snames],
+ [{kernel, [{sync_nodes_optional, Nodes},
+ {sync_nodes_timeout, 10000},
+ {global_groups,
+ [{gg1, Nodes},
+ {gg2, [node_name(Sname) || Sname <- [ggq,ggw]]}]}]},
+ {a, [{key2, val2}]}].
+
+%% Start a node with short name SnameStr, and unpack P1H
+unpack_p1h(Conf,Sname) ->
+ PrivDir = priv_dir(Conf),
+ [Node] = start_nodes(Conf,[Sname],"create_p1h"),
+ ok = rpc_inst(Node, unpack_p1h, [PrivDir]),
+ Node.
+
+%% On the given node, install P1H and make it permanent
+%% This function is to be called after unpack_p1h/2, with the same node.
+permanent_p1h(Node) ->
+ ok = rpc_inst(Node, permanent_p1h, []).
+
+%% For each node in ToNodes, create a target installation which is
+%% indentical to the target installation for FromNode.
+copy_installed(Conf,FromNode,ToNodes) ->
+ PrivDir = priv_dir(Conf),
+ DataDir = ?config(data_dir,Conf),
+ lists:foreach(
+ fun(Node) ->
+ ok = copy_tree(Conf,filename:join(PrivDir,FromNode),Node,PrivDir),
+ NodeDir = filename:join(PrivDir,Node),
+ ok = subst_file(filename:join(DataDir, "start"),
+ filename:join([NodeDir, "bin", "start"]),
+ [{"ROOT",NodeDir}]),
+ LogDir = filename:join(NodeDir,log),
+ {ok,Logs} = file:list_dir(LogDir),
+ lists:foreach(fun(Log) ->
+ file:delete(filename:join(LogDir,Log))
+ end,
+ Logs)
+ end,
+ ToNodes).
+
+start_nodes(Conf,Snames,Tag) ->
+ PrivDir = priv_dir(Conf),
+ Nodes =
+ lists:map(
+ fun(Sname) ->
+ NodeDir = filename:join(PrivDir,Sname),
+ Node = node_name(Sname),
+
+ Script = filename:join([NodeDir,"bin","start"]),
+ Cmd = "env NODENAME="++atom_to_list(Sname) ++ " " ++ Script,
+ %% {ok,StartFile} = file:read_file(Cmd),
+ %% io:format("~s:\n~s~n~n",[Start,binary_to_list(StartFile)]),
+ Res = os:cmd(Cmd),
+ io:format("Start ~p: ~p~n=>\t~p~n", [Sname,Cmd,Res]),
+ Node
+ end,
+ Snames),
+ wait_nodes_up(Nodes,Tag),
+ Nodes.
+
+tc_sname(Config) ->
+ tc_sname(Config,"").
+tc_sname(Config,Fix) when is_atom(Fix) ->
+ tc_sname(Config,atom_to_list(Fix));
+tc_sname(Config,Fix) when is_list(Fix) ->
+ list_to_atom(
+ atom_to_list(?MODULE)
+ ++ "-" ++ atom_to_list(?config(sname_prefix, Config)) ++
+ case Fix of
+ "" -> "";
+ _ -> "-" ++ Fix
+ end).
+
+tc_full_node_name(Config) ->
+ tc_full_node_name(Config,"").
+tc_full_node_name(Config,Fix) ->
+ node_name(tc_sname(Config,Fix)).
+
+
+%% When installing a release for which the sys.config includes added
+%% or changed global group(s), this node (test_sever@host) will be
+%% disconnected from the test node (Node) by global_group.erl. This
+%% will cause the rpc:call to terminate with {badrpc,nodedown} even if
+%% the installation succeeds. This function installs the release,
+%% accepts the faulty return value and then checks if the release was
+%% successfully installed.
+install_release_changed_gg(Node,RelVsn) ->
+ stop_cover(Node),
+ {badrpc,nodedown} = rpc:call(Node,release_handler,install_release,[RelVsn]),
+ timer:sleep(100),
+ wait_installed(Node,RelVsn,4).
+
+wait_installed(Node,RelVsn,0) ->
+ ?t:fail("install_release_changed_gg failed for " ++ RelVsn ++
+ " on " ++ atom_to_list(Node));
+wait_installed(Node,RelVsn,N) ->
+ Rels = rpc:call(Node,release_handler,which_releases,[]),
+ case lists:keyfind(RelVsn, 2, Rels) of
+ {"SASL-test", RelVsn, _Libs, current} ->
+ start_cover(Node),
+ ok;
+ _ ->
+ timer:sleep(500),
+ wait_installed(Node,RelVsn,N-1)
+ end.
+
+%% Start/stop cover measurements on the given node
+start_cover(Node) ->
+ cover_fun(Node,start).
+stop_cover(Node) ->
+ cover_fun(Node,stop).
+
+cover_fun(Node,Func) ->
+ case ?t:is_cover() of
+ true ->
+ cover:Func(Node);
+ false ->
+ ok
+ end.
+
+%%%-----------------------------------------------------------------
+%%% Create a fake release ....
+
+%% This function will create and install a release build on the
+%% current running OTP release. It includes kernel, stdlib and sasl,
+%% and possibly other applications if they are listed in AppDirs =
+%% [{App,Vsn,LibDir}]
+create_and_install_fake_first_release(Dir,AppDirs) ->
+ %% Create the first release
+ {RelName,RelVsn} = init:script_id(),
+ {Rel,_} = create_fake_release(Dir,RelName,RelVsn,AppDirs),
+ ReleasesDir = filename:join(Dir, "releases"),
+ RelDir = filename:dirname(Rel),
+
+ %% And install it
+ RelVsnDir = filename:join(ReleasesDir, RelVsn),
+ ok = filelib:ensure_dir(filename:join(RelVsnDir,"*")),
+
+ ok = copy_file(Rel++".rel",RelVsnDir),
+ ok = copy_file(Rel++".boot",filename:join(RelVsnDir, "start.boot")),
+ ok = copy_file(filename:join(RelDir,"sys.config"),RelVsnDir),
+
+ ok = release_handler:create_RELEASES(code:root_dir(),
+ ReleasesDir,
+ Rel++".rel",
+ AppDirs),
+
+ Rel.
+
+%% This function create a new release, including a relup file. It can
+%% be upgraded to from the release created by
+%% create_and_install_fake_first_release/2. Unpack first by calls to
+%% release_handler:set_unpacked and release_handler:install_file.
+create_fake_upgrade_release(Dir,RelVsn,AppDirs,{UpFrom,DownTo,ExtraLibs}) ->
+ %% Create a new release
+ {RelName,_} = init:script_id(),
+ {Rel,Paths} = create_fake_release(Dir,RelName,RelVsn,AppDirs),
+ RelDir = filename:dirname(Rel),
+
+ %% And a relup file so it can be upgraded to
+ RelupPath = Paths ++ [filename:join([Lib,"*","ebin"]) || Lib <- ExtraLibs],
+ ok = systools:make_relup(Rel,[UpFrom],[DownTo],
+ [{path,RelupPath},
+ {outdir,RelDir}]),
+
+ Rel.
+
+
+create_fake_release(Dir,RelName,RelVsn,AppDirs) ->
+ %% Create .rel files
+ RelDir = filename:join(Dir,"rel_" ++ RelVsn),
+ Rel = filename:join([RelDir,"rel_" ++ RelVsn]),
+ ok = filelib:ensure_dir(Rel),
+ ErtsVsn = erlang:system_info(version),
+
+ {Apps,Paths} =
+ lists:foldl(fun({App,Vsn,Lib},{As,Ps}) ->
+ {[{App,Vsn}|As],
+ lists:umerge([filename:join([Lib,"*",ebin])],Ps)}
+ end,
+ {[],[]},
+ AppDirs),
+
+ create_rel_file(Rel++".rel",RelName,RelVsn,ErtsVsn,Apps),
+
+ %% Generate boot scripts
+ ok = systools:make_script(Rel,[local,
+ {path, Paths},
+ {outdir,RelDir}]),
+ ok = copy_file(Rel++".boot", filename:join(RelDir,"start.boot")),
+
+ %% Use an own 'releases' directory - we don't want to change the
+ %% contents of $OTP_ROOT/releases
+ %% Inform SASL about this via sys.config
+ ReleasesDir = filename:join(Dir, "releases"),
+ Config = [{sasl,[{releases_dir,ReleasesDir}]}],
+ ok = write_term_file(filename:join(RelDir,"sys.config"), Config),
+
+ {Rel,Paths}.
+
+
+rpc_inst(Node,Func,Args) ->
+ rpc:call(Node,installer,Func,[node()|Args]).
diff --git a/lib/sasl/test/release_handler_SUITE_data/Makefile.src b/lib/sasl/test/release_handler_SUITE_data/Makefile.src
new file mode 100644
index 0000000000..85e25fdc2f
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/Makefile.src
@@ -0,0 +1,108 @@
+EFLAGS=+debug_info
+
+P2B= \
+ P2B/a-2.0/ebin/a.beam \
+ P2B/a-2.0/ebin/a_sup.beam
+
+LIB= \
+ lib/a-1.1/ebin/a.beam \
+ lib/a-1.1/ebin/a_sup.beam \
+ lib/a-1.0/ebin/a.beam \
+ lib/a-1.0/ebin/a_sup.beam \
+
+APP= \
+ app1_app2/lib1/app1-1.0/ebin/app1_sup.@EMULATOR@ \
+ app1_app2/lib1/app1-1.0/ebin/app1_server.@EMULATOR@ \
+ app1_app2/lib1/app1-1.0/ebin/app1.@EMULATOR@ \
+ app1_app2/lib1/app2-1.0/ebin/app2_sup.@EMULATOR@ \
+ app1_app2/lib1/app2-1.0/ebin/app2_server.@EMULATOR@ \
+ app1_app2/lib1/app2-1.0/ebin/app2.@EMULATOR@ \
+ app1_app2/lib2/app1-2.0/ebin/app1_sup.@EMULATOR@ \
+ app1_app2/lib2/app1-2.0/ebin/app1_server.@EMULATOR@ \
+ app1_app2/lib2/app1-2.0/ebin/app1.@EMULATOR@ \
+ app1_app2/lib2/app2-1.0/ebin/app2_sup.@EMULATOR@ \
+ app1_app2/lib2/app2-1.0/ebin/app2_server.@EMULATOR@ \
+ app1_app2/lib2/app2-1.0/ebin/app2.@EMULATOR@
+
+OTP2740= \
+ otp_2740/vsn_atom.@EMULATOR@ \
+ otp_2740/vsn_list.@EMULATOR@ \
+ otp_2740/vsn_numeric.@EMULATOR@ \
+ otp_2740/vsn_tuple.@EMULATOR@ \
+ otp_2740/vsn_string.@EMULATOR@
+
+C= \
+ c/aa.@EMULATOR@ \
+ c/b.@EMULATOR@ \
+ c/c_sup.@EMULATOR@
+
+
+all: $(P2B) $(LIB) $(APP) $(OTP2740) $(C)
+
+P2B/a-2.0/ebin/a.@EMULATOR@: P2B/a-2.0/src/a.erl
+ erlc $(EFLAGS) -oP2B/a-2.0/ebin P2B/a-2.0/src/a.erl
+P2B/a-2.0/ebin/a_sup.@EMULATOR@: P2B/a-2.0/src/a_sup.erl
+ erlc $(EFLAGS) -oP2B/a-2.0/ebin P2B/a-2.0/src/a_sup.erl
+
+
+lib/a-1.0/ebin/a.@EMULATOR@: lib/a-1.0/src/a.erl
+ erlc $(EFLAGS) -olib/a-1.0/ebin lib/a-1.0/src/a.erl
+lib/a-1.0/ebin/a_sup.@EMULATOR@: lib/a-1.0/src/a_sup.erl
+ erlc $(EFLAGS) -olib/a-1.0/ebin lib/a-1.0/src/a_sup.erl
+
+
+lib/a-1.1/ebin/a.@EMULATOR@: lib/a-1.1/src/a.erl
+ erlc $(EFLAGS) -olib/a-1.1/ebin lib/a-1.1/src/a.erl
+lib/a-1.1/ebin/a_sup.@EMULATOR@: lib/a-1.1/src/a_sup.erl
+ erlc $(EFLAGS) -olib/a-1.1/ebin lib/a-1.1/src/a_sup.erl
+
+
+app1_app2/lib1/app1-1.0/ebin/app1_sup.@EMULATOR@: app1_app2/lib1/app1-1.0/src/app1_sup.erl
+ erlc $(EFLAGS) -oapp1_app2/lib1/app1-1.0/ebin app1_app2/lib1/app1-1.0/src/app1_sup.erl
+app1_app2/lib1/app1-1.0/ebin/app1_server.@EMULATOR@: app1_app2/lib1/app1-1.0/src/app1_server.erl
+ erlc $(EFLAGS) -oapp1_app2/lib1/app1-1.0/ebin app1_app2/lib1/app1-1.0/src/app1_server.erl
+app1_app2/lib1/app1-1.0/ebin/app1.@EMULATOR@: app1_app2/lib1/app1-1.0/src/app1.erl
+ erlc $(EFLAGS) -oapp1_app2/lib1/app1-1.0/ebin app1_app2/lib1/app1-1.0/src/app1.erl
+
+
+app1_app2/lib1/app2-1.0/ebin/app2_sup.@EMULATOR@: app1_app2/lib1/app2-1.0/src/app2_sup.erl
+ erlc $(EFLAGS) -oapp1_app2/lib1/app2-1.0/ebin app1_app2/lib1/app2-1.0/src/app2_sup.erl
+app1_app2/lib1/app2-1.0/ebin/app2_server.@EMULATOR@: app1_app2/lib1/app2-1.0/src/app2_server.erl
+ erlc $(EFLAGS) -oapp1_app2/lib1/app2-1.0/ebin app1_app2/lib1/app2-1.0/src/app2_server.erl
+app1_app2/lib1/app2-1.0/ebin/app2.@EMULATOR@: app1_app2/lib1/app2-1.0/src/app2.erl
+ erlc $(EFLAGS) -oapp1_app2/lib1/app2-1.0/ebin app1_app2/lib1/app2-1.0/src/app2.erl
+
+
+app1_app2/lib2/app1-2.0/ebin/app1_sup.@EMULATOR@: app1_app2/lib2/app1-2.0/src/app1_sup.erl
+ erlc $(EFLAGS) -oapp1_app2/lib2/app1-2.0/ebin app1_app2/lib2/app1-2.0/src/app1_sup.erl
+app1_app2/lib2/app1-2.0/ebin/app1_server.@EMULATOR@: app1_app2/lib2/app1-2.0/src/app1_server.erl
+ erlc $(EFLAGS) -oapp1_app2/lib2/app1-2.0/ebin app1_app2/lib2/app1-2.0/src/app1_server.erl
+app1_app2/lib2/app1-2.0/ebin/app1.@EMULATOR@: app1_app2/lib2/app1-2.0/src/app1.erl
+ erlc $(EFLAGS) -oapp1_app2/lib2/app1-2.0/ebin app1_app2/lib2/app1-2.0/src/app1.erl
+
+
+app1_app2/lib2/app2-1.0/ebin/app2_sup.@EMULATOR@: app1_app2/lib2/app2-1.0/src/app2_sup.erl
+ erlc $(EFLAGS) -oapp1_app2/lib2/app2-1.0/ebin app1_app2/lib2/app2-1.0/src/app2_sup.erl
+app1_app2/lib2/app2-1.0/ebin/app2_server.@EMULATOR@: app1_app2/lib2/app2-1.0/src/app2_server.erl
+ erlc $(EFLAGS) -oapp1_app2/lib2/app2-1.0/ebin app1_app2/lib2/app2-1.0/src/app2_server.erl
+app1_app2/lib2/app2-1.0/ebin/app2.@EMULATOR@: app1_app2/lib2/app2-1.0/src/app2.erl
+ erlc $(EFLAGS) -oapp1_app2/lib2/app2-1.0/ebin app1_app2/lib2/app2-1.0/src/app2.erl
+
+
+otp_2740/vsn_atom.@EMULATOR@: otp_2740/vsn_atom.erl
+ erlc $(EFLAGS) -ootp_2740 otp_2740/vsn_atom.erl
+otp_2740/vsn_list.@EMULATOR@: otp_2740/vsn_list.erl
+ erlc $(EFLAGS) -ootp_2740 otp_2740/vsn_list.erl
+otp_2740/vsn_numeric.@EMULATOR@: otp_2740/vsn_numeric.erl
+ erlc $(EFLAGS) -ootp_2740 otp_2740/vsn_numeric.erl
+otp_2740/vsn_tuple.@EMULATOR@: otp_2740/vsn_tuple.erl
+ erlc $(EFLAGS) -ootp_2740 otp_2740/vsn_tuple.erl
+otp_2740/vsn_string.@EMULATOR@: otp_2740/vsn_string.erl
+ erlc $(EFLAGS) -ootp_2740 otp_2740/vsn_string.erl
+
+c/aa.@EMULATOR@: c/aa.erl
+ erlc $(EFLAGS) -oc c/aa.erl
+c/b.@EMULATOR@: c/b.erl
+ erlc $(EFLAGS) -oc c/b.erl
+c/c_sup.@EMULATOR@: c/c_sup.erl
+ erlc $(EFLAGS) -oc c/c_sup.erl
diff --git a/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/ebin/a.app b/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/ebin/a.app
new file mode 100644
index 0000000000..200cfcfe47
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/ebin/a.app
@@ -0,0 +1,8 @@
+{application, a,
+ [{description, "A CXC 138 11"},
+ {vsn, "2.0"},
+ {modules, [{a, 1}, {a_sup,1}]},
+ {registered, [a_sup]},
+ {applications, [kernel, stdlib]},
+ {env, [{key1, val1}]},
+ {mod, {a_sup, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a.erl b/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a.erl
new file mode 100644
index 0000000000..cfe38b55ce
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a.erl
@@ -0,0 +1,47 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(a).
+
+
+-behaviour(gen_server).
+
+%% External exports
+-export([start_link/0, a/0]).
+%% Internal exports
+-export([init/1, handle_call/3, handle_info/2, terminate/2]).
+
+start_link() -> gen_server:start_link({local, aa}, a, [], []).
+
+a() -> gen_server:call(aa, a).
+
+%%-----------------------------------------------------------------
+%% Callback functions from gen_server
+%%-----------------------------------------------------------------
+init([]) ->
+ process_flag(trap_exit, true),
+ {ok, state}.
+
+handle_call(a, _From, State) ->
+ X = application:get_all_env(a),
+ {reply, X, State}.
+
+handle_info(_, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a_sup.erl b/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a_sup.erl
new file mode 100644
index 0000000000..a141c1767b
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/P2B/a-2.0/src/a_sup.erl
@@ -0,0 +1,37 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(a_sup).
+
+
+-behaviour(supervisor).
+
+%% External exports
+-export([start/2]).
+
+%% Internal exports
+-export([init/1]).
+
+start(_, _) ->
+ supervisor:start_link({local, a_sup}, a_sup, []).
+
+init([]) ->
+ SupFlags = {one_for_one, 4, 3600},
+ Config = {a,
+ {a, start_link, []},
+ permanent, 2000, worker, [a]},
+ {ok, {SupFlags, [Config]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/ebin/app1.app b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/ebin/app1.app
new file mode 100644
index 0000000000..0489cb2595
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/ebin/app1.app
@@ -0,0 +1,9 @@
+{application, app1,
+ [{description, "very simple example application"},
+ {id, "app1"},
+ {vsn, "1.0"},
+ {modules, [app1, app1_sup, app1_server]},
+ {registered, [harry]},
+ {applications, [kernel, stdlib, sasl]},
+ {env, [{var,val1}]},
+ {mod, {app1, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1.erl
new file mode 100644
index 0000000000..f123c8f470
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1.erl
@@ -0,0 +1,22 @@
+-module(app1).
+
+-behaviour(application).
+
+%% Application callbacks
+-export([start/2, stop/1]).
+-export([config_change/3]).
+
+start(_Type, _StartArgs) ->
+ case app1_sup:start_link() of
+ {ok, Pid} ->
+ {ok, Pid};
+ Error ->
+ Error
+ end.
+
+stop(_State) ->
+ ok.
+
+config_change(Changed, _New, _Removed) ->
+ catch ets:insert(otp_6162, hd(Changed)),
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_server.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_server.erl
new file mode 100644
index 0000000000..9b49e772cc
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_server.erl
@@ -0,0 +1,32 @@
+-module(app1_server).
+
+-behaviour(gen_server).
+
+%% API
+-export([start_link/0]).
+
+%% gen_server callbacks
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
+ terminate/2, code_change/3]).
+
+start_link() ->
+ gen_server:start_link({local, harry}, ?MODULE, [], []).
+
+init([]) ->
+ {ok, []}.
+
+handle_call(_Request, _From, State) ->
+ Reply = ok,
+ {reply, Reply, State}.
+
+handle_cast(_Msg, State) ->
+ {noreply, State}.
+
+handle_info(_Info, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
+
+code_change(_OldVsn, State, _Extra) ->
+ {ok, State}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_sup.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_sup.erl
new file mode 100644
index 0000000000..e6ad9b6967
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app1-1.0/src/app1_sup.erl
@@ -0,0 +1,17 @@
+-module(app1_sup).
+
+-behaviour(supervisor).
+
+%% API
+-export([start_link/0]).
+
+%% Supervisor callbacks
+-export([init/1]).
+
+start_link() ->
+ supervisor:start_link(?MODULE, []).
+
+init([]) ->
+ AChild = {harry,{app1_server,start_link,[]},
+ permanent,2000,worker,[app1_server]},
+ {ok,{{one_for_all,0,1}, [AChild]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/ebin/app2.app b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/ebin/app2.app
new file mode 100644
index 0000000000..d48018cbda
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/ebin/app2.app
@@ -0,0 +1,9 @@
+{application, app2,
+ [{description, "very simple example application"},
+ {id, "app2"},
+ {vsn, "1.0"},
+ {modules, [app2, app2_sup, app2_server]},
+ {registered, [ginny]},
+ {applications, [kernel, stdlib, sasl]},
+ {env, []},
+ {mod, {app2, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2.erl
new file mode 100644
index 0000000000..a41c39730c
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2.erl
@@ -0,0 +1,17 @@
+-module(app2).
+
+-behaviour(application).
+
+%% Application callbacks
+-export([start/2, stop/1]).
+
+start(_Type, _StartArgs) ->
+ case app2_sup:start_link() of
+ {ok, Pid} ->
+ {ok, Pid};
+ Error ->
+ Error
+ end.
+
+stop(_State) ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_server.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_server.erl
new file mode 100644
index 0000000000..d8440230ff
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_server.erl
@@ -0,0 +1,32 @@
+-module(app2_server).
+
+-behaviour(gen_server).
+
+%% API
+-export([start_link/0]).
+
+%% gen_server callbacks
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
+ terminate/2, code_change/3]).
+
+start_link() ->
+ gen_server:start_link({local, ginny}, ?MODULE, [], []).
+
+init([]) ->
+ {ok, []}.
+
+handle_call(_Request, _From, State) ->
+ Reply = ok,
+ {reply, Reply, State}.
+
+handle_cast(_Msg, State) ->
+ {noreply, State}.
+
+handle_info(_Info, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
+
+code_change(_OldVsn, State, _Extra) ->
+ {ok, State}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_sup.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_sup.erl
new file mode 100644
index 0000000000..80b0952d4b
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib1/app2-1.0/src/app2_sup.erl
@@ -0,0 +1,17 @@
+-module(app2_sup).
+
+-behaviour(supervisor).
+
+%% API
+-export([start_link/0]).
+
+%% Supervisor callbacks
+-export([init/1]).
+
+start_link() ->
+ supervisor:start_link(?MODULE, []).
+
+init([]) ->
+ AChild = {ginny,{app2_server,start_link,[]},
+ permanent,2000,worker,[app2_server]},
+ {ok,{{one_for_all,0,1}, [AChild]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.app b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.app
new file mode 100644
index 0000000000..3c65adfbb3
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.app
@@ -0,0 +1,9 @@
+{application, app1,
+ [{description, "very simple example application"},
+ {id, "app1"},
+ {vsn, "2.0"},
+ {modules, [app1, app1_sup, app1_server]},
+ {registered, [harry]},
+ {applications, [kernel, stdlib, sasl]},
+ {env, [{var,val2}]},
+ {mod, {app1, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.appup b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.appup
new file mode 100644
index 0000000000..e5e0cbda0e
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/ebin/app1.appup
@@ -0,0 +1,4 @@
+{"2.0",
+ [{"1.0", [{load_module, app1_server}]}],
+ [{"1.0", [{load_module, app1_server}]}]
+}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1.erl
new file mode 100644
index 0000000000..f123c8f470
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1.erl
@@ -0,0 +1,22 @@
+-module(app1).
+
+-behaviour(application).
+
+%% Application callbacks
+-export([start/2, stop/1]).
+-export([config_change/3]).
+
+start(_Type, _StartArgs) ->
+ case app1_sup:start_link() of
+ {ok, Pid} ->
+ {ok, Pid};
+ Error ->
+ Error
+ end.
+
+stop(_State) ->
+ ok.
+
+config_change(Changed, _New, _Removed) ->
+ catch ets:insert(otp_6162, hd(Changed)),
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_server.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_server.erl
new file mode 100644
index 0000000000..660d095ebf
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_server.erl
@@ -0,0 +1,35 @@
+-module(app1_server).
+
+-behaviour(gen_server).
+
+%% API
+-export([start_link/0]).
+
+%% gen_server callbacks
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
+ terminate/2, code_change/3]).
+
+start_link() ->
+ gen_server:start_link({local, harry}, ?MODULE, [], []).
+
+init([]) ->
+ {ok, []}.
+
+handle_call(error, _From, State) ->
+ Reply = error,
+ {reply, Reply, State};
+handle_call(_Request, _From, State) ->
+ Reply = ok,
+ {reply, Reply, State}.
+
+handle_cast(_Msg, State) ->
+ {noreply, State}.
+
+handle_info(_Info, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
+
+code_change(_OldVsn, State, _Extra) ->
+ {ok, State}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_sup.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_sup.erl
new file mode 100644
index 0000000000..e6ad9b6967
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app1-2.0/src/app1_sup.erl
@@ -0,0 +1,17 @@
+-module(app1_sup).
+
+-behaviour(supervisor).
+
+%% API
+-export([start_link/0]).
+
+%% Supervisor callbacks
+-export([init/1]).
+
+start_link() ->
+ supervisor:start_link(?MODULE, []).
+
+init([]) ->
+ AChild = {harry,{app1_server,start_link,[]},
+ permanent,2000,worker,[app1_server]},
+ {ok,{{one_for_all,0,1}, [AChild]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/ebin/app2.app b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/ebin/app2.app
new file mode 100644
index 0000000000..d48018cbda
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/ebin/app2.app
@@ -0,0 +1,9 @@
+{application, app2,
+ [{description, "very simple example application"},
+ {id, "app2"},
+ {vsn, "1.0"},
+ {modules, [app2, app2_sup, app2_server]},
+ {registered, [ginny]},
+ {applications, [kernel, stdlib, sasl]},
+ {env, []},
+ {mod, {app2, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2.erl
new file mode 100644
index 0000000000..a41c39730c
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2.erl
@@ -0,0 +1,17 @@
+-module(app2).
+
+-behaviour(application).
+
+%% Application callbacks
+-export([start/2, stop/1]).
+
+start(_Type, _StartArgs) ->
+ case app2_sup:start_link() of
+ {ok, Pid} ->
+ {ok, Pid};
+ Error ->
+ Error
+ end.
+
+stop(_State) ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_server.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_server.erl
new file mode 100644
index 0000000000..d8440230ff
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_server.erl
@@ -0,0 +1,32 @@
+-module(app2_server).
+
+-behaviour(gen_server).
+
+%% API
+-export([start_link/0]).
+
+%% gen_server callbacks
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
+ terminate/2, code_change/3]).
+
+start_link() ->
+ gen_server:start_link({local, ginny}, ?MODULE, [], []).
+
+init([]) ->
+ {ok, []}.
+
+handle_call(_Request, _From, State) ->
+ Reply = ok,
+ {reply, Reply, State}.
+
+handle_cast(_Msg, State) ->
+ {noreply, State}.
+
+handle_info(_Info, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
+
+code_change(_OldVsn, State, _Extra) ->
+ {ok, State}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_sup.erl b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_sup.erl
new file mode 100644
index 0000000000..80b0952d4b
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/app1_app2/lib2/app2-1.0/src/app2_sup.erl
@@ -0,0 +1,17 @@
+-module(app2_sup).
+
+-behaviour(supervisor).
+
+%% API
+-export([start_link/0]).
+
+%% Supervisor callbacks
+-export([init/1]).
+
+start_link() ->
+ supervisor:start_link(?MODULE, []).
+
+init([]) ->
+ AChild = {ginny,{app2_server,start_link,[]},
+ permanent,2000,worker,[app2_server]},
+ {ok,{{one_for_all,0,1}, [AChild]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/c/aa.erl b/lib/sasl/test/release_handler_SUITE_data/c/aa.erl
new file mode 100644
index 0000000000..1c853c85b2
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/c/aa.erl
@@ -0,0 +1,41 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(aa).
+
+
+-behaviour(gen_server).
+
+%% External exports
+-export([start_link/0]).
+%% Internal exports
+-export([init/1, handle_info/2, terminate/2]).
+
+start_link() -> gen_server:start_link({local, cc}, aa, [], []).
+
+%%-----------------------------------------------------------------
+%% Callback functions from gen_server
+%%-----------------------------------------------------------------
+init([]) ->
+ process_flag(trap_exit, true),
+ {ok, state}.
+
+handle_info(_, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/c/b.erl b/lib/sasl/test/release_handler_SUITE_data/c/b.erl
new file mode 100644
index 0000000000..d8426a515e
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/c/b.erl
@@ -0,0 +1,38 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(b).
+
+
+%% External exports
+-export([start_link/0]).
+%% Internal exports
+-export([init/0]).
+
+start_link() -> {ok, proc_lib:spawn_link(b, init, [])}.
+
+%%-----------------------------------------------------------------
+%% Callback functions from gen_server
+%%-----------------------------------------------------------------
+init() ->
+ register(bb, self()),
+ loop().
+
+loop() ->
+ receive
+ hej -> ok
+ end.
diff --git a/lib/sasl/test/release_handler_SUITE_data/c/c.app b/lib/sasl/test/release_handler_SUITE_data/c/c.app
new file mode 100644
index 0000000000..908a94cf2d
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/c/c.app
@@ -0,0 +1,8 @@
+{application, c,
+ [{description, "C CXC 138 11"},
+ {vsn, "1.0"},
+ {modules, [b, {aa, 1}, {c_sup,1}]},
+ {registered, [cc,bb,c_sup]},
+ {applications, [kernel, stdlib]},
+ {env, [{key1, val1}]},
+ {mod, {c_sup, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/c/c_sup.erl b/lib/sasl/test/release_handler_SUITE_data/c/c_sup.erl
new file mode 100644
index 0000000000..069eb3b99b
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/c/c_sup.erl
@@ -0,0 +1,40 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(c_sup).
+
+
+-behaviour(supervisor).
+
+%% External exports
+-export([start/2]).
+
+%% Internal exports
+-export([init/1]).
+
+start(_, _) ->
+ supervisor:start_link({local, c_sup}, c_sup, []).
+
+init([]) ->
+ SupFlags = {one_for_one, 4, 3600},
+ Config1 = {c,
+ {aa, start_link, []},
+ permanent, 2000, worker, [aa]},
+ Config2 = {b,
+ {b, start_link, []},
+ permanent, 2000, worker, [b]},
+ {ok, {SupFlags, [Config1, Config2]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/clients/start_cli1 b/lib/sasl/test/release_handler_SUITE_data/clients/start_cli1
new file mode 100755
index 0000000000..ee3d8c97cf
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/clients/start_cli1
@@ -0,0 +1,38 @@
+#!/bin/sh
+#
+# This program invokes the erlang emulator by calling run_erl.
+# It should only be used at an embedded target system.
+# It should be modified to give the correct flags to erl (via start_erl),
+# e.g -mode embedded -sname XXX
+#
+# Usage: start [Data]
+#
+
+if [ "x${NODENAME}" = "x" ]
+then
+ echo "ERROR: Variable \$NODENAME is not set!!"
+ exit 1
+fi
+
+TESTHOST=`hostname | sed 's/[.].*//'`
+IPADDR=%IPADDR%
+
+ROOTDIR=%ROOT%
+CLIENTDIR=$ROOTDIR/clients/type1/$NODENAME@$TESTHOST
+
+RELDIR=$CLIENTDIR/releases
+
+# Note that this scripts is modified an copied to $CLIENTDIR/bin/start
+# in release_handler_SUITE:copy_client - therefore HEART_COMMAND is as follows:
+HEART_COMMAND=$CLIENTDIR/bin/start
+HW_WD_DISABLE=true
+export HW_WD_DISABLE HEART_COMMAND
+
+START_ERL_DATA=${1:-$RELDIR/start_erl.data}
+
+if [ ! -d /tmp/$NODENAME@$TESTHOST ]
+then
+ mkdir /tmp/$NODENAME@$TESTHOST
+fi
+
+$ROOTDIR/bin/run_erl /tmp/$NODENAME@$TESTHOST/ $CLIENTDIR/log "exec $ROOTDIR/bin/start_erl $ROOTDIR $RELDIR $START_ERL_DATA -heart -sname $NODENAME -sasl start_prg \\\"$CLIENTDIR/bin/start\\\" masters \[\\'%MASTER%@$TESTHOST\\'\] client_directory \\\"$CLIENTDIR\\\" -loader inet -id $NODENAME -hosts $IPADDR" > $CLIENTDIR/log/run_erl.out 2>&1 &
diff --git a/lib/sasl/test/release_handler_SUITE_data/clients/start_cli2 b/lib/sasl/test/release_handler_SUITE_data/clients/start_cli2
new file mode 100755
index 0000000000..88912cf884
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/clients/start_cli2
@@ -0,0 +1,37 @@
+#!/bin/sh
+#
+# This program invokes the erlang emulator by calling run_erl.
+# It should only be used at an embedded target system.
+# It should be modified to give the correct flags to erl (via start_erl),
+# e.g -mode embedded -sname XXX
+#
+# Usage: start [Data]
+#
+
+if [ "x${NODENAME}" = "x" ]
+then
+ echo "ERROR: Variable \$NODENAME is not set!!"
+ exit 1
+fi
+
+TESTHOST=`hostname | sed 's/[.].*//'`
+
+ROOTDIR=%ROOT%
+CLIENTDIR=$ROOTDIR/clients/type1/$NODENAME@$TESTHOST
+
+RELDIR=$CLIENTDIR/releases
+
+# Note that this scripts is modified an copied to $CLIENTDIR/bin/start
+# in release_handler_SUITE:copy_client - therefore HEART_COMMAND is as follows:
+HEART_COMMAND=$CLIENTDIR/bin/start
+HW_WD_DISABLE=true
+export HW_WD_DISABLE HEART_COMMAND
+
+START_ERL_DATA=${1:-$RELDIR/start_erl.data}
+
+if [ ! -d /tmp/$NODENAME@$TESTHOST ]
+then
+ mkdir /tmp/$NODENAME@$TESTHOST
+fi
+
+$ROOTDIR/bin/run_erl /tmp/$NODENAME@$TESTHOST/ $CLIENTDIR/log "exec $ROOTDIR/bin/start_erl $ROOTDIR $RELDIR $START_ERL_DATA -heart -sname $NODENAME -sasl start_prg \\\"$CLIENTDIR/bin/start\\\" masters \[\\'%MASTER%@$TESTHOST\\',\\'master2@$TESTHOST\\'\] client_directory \\\"$CLIENTDIR\\\"" > /dev/null 2>&1 &
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/ebin/a.app b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/ebin/a.app
new file mode 100644
index 0000000000..e938137f67
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/ebin/a.app
@@ -0,0 +1,8 @@
+{application, a,
+ [{description, "A CXC 138 11"},
+ {vsn, "1.0"},
+ {modules, [{a, 1}, {a_sup,1}]},
+ {registered, [a_sup]},
+ {applications, [kernel, stdlib]},
+ {env, [{key1, val1}]},
+ {mod, {a_sup, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.app b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.app
new file mode 100644
index 0000000000..e938137f67
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.app
@@ -0,0 +1,8 @@
+{application, a,
+ [{description, "A CXC 138 11"},
+ {vsn, "1.0"},
+ {modules, [{a, 1}, {a_sup,1}]},
+ {registered, [a_sup]},
+ {applications, [kernel, stdlib]},
+ {env, [{key1, val1}]},
+ {mod, {a_sup, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.erl b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.erl
new file mode 100644
index 0000000000..bb500bed69
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a.erl
@@ -0,0 +1,49 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(a).
+
+
+-behaviour(gen_server).
+
+-vsn(1).
+
+%% External exports
+-export([start_link/0, a/0]).
+%% Internal exports
+-export([init/1, handle_call/3, handle_info/2, terminate/2]).
+
+start_link() -> gen_server:start_link({local, aa}, a, [], []).
+
+a() -> gen_server:call(aa, a).
+
+%%-----------------------------------------------------------------
+%% Callback functions from gen_server
+%%-----------------------------------------------------------------
+init([]) ->
+ process_flag(trap_exit, true),
+ {ok, state}.
+
+handle_call(a, _From, State) ->
+ X = application:get_all_env(a),
+ {reply, X, State}.
+
+handle_info(_, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a_sup.erl b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a_sup.erl
new file mode 100644
index 0000000000..a141c1767b
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.0/src/a_sup.erl
@@ -0,0 +1,37 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(a_sup).
+
+
+-behaviour(supervisor).
+
+%% External exports
+-export([start/2]).
+
+%% Internal exports
+-export([init/1]).
+
+start(_, _) ->
+ supervisor:start_link({local, a_sup}, a_sup, []).
+
+init([]) ->
+ SupFlags = {one_for_one, 4, 3600},
+ Config = {a,
+ {a, start_link, []},
+ permanent, 2000, worker, [a]},
+ {ok, {SupFlags, [Config]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.app b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.app
new file mode 100644
index 0000000000..1c3053b2fa
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.app
@@ -0,0 +1,8 @@
+{application, a,
+ [{description, "A CXC 138 11"},
+ {vsn, "1.1"},
+ {modules, [{a, 2}, {a_sup,1}]},
+ {registered, [a_sup]},
+ {applications, [kernel, stdlib]},
+ {env, [{key1, val1}]},
+ {mod, {a_sup, []}}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.appup b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.appup
new file mode 100644
index 0000000000..05db4cb541
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/ebin/a.appup
@@ -0,0 +1,3 @@
+{"1.1",
+ [{"1.0",[{update,a,{advanced,extra_par}}]}],
+ []}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a.erl b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a.erl
new file mode 100644
index 0000000000..c082ad5339
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a.erl
@@ -0,0 +1,54 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(a).
+
+
+-behaviour(gen_server).
+
+%% External exports
+-export([start_link/0, a/0, b/0]).
+%% Internal exports
+-export([init/1, handle_call/3, handle_info/2, terminate/2, code_change/3]).
+
+start_link() -> gen_server:start_link({local, aa}, a, [], []).
+
+a() -> gen_server:call(aa, a).
+b() -> gen_server:call(aa, b).
+
+%%-----------------------------------------------------------------
+%% Callback functions from gen_server
+%%-----------------------------------------------------------------
+init([]) ->
+ process_flag(trap_exit, true),
+ {ok, {state, bval}}.
+
+handle_call(a, _From, State) ->
+ X = application:get_all_env(a),
+ {reply, X, State};
+
+handle_call(b, _From, State) ->
+ {reply, {ok, element(2, State)}, State}.
+
+handle_info(_, State) ->
+ {noreply, State}.
+
+terminate(_Reason, _State) ->
+ ok.
+
+code_change(1, Extra, State) ->
+ {ok, {state, bval}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a_sup.erl b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a_sup.erl
new file mode 100644
index 0000000000..a141c1767b
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/a-1.1/src/a_sup.erl
@@ -0,0 +1,37 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+-module(a_sup).
+
+
+-behaviour(supervisor).
+
+%% External exports
+-export([start/2]).
+
+%% Internal exports
+-export([init/1]).
+
+start(_, _) ->
+ supervisor:start_link({local, a_sup}, a_sup, []).
+
+init([]) ->
+ SupFlags = {one_for_one, 4, 3600},
+ Config = {a,
+ {a, start_link, []},
+ permanent, 2000, worker, [a]},
+ {ok, {SupFlags, [Config]}}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/ebin/installer.app b/lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/ebin/installer.app
new file mode 100644
index 0000000000..6f77317f6a
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/ebin/installer.app
@@ -0,0 +1,6 @@
+{application, installer,
+ [{description, "Installer application"},
+ {vsn, "1.0"},
+ {modules, [{installer, 1}]},
+ {registered, []},
+ {applications, [kernel, stdlib, sasl]}]}.
diff --git a/lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/src/installer.erl b/lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/src/installer.erl
new file mode 120000
index 0000000000..c2f93b822d
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/lib/installer-1.0/src/installer.erl
@@ -0,0 +1 @@
+../../../../installer.erl \ No newline at end of file
diff --git a/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_atom.erl b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_atom.erl
new file mode 100644
index 0000000000..883688c231
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_atom.erl
@@ -0,0 +1,26 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+
+-module(vsn_atom).
+
+-vsn(atom).
+
+-export([ok/0]).
+
+ok() ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_list.erl b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_list.erl
new file mode 100644
index 0000000000..34c38307ba
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_list.erl
@@ -0,0 +1,26 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+
+-module(vsn_list).
+
+-vsn([list, "of", {some, terms}]).
+
+-export([ok/0]).
+
+ok() ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_numeric.erl b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_numeric.erl
new file mode 100644
index 0000000000..6bf52753fd
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_numeric.erl
@@ -0,0 +1,26 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+
+-module(vsn_numeric).
+
+-vsn(231894).
+
+-export([ok/0]).
+
+ok() ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_string.erl b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_string.erl
new file mode 100644
index 0000000000..aa430a0bb3
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_string.erl
@@ -0,0 +1,26 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+
+-module(vsn_string).
+
+-vsn("a string").
+
+-export([ok/0]).
+
+ok() ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_tuple.erl b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_tuple.erl
new file mode 100644
index 0000000000..3ff1018994
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/otp_2740/vsn_tuple.erl
@@ -0,0 +1,26 @@
+%% ``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 via the world wide web 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.
+%%
+%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
+%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
+%% AB. All Rights Reserved.''
+%%
+%% $Id$
+%%
+
+-module(vsn_tuple).
+
+-vsn({tuple, ["of", terms]}).
+
+-export([ok/0]).
+
+ok() ->
+ ok.
diff --git a/lib/sasl/test/release_handler_SUITE_data/start b/lib/sasl/test/release_handler_SUITE_data/start
new file mode 100755
index 0000000000..45e526c15f
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/start
@@ -0,0 +1,29 @@
+#!/bin/sh
+#
+# This program invokes the erlang emulator by calling run_erl.
+# It should only be used at an embedded target system.
+# It should be modified to give the correct flags to erl (via start_erl),
+# e.g -mode embedded -sname XXX
+#
+# Usage: start [Data]
+#
+ROOTDIR=%ROOT%
+
+if [ "x${NODENAME}" = "x" ]
+then
+ echo "ERROR: Variable \$NODENAME is not set!!"
+ exit 1
+fi
+
+if [ -z "$RELDIR" ]
+then
+ RELDIR=$ROOTDIR/releases
+fi
+
+HEART_COMMAND=$ROOTDIR/bin/start
+HW_WD_DISABLE=true
+export HW_WD_DISABLE HEART_COMMAND
+
+START_ERL_DATA=${1:-$RELDIR/start_erl.data}
+
+$ROOTDIR/bin/run_erl /tmp/ $ROOTDIR/log "exec $ROOTDIR/bin/start_erl $ROOTDIR $RELDIR $START_ERL_DATA -heart -sname $NODENAME" > $ROOTDIR/log/run_erl.out 2>&1 &
diff --git a/lib/sasl/test/release_handler_SUITE_data/target_system.erl b/lib/sasl/test/release_handler_SUITE_data/target_system.erl
new file mode 120000
index 0000000000..4d36c59632
--- /dev/null
+++ b/lib/sasl/test/release_handler_SUITE_data/target_system.erl
@@ -0,0 +1 @@
+../../examples/src/target_system.erl \ No newline at end of file
diff --git a/lib/sasl/test/sasl.cover b/lib/sasl/test/sasl.cover
new file mode 100644
index 0000000000..d19d3d0180
--- /dev/null
+++ b/lib/sasl/test/sasl.cover
@@ -0,0 +1,2 @@
+{incl_app,sasl,details}.
+
diff --git a/lib/sasl/test/sasl.spec b/lib/sasl/test/sasl.spec
new file mode 100644
index 0000000000..f3de90c9aa
--- /dev/null
+++ b/lib/sasl/test/sasl.spec
@@ -0,0 +1 @@
+{suites,"../sasl_test",all}.
diff --git a/lib/sasl/test/sasl_SUITE.erl b/lib/sasl/test/sasl_SUITE.erl
new file mode 100644
index 0000000000..454095db6a
--- /dev/null
+++ b/lib/sasl/test/sasl_SUITE.erl
@@ -0,0 +1,98 @@
+%%
+%% %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%
+%%
+-module(sasl_SUITE).
+-include_lib("common_test/include/ct.hrl").
+
+
+% Default timetrap timeout (set in init_per_testcase).
+-define(default_timeout, ?t:minutes(1)).
+-define(application, sasl).
+
+% Test server specific exports
+-export([all/0,groups/0,init_per_group/2,end_per_group/2]).
+-export([init_per_testcase/2, end_per_testcase/2]).
+
+% Test cases must be exported.
+-export([app_test/1,
+ log_mf_h_env/1]).
+
+all() ->
+ [app_test, log_mf_h_env].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+init_per_testcase(_Case, Config) ->
+ ?line Dog=test_server:timetrap(?default_timeout),
+ [{watchdog, Dog}|Config].
+end_per_testcase(_Case, Config) ->
+ Dog=?config(watchdog, Config),
+ test_server:timetrap_cancel(Dog),
+ ok.
+
+app_test(Config) when is_list(Config) ->
+ ?line ?t:app_test(sasl, allow),
+ ok.
+
+%% OTP-9185 - fail sasl start if some but not all log_mf_h env vars
+%% are given.
+log_mf_h_env(Config) ->
+ PrivDir = ?config(priv_dir,Config),
+ LogDir = filename:join(PrivDir,sasl_SUITE_log_dir),
+ ok = file:make_dir(LogDir),
+ application:stop(sasl),
+ SaslEnv = application:get_all_env(sasl),
+ lists:foreach(fun({E,_V}) -> application:unset_env(sasl,E) end, SaslEnv),
+
+ ok = application:set_env(sasl,error_logger_mf_dir,LogDir),
+ match_error(missing_config,application:start(sasl)),
+
+ ok = application:set_env(sasl,error_logger_mf_maxbytes,"xx"),
+ match_error(bad_config,application:start(sasl)),
+
+ ok = application:set_env(sasl,error_logger_mf_maxbytes,50000),
+ match_error(missing_config,application:start(sasl)),
+
+ ok = application:set_env(sasl,error_logger_mf_maxfiles,"xx"),
+ match_error(bad_config,application:start(sasl)),
+
+ ok = application:set_env(sasl,error_logger_mf_maxfiles,2),
+ ok = application:unset_env(sasl,error_logger_mf_dir),
+ match_error(missing_config,application:start(sasl)),
+
+ ok = application:set_env(sasl,error_logger_mf_dir,xx),
+ match_error(bad_config,application:start(sasl)),
+
+ ok = application:set_env(sasl,error_logger_mf_dir,LogDir),
+ ok = application:start(sasl).
+
+
+%%-----------------------------------------------------------------
+%% Internal
+match_error(Expected,{error,{bad_return,{_,{'EXIT',{Expected,{sasl,_}}}}}}) ->
+ ok;
+match_error(Expected,Actual) ->
+ ?t:fail({unexpected_return,Expected,Actual}).
diff --git a/lib/sasl/test/systools_SUITE.erl b/lib/sasl/test/systools_SUITE.erl
new file mode 100644
index 0000000000..9190b111ef
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE.erl
@@ -0,0 +1,2112 @@
+%%
+%% %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%
+%%
+%%
+%% Test suite for the systools module.
+%%
+%% The systools module is a wrapper for a number of modules that
+%% handle large parts of the release building functionality
+%% (e.g. checking app files, building a tar file, building
+%% release upgrad scripts.
+%%
+
+
+-module(systools_SUITE).
+
+%-define(debug, true).
+
+-include_lib("test_server/include/test_server.hrl").
+-define(format(S, A), ok).
+-define(datadir, ?config(data_dir, Config)).
+-define(privdir, ?config(priv_dir, Config)).
+-define(copydir, ?config(copy_dir, Config)).
+
+-include_lib("kernel/include/file.hrl").
+
+-export([all/0,suite/0,groups/0,init_per_group/2,end_per_group/2]).
+
+-export([ script_options/1, normal_script/1, no_mod_vsn_script/1,
+ wildcard_script/1, variable_script/1,
+ abnormal_script/1, src_tests_script/1, crazy_script/1,
+ warn_shadow_script/1,
+ included_script/1, included_override_script/1,
+ included_fail_script/1, included_bug_script/1, exref_script/1]).
+-export([ tar_options/1, normal_tar/1, no_mod_vsn_tar/1, variable_tar/1,
+ src_tests_tar/1, shadow_tar/1, var_tar/1,
+ exref_tar/1, link_tar/1]).
+-export([ normal_relup/1, abnormal_relup/1, no_appup_relup/1,
+ bad_appup_relup/1, app_start_type_relup/1, otp_3065/1]).
+-export([
+ otp_6226/1]).
+-export([init_per_suite/1, end_per_suite/1,
+ init_per_testcase/2, end_per_testcase/2]).
+
+-import(lists, [foldl/3]).
+
+-define(default_timeout, ?t:minutes(20)).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+suite() ->
+ [{ct_hooks, [ts_install_cth]}].
+
+all() ->
+ [{group, script}, {group, tar}, {group, relup},
+ {group, tickets}].
+
+groups() ->
+ [{script, [],
+ [script_options, normal_script, no_mod_vsn_script,
+ wildcard_script, variable_script, abnormal_script,
+ src_tests_script, crazy_script, warn_shadow_script,
+ included_script, included_override_script,
+ included_fail_script, included_bug_script, exref_script,
+ otp_3065]},
+ {tar, [],
+ [tar_options, normal_tar, no_mod_vsn_tar, variable_tar,
+ src_tests_tar, shadow_tar, var_tar,
+ exref_tar, link_tar]},
+ {relup, [],
+ [normal_relup, abnormal_relup, no_appup_relup,
+ bad_appup_relup, app_start_type_relup]},
+ {tickets, [], [otp_6226]}].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+init_per_suite(Config) when is_list(Config) ->
+ %% Make of copy of the data directory.
+ DataDir = ?datadir,
+ PrivDir = ?privdir,
+ ?line CopyDir = fname(PrivDir, "datacopy"),
+ ?line TarFile = fname(PrivDir, "datacopy.tgz"),
+ ?line {ok, Tar} = erl_tar:open(TarFile, [write, compressed]),
+ ?line ok = erl_tar:add(Tar, DataDir, CopyDir, [compressed]),
+ ?line ok = erl_tar:close(Tar),
+ ?line ok = erl_tar:extract(TarFile, [compressed]),
+ ?line ok = file:delete(TarFile),
+
+ %% Compile source files in the copy directory.
+ ?line Sources = filelib:wildcard(fname([CopyDir,'*','*','*','*','*.erl'])),
+ ?line lists:foreach(fun compile_source/1, Sources),
+
+ %% To use in end_per_testcase
+ Path = code:get_path(),
+ {ok,Cwd} = file:get_cwd(),
+
+ [{copy_dir, CopyDir}, {cwd,Cwd}, {path,Path} | Config].
+
+compile_source(File) ->
+ %% The compiler will no longer create a Beam file
+ %% with a module name that does not match the output
+ %% file, so we must compile to a binary and write
+ %% the output file ourselves.
+ U = filename:dirname(filename:dirname(File)),
+ Base = filename:rootname(filename:basename(File)),
+ OutFile = filename:join([U,"ebin",Base++".beam"]),
+ OutFileTemp = OutFile ++ "#",
+ {ok,_,Code} = compile:file(File, [binary]),
+ ok = file:write_file(OutFileTemp, Code),
+ file:rename(OutFileTemp, OutFile).
+
+end_per_suite(Conf) when is_list(Conf) ->
+ %% Nothing.
+ Conf.
+
+init_per_testcase(link_tar, Config) ->
+ case os:type() of
+ {unix, _} -> init_per_testcase(dummy, Config);
+ {win32, _} -> {skip, "Skip on windows"}
+ end;
+init_per_testcase(_Case, Config) ->
+ ?line Dog = test_server:timetrap(?default_timeout),
+ [{watchdog, Dog}|Config].
+
+end_per_testcase(_Case, Config) ->
+ Dog=?config(watchdog, Config),
+ test_server:timetrap_cancel(Dog),
+ case {?config(path,Config),?config(cwd,Config)} of
+ {undefined,undefined} ->
+ ok;
+ {Path,Cwd} ->
+ true = code:set_path(Path),
+ ok = file:set_cwd(Cwd)
+ end,
+ ok.
+
+
+
+%% Usage:
+%% systools:make_script("RelName")
+%% Make a boot file from RelName.rel.
+%% Generates RelName.{script,boot}
+%% systools:make_tar("RelName")
+%% Make a release package from RelName.rel.
+%% Generates RelName.tar,Z
+%% systools:script2boot(File)
+%% File.script -> File.boot
+%% systools:make_relup("Target", ["UpFromRel"...], ["DownToRel"...], Opts)
+%% Gather all appup scripts to the relup file
+%%
+
+
+%% make_script
+%%
+script_options(suite) -> [];
+script_options(doc) ->
+ ["Check illegal script options."];
+script_options(Config) when is_list(Config) ->
+ ?line {'EXIT',{{badarg,[{path,["Path",12,"Another"]}]}, _}} =
+ (catch systools:make_script("release", [{path,["Path",12,"Another"]}])),
+ ?line {'EXIT',{{badarg,[sillent]}, _}} =
+ (catch systools:make_script("release",
+ [{path,["Path","Another"]},sillent])),
+ ?line {'EXIT',{{badarg,[locall]}, _}} =
+ (catch systools:make_script("release",
+ [{path,["Path","Another"]},locall])),
+ ?line {'EXIT',{{badarg,[src_testsxx]}, _}} =
+ (catch systools:make_script("release",
+ [{path,["Path"]},src_testsxx])),
+ ?line {'EXIT',{{badarg,[{variables, {"TEST", "/home/lib"}}]}, _}} =
+ (catch systools:make_script("release",
+ [{variables, {"TEST", "/home/lib"}}])),
+ ?line {'EXIT',{{badarg,[{variables, [{a, b}, {"a", "b"}]}]}, _}} =
+ (catch systools:make_script("release",
+ [{variables, [{a, b}, {"a", "b"}]}])),
+ ?line {'EXIT',{{badarg,[exreff]}, _}} =
+ (catch systools:make_script("release",
+ [{path,["Path","Another"]},exreff])),
+ ?line {'EXIT',{{badarg,[{exref,["appl"]}]}, _}} =
+ (catch systools:make_script("release", [{exref,["appl"]}])),
+ ?line {'EXIT',{{badarg,[{machine, "appl"}]}, _}} =
+ (catch systools:make_script("release", [{machine,"appl"}])),
+ ok.
+
+
+%% make_script
+%%
+normal_script(suite) -> [];
+normal_script(doc) ->
+ ["Check that make_script handles normal case."];
+normal_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line PSAVE = code:get_path(), % Save path
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P1 = fname([LibDir, 'db-2.1', ebin]),
+ ?line P2 = fname([LibDir, 'fe-3.1', ebin]),
+
+ ?line true = code:add_patha(P1),
+ ?line true = code:add_patha(P2),
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line ok = systools:make_script(filename:basename(LatestName)),
+ ?line {ok, _} = read_script_file(LatestName), % Check readabillity
+
+ %% Check the same but w. silent flag
+ ?line {ok, _, []} = systools:make_script(LatestName, [silent]),
+
+ %% Use the local option
+ ?line ok = systools:make_script(LatestName, [local]),
+ ?line ok = check_script_path(LatestName),
+
+ %% use the path option
+ ?line code:set_path(PSAVE), % Restore path
+ %% Mess up std path:
+ ?line true = code:add_patha(fname([LibDir, 'db-1.0', ebin])),
+ ?line true = code:add_patha(fname([LibDir, 'fe-2.1', ebin])),
+
+ ?line error = systools:make_script(LatestName), %should fail
+ ?line ok = systools:make_script(LatestName,[{path, [P1, P2]}]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ?line code:set_path(PSAVE), % Restore path
+ ok.
+
+
+%% make_script
+%%
+no_mod_vsn_script(suite) -> [];
+no_mod_vsn_script(doc) ->
+ ["Check that make_script handles normal case.",
+ "Modules specified without version in .app file (db-3.1)."
+ "Note that this is now the normal way - i.e. systools now "
+ "ignores the module versions in the .app file."];
+no_mod_vsn_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line PSAVE = code:get_path(), % Save path
+
+ ?line {LatestDir, LatestName} = create_script(latest_no_mod_vsn,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P1 = fname([LibDir, 'db-3.1', ebin]),
+ ?line P2 = fname([LibDir, 'fe-3.1', ebin]),
+
+ ?line true = code:add_patha(P1),
+ ?line true = code:add_patha(P2),
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line ok = systools:make_script(filename:basename(LatestName)),
+ ?line {ok, _} = read_script_file(LatestName), % Check readabillity
+
+ %% Check the same but w. silent flag
+ ?line {ok, _, []} = systools:make_script(LatestName, [silent]),
+
+ %% Use the local option
+ ?line ok = systools:make_script(LatestName, [local]),
+ ?line ok = check_script_path(LatestName),
+
+ %% use the path option
+ ?line code:set_path(PSAVE), % Restore path
+ %% Mess up std path:
+ ?line true = code:add_patha(fname([LibDir, 'db-1.0', ebin])),
+ ?line true = code:add_patha(fname([LibDir, 'fe-2.1', ebin])),
+
+ ?line error = systools:make_script(LatestName), %should fail
+ ?line ok = systools:make_script(LatestName,
+ [{path, [P1, P2]}]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ?line code:set_path(PSAVE), % Restore path
+ ok.
+
+
+%% make_script
+%%
+wildcard_script(suite) -> [];
+wildcard_script(doc) ->
+ ["Check that make_script handles wildcards in path."];
+wildcard_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line WildDir = fname([LibDir, '*', ebin]),
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line error = systools:make_script(filename:basename(LatestName)),
+
+ ?line ok = systools:make_script(LatestName,
+ [{path, [WildDir]}]),
+
+ ?line {ok, _} = read_script_file(LatestName), % Check readabillity
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+
+%% make_script
+%%
+variable_script(suite) -> [];
+variable_script(doc) ->
+ ["Add own installation dependent variable in script."];
+variable_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line ok = systools:make_script(LatestName,
+ [{path, P},
+ {variables, [{"TEST", LibDir}]}]),
+
+ %% Check variables
+ ?line ok = check_var_script_file([fname(['$TEST', 'db-2.1', ebin]),
+ fname(['$TEST', 'fe-3.1', ebin])],
+ P,
+ LatestName),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% make_script
+%%
+abnormal_script(suite) -> [];
+abnormal_script(doc) ->
+ ["Abnormal cases."];
+abnormal_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+
+ ?line ok = file:set_cwd(LatestDir),
+ ?line LibDir = fname([DataDir, d_bad_app_vsn, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ %% Check wrong app vsn
+ ?line error = systools:make_script(LatestName, [{path, P}]),
+ ?line {error,
+ systools_make,
+ [{error_reading, {db, {no_valid_version,
+ {{"should be","2.1"},
+ {"found file", _, "2.0"}}}}}]} =
+ systools:make_script(LatestName, [silent, {path, P}]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+
+%% make_script
+%%
+src_tests_script(suite) -> [];
+src_tests_script(doc) ->
+ ["Do not check date of object file or that source code can be found."];
+src_tests_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line PSAVE = code:get_path(), % Save path
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_missing_src, lib]),
+ ?line P1 = fname([LibDir, 'db-2.1', ebin]),
+ ?line P2 = fname([LibDir, 'fe-3.1', ebin]),
+ N = [P1, P2],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% Manipulate the modification date of a beam file so it seems
+ %% older than its .erl file
+ ?line Erl = filename:join([P1,"..","src","db1.erl"]),
+ ?line {ok, FileInfo=#file_info{mtime={{Y,M,D},T}}} = file:read_file_info(Erl),
+ ?line Beam = filename:join(P1,"db1.beam"),
+ ?line ok=file:write_file_info(Beam, FileInfo#file_info{mtime={{Y-1,M,D},T}}),
+
+ %% Remove a .erl file
+ ?line Erl2 = filename:join([P1,"..","src","db2.erl"]),
+ ?line file:delete(Erl2),
+
+ %% Then make script - two warnings should be issued when
+ %% src_tests is given
+ %% 1. old object code for db1.beam
+ %% 2. missing source code for db2.beam
+ ?line {ok, _, [{warning,{obj_out_of_date,_}},
+ {warning,{source_not_found,_}}]} =
+ systools:make_script(LatestName, [silent, {path, N}, src_tests]),
+
+ %% Without the src_tests option, no warning should be issued
+ ?line {ok, _, []} =
+ systools:make_script(LatestName, [silent, {path, N}]),
+
+ %% Check that the old no_module_tests option (from the time when
+ %% it was default to do the src_test) is ignored
+ ?line {ok, _, [{warning,{obj_out_of_date,_}},
+ {warning,{source_not_found,_}}]} =
+ systools:make_script(LatestName, [silent,
+ {path, N},
+ no_module_tests,
+ src_tests]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ?line code:set_path(PSAVE),
+ ok.
+
+%% make_script
+%%
+warn_shadow_script(suite) -> [];
+warn_shadow_script(doc) ->
+ ["Check that jam file out of date warning doesn't",
+ "shadow bad module version error."];
+warn_shadow_script(Config) when is_list(Config) ->
+ %% This test has been removed since the 'vsn' attribute is
+ %% not used any more, starting with R6. No warning
+ %% 'obj_out_of_date' seemed to be generated.
+ true.
+
+
+%% make_script
+%%
+crazy_script(suite) -> [];
+crazy_script(doc) ->
+ ["Do the crazy cases."];
+crazy_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest, Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% Run with bad path
+ ?line error = systools:make_script(LatestName),
+ ?line {error, _, [{error_reading, _}, {error_reading, _}]} =
+ systools:make_script(LatestName, [silent]),
+
+ %% Run with .rel file lacking kernel
+ ?line {LatestDir2, LatestName2} = create_script(latest_nokernel, Config),
+ ?line ok = file:set_cwd(LatestDir2),
+
+ ?line error = systools:make_script(LatestName2),
+ ?line {error, _, {missing_mandatory_app,[kernel,stdlib]}} =
+ systools:make_script(LatestName2, [silent,{path,P}]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% make_script
+%%
+included_script(suite) -> [];
+included_script(doc) ->
+ ["Check that make_script handles generation of script",
+ "for applications with included applications."];
+included_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line {LatestDir, LatestName} = create_include_files(inc1, Config),
+ ?line ok = file:set_cwd(LatestDir),
+ ?line ok = systools:make_script(LatestName),
+ ?line ok = check_include_script(LatestName,
+ [t1, t2, t3, t5, t4, t6],
+ [t1, t3, t6]),
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% make_script
+%%
+included_override_script(suite) -> [];
+included_override_script(doc) ->
+ ["Check that make_script handles generation of script",
+ "for applications with included applications which are override by",
+ "the .rel file."];
+included_override_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line {LatestDir, LatestName} = create_include_files(inc2, Config),
+ ?line ok = file:set_cwd(LatestDir),
+ ?line ok = systools:make_script(LatestName),
+ ?line ok = check_include_script(LatestName,
+ [t1, t2, t3, t4, t6, t5],
+ [t1, t3, t6, t5]),
+
+ ?line {_, LatestName1} = create_include_files(inc3, Config),
+ ?line ok = systools:make_script(LatestName1),
+ ?line ok = check_include_script(LatestName1,
+ [t3, t5, t4, t6, t1, t2],
+ [t3, t6, t1, t2]),
+
+ ?line {_, LatestName2} = create_include_files(inc4, Config),
+ ?line ok = systools:make_script(LatestName2),
+ ?line ok = check_include_script(LatestName2,
+ [t3, t4, t6, t5, t1, t2],
+ [t3, t6, t5, t1, t2]),
+
+ ?line {_, LatestName3} = create_include_files(inc5, Config),
+ ?line ok = systools:make_script(LatestName3),
+ ?line ok = check_include_script(LatestName3,
+ [t3, t4, t6, t1, t2],
+ [t3, t6, t1, t2]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% make_script
+%%
+included_fail_script(suite) -> [];
+included_fail_script(doc) ->
+ ["Check that make_script handles errors then generating",
+ "script with included applications."];
+included_fail_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line {LatestDir, LatestName} = create_include_files(inc6, Config),
+ ?line ok = file:set_cwd(LatestDir),
+ ?line {error, _, {undefined_applications,[t2]}} =
+ systools:make_script(LatestName, [silent]),
+
+ ?line {_, LatestName1} = create_include_files(inc7, Config),
+ ?line {error, _, {duplicate_include,[{{t5,t7,_,_},{t5,t6,_,_}}]}} =
+ systools:make_script(LatestName1, [silent]),
+
+ ?line {_, LatestName3} = create_include_files(inc9, Config),
+ ?line {error, _, {circular_dependencies,[{t10,_},{t8,_}]}} =
+ systools:make_script(LatestName3, [silent]),
+
+ ?line {_, LatestName4} = create_include_files(inc10, Config),
+ ?line {error, _, [{error_reading,{t9,{override_include,[t7]}}}]} =
+ systools:make_script(LatestName4, [silent]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% make_script
+%%
+included_bug_script(suite) -> [];
+included_bug_script(doc) ->
+ ["Check that make_script handles generation of script",
+ "with difficult dependency for included applications."];
+included_bug_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line {LatestDir, LatestName} = create_include_files(inc11, Config),
+ ?line ok = file:set_cwd(LatestDir),
+ ?line ok = systools:make_script(LatestName),
+ ?line ok = check_include_script(LatestName,
+ [t13, t11, t12],
+ [t11, t12]),
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+
+%% make_script
+%%
+otp_3065(suite) -> [];
+otp_3065(doc) ->
+ ["Circular dependencies in systools:make_script()."];
+otp_3065(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line {LatestDir, LatestName} = create_include_files(otp_3065, Config),
+ ?line ok = file:set_cwd(LatestDir),
+ ?line ok = systools:make_script(LatestName),
+ ?line ok = check_include_script(LatestName,
+ [aa12, chAts, chTraffic],
+ [chTraffic]),
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+
+%% make_script
+%%
+exref_script(suite) -> [];
+exref_script(doc) ->
+ ["Check that make_script exref option works."];
+exref_script(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line PSAVE = code:get_path(), % Save path
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {ok, _, _} = systools:make_script(LatestName, [{path,P}, silent]),
+
+ %% Complete exref
+ ?line {ok, _, W1} =
+ systools:make_script(LatestName, [exref, {path,P}, silent]),
+ ?line check_exref_warnings(with_db1, W1),
+ ?line {ok, _} = read_script_file(LatestName), % Check readabillity
+
+ %% Only exref the db application.
+ ?line {ok, _, W2} =
+ systools:make_script(LatestName, [{exref,[db]}, {path,P}, silent]),
+ ?line check_exref_warnings(with_db1, W2),
+ ?line {ok, _} = read_script_file(LatestName), % Check readabillity
+
+ %% Only exref the fe application.
+ ?line {ok, _, W3} =
+ systools:make_script(LatestName, [{exref,[fe]}, {path,P}, silent]),
+ ?line check_exref_warnings(without_db1, W3),
+ ?line {ok, _} = read_script_file(LatestName), % Check readabillity
+
+ %% exref the db and stdlib applications.
+ ?line {ok, _, W4} =
+ systools:make_script(LatestName, [{exref,[db,stdlib]}, {path,P}, silent]),
+ ?line check_exref_warnings(with_db1, W4),
+ ?line {ok, _} = read_script_file(LatestName), % Check readabillity
+ ?line ok = file:set_cwd(OldDir),
+ ?line code:set_path(PSAVE), % Restore path
+ ok.
+
+check_exref_warnings(with_db1, W) ->
+ case get_exref(undef, W) of
+ {ok, [{db2,non_existing_func,0},
+ {fe2,non_existing_func,0},
+ {lists,non_existing_func,1}]} ->
+ ok;
+ {ok, L} ->
+ test_server:fail({exref_warning_undef, L});
+ _E ->
+ test_server:fail({bad_undef,_E})
+ end;
+check_exref_warnings(without_db1, W) ->
+ case get_exref(undef, W) of
+ false ->
+ ok;
+ {ok, L} ->
+ test_server:fail({exref_warning_undef, L})
+ end.
+
+get_exref(undef, W) -> filter(no_hipe(get_exref1(exref_undef, W))).
+
+filter(false) ->
+ false;
+filter({ok, W}) ->
+ {ok, filter(W)};
+filter(L) ->
+ lists:filter(fun%({hipe_consttab,_,_}) -> false;
+ ({int,_,_}) -> false;
+ ({i,_,_}) -> false;
+ ({crypto,_,_}) -> false;
+ (_) -> true
+ end,
+ L).
+
+get_exref1(T, [{warning, {T, Value}}|_]) -> {ok, Value};
+get_exref1(T, [_|W]) -> get_exref1(T, W);
+get_exref1(_, []) -> false.
+
+no_hipe(false) ->
+ false;
+no_hipe({ok, Value}) ->
+ case erlang:system_info(hipe_architecture) of
+ undefined ->
+ Hipe = "hipe",
+ Fun = fun({M,_,_}) -> not lists:prefix(Hipe, atom_to_list(M)) end,
+ NewValue = lists:filter(Fun, Value),
+ {ok, NewValue};
+ _Arch ->
+ {ok, Value}
+ end.
+
+%% tar_options
+%%
+tar_options(suite) -> [];
+tar_options(doc) ->
+ ["Check illegal tar options."];
+tar_options(Config) when is_list(Config) ->
+ ?line {'EXIT',{{badarg,[{path,["Path",12,"Another"]}]}, _}} =
+ (catch systools:make_tar("release", [{path,["Path",12,"Another"]}])),
+ ?line {'EXIT',{{badarg,[sillent]}, _}} =
+ (catch systools:make_tar("release",
+ [{path,["Path","Another"]},sillent])),
+ ?line {'EXIT',{{badarg,[{dirs,["dirs"]}]}, _}} =
+ (catch systools:make_tar("release", [{dirs, ["dirs"]}])),
+ ?line {'EXIT',{{badarg,[{erts, illegal}]}, _}} =
+ (catch systools:make_tar("release", [{erts, illegal}])),
+ ?line {'EXIT',{{badarg,[src_testsxx]}, _}} =
+ (catch systools:make_tar("release",
+ [{path,["Path"]},src_testsxx])),
+ ?line {'EXIT',{{badarg,[{variables, [{a, b}, {"a", "b"}]}]}, _}} =
+ (catch systools:make_tar("release",
+ [{variables, [{a, b}, {"a", "b"}]}])),
+ ?line {'EXIT',{{badarg,[{var_tar, illegal}]}, _}} =
+ (catch systools:make_tar("release", [{var_tar, illegal}])),
+ ?line {'EXIT',{{badarg,[exreff]}, _}} =
+ (catch systools:make_tar("release",
+ [{path,["Path","Another"]},exreff])),
+ ?line {'EXIT',{{badarg,[{exref,["appl"]}]}, _}} =
+ (catch systools:make_tar("release", [{exref,["appl"]}])),
+ ?line {'EXIT',{{badarg,[{machine, "appl"}]}, _}} =
+ (catch systools:make_tar("release", [{machine,"appl"}])),
+ ok.
+
+
+%% normal_tar
+%%
+normal_tar(suite) -> [];
+normal_tar(doc) ->
+ ["Check normal case"];
+normal_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {ok, _, _} = systools:make_script(LatestName, [silent, {path, P}]),
+ ?line ok = systools:make_tar(LatestName, [{path, P}]),
+ ?line ok = check_tar(fname([lib,'db-2.1',ebin,'db.app']), LatestName),
+ ?line {ok, _, _} = systools:make_tar(LatestName, [{path, P}, silent]),
+ ?line ok = check_tar(fname([lib,'fe-3.1',ebin,'fe.app']), LatestName),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% no_mod_vsn_tar
+%%
+no_mod_vsn_tar(suite) -> [];
+no_mod_vsn_tar(doc) ->
+ ["Check normal case",
+ "Modules specified without version in .app file (db-3.1)."
+ "Note that this is now the normal way - i.e. systools now "
+ "ignores the module versions in the .app file."];
+no_mod_vsn_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest_no_mod_vsn,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-3.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {ok, _, _} = systools:make_script(LatestName, [silent, {path, P}]),
+ ?line ok = systools:make_tar(LatestName, [{path, P}]),
+ ?line ok = check_tar(fname([lib,'db-3.1',ebin,'db.app']), LatestName),
+ ?line {ok, _, _} = systools:make_tar(LatestName, [{path, P}, silent]),
+ ?line ok = check_tar(fname([lib,'fe-3.1',ebin,'fe.app']), LatestName),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% variable_tar
+%%
+variable_tar(suite) -> [];
+variable_tar(doc) ->
+ ["Use variable and create separate tar (included in generated tar)."];
+variable_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {ok, _, _} = systools:make_script(LatestName,
+ [silent,
+ {path, P},
+ {variables,[{"TEST", LibDir}]}]),
+
+ ?line ok = systools:make_tar(LatestName, [{path, P},
+ {variables,[{"TEST", LibDir}]}]),
+ ?line ok = check_var_tar("TEST", LatestName),
+
+ ?line {ok, _, _} = systools:make_tar(LatestName,
+ [{path, P}, silent,
+ {variables,[{"TEST", LibDir}]}]),
+ ?line ok = check_var_tar("TEST", LatestName),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% link_tar
+%%
+link_tar(suite) -> [];
+link_tar(doc) ->
+ ["Check that symlinks in applications are handled correctly"];
+link_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_links, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ %% Make some links
+ ?line Db1Erl = fname(['db-2.1',src,'db1.erl']),
+ ?line NormalDb1Erl = fname([DataDir,d_normal,lib,Db1Erl]),
+ ?line LinkDb1Erl = fname([LibDir, Db1Erl]),
+ ?line ok = file:make_symlink(NormalDb1Erl, LinkDb1Erl),
+ ?line Db1Beam = fname(['db-2.1',ebin,'db1.beam']),
+ ?line NormalDb1Beam = fname([DataDir,d_normal,lib,Db1Beam]),
+ ?line LinkDb1Beam = fname([LibDir, Db1Beam]),
+ ?line ok = file:make_symlink(NormalDb1Beam, LinkDb1Beam),
+ ?line FeApp = fname(['fe-3.1',ebin,'fe.app']),
+ ?line NormalFeApp = fname([DataDir,d_normal,lib,FeApp]),
+ ?line LinkFeApp = fname([LibDir, FeApp]),
+ ?line ok = file:make_symlink(NormalFeApp, LinkFeApp),
+
+ %% Create the tar and check that the linked files are included as
+ %% regular files
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {ok,_,[]} = systools:make_script(LatestName, [{path, P},silent]),
+
+ ?line {ok, _, []} = systools:make_tar(LatestName, [{path, P}, silent]),
+ ?line ok = check_tar_regular(?privdir,
+ [fname([lib,FeApp]),
+ fname([lib,Db1Beam])],
+ LatestName),
+
+ ?line {ok, _, []} = systools:make_tar(LatestName, [{path, P}, silent,
+ {dirs, [src]}]),
+ ?line ok = check_tar_regular(?privdir,
+ [fname([lib,FeApp]),
+ fname([lib,Db1Beam]),
+ fname([lib,Db1Erl])],
+ LatestName),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% src_tests_tar
+%%
+src_tests_tar(suite) -> [];
+src_tests_tar(doc) ->
+ ["Do not check date of object file or that source code can be found."];
+src_tests_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_missing_src, lib]),
+ ?line P1 = fname([LibDir, 'db-2.1', ebin]),
+ ?line P2 = fname([LibDir, 'fe-3.1', ebin]),
+ P = [P1, P2],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% Manipulate the modification date of a beam file so it seems
+ %% older than the .erl file
+ Erl = filename:join([P1,"..","src","db1.erl"]),
+ {ok, FileInfo=#file_info{mtime={{Y,M,D},T}}} = file:read_file_info(Erl),
+ Beam = filename:join(P1,"db1.beam"),
+ ok = file:write_file_info(Beam, FileInfo#file_info{mtime={{Y-1,M,D},T}}),
+
+ %% Remove a .erl file
+ ?line Erl2 = filename:join([P1,"..","src","db2.erl"]),
+ ?line file:delete(Erl2),
+
+ ?line ok = systools:make_script(LatestName, [{path, P}]),
+
+ %% Then make tar - two warnings should be issued when
+ %% src_tests is given
+ %% 1. old object code for db1.beam
+ %% 2. missing source code for db2.beam
+ ?line {ok, _, [{warning,{obj_out_of_date,_}},
+ {warning,{source_not_found,_}}]} =
+ systools:make_tar(LatestName, [{path, P}, silent,
+ {dirs, [src]},
+ src_tests]),
+ ?line ok = check_tar(fname([lib,'db-2.1',src,'db1.erl']), LatestName),
+
+ %% Without the src_tests option, no warning should be issued
+ ?line {ok, _, []} = systools:make_tar(LatestName, [{path, P}, silent,
+ {dirs, [src]}]),
+ ?line ok = check_tar(fname([lib,'db-2.1',src,'db1.erl']), LatestName),
+
+ %% Check that the old no_module_tests option (from the time when
+ %% it was default to do the src_test) is ignored
+ ?line {ok, _, [{warning,{obj_out_of_date,_}},
+ {warning,{source_not_found,_}}]} =
+ systools:make_tar(LatestName, [{path, P}, silent,
+ {dirs, [src]},
+ no_module_tests,
+ src_tests]),
+ ?line ok = check_tar(fname([lib,'db-2.1',src,'db1.erl']), LatestName),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% shadow_tar
+%%
+shadow_tar(suite) -> [];
+shadow_tar(doc) ->
+ ["Check that jam file out of date warning doesn't",
+ "shadow bad module version error."];
+shadow_tar(Config) when is_list(Config) ->
+ % This test has been commented out since the 'vsn' attribute is not used
+ % any more, starting with R6. No warning 'obj_out_of_date' seemed to be
+ % generated.
+ true;
+shadow_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line PSAVE = code:get_path(), % Save path
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, 'd_bad_mod+warn', lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {error, _, _} = systools:make_tar(LatestName, [{path, P}, silent]),
+ ?line {error, _, _} = systools:make_tar(LatestName, [{path, P}, silent,
+ {dirs, [src]}]),
+ ?line ok = file:set_cwd(OldDir),
+ ?line code:set_path(PSAVE),
+ ok.
+
+
+%% var_tar
+%%
+var_tar(suite) -> [];
+var_tar(doc) ->
+ ["Check that make_tar handles generation and placement of tar",
+ "files for variables outside the main tar file.",
+ "Test the {var_tar, include | ownfile | omit} option."];
+var_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+ ?line PSAVE = code:get_path(), % Save path
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {ok, _, _} = systools:make_script(LatestName,
+ [silent,
+ {path, P},
+ {variables,[{"TEST", LibDir}]}]),
+
+ ?line ok = systools:make_tar(LatestName, [{path, P},
+ {var_tar, ownfile},
+ {variables,[{"TEST", LibDir}]}]),
+
+ ?line true = exists_tar_file("TEST"), %% Also removes the file !
+ ?line {error, {not_generated, _}} = check_var_tar("TEST", LatestName),
+
+ ?line ok = systools:make_tar(LatestName, [{path, P},
+ {var_tar, omit},
+ {variables,[{"TEST", LibDir}]}]),
+
+ ?line {error, {not_generated, _}} = check_var_tar("TEST", LatestName),
+ ?line false = exists_tar_file("TEST"),
+
+ ?line ok = systools:make_tar(LatestName, [{path, P},
+ {var_tar, include},
+ {variables,[{"TEST", LibDir}]}]),
+
+ ?line ok = check_var_tar("TEST", LatestName),
+ ?line false = exists_tar_file("TEST"),
+
+ ?line ok = file:set_cwd(OldDir),
+ ?line code:set_path(PSAVE),
+ ok.
+
+
+%% exref_tar
+%%
+exref_tar(suite) -> [];
+exref_tar(doc) ->
+ ["Check exref option."];
+exref_tar(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'fe-3.1', ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line {ok, _, _} = systools:make_script(LatestName, [silent, {path, P}]),
+
+ %% Complete exref
+ ?line {ok, _, W1} =
+ systools:make_tar(LatestName, [exref, {path, P}, silent]),
+ ?line check_exref_warnings(with_db1, W1),
+ ?line ok = check_tar(fname([lib,'db-2.1',ebin,'db.app']), LatestName),
+
+ %% Only exref the db application.
+ ?line {ok, _, W2} =
+ systools:make_tar(LatestName, [{exref, [db]}, {path, P}, silent]),
+ ?line check_exref_warnings(with_db1, W2),
+ ?line ok = check_tar(fname([lib,'fe-3.1',ebin,'fe.app']), LatestName),
+
+ %% Only exref the fe application.
+ ?line {ok, _, W3} =
+ systools:make_tar(LatestName, [{exref, [fe]}, {path, P}, silent]),
+ ?line check_exref_warnings(without_db1, W3),
+ ?line ok = check_tar(fname([lib,'db-2.1',ebin,'db.app']), LatestName),
+
+ %% exref the db and stdlib applications.
+ ?line {ok, _, W4} =
+ systools:make_tar(LatestName, [{exref, [db, stdlib]},
+ {path, P}, silent]),
+ ?line check_exref_warnings(with_db1, W4),
+ ?line ok = check_tar(fname([lib,'fe-3.1',ebin,'fe.app']), LatestName),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% The relup stuff.
+%%
+%%
+
+
+%% make_relup
+%%
+normal_relup(suite) -> [];
+normal_relup(doc) ->
+ ["Check normal case"];
+normal_relup(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir,LatestName} = create_script(latest0,Config),
+ ?line {_LatestDir1,LatestName1} = create_script(latest1,Config),
+ ?line {_LatestDir2,LatestName2} = create_script(latest2,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = [fname([DataDir, d_normal, lib])],
+ ?line P = [fname([LibDir, '*', ebin]),
+ fname([DataDir, lib, kernel, ebin]),
+ fname([DataDir, lib, stdlib, ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% OTP-2561: Check that the option 'restart_emulator' generates a
+ %% "restart_new_emulator" instruction.
+ ?line {ok, _ , _, []} =
+ systools:make_relup(LatestName, [LatestName1], [LatestName1],
+ [{path, P},restart_emulator,silent]),
+ ?line ok = check_relup([{db, "2.1"}], [{db, "1.0"}]),
+ ?line ok = check_restart_emulator(),
+
+ %% This is the ultra normal case
+ ?line ok = systools:make_relup(LatestName, [LatestName1], [LatestName1],
+ [{path, P}]),
+ ?line ok = check_relup([{db, "2.1"}], [{db, "1.0"}]),
+ ?line {ok, _, _, []} =
+ systools:make_relup(LatestName, [LatestName1], [LatestName1],
+ [{path, P}, silent]),
+ ?line ok = check_relup([{db, "2.1"}], [{db, "1.0"}]),
+
+ %% Check that warnings get through
+ ?line ok = systools:make_relup(LatestName, [LatestName2], [LatestName1],
+ [{path, P}]),
+ ?line ok = check_relup([{fe, "3.1"}, {db, "2.1"}], [{db, "1.0"}]),
+ ?line {ok, _, _, [{erts_vsn_changed, _}]} =
+ systools:make_relup(LatestName, [LatestName2], [LatestName1],
+ [{path, P}, silent]),
+ ?line ok = check_relup([{fe, "3.1"}, {db, "2.1"}], [{db, "1.0"}]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+
+%% This test fails if wrong version numbers are seen in the relup file
+%% or if any application is missing. This was triggered by OTP-1360.
+check_relup(UpVsnL, DnVsnL) ->
+ {ok, [{_V1, [{_, _, Up}], [{_, _, Dn}]}]} = file:consult(relup),
+ [] = foldl(fun(X, Acc) ->
+ true = lists:member(X, Acc),
+ lists:delete(X, Acc) end,
+ UpVsnL,
+ [{App, Vsn} || {load_object_code,{App,Vsn,_}} <- Up]),
+ [] = foldl(fun(X, Acc) ->
+ true = lists:member(X, Acc),
+ lists:delete(X, Acc) end,
+ DnVsnL,
+ [{App, Vsn} || {load_object_code,{App,Vsn,_}} <- Dn]),
+ ok.
+
+check_restart_emulator() ->
+ {ok, [{_V1, [{_, _, Up}], [{_, _, Dn}]}]} = file:consult(relup),
+ restart_new_emulator = lists:last(Up),
+ restart_new_emulator = lists:last(Dn),
+ ok.
+
+%% make_relup
+%%
+no_appup_relup(suite) -> [];
+no_appup_relup(doc) ->
+ ["Check that appup files may be missing, but only if we don't need them."];
+no_appup_relup(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir,LatestName} = create_script(latest_small,Config),
+ ?line {_LatestDir0,LatestName0} = create_script(latest_small0,Config),
+ ?line {_LatestDir1,LatestName1} = create_script(latest_small1,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line P1 = [fname([DataDir, d_no_appup, lib, 'fe-3.1', ebin]),
+ fname([DataDir, lib, kernel, ebin]),
+ fname([DataDir, lib, stdlib, ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% Check that appup might be missing
+ ?line ok =
+ systools:make_relup(LatestName, [LatestName], [], [{path, P1}]),
+ ?line {ok,_, _, []} =
+ systools:make_relup(LatestName, [LatestName], [],
+ [silent, {path, P1}]),
+
+ %% Check that appup might NOT be missing when we need it
+ ?line error =
+ systools:make_relup(LatestName, [LatestName0], [], [{path, P1}]),
+ ?line {error,_,{file_problem, {_,{error,{open,_,_}}}}} =
+ systools:make_relup(LatestName, [], [LatestName0],
+ [silent, {path, P1}]),
+
+ %% Check that appups missing vsn traps
+ ?line P2 = [fname([DataDir, d_no_appup, lib, 'fe-2.1', ebin]),
+ fname([DataDir, lib, kernel, ebin]),
+ fname([DataDir, lib, stdlib, ebin])],
+
+ ?line error =
+ systools:make_relup(LatestName0, [LatestName1], [], [{path, P2}]),
+ ?line {error,_,{no_relup, _, _, _}} =
+ systools:make_relup(LatestName0, [], [LatestName1],
+ [silent, {path, P2}]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% make_relup
+%%
+bad_appup_relup(suite) -> [];
+bad_appup_relup(doc) ->
+ ["Check that badly written appup files are detected"];
+bad_appup_relup(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir,LatestName} = create_script(latest_small,Config),
+ ?line {_LatestDir0,LatestName0} = create_script(latest_small0,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line N2 = [fname([DataDir, d_bad_appup, lib, 'fe-3.1', ebin]),
+ fname([DataDir, lib, kernel, ebin]),
+ fname([DataDir, lib, stdlib, ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% Check that bad appup is trapped
+ ?line error =
+ systools:make_relup(LatestName, [LatestName0], [], [{path, N2}]),
+ ?line {error,_,{file_problem, {_, {error, {parse,_, _}}}}} =
+ systools:make_relup(LatestName, [], [LatestName0],
+ [silent, {path, N2}]),
+
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+%% make_relup
+%%
+abnormal_relup(suite) -> [];
+abnormal_relup(doc) ->
+ ["Check some abnormal cases"];
+abnormal_relup(Config) when is_list(Config) ->
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir,LatestName} = create_script(latest0,Config),
+ ?line {_LatestDir1,LatestName1} = create_script(latest1,Config),
+
+ %% Check wrong app vsn
+ ?line DataDir = filename:absname(?copydir),
+ ?line P = [fname([DataDir, d_bad_app_vsn, lib, 'db-2.1', ebin]),
+ fname([DataDir, d_bad_app_vsn, lib, 'fe-3.1', ebin]),
+ fname([DataDir, lib, kernel, ebin]),
+ fname([DataDir, lib, stdlib, ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+ ?line error = systools:make_relup(LatestName, [LatestName1], [LatestName1],
+ [{path, P}]),
+ ?line R0 = systools:make_relup(LatestName, [LatestName1], [LatestName1],
+ [silent, {path, P}]),
+ ?line {error,systools_make,
+ [{error_reading,{db,{no_valid_version,
+ {{"should be","2.1"},
+ {"found file", _, "2.0"}}}}}]} = R0,
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+
+%% Check that application start type is used in relup
+app_start_type_relup(suite) ->
+ [];
+app_start_type_relup(doc) ->
+ ["Release upgrade file with various application start types"];
+app_start_type_relup(Config) when is_list(Config) ->
+ ?line PrivDir = ?config(priv_dir, Config),
+ ?line {Dir1,Name1} = create_script(latest_app_start_type1,Config),
+ ?line {Dir2,Name2} = create_script(latest_app_start_type2,Config),
+ ?line Release1 = filename:join(Dir1,Name1),
+ ?line Release2 = filename:join(Dir2,Name2),
+
+ ?line {ok, Release2Relup, systools_relup, []} = systools:make_relup(Release2, [Release1], [Release1], [{outdir, PrivDir}, silent]),
+ ?line {"2", [{"1",[], UpInstructions}], [{"1",[], DownInstructions}]} = Release2Relup,
+ %% ?t:format("Up: ~p",[UpInstructions]),
+ %% ?t:format("Dn: ~p",[DownInstructions]),
+ ?line [{load_object_code, {mnesia, _, _}},
+ {load_object_code, {sasl, _, _}},
+ {load_object_code, {webtool, _, _}},
+ {load_object_code, {snmp, _, _}},
+ {load_object_code, {xmerl, _, _}},
+ point_of_no_return
+ | UpInstructionsT] = UpInstructions,
+ ?line true = lists:member({apply,{application,start,[mnesia,permanent]}}, UpInstructionsT),
+ ?line true = lists:member({apply,{application,start,[sasl,transient]}}, UpInstructionsT),
+ ?line true = lists:member({apply,{application,start,[webtool,temporary]}}, UpInstructionsT),
+ ?line true = lists:member({apply,{application,load,[snmp]}}, UpInstructionsT),
+ ?line false = lists:any(fun({apply,{application,_,[xmerl|_]}}) -> true; (_) -> false end, UpInstructionsT),
+ ?line [point_of_no_return | DownInstructionsT] = DownInstructions,
+ ?line true = lists:member({apply,{application,stop,[mnesia]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,stop,[sasl]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,stop,[webtool]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,stop,[snmp]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,stop,[xmerl]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,unload,[mnesia]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,unload,[sasl]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,unload,[webtool]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,unload,[snmp]}}, DownInstructionsT),
+ ?line true = lists:member({apply,{application,unload,[xmerl]}}, DownInstructionsT),
+ ok.
+
+
+otp_6226(suite) ->
+ [];
+otp_6226(doc) ->
+ ["{outdir,Dir} option for systools:make_script()"];
+otp_6226(Config) when is_list(Config) ->
+ PrivDir = ?privdir,
+ ?line {ok, OldDir} = file:get_cwd(),
+
+ ?line {LatestDir, LatestName} = create_script(latest0,Config),
+ ?line {_LatestDir, LatestName1} = create_script(latest1,Config),
+
+ ?line DataDir = filename:absname(?copydir),
+ ?line LibDir = fname([DataDir, d_normal, lib]),
+ ?line P = [fname([LibDir, 'db-2.1', ebin]),
+ fname([LibDir, 'db-1.0', ebin]),
+ fname([LibDir, 'fe-3.1', ebin]),
+ fname([DataDir, lib, kernel, ebin]),
+ fname([DataDir, lib, stdlib, ebin])],
+
+ ?line ok = file:set_cwd(LatestDir),
+
+
+ %% Create an outdir1 directory
+ ?line ok = file:make_dir("outdir1"),
+
+ %% ==== Now test systools:make_script ====
+ %% a) badarg
+ ?line {'EXIT', {{badarg,[{outdir,outdir1}]}, _}} =
+ (catch systools:make_script(LatestName, [{outdir,outdir1},
+ {path,P},silent])),
+
+ %% b) absolute path
+ Outdir1 = filename:join(PrivDir, "outdir1"),
+ ?line {ok,_,[]} = systools:make_script(LatestName, [{outdir,Outdir1},
+ {path,P},silent]),
+ ?line Script1 = filename:join(Outdir1, LatestName ++ ".script"),
+ ?line Boot1 = filename:join(Outdir1, LatestName ++ ".boot"),
+ ?line true = filelib:is_file(Script1),
+ ?line true = filelib:is_file(Boot1),
+ ?line ok = file:delete(Script1),
+ ?line ok = file:delete(Boot1),
+
+ %% c) relative path
+ ?line {ok,_,[]} = systools:make_script(LatestName, [{outdir,"./outdir1"},
+ {path,P},silent]),
+ ?line true = filelib:is_file(Script1),
+ ?line true = filelib:is_file(Boot1),
+ ?line ok = file:delete(Script1),
+ ?line ok = file:delete(Boot1),
+
+ %% d) absolute but incorrect path
+ ?line Outdir2 = filename:join(PrivDir, "outdir2"),
+ ?line Script2 = filename:join(Outdir2, LatestName ++ ".script"),
+ ?line {error,_,{open,Script2,_}} =
+ systools:make_script(LatestName, [{outdir,Outdir2},{path,P},silent]),
+
+ %% e) relative but incorrect path
+ ?line {error,_,{open,_,_}} =
+ systools:make_script(LatestName, [{outdir,"./outdir2"},{path,P},silent]),
+
+ %% f) with .rel in another directory than cwd
+ ?line ok = file:set_cwd(Outdir1),
+ ?line {ok,_,[]} = systools:make_script(filename:join(PrivDir, LatestName),
+ [{outdir,"."},{path,P},silent]),
+ ?line true = filelib:is_file(LatestName ++ ".script"),
+ ?line true = filelib:is_file(LatestName ++ ".boot"),
+ ?line ok = file:delete(LatestName ++ ".script"),
+ ?line ok = file:delete(LatestName ++ ".boot"),
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% ==== Now test systools:make_tar =====
+ ?line {ok,_,[]} = systools:make_script(LatestName, [{path,P},silent]),
+ %% a) badarg
+ ?line {'EXIT', {{badarg, [{outdir,outdir1}]}, _}} =
+ (catch systools:make_tar(LatestName,[{outdir,outdir1},{path,P},silent])),
+
+ %% b) absolute path
+ ?line {ok,_,[]} = systools:make_tar(LatestName, [{outdir,Outdir1},
+ {path,P},silent]),
+ ?line Tar1 = filename:join(Outdir1,LatestName++".tar.gz"),
+ ?line true = filelib:is_file(Tar1),
+ ?line ok = file:delete(Tar1),
+
+ %% c) relative path
+ ?line {ok,_,[]} = systools:make_tar(LatestName, [{outdir,"./outdir1"},
+ {path,P},silent]),
+ ?line true = filelib:is_file(Tar1),
+ ?line ok = file:delete(Tar1),
+
+ %% d) absolute but incorrect path
+ ?line Tar2 = filename:join(Outdir2,LatestName++".tar.gz"),
+ ?line {error,_,{tar_error,{open,Tar2,{Tar2,enoent}}}} =
+ systools:make_tar(LatestName, [{outdir,Outdir2},{path,P},silent]),
+
+ %% e) relative but incorrect path
+ ?line {error,_,{tar_error,{open,_,_}}} =
+ systools:make_tar(LatestName, [{outdir,"./outdir2"},{path,P},silent]),
+
+ %% f) with .rel in another directory than cwd
+ ?line ok = file:set_cwd(Outdir1),
+ ?line {ok,_,[]} = systools:make_tar(filename:join(PrivDir, LatestName),
+ [{outdir,"."},{path,P},silent]),
+ ?line true = filelib:is_file(Tar1),
+ ?line ok = file:set_cwd(LatestDir),
+
+ %% ===== Now test systools:make_relup =====
+ %% a) badarg
+ ?line {'EXIT', {{badarg, [{outdir,outdir1}]}, _}} =
+ (catch systools:make_relup(LatestName,[LatestName1],[LatestName1],
+ [{outdir,outdir1},
+ {path,P},silent])),
+
+ %% b) absolute path
+ Relup = filename:join(Outdir1, "relup"),
+ ?line {ok,_,_,[]} = systools:make_relup(LatestName,[LatestName1],[LatestName1],
+ [{outdir,Outdir1},
+ {path,P},silent]),
+ ?line true = filelib:is_file(Relup),
+ ?line ok = file:delete(Relup),
+
+ %% c) relative path
+ ?line {ok,_,_,[]} = systools:make_relup(LatestName,[LatestName1],[LatestName1],
+ [{outdir,"./outdir1"},
+ {path,P},silent]),
+ ?line true = filelib:is_file(Relup),
+ ?line ok = file:delete(Relup),
+
+ %% d) absolute but incorrect path
+ ?line {error,_,{file_problem,{"relup",enoent}}} =
+ systools:make_relup(LatestName,[LatestName1],[LatestName1],
+ [{outdir,Outdir2},{path,P},silent]),
+
+ %% e) relative but incorrect path
+ ?line {error,_,{file_problem,{"relup",enoent}}} =
+ systools:make_relup(LatestName,[LatestName1],[LatestName1],
+ [{outdir,"./outdir2"},{path,P},silent]),
+
+ %% f) with .rel in another directory than cwd
+ %% -- not necessary to test since relup by default is placed in
+ %% cwd, not in the same directory as the .rel file --
+
+ %% Change back to previous working directory
+ ?line ok = file:set_cwd(OldDir),
+ ok.
+
+
+%%%%%%
+%%%%%% Utilities
+%%%%%%
+
+check_script_path(RelName) ->
+ {ok, [Conts]} = read_script_file(RelName),
+ {script, {_, _}, ListOfThings} = Conts,
+ case lists:keysearch(path, 1, ListOfThings) of
+ {value, {path, [$$,$R,$O,$O,$T | _]}} -> %"$ROOT..."
+ false;
+ _ -> ok
+ end.
+
+check_var_script_file(VarDirs, NoExistDirs, RelName) ->
+ {ok, [Conts]} = read_script_file(RelName),
+ {script, {_, _}, ListOfThings} = Conts,
+ AllPaths = lists:append(lists:map(fun({path, P}) -> P;
+ (_) -> []
+ end,
+ ListOfThings)),
+ case lists:filter(fun(VarDir) -> lists:member(VarDir, AllPaths) end,
+ VarDirs) of
+ VarDirs ->
+ ok;
+ _ ->
+ test_server:fail("All variable dirs not in generated script")
+ end,
+ case lists:filter(fun(NoExistDir) -> lists:member(NoExistDir, AllPaths) end,
+ NoExistDirs) of
+ [] ->
+ ok;
+ _ ->
+ test_server:fail("Unexpected dirs in generated script")
+ end.
+
+check_include_script(RelName, ExpectedLoad, ExpectedStart) ->
+ {ok, [Conts]} = read_script_file(RelName),
+ {script, {_, _}, ListOfThings} = Conts,
+
+ %% Check that the applications are loaded in given order !
+ ActualLoad =
+ [App || {apply,{application,load,[{application,App,_}]}} <- ListOfThings,
+ App=/=kernel,
+ App=/=stdlib],
+
+ if ActualLoad =:= ExpectedLoad -> ok;
+ true -> test_server:fail({bad_load_order, ActualLoad, ExpectedLoad})
+ end,
+
+ %% Check that applications are started in given order !
+ ActualStart =
+ [App || {apply,{application,start_boot,[App|_]}} <- ListOfThings,
+ App =/= kernel,
+ App =/= stdlib],
+
+ if ActualStart =:= ExpectedStart -> ok;
+ true -> test_server:fail({bad_start_order, ActualStart,ExpectedStart})
+ end,
+
+ ok.
+
+read_script_file(RelName) ->
+ file:consult(RelName ++ ".script").
+
+check_var_tar(Variable, RelName) ->
+ Expected = tar_name(Variable),
+ case check_tar(Expected,RelName) of
+ ok ->
+ ok;
+ {error, {erroneous_tar_file, _, missing, _}} ->
+ {error, {not_generated, Expected}}
+ end.
+
+exists_tar_file(Name) ->
+ File = tar_name(Name),
+ case filelib:is_regular(File) of
+ true ->
+ ok = file:delete(File),
+ true;
+ _ ->
+ false
+ end.
+
+%% Take a snap of the generated tar file and check if a certain
+%% file is included.
+%% This ensures at least that the tar file is generated.
+check_tar(File, RelName) ->
+ TarContents = tar_contents(RelName),
+ case lists:member(File,TarContents) of
+ true -> ok;
+ _ -> {error, {erroneous_tar_file, tar_name(RelName), missing, File}}
+ end.
+
+%% Check that the given files exist in the tar file, and that they are
+%% not symlinks
+check_tar_regular(PrivDir, Files, RelName) ->
+ TmpDir = fname(PrivDir,tmp),
+ ok = file:make_dir(TmpDir),
+ ok = erl_tar:extract(tar_name(RelName),
+ [{files,Files},{cwd,TmpDir},compressed]),
+ R = lists:foldl(fun(File,Acc) ->
+ case file:read_link_info(fname(TmpDir,File)) of
+ {ok,#file_info{type=regular}} ->
+ Acc;
+ {ok,#file_info{type=Other}} ->
+ [{File,Other}|Acc];
+ _ ->
+ [{File,missing}|Acc]
+ end
+ end,
+ [],
+ Files),
+ delete_tree(TmpDir),
+ case R of
+ [] ->
+ ok;
+ NotThere ->
+ {error,{erroneous_tar_file,tar_name(RelName),NotThere}}
+ end.
+
+delete_tree(Dir) ->
+ case filelib:is_dir(Dir) of
+ true ->
+ {ok,Files} = file:list_dir(Dir),
+ lists:foreach(fun(File) -> delete_tree(filename:join(Dir,File)) end,
+ Files),
+ file:del_dir(Dir);
+ false ->
+ ok = file:delete(Dir)
+ end.
+
+tar_contents(Name) ->
+ {ok, Cont} = erl_tar:table(Name ++ ".tar.gz", [compressed]),
+ Cont.
+
+tar_name(Name) ->
+ Name ++ ".tar.gz".
+
+create_script(latest,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, latest),
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 3\", \"LATEST\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{kernel, \"~s\"}, {stdlib, \"~s\"}, \n"
+ " {db, \"2.1\"}, {fe, \"3.1\"}]}.\n",
+ [KernelVer,StdlibVer]),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest_no_mod_vsn,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, latest),
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 3\", \"LATESTNOMOD\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{kernel, \"~s\"}, {stdlib, \"~s\"}, \n"
+ " {db, \"3.1\"}, {fe, \"3.1\"}]}.\n",
+ [KernelVer,StdlibVer]),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest0,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, 'latest-1'),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 2\", \"LATEST0\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{kernel, \"1.0\"}, {stdlib, \"1.0\"}, \n"
+ " {db, \"2.1\"}, {fe, \"3.1\"}]}.\n",
+ []),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest1,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, latest),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 2\", \"LATEST1\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{kernel, \"1.0\"}, {stdlib, \"1.0\"}, \n"
+ " {db, \"1.0\"}, {fe, \"3.1\"}]}.\n",
+ []),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest2,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, 'latest-2'),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 1\", \"LATEST2\"}, \n"
+ " {erts, \"4.3\"}, \n"
+ " [{kernel, \"1.0\"}, {stdlib, \"1.0\"}, \n"
+ " {db, \"1.0\"}, {fe, \"2.1\"}]}.\n",
+ []),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest_small,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, 'latest-small'),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 2\", \"LATEST_SMALL\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{kernel, \"1.0\"}, {stdlib, \"1.0\"}, \n"
+ " {fe, \"3.1\"}]}.\n",
+ []),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest_small0,Config) -> %Differs in fe vsn
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, 'latest-small0'),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 2\", \"LATEST_SMALL0\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{kernel, \"1.0\"}, {stdlib, \"1.0\"}, \n"
+ " {fe, \"2.1\"}]}.\n",
+ []),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest_small1,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, 'latest-small1'),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 2\", \"LATEST_SMALL1\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{kernel, \"1.0\"}, {stdlib, \"1.0\"}, \n"
+ " {fe, \"500.18.7\"}]}.\n",
+ []),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest_nokernel,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, 'latest-nokernel'),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line io:format(Fd,
+ "{release, {\"Test release 3\", \"LATEST_NOKERNEL\"}, \n"
+ " {erts, \"4.4\"}, \n"
+ " [{db, \"2.1\"}, {fe, \"3.1\"}]}.\n",
+ []),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest_app_start_type1,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, latest_app_start_type1),
+ ?line ErtsVer = erlang:system_info(version),
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line RelfileContent =
+ {release,{"Test release", "1"},
+ {erts,ErtsVer},
+ [{kernel,KernelVer},
+ {stdlib,StdlibVer}]},
+ ?line io:format(Fd,"~p.~n",[RelfileContent]),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)};
+create_script(latest_app_start_type2,Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, latest_app_start_type2),
+ ?line ErtsVer = erlang:system_info(version),
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+ ?line OtherApps = [{mnesia,permanent},
+ {sasl,transient},
+ {webtool,temporary},
+ {snmp,load},
+ {xmerl,none}],
+ ?line lists:foreach(fun({App,_}) -> application:load(App) end,
+ OtherApps),
+ ?line Loaded = application:loaded_applications(),
+ ?line OtherAppsRel =
+ lists:map(fun({App,StartType}) ->
+ {_,_,Ver} = lists:keyfind(App,1,Loaded),
+ {App,Ver,StartType}
+ end,
+ OtherApps),
+ ?line {ok,Fd} = file:open(Name++".rel",write),
+ ?line RelfileContent =
+ {release,{"Test release", "2"},
+ {erts,ErtsVer},
+ [{kernel,KernelVer},
+ {stdlib,StdlibVer} | OtherAppsRel]},
+ ?line io:format(Fd,"~p.~n",[RelfileContent]),
+ ?line ok = file:close(Fd),
+ {filename:dirname(Name), filename:basename(Name)}.
+
+create_include_files(inc1, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc1),
+ create_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t6, \"1.0\"}, {t5, \"1.0\"}, \n"
+ " {t4, \"1.0\"}, {t3, \"1.0\"}, {t2, \"1.0\"}, \n"
+ " {t1, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc2, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc2),
+ create_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t6 does not include t5 !
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t6, \"1.0\", [t4]}, {t5, \"1.0\"}, \n"
+ " {t4, \"1.0\"}, {t3, \"1.0\"}, {t2, \"1.0\"}, \n"
+ " {t1, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc3, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc3),
+ create_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t3 does not include t2 !
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t6, \"1.0\"}, {t5, \"1.0\"}, \n"
+ " {t4, \"1.0\"}, {t3, \"1.0\", []}, {t2, \"1.0\"}, \n"
+ " {t1, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc4, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc4),
+ create_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t3 does not include t2 !
+ %% t6 does not include t5 !
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t6, \"1.0\", [t4]}, {t5, \"1.0\"}, \n"
+ " {t4, \"1.0\"}, {t3, \"1.0\", []}, {t2, \"1.0\"}, \n"
+ " {t1, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc5, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc5),
+ create_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t6 does not include t5 !
+ %% exclude t5.
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t6, \"1.0\", [t4]}, \n"
+ " {t4, \"1.0\"}, {t3, \"1.0\", []}, {t2, \"1.0\"}, \n"
+ " {t1, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc6, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc6),
+ create_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t3 does include non existing t2 !
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t6, \"1.0\"}, {t5, \"1.0\"}, \n"
+ " {t4, \"1.0\"}, {t3, \"1.0\"}, \n"
+ " {t1, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc7, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc7),
+ create_apps(PrivDir),
+ create_app(t7, PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t7 and t6 does include t5 !
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t7, \"1.0\"}, {t6, \"1.0\"}, {t5, \"1.0\"}, \n"
+ " {t4, \"1.0\"}, {t3, \"1.0\"}, {t2, \"1.0\"}, \n"
+ " {t1, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc8, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc8),
+ create_circular_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t8 uses t9 and t10 includes t9 !
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t8, \"1.0\"}, {t9, \"1.0\"}, {t10, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc9, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc9),
+ create_circular_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t8 uses t9, t9 uses t10 and t10 includes t8 ==> circular !!
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t8, \"1.0\"}, {t9, \"1.0\"}, {t10, \"1.0\", [t8]}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc10, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc10),
+ create_circular_apps(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ %% t9 tries to include not specified (in .app file) application !
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t8, \"1.0\"}, {t9, \"1.0\", [t7]}, {t10, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(inc11, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, inc11),
+ create_apps2(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {t11, \"1.0\"}, \n"
+ " {t12, \"1.0\"}, \n"
+ " {t13, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)};
+
+create_include_files(otp_3065, Config) ->
+ ?line PrivDir = ?privdir,
+ ?line Name = fname(PrivDir, otp_3065),
+ create_apps_3065(PrivDir),
+
+ ?line Apps = application_controller:which_applications(),
+ ?line {value,{_,_,KernelVer}} = lists:keysearch(kernel,1,Apps),
+ ?line {value,{_,_,StdlibVer}} = lists:keysearch(stdlib,1,Apps),
+
+ Rel = "{release, {\"test\",\"R1A\"}, {erts, \"45\"},\n"
+ " [{kernel, \"" ++ KernelVer ++ "\"}, {stdlib, \""
+ ++ StdlibVer ++ "\"},\n"
+ " {chAts, \"1.0\"}, {aa12, \"1.0\"}, \n"
+ " {chTraffic, \"1.0\"}]}.\n",
+ file:write_file(Name ++ ".rel", list_to_binary(Rel)),
+ {filename:dirname(Name), filename:basename(Name)}.
+
+create_apps(Dir) ->
+ T1 = "{application, t1,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [kernel, stdlib]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't1.app'), list_to_binary(T1)),
+
+ T2 = "{application, t2,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [t1]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't2.app'), list_to_binary(T2)),
+
+ T3 = "{application, t3,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, [t2]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't3.app'), list_to_binary(T3)),
+
+ T4 = "{application, t4,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [t3]},\n"
+ " {included_applications, []},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't4.app'), list_to_binary(T4)),
+
+ T5 = "{application, t5,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [t3]},\n"
+ " {included_applications, []},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't5.app'), list_to_binary(T5)),
+
+ T6 = "{application, t6,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, [t4, t5]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't6.app'), list_to_binary(T6)).
+
+create_app(t7, Dir) ->
+ T7 = "{application, t7,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, [t5]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't7.app'), list_to_binary(T7)).
+
+create_circular_apps(Dir) ->
+ T8 = "{application, t8,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [t9]},\n"
+ " {included_applications, []},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't8.app'), list_to_binary(T8)),
+
+ T9 = "{application, t9,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [t10]},\n"
+ " {included_applications, []},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't9.app'), list_to_binary(T9)),
+
+ T10 = "{application, t10,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, [t8, t9]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't10.app'), list_to_binary(T10)).
+
+create_apps2(Dir) ->
+ T11 = "{application, t11,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, [t13]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't11.app'), list_to_binary(T11)),
+
+ T12 = "{application, t12,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [t11]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't12.app'), list_to_binary(T12)),
+
+ T13 = "{application, t13,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, []},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 't13.app'), list_to_binary(T13)).
+
+
+
+create_apps_3065(Dir) ->
+ T11 = "{application, chTraffic,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, [chAts]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 'chTraffic.app'), list_to_binary(T11)),
+
+ T12 = "{application, chAts,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, []},\n"
+ " {included_applications, [aa12]},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 'chAts.app'), list_to_binary(T12)),
+
+ T13 = "{application, aa12,\n"
+ " [{vsn, \"1.0\"},\n"
+ " {description, \"test\"},\n"
+ " {modules, []},\n"
+ " {applications, [chAts]},\n"
+ " {included_applications, []},\n"
+ " {registered, []}]}.\n",
+ file:write_file(fname(Dir, 'aa12.app'), list_to_binary(T13)).
+
+fname(N) ->
+ filename:join(N).
+
+fname(Dir, Basename) ->
+ filename:join(Dir, Basename).
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.app
new file mode 100644
index 0000000000..d375768b99
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.app
@@ -0,0 +1,8 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "2.0"},
+ {modules, [{db1, "1.0"}, {db2, "1.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {db1, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.appup b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.appup
new file mode 100644
index 0000000000..621838f0b4
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/ebin/db.appup
@@ -0,0 +1,20 @@
+%%
+%% Release upgrade script for db (data base)
+%%
+
+{
+ "2.1",
+%%% Upgrade from:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]},
+ {"1.1", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db1.erl b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db1.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db1.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/db-2.1/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.app
new file mode 100644
index 0000000000..d3bd85cda6
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.app
@@ -0,0 +1,8 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "3.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {fe2, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.appup b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.appup
new file mode 100644
index 0000000000..4ab13c1bae
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/ebin/fe.appup
@@ -0,0 +1,27 @@
+%%
+%% Release upgrade script for fe (front end)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"2.1.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {{advanced, extra}, soft_purge, soft_purge,
+ [fe1, fe2]}
+ ]},
+
+ {"2.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe1, fe2]}
+ ]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"2.1", [{update, fe2, soft, soft_purge, soft_purge, []},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe2]}
+ ]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe1.erl b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe1.erl
new file mode 100644
index 0000000000..aa5bfa8098
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe1.erl
@@ -0,0 +1,2 @@
+-module(fe1).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe2.erl b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe2.erl
new file mode 100644
index 0000000000..869f3b93c8
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe2.erl
@@ -0,0 +1,2 @@
+-module(fe2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe3.erl b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_app_vsn/lib/fe-3.1/src/fe3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.app
new file mode 100644
index 0000000000..0696e2494c
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.app
@@ -0,0 +1,7 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "3.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {mod, {fe1, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.appup b/lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.appup
new file mode 100644
index 0000000000..dac4c00851
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_appup/lib/fe-3.1/ebin/fe.appup
@@ -0,0 +1,27 @@
+%%
+%% Release upgrade script for fe (front end)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"2.1.1" [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge,
+ [fe1, fe2]}
+ ]},
+
+ {"2.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe1, fe2]}
+ ]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"2.1", [{update, fe2, soft, soft_purge, soft_purge, []},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe2]}
+ ]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.app
new file mode 100644
index 0000000000..191919f8d3
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.app
@@ -0,0 +1,8 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "2.1"},
+ {modules, [{db1, "1.0"}, {db2, "1.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {db1, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.appup b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.appup
new file mode 100644
index 0000000000..621838f0b4
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/ebin/db.appup
@@ -0,0 +1,20 @@
+%%
+%% Release upgrade script for db (data base)
+%%
+
+{
+ "2.1",
+%%% Upgrade from:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]},
+ {"1.1", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db1.erl b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db1.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db1.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/db-2.1/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.app
new file mode 100644
index 0000000000..d3bd85cda6
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.app
@@ -0,0 +1,8 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "3.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {fe2, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.appup b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.appup
new file mode 100644
index 0000000000..2db69eba76
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/ebin/fe.appup
@@ -0,0 +1,27 @@
+%%
+%% Release upgrade script for fe (front end)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"2.1.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge,
+ [fe1, fe2]}
+ ]},
+
+ {"2.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe1, fe2]}
+ ]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"2.1", [{update, fe2, soft, soft_purge, soft_purge, []},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe2]}
+ ]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe1.erl b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe1.erl
new file mode 100644
index 0000000000..cdbb9ef532
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe1.erl
@@ -0,0 +1,2 @@
+-module(fe1).
+-vsn("1.1").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe2.erl b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe2.erl
new file mode 100644
index 0000000000..869f3b93c8
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe2.erl
@@ -0,0 +1,2 @@
+-module(fe2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe3.erl b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_bad_mod+warn/lib/fe-3.1/src/fe3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.app
new file mode 100644
index 0000000000..3e0ac3c3c9
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.app
@@ -0,0 +1,8 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "2.1"},
+ {modules, [{db1, "1.0"}, {db2, "1.0"}, {db3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {db1, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.appup b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.appup
new file mode 100644
index 0000000000..621838f0b4
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/ebin/db.appup
@@ -0,0 +1,20 @@
+%%
+%% Release upgrade script for db (data base)
+%%
+
+{
+ "2.1",
+%%% Upgrade from:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]},
+ {"1.1", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db3.erl b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/db-2.1/src/db3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/ebin/fe.appup b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/ebin/fe.appup
new file mode 100644
index 0000000000..4ab13c1bae
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/ebin/fe.appup
@@ -0,0 +1,27 @@
+%%
+%% Release upgrade script for fe (front end)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"2.1.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {{advanced, extra}, soft_purge, soft_purge,
+ [fe1, fe2]}
+ ]},
+
+ {"2.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe1, fe2]}
+ ]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"2.1", [{update, fe2, soft, soft_purge, soft_purge, []},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe2]}
+ ]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe1.erl b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe1.erl
new file mode 100644
index 0000000000..aa5bfa8098
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe1.erl
@@ -0,0 +1,2 @@
+-module(fe1).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe2.erl b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe2.erl
new file mode 100644
index 0000000000..869f3b93c8
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe2.erl
@@ -0,0 +1,2 @@
+-module(fe2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe3.erl b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_links/lib/fe-3.1/src/fe3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.app
new file mode 100644
index 0000000000..191919f8d3
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.app
@@ -0,0 +1,8 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "2.1"},
+ {modules, [{db1, "1.0"}, {db2, "1.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {db1, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.appup b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.appup
new file mode 100644
index 0000000000..621838f0b4
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/ebin/db.appup
@@ -0,0 +1,20 @@
+%%
+%% Release upgrade script for db (data base)
+%%
+
+{
+ "2.1",
+%%% Upgrade from:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]},
+ {"1.1", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db1.erl b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db1.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db1.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/db-2.1/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.app
new file mode 100644
index 0000000000..d3bd85cda6
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.app
@@ -0,0 +1,8 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "3.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {fe2, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.appup b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.appup
new file mode 100644
index 0000000000..4ab13c1bae
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/ebin/fe.appup
@@ -0,0 +1,27 @@
+%%
+%% Release upgrade script for fe (front end)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"2.1.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {{advanced, extra}, soft_purge, soft_purge,
+ [fe1, fe2]}
+ ]},
+
+ {"2.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe1, fe2]}
+ ]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"2.1", [{update, fe2, soft, soft_purge, soft_purge, []},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe2]}
+ ]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe1.erl b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe1.erl
new file mode 100644
index 0000000000..cdbb9ef532
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe1.erl
@@ -0,0 +1,2 @@
+-module(fe1).
+-vsn("1.1").
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe2.erl b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe2.erl
new file mode 100644
index 0000000000..869f3b93c8
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe2.erl
@@ -0,0 +1,2 @@
+-module(fe2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe3.erl b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_missing_src/lib/fe-3.1/src/fe3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.app
new file mode 100644
index 0000000000..47ea248720
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.app
@@ -0,0 +1,8 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "2.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {fe2, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.appup b/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.appup
new file mode 100644
index 0000000000..2db69eba76
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-2.1/ebin/fe.appup
@@ -0,0 +1,27 @@
+%%
+%% Release upgrade script for fe (front end)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"2.1.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge,
+ [fe1, fe2]}
+ ]},
+
+ {"2.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe1, fe2]}
+ ]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"2.1", [{update, fe2, soft, soft_purge, soft_purge, []},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe2]}
+ ]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-3.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-3.1/ebin/fe.app
new file mode 100644
index 0000000000..0696e2494c
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_no_appup/lib/fe-3.1/ebin/fe.app
@@ -0,0 +1,7 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "3.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {mod, {fe1, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/ebin/db.app
new file mode 100644
index 0000000000..22530ee335
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/ebin/db.app
@@ -0,0 +1,8 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "1.0"},
+ {modules, [{db1, "1.0"}, {db2, "1.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {db1, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db1.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db1.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db1.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.0/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/ebin/db.app
new file mode 100644
index 0000000000..7243a0a96a
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/ebin/db.app
@@ -0,0 +1,8 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "1.1"},
+ {modules, [{db1, "1.0"}, {db2, "1.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {db1, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db1.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db1.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db1.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-1.1/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.app
new file mode 100644
index 0000000000..202d7f1234
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.app
@@ -0,0 +1,7 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "2.1"},
+ {modules, [{db1, "1.0"}, {db2, "1.0"}]},
+ {registered, []},
+ {applications, []},
+ {mod, {db1, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.appup b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.appup
new file mode 100644
index 0000000000..621838f0b4
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/ebin/db.appup
@@ -0,0 +1,20 @@
+%%
+%% Release upgrade script for db (data base)
+%%
+
+{
+ "2.1",
+%%% Upgrade from:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]},
+ {"1.1", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db1.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db1.erl
new file mode 100644
index 0000000000..7cddf6bb63
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db1.erl
@@ -0,0 +1,13 @@
+-module(db1).
+-vsn("1.0").
+
+-export([a/0]).
+
+a() ->
+ lists:non_existing_func("dummy_list"),
+ b().
+
+b() ->
+ fe2:non_existing_func(),
+ db2:non_existing_func(),
+ fe1:a().
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-2.1/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.app b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.app
new file mode 100644
index 0000000000..97643561eb
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.app
@@ -0,0 +1,7 @@
+{application, db,
+ [{description, "ERICSSON NR FOR DB"},
+ {vsn, "3.1"},
+ {modules, [db1, db2]},
+ {registered, []},
+ {applications, []},
+ {mod, {db1, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.appup b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.appup
new file mode 100644
index 0000000000..e636eee158
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/ebin/db.appup
@@ -0,0 +1,20 @@
+%%
+%% Release upgrade script for db (data base)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]},
+ {"1.1", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"1.0", [{update, db1, soft, soft_purge, soft_purge, []},
+ {update, db2, soft, soft_purge, soft_purge, [db1]}]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db1.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db1.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db1.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db2.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db2.erl
new file mode 100644
index 0000000000..a17640316e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/db-3.1/src/db2.erl
@@ -0,0 +1,2 @@
+-module(db2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/ebin/fe.app
new file mode 100644
index 0000000000..c7ba1dfe91
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/ebin/fe.app
@@ -0,0 +1,8 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "2.1.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {fe2, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe1.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe1.erl
new file mode 100644
index 0000000000..aa5bfa8098
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe1.erl
@@ -0,0 +1,2 @@
+-module(fe1).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe2.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe2.erl
new file mode 100644
index 0000000000..869f3b93c8
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe2.erl
@@ -0,0 +1,2 @@
+-module(fe2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe3.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1.1/src/fe3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/ebin/fe.app
new file mode 100644
index 0000000000..47ea248720
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/ebin/fe.app
@@ -0,0 +1,8 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "2.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {env, []},
+ {start, {fe2, start, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe1.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe1.erl
new file mode 100644
index 0000000000..aa5bfa8098
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe1.erl
@@ -0,0 +1,2 @@
+-module(fe1).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe2.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe2.erl
new file mode 100644
index 0000000000..869f3b93c8
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe2.erl
@@ -0,0 +1,2 @@
+-module(fe2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe3.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-2.1/src/fe3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.app b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.app
new file mode 100644
index 0000000000..0696e2494c
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.app
@@ -0,0 +1,7 @@
+{application, fe,
+ [{description, "ERICSSON NR FOR FE"},
+ {vsn, "3.1"},
+ {modules, [{fe1, "1.0"}, {fe2, "1.0"}, {fe3, "2.0"}]},
+ {registered, []},
+ {applications, []},
+ {mod, {fe1, []}}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.appup b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.appup
new file mode 100644
index 0000000000..2db69eba76
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/ebin/fe.appup
@@ -0,0 +1,27 @@
+%%
+%% Release upgrade script for fe (front end)
+%%
+
+{
+ "3.1",
+%%% Upgrade from:
+ [
+ {"2.1.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge,
+ [fe1, fe2]}
+ ]},
+
+ {"2.1", [{update, fe1, soft, soft_purge, soft_purge, []},
+ {update, fe2, soft, soft_purge, soft_purge, [fe1]},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe1, fe2]}
+ ]}
+ ],
+
+%%% Downgrade to:
+ [
+ {"2.1", [{update, fe2, soft, soft_purge, soft_purge, []},
+ {update, fe3, {advanced, extra}, soft_purge, soft_purge, [fe2]}
+ ]}
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe1.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe1.erl
new file mode 100644
index 0000000000..8aca89b2c7
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe1.erl
@@ -0,0 +1,7 @@
+-module(fe1).
+-vsn("1.0").
+
+-export([a/0]).
+
+a() ->
+ ok.
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe2.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe2.erl
new file mode 100644
index 0000000000..869f3b93c8
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe2.erl
@@ -0,0 +1,2 @@
+-module(fe2).
+-vsn("1.0").
diff --git a/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe3.erl b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe3.erl
new file mode 100644
index 0000000000..6473342f52
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/d_normal/lib/fe-3.1/src/fe3.erl
@@ -0,0 +1,2 @@
+-module(fe3).
+-vsn("2.0").
diff --git a/lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.app b/lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.app
new file mode 100644
index 0000000000..e33314be7a
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.app
@@ -0,0 +1,6 @@
+{application, kernel,
+ [{description, "FAKE KERNEL"},
+ {vsn, "1.0"},
+ {modules, []},
+ {registered, []},
+ {applications, []}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.appup b/lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.appup
new file mode 100644
index 0000000000..c53f07591f
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/lib/kernel/ebin/kernel.appup
@@ -0,0 +1,12 @@
+%%
+%% Fake release upgrade script for kernel
+%%
+
+{
+ "4.4.1",
+ [
+ ],
+
+ [
+ ]
+}.
diff --git a/lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.app b/lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.app
new file mode 100644
index 0000000000..288fcfe74e
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.app
@@ -0,0 +1,6 @@
+{application, stdlib,
+ [{description, "FAKE STDLIB"},
+ {vsn, "1.0"},
+ {modules, []},
+ {registered, []},
+ {applications, []}]}.
diff --git a/lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.appup b/lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.appup
new file mode 100644
index 0000000000..b521eb5d71
--- /dev/null
+++ b/lib/sasl/test/systools_SUITE_data/lib/stdlib/ebin/stdlib.appup
@@ -0,0 +1,12 @@
+%%
+%% Fake release upgrade script for stdlib
+%%
+
+{
+ "1.1",
+ [
+ ],
+
+ [
+ ]
+}.
diff --git a/lib/sasl/test/systools_rc_SUITE.erl b/lib/sasl/test/systools_rc_SUITE.erl
new file mode 100644
index 0000000000..bb93f38fa7
--- /dev/null
+++ b/lib/sasl/test/systools_rc_SUITE.erl
@@ -0,0 +1,488 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2010. 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(systools_rc_SUITE).
+
+-include_lib("test_server/include/test_server.hrl").
+-include_lib("sasl/src/systools.hrl").
+-export([all/0,groups/0,init_per_group/2,end_per_group/2,
+ syntax_check/1, translate/1, translate_app/1]).
+
+%%-----------------------------------------------------------------
+%% erl -compile systools_rc_SUITE @i ../src/ @i ../../test_server/include/
+%% c(systools_rc_SUITE, [{i, "../src"}, {i, "../../test_server/include"}]).
+%%-----------------------------------------------------------------
+all() ->
+ [syntax_check, translate, translate_app].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+syntax_check(suite) -> [];
+syntax_check(Config) when is_list(Config) ->
+ PreApps =
+ [#application{name = test,
+ description = "TEST",
+ vsn = "0.1",
+ modules = [{foo,1},{bar,1},{baz,1},{old_mod,1}],
+ regs = [],
+ mod = {sasl, []}},
+ #application{name = snmp,
+ description = "SNMP",
+ vsn = "1.0",
+ modules = [snmp],
+ regs = [],
+ mod = {snmp, []}}],
+ Apps =
+ [#application{name = test,
+ description = "TEST",
+ vsn = "1.0",
+ modules = [{foo,1},{bar,1},{baz,1},{new_mod,1}],
+ regs = [],
+ mod = {sasl, []}}],
+ S1 = [
+ {update, bar, {advanced, extra}, brutal_purge, brutal_purge, []},
+ {update, foo, soft, soft_purge, soft_purge, [bar]},
+ {update, baz, 5000, soft, brutal_purge, brutal_purge, []},
+ {add_module, new_mod},
+ {remove_application, snmp}
+ ],
+ ?line {ok, _} = systools_rc:translate_scripts([S1], Apps, PreApps),
+ S2 = [
+ {apply, {m, f, [a]}},
+ {load_object_code, {tst, "1.0", [new_mod]}},
+ point_of_no_return,
+ {update, bar, {advanced, extra}, brutal_purge, brutal_purge, []},
+ {update, foo, soft, soft_purge, soft_purge, [bar]},
+ {load, {new_mod, soft_purge, soft_purge}},
+ {remove, {old_mod, soft_purge, soft_purge}},
+ {purge, [m1, m2]},
+ {suspend, [m1]},
+ {code_change, [{m1, extra}]},
+ {resume, [m1]},
+ {stop, [m3,m4]},
+ {start, [m3,m4]},
+ {sync_nodes, id1, {m, f, [a]}},
+ {sync_nodes, id2, [cp1, cp2]},
+ {apply, {m,f,[a]}},
+ restart_new_emulator
+ ],
+ ?line {ok, _} = systools_rc:translate_scripts([S2], Apps, []),
+ S3 = [{apply, {m, f, a}}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S3], Apps, []),
+ S3_1 = [{apply, {m, 3, a}}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S3_1], Apps, []),
+ S4 = [{apply, {m, f}}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S4], Apps, []),
+ S5 = [{load_object_code, hej}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S5], Apps, []),
+ S6 = [{load_object_code, {342, "1.0", [foo]}}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S6], Apps, []),
+ S7 = [{load_object_code, {tets, "1.0", foo}}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S7], Apps, []),
+ S8 = [{suspend, [m1]}, point_of_no_return],
+ ?line {error, _, _} = systools_rc:translate_scripts([S8], Apps, []),
+ S9 = [{update, ba, {advanced, extra}, brutal_purge, brutal_purge, []}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S9], Apps, []),
+ S10 = [{update, bar, {advanced, extra}, brutal_purge, brutal_purge, [baz]}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S10], Apps, []),
+ S11 = [{update, bar, {advanced, extra}, brutal_purge, brutal_purge, [ba]}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S11], Apps, []),
+ S12 = [{update, bar, advanced, brutal_purge, brutal_purge, []}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S12], Apps, []),
+ S13 = [{update, bar, {advanced, extra}, rutal_purge, brutal_purge, [ba]}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S13], Apps, []),
+ S14 = [{update, bar, {advanced, extra}, brutal_purge, rutal_purge, [ba]}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S14], Apps, []),
+ S15 = [{update, bar, {advanced, extra}, brutal_purge, brutal_purge, ba}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S15], Apps, []),
+ S16 = [{code_change, [module]}],
+ ?line {error, _, _} = systools_rc:translate_scripts([S16], Apps, []),
+ ?line ok.
+
+translate(suite) -> [];
+translate(Config) when is_list(Config) ->
+ Apps =
+ [#application{name = test,
+ description = "TEST",
+ vsn = "1.0",
+ modules = [{foo,1},{bar,1},{baz,1},
+ {x,1},{y,1},{z,1}],
+ regs = [],
+ mod = {sasl, []}}],
+ %% Simple translation (1)
+ Up1 = [{update, foo, soft, soft_purge, soft_purge, []}],
+ ?line {ok, X1} = systools_rc:translate_scripts([Up1], Apps, []),
+ ?line [{load_object_code, {test,"1.0",[foo]}},
+ point_of_no_return,
+ {suspend,[foo]},
+ {load,{foo,soft_purge,soft_purge}},
+ {resume,[foo]}] = X1,
+
+ %% Simple translation (2)
+ Up2 = [{update, foo, {advanced, extra}, soft_purge, soft_purge, []}],
+ ?line {ok, X2} = systools_rc:translate_scripts([Up2], Apps, []),
+ ?line [{load_object_code, {test,"1.0",[foo]}},
+ point_of_no_return,
+ {suspend,[foo]},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change, up, [{foo, extra}]},
+ {resume,[foo]}] = X2,
+
+ ?line {ok, X22} = systools_rc:translate_scripts(dn,[Up2], Apps, []),
+ ?line [{load_object_code, {test,"1.0",[foo]}},
+ point_of_no_return,
+ {suspend,[foo]},
+ {code_change, down, [{foo, extra}]},
+ {load,{foo,soft_purge,soft_purge}},
+ {resume,[foo]}] = X22,
+
+ Up2a = [{update, foo, static, default, {advanced,extra},
+ soft_purge, soft_purge, []}],
+ ?line {ok, X2a} = systools_rc:translate_scripts([Up2a], Apps, []),
+ ?line [{load_object_code, {test,"1.0",[foo]}},
+ point_of_no_return,
+ {suspend,[foo]},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change, up, [{foo, extra}]},
+ {resume,[foo]}] = X2a,
+
+ ?line {ok, X22a} = systools_rc:translate_scripts(dn,[Up2a], Apps, []),
+ ?line [{load_object_code, {test,"1.0",[foo]}},
+ point_of_no_return,
+ {suspend,[foo]},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change, down, [{foo, extra}]},
+ {resume,[foo]}] = X22a,
+
+ %% Simple dependency (1)
+ Up3 = [{update, foo, soft, soft_purge, soft_purge, [bar]},
+ {update, bar, soft, soft_purge, soft_purge, []}],
+ ?line {ok, X31} = systools_rc:translate_scripts([Up3], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,bar]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X31,
+ ?line {ok, X32} = systools_rc:translate_scripts(dn,[Up3], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,bar]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X32,
+
+ Up3a = [{update, foo, static, default, soft, soft_purge, soft_purge, [bar]},
+ {update, bar, static, default, soft, soft_purge, soft_purge, []}],
+ ?line {ok, X3a1} = systools_rc:translate_scripts([Up3a], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo, bar]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X3a1,
+ ?line {ok, X3a2} = systools_rc:translate_scripts(dn,[Up3a], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,bar]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X3a2,
+
+ %% Simple dependency (2)
+ Up4 = [{update, foo, soft, soft_purge, soft_purge, [bar]},
+ {update, bar, {advanced, []}, soft_purge, soft_purge, []}],
+ ?line {ok, X4} = systools_rc:translate_scripts(up,[Up4], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,bar]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change,up,[{bar,[]}]},
+ {resume,[bar,foo]}] = X4,
+
+ ?line {ok, X42} = systools_rc:translate_scripts(dn,[Up4], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,bar]},
+ {code_change,down,[{bar,[]}]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X42,
+
+ Up4a = [{update, foo, soft, soft_purge, soft_purge, [bar]},
+ {update, bar, static, infinity, {advanced, []},
+ soft_purge, soft_purge, []}],
+ ?line {ok, X4a} = systools_rc:translate_scripts(up,[Up4a], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,{bar,infinity}]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change,up,[{bar,[]}]},
+ {resume,[bar,foo]}] = X4a,
+
+ ?line {ok, X42a} = systools_rc:translate_scripts(dn,[Up4a], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,{bar,infinity}]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {code_change,down,[{bar,[]}]},
+ {resume,[bar,foo]}] = X42a,
+
+ Up4b = [{update, foo, soft, soft_purge, soft_purge, [bar]},
+ {update, bar, dynamic, infinity, {advanced, []},
+ soft_purge, soft_purge, []}],
+ ?line {ok, X4b} = systools_rc:translate_scripts(up,[Up4b], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,{bar,infinity}]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change,up,[{bar,[]}]},
+ {resume,[bar,foo]}] = X4b,
+
+ ?line {ok, X42b} = systools_rc:translate_scripts(dn,[Up4b], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,{bar,infinity}]},
+ {code_change,down,[{bar,[]}]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X42b,
+
+ %% More complex dependency
+ Up5 = [{update, foo, soft, soft_purge, soft_purge, [bar, baz]},
+ {update, bar, {advanced, []}, soft_purge, soft_purge, []},
+ {update, baz, {advanced, baz}, soft_purge, soft_purge, [bar]}],
+ ?line {ok, X5} = systools_rc:translate_scripts([Up5], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,baz,bar]}},
+ point_of_no_return,
+ {suspend,[foo,baz,bar]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{baz,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change,up,[{baz,baz},{bar,[]}]},
+ {resume,[bar,baz,foo]}] = X5,
+
+ ?line {ok, X52} = systools_rc:translate_scripts(dn,[Up5], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,baz,bar]}},
+ point_of_no_return,
+ {suspend,[foo,baz,bar]},
+ {code_change,down,[{baz,baz},{bar,[]}]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{baz,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {resume,[bar,baz,foo]}] = X52,
+
+ Up5a = [{update, foo, dynamic, infinity, soft, soft_purge,
+ soft_purge, [bar, baz]},
+ {update, bar, static, 7000, {advanced, []}, soft_purge,
+ soft_purge, []},
+ {update, baz, dynamic, default, {advanced, baz}, soft_purge,
+ soft_purge, [bar]}],
+ ?line {ok, X5a} = systools_rc:translate_scripts([Up5a], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,baz,bar]}},
+ point_of_no_return,
+ {suspend,[{foo,infinity},baz,{bar,7000}]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{baz,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change,up,[{baz,baz}, {bar,[]}]},
+ {resume,[bar,baz,foo]}] = X5a,
+
+ ?line {ok, X52a} = systools_rc:translate_scripts(dn,[Up5a], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,baz,bar]}},
+ point_of_no_return,
+ {suspend,[{foo,infinity},baz,{bar,7000}]},
+ {code_change,down,[{baz,baz}]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{baz,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {code_change,down,[{bar,[]}]},
+ {resume,[bar,baz,foo]}] = X52a,
+
+ Up5b = [{update, foo, dynamic, infinity, soft, soft_purge,
+ soft_purge, [bar, baz]},
+ {update, bar, dynamic, 7000, {advanced, []}, soft_purge,
+ soft_purge, []},
+ {update, baz, static, default, {advanced, baz}, soft_purge,
+ soft_purge, [bar]}],
+ ?line {ok, X5b} = systools_rc:translate_scripts([Up5b], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,baz,bar]}},
+ point_of_no_return,
+ {suspend,[{foo,infinity},baz,{bar,7000}]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{baz,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {code_change,up,[{baz,baz},{bar,[]}]},
+ {resume,[bar,baz,foo]}] = X5b,
+
+ ?line {ok, X52b} = systools_rc:translate_scripts(dn,[Up5b], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,baz,bar]}},
+ point_of_no_return,
+ {suspend,[{foo,infinity},baz,{bar,7000}]},
+ {code_change,down,[{bar,[]}]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{baz,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {code_change,down,[{baz,baz}]},
+ {resume,[bar,baz,foo]}] = X52b,
+
+ %% Simple circular dependency (1)
+ Up6 = [{update, foo, soft, soft_purge, soft_purge, [bar]},
+ {update, bar, soft, soft_purge, soft_purge, [foo]}],
+ ?line {ok, X61} = systools_rc:translate_scripts([Up6], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,bar]},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X61,
+ ?line {ok, X62} = systools_rc:translate_scripts(dn,[Up6], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {suspend,[foo,bar]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {resume,[bar,foo]}] = X62,
+
+ %% Simple circular dependency (2)
+ Up7 = [{update, foo, soft, soft_purge, soft_purge, [bar, baz]},
+ {update, bar, soft, soft_purge, soft_purge, [foo]},
+ {update, baz, soft, soft_purge, soft_purge, [bar]}],
+ ?line {ok, X71} = systools_rc:translate_scripts([Up7], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar,baz]}},
+ point_of_no_return,
+ {suspend,[foo,bar,baz]},
+ {load,{baz,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{foo,soft_purge,soft_purge}},
+ {resume,[baz, bar, foo]}] = X71,
+ ?line {ok, X72} = systools_rc:translate_scripts(dn,[Up7], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar,baz]}},
+ point_of_no_return,
+ {suspend,[foo,bar,baz]},
+ {load,{foo,soft_purge,soft_purge}},
+ {load,{bar,soft_purge,soft_purge}},
+ {load,{baz,soft_purge,soft_purge}},
+ {resume,[baz,bar,foo]}] = X72,
+
+ %% Complex circular dependencies, check only order
+ %%
+ Up8 = [{update, foo, soft, soft_purge, soft_purge, [baz]},
+ {update, y, soft, soft_purge, soft_purge, [bar]},
+ {update, x, soft, soft_purge, soft_purge, [y, z]},
+ {update, z, soft, soft_purge, soft_purge, [x]},
+ {update, bar, soft, soft_purge, soft_purge, [baz]},
+ {update, baz, soft, soft_purge, soft_purge, [bar]}],
+ ?line {ok, X8} = systools_rc:translate_scripts([Up8], Apps, []),
+ ?line {value, {suspend, Order}} = lists:keysearch(suspend, 1, X8),
+ ?line Rest = case lists:reverse(Order) of
+ [bar, baz | R] -> R;
+ [baz, bar | R] -> R
+ end,
+ ?line case Rest of
+ [y, z, x, foo] -> ok;
+ [y, x, z, foo] -> ok;
+ [foo, y, z, x] -> ok;
+ [foo, y, x, z] -> ok;
+ [y, foo, z, x] -> ok;
+ [y, foo, x, z] -> ok
+ end,
+
+ %% Check that order among other instructions isn't changed
+ Up9 = [{update, foo, soft, soft_purge, soft_purge, [baz]},
+ {apply, {m, f, [1]}},
+ {update, y, soft, soft_purge, soft_purge, [bar]},
+ {apply, {m, f, [2]}},
+ {update, x, soft, soft_purge, soft_purge, [y, z]},
+ {apply, {m, f, [3]}},
+ {update, z, soft, soft_purge, soft_purge, [x]},
+ {apply, {m, f, [4]}},
+ {update, bar, soft, soft_purge, soft_purge, [baz]},
+ {apply, {m, f, [5]}},
+ {update, baz, soft, soft_purge, soft_purge, [bar]},
+ {apply, {m, f, [6]}}],
+ ?line {ok, X9} = systools_rc:translate_scripts([Up9], Apps, []),
+ Other2 = [X || {apply, {m, f, [X]}} <- X9],
+ ?line [1,2,3,4,5,6] = lists:sort(Other2),
+ ?line ok.
+
+
+translate_app(suite) -> [];
+translate_app(Config) when is_list(Config) ->
+ PreApps =
+ [#application{name = test,
+ description = "TEST",
+ vsn = "1.0",
+ modules = [{foo,1},{bar,1},{baz,1}],
+ regs = [],
+ mod = {sasl, []}},
+ #application{name = pelle,
+ description = "PELLE",
+ vsn = "1.0",
+ modules = [pelle, kalle],
+ regs = [],
+ mod = {pelle, []}}],
+ Apps =
+ [#application{name = test,
+ description = "TEST",
+ vsn = "1.0",
+ modules = [{foo,1},{bar,1},{baz,1}],
+ regs = [],
+ mod = {sasl, []}}],
+ %% Simple translation (1)
+ Up1 = [{add_module, foo},
+ {add_module, bar}],
+ ?line {ok, X1} = systools_rc:translate_scripts([Up1], Apps, []),
+ ?line [{load_object_code,{test,"1.0",[foo,bar]}},
+ point_of_no_return,
+ {load,{foo,brutal_purge,brutal_purge}},
+ {load,{bar,brutal_purge,brutal_purge}}] = X1,
+
+ %% Simple translation (2)
+ Up2 = [{add_application, test}],
+ ?line {ok, X2} = systools_rc:translate_scripts([Up2], Apps, []),
+io:format("X2=~p~n", [X2]),
+ ?line [{load_object_code,{test,"1.0",[foo,bar,baz]}},
+ point_of_no_return,
+ {load,{foo,brutal_purge,brutal_purge}},
+ {load,{bar,brutal_purge,brutal_purge}},
+ {load,{baz,brutal_purge,brutal_purge}},
+ {apply,{application,start,[test,permanent]}}] = X2,
+
+ %% Simple translation (3)
+ Up3 = [{remove_application, pelle}],
+ ?line {ok, X3} = systools_rc:translate_scripts([Up3], Apps, PreApps),
+ ?line [point_of_no_return,
+ {apply,{application,stop,[pelle]}},
+ {remove,{pelle,brutal_purge,brutal_purge}},
+ {remove,{kalle,brutal_purge,brutal_purge}},
+ {purge,[pelle,kalle]},
+ {apply,{application,unload,[pelle]}}] = X3,
+ ?line ok.
diff --git a/lib/snmp/doc/src/files.mk b/lib/snmp/doc/src/files.mk
index bd94cd6bac..61c91c9729 100644
--- a/lib/snmp/doc/src/files.mk
+++ b/lib/snmp/doc/src/files.mk
@@ -157,4 +157,5 @@ MIB_FILES = \
$(MIBSDIR)/SNMP-VIEW-BASED-ACM-MIB.mib \
$(MIBSDIR)/SNMP-USM-AES-MIB.mib \
$(MIBSDIR)/INET-ADDRESS-MIB.mib \
+ $(MIBSDIR)/TRANSPORT-ADDRESS-MIB.mib \
$(MIBSDIR)/OTP-SNMPEA-MIB.mib
diff --git a/lib/snmp/doc/src/notes.xml b/lib/snmp/doc/src/notes.xml
index 2efeb8ae3f..6a20d8ee3a 100644
--- a/lib/snmp/doc/src/notes.xml
+++ b/lib/snmp/doc/src/notes.xml
@@ -33,6 +33,116 @@
</header>
<section>
+ <title>SNMP Development Toolkit 4.20</title>
+ <p>Version 4.20 supports code replacement in runtime from/to
+ version 4.19 and 4.18.</p>
+
+ <section>
+ <title>Improvements and new features</title>
+<!--
+ <p>-</p>
+-->
+ <list type="bulleted">
+ <item>
+ <p>[agent] Added support for sending traps to IPv6 targets. </p>
+ <p>See the
+ <seealso marker="snmp_agent_config_files#target_addr">target address config file</seealso>,
+ the <seealso marker="snmpa_conf#target_addr_entry">target_addr_entry/11</seealso> function or
+ <seealso marker="snmp_target_mib#add_addr">add_addr/11</seealso> for more info. </p>
+ <p>Own Id: OTP-9088</p>
+ <p>Aux Id: Seq 11790</p>
+ </item>
+
+
+ <item>
+ <p>[agent] To be able to handle multiple engine-id(s) when
+ sending trap(s), the function
+ <seealso marker="snmp_community_mib#add_community">
+ add_community/6</seealso> has been added. </p>
+ <p>Own Id: OTP-9119</p>
+ <p>Aux Id: Seq 11792</p>
+ </item>
+
+ <item>
+ <p>[manager] The API for snmp requests has been augmented to
+ allow the caller to override some configuration. </p>
+ <p>This has been done by introducing a new set of API functions, see
+ <seealso marker="snmpm#sync_get2">sync_get2/3,4</seealso>,
+ <seealso marker="snmpm#async_get2">async_get2/3,4</seealso>,
+ <seealso marker="snmpm#sync_get_next2">sync_get_next2/3,4</seealso>,
+ <seealso marker="snmpm#async_get_next2">async_get_next2/3,4</seealso>,
+ <seealso marker="snmpm#sync_get_bulk2">sync_get_bulk2/5,6</seealso>,
+ <seealso marker="snmpm#async_get_bulk2">async_get_bulk2/5,6</seealso>,
+ <seealso marker="snmpm#sync_set2">sync_set2/3,4</seealso> and
+ <seealso marker="snmpm#async_set2">async_set2/3,4</seealso>
+ for more info. </p>
+ <p>Own Id: OTP-9162</p>
+ </item>
+
+ <item>
+ <p>[manager] The old API functions (for get and set
+ requests:
+ snmpm:g/3,4,5,6,7, snmpm:ag/3,4,5,6,7,
+ snmpm:gn/3,4,5,6,7, snmpm:agn/3,4,5,6,7,
+ snmpm:s/3,4,5,6,7, snmpm:s/3,4,5,6,7,
+ snmpm:gb/5,6,7,8,9 and snmpm:agb/5,6,7,8,9)
+ are now officially deprecated.
+ They will be removed as of R16B. </p>
+ <p>Own Id: OTP-9174</p>
+ </item>
+
+ <item>
+ <p>[agent] Pass extra info through the agent to the net-if
+ process when sending notifications. </p>
+ <p>See
+ <seealso marker="snmpa#send_notification2">
+ snmpa:send_notification2/3</seealso> for more info.
+ See also the incomming net-if messages when sending a
+ <seealso marker="snmp_agent_netif#im_send_pdu">trap</seealso>
+ (send_pdu message) and
+ <seealso marker="snmp_agent_netif#im_send_pdu_req">
+ notification</seealso> (send_pdu_req message). </p>
+ <p>Own Id: OTP-9183</p>
+ <p>Aux Id: Seq 11817</p>
+ </item>
+
+ <item>
+ <p>Added type specs for functions that do not return. </p>
+ <p>Kostis Sagonas</p>
+ <p>Own Id: OTP-9208</p>
+ </item>
+ </list>
+ </section>
+
+ <section>
+ <title>Fixed Bugs and Malfunctions</title>
+<!--
+ <p>-</p>
+-->
+
+ <list type="bulleted">
+ <item>
+ <p>Fixed endode/decode of values of type <c>Counter32</c>. </p>
+ <p>This type (<c>Counter32</c>) is an unsigned integer 32,
+ but is actually encoded as an signed integer 32.
+ The encode/decode functions however, treated it as if it was
+ encodeded as an unsigned integer 32. </p>
+ <p>Own Id: OTP-9022</p>
+ </item>
+
+ </list>
+ </section>
+
+
+ <section>
+ <title>Incompatibilities</title>
+ <p>-</p>
+ </section>
+
+ </section> <!-- 4.20 -->
+
+
+ <section>
<title>SNMP Development Toolkit 4.19</title>
<p>Version 4.19 supports code replacement in runtime from/to
version 4.18.</p>
@@ -126,6 +236,7 @@ snmp_view_basec_acm_mib:vacmAccessTable(set, RowIndex, Cols).
</section> <!-- 4.19 -->
+
<section>
<title>SNMP Development Toolkit 4.18</title>
<p>Version 4.18 supports code replacement in runtime from/to
@@ -226,7 +337,7 @@ snmp_view_basec_acm_mib:vacmAccessTable(set, RowIndex, Cols).
<p>The config utility
(<seealso marker="snmp#config">snmp:config/0</seealso>)
generated a default notify.conf
- with a bad name for the starndard trap entry (was "stadard trap",
+ with a bad name for the standard trap entry (was "stadard trap",
but should have been "standard trap"). This has been corrected. </p>
<p>Kenji Rikitake</p>
<p>Own Id: OTP-8433</p>
@@ -430,7 +541,7 @@ snmp_view_basec_acm_mib:vacmAccessTable(set, RowIndex, Cols).
<p>The config utility
(<seealso marker="snmp#config">snmp:config/0</seealso>)
generated a default notify.conf
- with a bad name for the starndard trap entry (was "stadard trap",
+ with a bad name for the standard trap entry (was "stadard trap",
but should have been "standard trap"). This has been corrected. </p>
<p>Kenji Rikitake</p>
<p>Own Id: OTP-8433</p>
diff --git a/lib/snmp/doc/src/snmp_agent_config_files.xml b/lib/snmp/doc/src/snmp_agent_config_files.xml
index b62269d506..bd5c537522 100644
--- a/lib/snmp/doc/src/snmp_agent_config_files.xml
+++ b/lib/snmp/doc/src/snmp_agent_config_files.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
@@ -367,56 +367,50 @@
<marker id="target_addr"></marker>
<title>Target Address Definitions</title>
<p>The information about Target Address Definitions should be
- stored in a file called
- <c>target_addr.conf</c>.
- </p>
+ stored in a file called <c>target_addr.conf</c>. </p>
<p>The corresponding tables are <c>snmpTargetAddrTable</c> in the
- SNMP-TARGET-MIB and <c>snmpTargetAddrExtTable</c> in the SNMP-COMMUNITY-MIB.
- </p>
- <p>Each entry is a term:
- </p>
- <p><c>{TargetName, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId}.</c> or <br></br>
-<c>{TargetName, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}.</c></p>
+ SNMP-TARGET-MIB and <c>snmpTargetAddrExtTable</c> in the
+ SNMP-COMMUNITY-MIB. </p>
+ <p>Each entry is a term: </p>
+ <p><c>{TargetName, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId}.</c> <br></br> or <br></br>
+<c>{TargetName, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}.</c> <br></br> or <br></br>
+<c>{TargetName, Domain, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}.</c></p>
<list type="bulleted">
<item>
<p><c>TargetName</c> is a unique non-empty string.
</p>
</item>
<item>
- <p><c>Ip</c> is a list of four integers.
- </p>
+ <p><c>Domain</c> is one of the atoms:
+ <c>transportDomainUdpIpv4</c> | <c>transportDomainUdpIpv6</c>. </p>
</item>
<item>
- <p><c>Udp</c> is an integer.
- </p>
+ <p><c>Ip</c> is a list of four or eight integers. </p>
</item>
<item>
- <p><c>Timeout</c> is an integer.
- </p>
+ <p><c>Udp</c> is an integer. </p>
</item>
<item>
- <p><c>RetryCount</c> is an integer.
- </p>
+ <p><c>Timeout</c> is an integer. </p>
</item>
<item>
- <p><c>TagList</c> is a string.
- </p>
+ <p><c>RetryCount</c> is an integer. </p>
</item>
<item>
- <p><c>ParamsName</c> is a string.
- </p>
+ <p><c>TagList</c> is a string. </p>
</item>
<item>
- <p><c>EngineId</c> is a string or the atom <c>discovery</c>.
- </p>
+ <p><c>ParamsName</c> is a string. </p>
</item>
<item>
- <p><c>TMask</c> is a string of size 0, or size 6 (default: []).
- </p>
+ <p><c>EngineId</c> is a string or the atom <c>discovery</c>. </p>
</item>
<item>
- <p><c>MaxMessageSize</c> is an integer (default: 2048).
- </p>
+ <p><c>TMask</c> is a list of integer() of size 0,
+ size 6 or size 10 (default: []). </p>
+ </item>
+ <item>
+ <p><c>MaxMessageSize</c> is an integer (default: 2048). </p>
</item>
</list>
<p>Note that if <c>EngineId</c> has the value <c>discovery</c>,
@@ -429,14 +423,10 @@
<marker id="target_params"></marker>
<title>Target Parameters Definitions</title>
<p>The information about Target Parameters Definitions should be
- stored in a file called
- <c>target_params.conf</c>.
- </p>
+ stored in a file called <c>target_params.conf</c>. </p>
<p>The corresponding table is <c>snmpTargetParamsTable</c> in the
- SNMP-TARGET-MIB.
- </p>
- <p>Each entry is a term:
- </p>
+ SNMP-TARGET-MIB. </p>
+ <p>Each entry is a term: </p>
<p><c>{ParamsName, MPModel, SecurityModel, SecurityName, SecurityLevel}.</c></p>
<list type="bulleted">
<item>
diff --git a/lib/snmp/doc/src/snmp_agent_netif.xml b/lib/snmp/doc/src/snmp_agent_netif.xml
index 1f2dbe80db..14ef3630b5 100644
--- a/lib/snmp/doc/src/snmp_agent_netif.xml
+++ b/lib/snmp/doc/src/snmp_agent_netif.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
@@ -65,16 +65,19 @@
</section>
<section>
+ <marker id="messages"></marker>
<title>Messages</title>
<p>The section <em>Messages</em> describes mandatory messages, which
Net if must send and be able to receive.
</p>
<section>
+ <marker id="outgoing_messages"></marker>
<title>Outgoing Messages</title>
<p>Net if must send the following message when it receives an
- SNMP PDU from the network that is aimed for the MasterAgent:
- </p>
+ SNMP PDU from the network that is aimed for the MasterAgent:
+ </p>
+ <marker id="om_snmp_pdu"></marker>
<pre>
MasterAgent ! {snmp_pdu, Vsn, Pdu, PduMS, ACMData, From, Extra}
</pre>
@@ -106,16 +109,18 @@ MasterAgent ! {snmp_pdu, Vsn, Pdu, PduMS, ACMData, From, Extra}
the request.</item>
</list>
<p>The following message is used to report that a response to a
- request has been received. The only request an agent can send
- is an Inform-Request.
- </p>
+ request has been received. The only request an agent can send
+ is an Inform-Request.
+ </p>
+ <marker id="om_snmp_response_received"></marker>
<pre>
Pid ! {snmp_response_received, Vsn, Pdu, From}
</pre>
<list type="bulleted">
<item><c>Pid</c> is the Process that waits for the response
for the request. The Pid was specified in the
- <c>send_pdu_req</c> message <seealso marker="#message">(see below)</seealso>.
+ <c>send_pdu_req</c> message
+ <seealso marker="#im_send_pdu_req">(see below)</seealso>.
</item>
<item><c>Vsn</c> is either <c>'version-1'</c>, <c>'version-2'</c>, or
<c>'version-3'</c>.
@@ -131,119 +136,153 @@ Pid ! {snmp_response_received, Vsn, Pdu, From}
</section>
<section>
+ <marker id="incoming_messages"></marker>
<title>Incoming Messages</title>
<p>This section describes the incoming messages which a Net if
- process must be able to receive.
- </p>
+ process must be able to receive.
+ </p>
<list type="bulleted">
<item>
+ <marker id="im_snmp_response"></marker>
<p><c>{snmp_response, Vsn, Pdu, Type, ACMData, To, Extra}</c></p>
<p>This message is sent to the Net if process from a master
agent as a response to a previously received request.
</p>
<list type="bulleted">
- <item><c>Vsn</c> is either <c>'version-1'</c>,
- <c>'version-2'</c>, or <c>'version-3'</c>.
+ <item>
+ <p><c>Vsn</c> is either <c>'version-1'</c>,
+ <c>'version-2'</c>, or <c>'version-3'</c>. </p>
</item>
- <item><c>Pdu</c> is an SNMP PDU record (as defined in
- snmp_types.hrl) with the SNMP response.
+ <item>
+ <p><c>Pdu</c> is an SNMP PDU record (as defined in
+ snmp_types.hrl) with the SNMP response. </p>
</item>
- <item><c>Type</c> is the <c>#pdu.type</c> of the original
- request.
+ <item>
+ <p><c>Type</c> is the <c>#pdu.type</c>
+ of the original request. </p>
</item>
- <item><c>ACMData</c> is data used by the Access Control
- Module in use. Normally this is just sent to
- <c>snmpa_mpd:generate_response_message</c> (see Reference Manual).
+ <item>
+ <p><c>ACMData</c> is data used by the Access Control
+ Module in use. Normally this is just sent to
+ <c>snmpa_mpd:generate_response_message</c>
+ (see Reference Manual). </p>
</item>
- <item><c>To</c> is the destination address. If UDP over IP
- is used, this should be a 2-tuple <c>{IP, UDPport}</c>,
- where <c>IP</c> is a 4-tuple with the IP address, and
- <c>UDPport</c> is an integer.
+ <item>
+ <p><c>To</c> is the destination address. If UDP over IP
+ is used, this should be a 2-tuple <c>{IP, UDPport}</c>,
+ where <c>IP</c> is a 4-tuple with the IP address, and
+ <c>UDPport</c> is an integer. </p>
</item>
- <item><c>Extra</c> is the term that the Net if process
- sent to the agent when the request was sent to the agent.
+ <item>
+ <p><c>Extra</c> is the term that the Net if process
+ sent to the agent when the request was sent to the agent. </p>
</item>
</list>
</item>
<item>
+ <marker id="im_discarded_pdu"></marker>
<p><c>{discarded_pdu, Vsn, ReqId, ACMData, Variable, Extra}</c></p>
<p>This message is sent from a master agent if it for some
- reason decided to discard the pdu.
- </p>
+ reason decided to discard the pdu. </p>
<list type="bulleted">
- <item><c>Vsn</c> is either <c>'version-1'</c>,
- <c>'version-2'</c>, or <c>'version-3'</c>.
+ <item>
+ <p><c>Vsn</c> is either <c>'version-1'</c>,
+ <c>'version-2'</c>, or <c>'version-3'</c>. </p>
</item>
- <item><c>ReqId</c> is the request id of the original
- request.
+ <item>
+ <p><c>ReqId</c> is the request id of the original request. </p>
</item>
- <item><c>ACMData</c> is data used by the Access Control
- Module in use. Normally this is just sent to
- <c>snmpa_mpd:generate_response_message</c> (see Reference Manual).
+ <item>
+ <p><c>ACMData</c> is data used by the Access Control
+ Module in use. Normally this is just sent to
+ <c>snmpa_mpd:generate_response_message</c>
+ (see Reference Manual). </p>
</item>
- <item><c>Variable</c> is the name of an snmp counter that
- represents the error, e.g. <c>snmpInBadCommunityUses</c>.
+ <item>
+ <p><c>Variable</c> is the name of an snmp counter that
+ represents the error, e.g. <c>snmpInBadCommunityUses</c>. </p>
</item>
- <item><c>Extra</c> is the term that the Net if process
- sent to the agent when the request was sent to the agent.
+ <item>
+ <p><c>Extra</c> is the term that the Net if process
+ sent to the agent when the request was sent to the agent. </p>
</item>
</list>
</item>
<item>
- <p><c>{send_pdu, Vsn, Pdu, MsgData, To}</c></p>
+ <marker id="im_send_pdu"></marker>
+ <p><c>{send_pdu, Vsn, Pdu, MsgData, To, Extra}</c></p>
<p>This message is sent from a master agent when a trap is
- to be sent.
- </p>
+ to be sent. </p>
<list type="bulleted">
- <item><c>Vsn</c> is either <c>'version-1'</c>,
- <c>'version-2'</c>, or <c>'version-3'</c>.
+ <item>
+ <p><c>Vsn</c> is either <c>'version-1'</c>,
+ <c>'version-2'</c>, or <c>'version-3'</c>.</p>
</item>
- <item><c>Pdu</c> is an SNMP PDU record (as defined in
- snmp_types.hrl) with the SNMP response.
+ <item>
+ <p><c>Pdu</c> is an SNMP PDU record (as defined in
+ snmp_types.hrl) with the SNMP response. </p>
+ </item>
+ <item>
+ <p><c>MsgData</c> is the message specific data used in
+ the SNMP message. This value is normally sent to
+ <c>snmpa_mpd:generate_message/4</c>. In SNMPv1 and
+ SNMPv2c, this message data is the community string. In
+ SNMPv3, it is the context information. </p>
</item>
- <item><c>MsgData</c> is the message specific data used in
- the SNMP message. This value is normally sent to
- <c>snmpa_mpd:generate_message/4</c>. In SNMPv1 and
- SNMPv2c, this message data is the community string. In
- SNMPv3, it is the context information.
+ <item>
+ <p><c>To</c> is a list of the destination addresses and
+ their corresponding security parameters. This value is
+ normally sent to <c>snmpa_mpd:generate_message/4</c>. </p>
</item>
- <item><c>To</c> is a list of the destination addresses and
- their corresponding security parameters. This value is
- normally sent to <c>snmpa_mpd:generate_message/4</c>.
+ <item>
+ <p><c>Extra</c> is any term that the notification sender
+ wishes to pass to the Net if process when sending a notification
+ (see
+ <seealso marker="snmpa#send_notification2">send notification
+ </seealso> for more info). </p>
</item>
</list>
</item>
<item>
- <p><c>{send_pdu_req, Vsn, Pdu, MsgData, To, Pid}</c></p>
- <p>This <marker id="message"></marker>
- message is sent from a master
- agent when a request is
- to be sent. The only request an agent can send is
- Inform-Request. The net if process needs to remember the
- request id and the Pid, and when a response is received for
- the request id, send it to Pid, using a
- <c>snmp_response_received</c> message.
- </p>
- <list type="bulleted">
- <item><c>Vsn</c> is either <c>'version-1'</c>,
- <c>'version-2'</c>, or <c>'version-3'</c>.
- </item>
- <item><c>Pdu</c> is an SNMP PDU record (as defined in
- snmp_types.hrl) with the SNMP response.
- </item>
- <item><c>MsgData</c> is the message specific data used in
- the SNMP message. This value is normally sent to
- <c>snmpa_mpd:generate_message/4</c>. In SNMPv1 and
- SNMPv2c, this message data is the community string. In
- SNMPv3, it is the context information.
+ <marker id="im_send_pdu_req"></marker>
+ <p><c>{send_pdu_req, Vsn, Pdu, MsgData, To, Pid, Extra}</c></p>
+ <p>This message is sent from a master agent when a request is to
+ be sent. The only request an agent can send is Inform-Request.
+ The net if process needs to remember the request id and the Pid,
+ and when a response is received for the request id, send it to Pid,
+ using a <c>snmp_response_received</c> message. </p>
+ <list type="bulleted">
+ <item>
+ <p><c>Vsn</c> is either <c>'version-1'</c>,
+ <c>'version-2'</c>, or <c>'version-3'</c>.</p>
+ </item>
+ <item>
+ <p><c>Pdu</c> is an SNMP PDU record (as defined in
+ snmp_types.hrl) with the SNMP response. </p>
+ </item>
+ <item>
+ <p><c>MsgData</c> is the message specific data used in
+ the SNMP message. This value is normally sent to
+ <c>snmpa_mpd:generate_message/4</c>. In SNMPv1 and
+ SNMPv2c, this message data is the community string. In
+ SNMPv3, it is the context information. </p>
+ </item>
+ <item>
+ <p><c>To</c> is a list of the destination addresses and
+ their corresponding security parameters. This value is
+ normally sent to <c>snmpa_mpd:generate_message/4</c>. </p>
+ </item>
+ <item>
+ <p><c>Pid</c> is a process identifier. </p>
+ </item>
+ <item>
+ <p><c>Extra</c> is any term that the notification sender
+ wishes to pass to the Net if process when sending a notification
+ (see
+ <seealso marker="snmpa#send_notification2">send notification
+ </seealso> for more info). </p>
</item>
- <item><c>To</c> is a list of the destination addresses and
- their corresponding security parameters. This value is
- normally sent to <c>snmpa_mpd:generate_message/4</c>.
- </item>
- <item><c>Pid</c> is a process identifier.
- </item>
- </list>
+ </list>
</item>
</list>
</section>
diff --git a/lib/snmp/doc/src/snmp_community_mib.xml b/lib/snmp/doc/src/snmp_community_mib.xml
index 7c7386af19..5e7bca3e27 100644
--- a/lib/snmp/doc/src/snmp_community_mib.xml
+++ b/lib/snmp/doc/src/snmp_community_mib.xml
@@ -1,10 +1,10 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
<header>
<copyright>
- <year>1999</year><year>2009</year>
+ <year>1999</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -35,11 +35,13 @@
<modulesummary>Instrumentation Functions for SNMP-COMMUNITY-MIB</modulesummary>
<description>
<p>The module <c>snmp_community_mib</c> implements the instrumentation
- functions for the
- SNMP-COMMUNITY-MIB, and functions for configuring the database.
- </p>
+ functions for the SNMP-COMMUNITY-MIB, and functions for configuring the
+ database. </p>
<p>The configuration files are described in the SNMP User's Manual.</p>
+
+ <marker id="configure"></marker>
</description>
+
<funcs>
<func>
<name>configure(ConfDir) -> void()</name>
@@ -68,8 +70,11 @@
</p>
<p>The configuration file read is: <c>community.conf</c>.
</p>
+
+ <marker id="reconfigure"></marker>
</desc>
</func>
+
<func>
<name>reconfigure(ConfDir) -> void()</name>
<fsummary>Configure the SNMP-COMMUNITY-MIB</fsummary>
@@ -96,28 +101,35 @@
where the configuration files are found.
</p>
<p>The configuration file read is: <c>community.conf</c>.</p>
+
<marker id="add_community"></marker>
</desc>
</func>
+
<func>
<name>add_community(Idx, CommName, SecName, CtxName, TransportTag) -> Ret</name>
+ <name>add_community(Idx, CommName, SecName, EngineId, CtxName, TransportTag) -> Ret</name>
<fsummary>Added one community</fsummary>
<type>
<v>Idx = string()</v>
<v>CommName = string()</v>
<v>SecName = string()</v>
+ <v>EngineId = string()</v>
<v>CtxName = string()</v>
<v>TransportTag = string()</v>
<v>Ret = {ok, Key} | {error, Reason}</v>
<v>Key = term()</v>
- <v>Reason = term()</v>
+ <v>Reason = term()</v>
</type>
<desc>
<p>Adds a community to the agent config.
- Equivalent to one line in the <c>community.conf</c> file.</p>
+ Equivalent to one line in the <c>community.conf</c> file.</p>
+ <p>With the <c>EngineId</c> argument it is possible to
+ override the configured engine-id (SNMP-FRAMEWORK-MIB).</p>
<marker id="delete_community"></marker>
</desc>
</func>
+
<func>
<name>delete_community(Key) -> Ret</name>
<fsummary>Delete one community</fsummary>
diff --git a/lib/snmp/doc/src/snmp_target_mib.xml b/lib/snmp/doc/src/snmp_target_mib.xml
index 4a36be19a3..d5151d41de 100644
--- a/lib/snmp/doc/src/snmp_target_mib.xml
+++ b/lib/snmp/doc/src/snmp_target_mib.xml
@@ -1,10 +1,10 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
<header>
<copyright>
- <year>1998</year><year>2009</year>
+ <year>1998</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -39,9 +39,21 @@
and functions for configuring the database. </p>
<p>The configuration files are described in the SNMP User's Manual.</p>
- <marker id="configure"></marker>
+ <marker id="types"></marker>
</description>
+ <section>
+ <title>DATA TYPES</title>
+ <code type="none"><![CDATA[
+transportDomain() = transportDomainUdpIpv4 | transportDomainUdpIpv6
+transportAddressIPv4() = [integer()], length 4
+transportAddressIPv6() = [integer()], length 8
+transportAddressMask() = [integer()], length 0 (default), 6 (IPv4) or 10 (IPv6)
+ ]]></code>
+
+ <marker id="configure"></marker>
+ </section>
+
<funcs>
<func>
<name>configure(ConfDir) -> void()</name>
@@ -118,17 +130,19 @@
<func>
<name>add_addr(Name, Ip, Port, Timeout, Retry, TagList, Params, EngineId, TMask, MMS) -> Ret</name>
+ <name>add_addr(Name, Domain, Ip, Port, Timeout, Retry, TagList, Params, EngineId, TMask, MMS) -> Ret</name>
<fsummary>Add one target address definition</fsummary>
<type>
<v>Name = string()</v>
- <v>Ip = [integer()], length 4</v>
+ <v>Domain = transportDomain()</v>
+ <v>Ip = transportAddressIPv4() | transportAddressIPv6() (depends on the value of Domain)</v>
<v>Port = integer()</v>
<v>Timeout = integer()</v>
<v>Retry = integer()</v>
<v>TagList = string()</v>
<v>ParamsName = string()</v>
<v>EngineId = string()</v>
- <v>TMask = string(), length 0 or 6</v>
+ <v>TMask = transportAddressMask() (depends on Domain)</v>
<v>MMS = integer()</v>
<v>Ret = {ok, Key} | {error, Reason}</v>
<v>Key = term()</v>
diff --git a/lib/snmp/doc/src/snmpa.xml b/lib/snmp/doc/src/snmpa.xml
index 1d680e80f5..27d89ea4e3 100644
--- a/lib/snmp/doc/src/snmpa.xml
+++ b/lib/snmp/doc/src/snmpa.xml
@@ -872,10 +872,138 @@ snmp_agent:register_subagent(SA1,[1,2,3], SA2).
then that sub-agent will be unregistered from all trees in
<c>Agent</c>. </p>
- <marker id="send_notification"></marker>
+ <marker id="send_notification2"></marker>
</desc>
</func>
+
+ <func>
+ <name>send_notification2(Agent, Notification, SendOpts) -> void()</name>
+ <fsummary>Send notification</fsummary>
+ <type>
+ <v>Agent = pid() | atom()</v>
+ <v>Notification = atom()</v>
+ <v>SendOpts = [send_option()]</v>
+ <v>send_option() = {receiver, receiver()} | {name, notify_name()} | {context, context_name()} | {varbinds, varbinds()} | {local_engine_id, string()} | {extra, extra_info()}</v>
+ <v>receiver() = no_receiver | {tag(), tag_receiver()} | notification_delivery_info()</v>
+ <v>tag() = term(()</v>
+ <v>tag_receiver() = pid() | registered_name() | {Mod, Func, Args}</v>
+ <v>registered_name() = atom()</v>
+ <v>Mod = atom()</v>
+ <v>Func = atom()</v>
+ <v>Args = list()</v>
+ <v>notify_name() = string()</v>
+ <v>context_name() = string()</v>
+ <v>varbinds() = [varbind()]</v>
+ <v>varbind() = {variable(), value()} | {column(), row_index(), value()} | {oid(), value()}</v>
+ <v>variable() = atom()</v>
+ <v>value() = term()</v>
+ <v>column() = atom()</v>
+ <v>row_index() = [int()]</v>
+ <v>extra_info() = term()</v>
+ </type>
+ <desc>
+ <p>Send the notification <c>Notification</c> to the management
+ targets defined for notify-name (<c>name</c>) in the
+ <c>snmpNotifyTable</c> in SNMP-NOTIFICATION-MIB from the
+ specified <c>context</c>. </p>
+
+ <p>If no <c>name</c> is specified (or if it is <c>""</c>), the
+ notification is sent to all management targets. </p>
+
+ <p>If no <c>context</c> is specified, the default context, <c>""</c>,
+ is used. </p>
+
+ <p>The send option <c>receiver</c> specifies where information
+ about delivery of Inform-Requests should be sent. The agent
+ sends Inform-Requests and waits for acknowledgments from the
+ management targets.
+ The <c>receiver</c> can have three values: </p>
+
+ <list type="bulleted">
+ <item>
+ <p><c>no_receiver</c> - No information is delivered. </p>
+ </item>
+
+ <item>
+ <p><c>notification_delivery_info()</c> - The information is
+ delivered via a function call according to this data. See the
+ <seealso marker="#data_types">DATA TYPES</seealso> section
+ above for details. </p>
+ </item>
+
+ <item>
+ <p><c>{tag(), tag_receiver()}</c> - The information is delivered
+ either via messages or via a function call according to the value
+ of <c>tag_receiver()</c>. </p>
+ <p>Delivery is done differently depending on the value
+ of <c>tag_receiver()</c>: </p>
+
+ <list>
+ <item>
+ <p><c>pid() | registered_name()</c> - The info will be delivered in
+ the following messages: </p>
+ <list>
+ <item>
+ <p><c>{snmp_targets, tag(), Addresses}</c></p>
+ <p>This informs the user which target addresses the
+ notification was sent to. </p>
+ </item>
+ <item>
+ <p><c>{snmp_notification, tag(), {got_response, Address}}</c></p>
+ <p>This informs the user that this target address
+ acknowledged the notification. </p>
+ </item>
+ <item>
+ <p><c>{snmp_notification, tag(), {no_response, Address}}</c></p>
+ <p>This informs the user that this target address
+ did not acknowledge the notification. </p>
+ </item>
+ </list>
+ <p>The notification is sent as an Inform-Request to each
+ target address in <c>Addresses</c> and if there are no
+ targets for which an Inform-Request is sent, <c>Addresses</c>
+ is the empty list <c>[]</c>. </p>
+ <p>The <c>tag_receiver()</c> will first be sent the
+ <c>snmp_targets</c> message, and then for each address in
+ <c>Addresses</c> list, one of the two <c>snmp_notification</c>
+ messages. </p>
+ </item>
+
+ <item>
+ <p><c>{Mod, Func, Args}</c> - The info will be delivered via
+ the function call: </p>
+ <p><c>Mod:Func([Msg | Args])</c></p>
+ <p>where <c>Msg</c> has the same content and purpose as the
+ messages descrived above.</p>
+ </item>
+
+ </list>
+ </item>
+ </list>
+
+ <note>
+ <p>The <c>extra</c> info is not normally interpreted by the agent,
+ instead it is passed through to the
+ <seealso marker="snmp_agent_netif">net-if</seealso> process. It is
+ up to the implementor of that process to make use of this data. </p>
+ <p>The version of net-if provided by this application makes no use
+ of this data, with one exception:
+ Any tuple containing the atom
+ <c>snmpa_default_notification_extra_info</c>
+ may be used by the agent and is therefor <em>reserved</em>. </p>
+ <p>See the net-if incomming messages for sending a
+ <seealso marker="snmp_agent_netif#im_send_pdu">
+ trap</seealso> and
+ <seealso marker="snmp_agent_netif#im_send_pdu_req">
+ notification</seealso> for more info. </p>
+ </note>
+
+ <marker id="send_notification"></marker>
+ </desc>
+ </func>
+
+
<func>
<name>send_notification(Agent, Notification, Receiver)</name>
<name>send_notification(Agent, Notification, Receiver, Varbinds)</name>
@@ -907,18 +1035,19 @@ snmp_agent:register_subagent(SA1,[1,2,3], SA2).
</type>
<desc>
<p>Sends the notification <c>Notification</c> to the
- management targets defined for <c>NotifyName</c> in the
- <c>snmpNotifyTable</c> in SNMP-NOTIFICATION-MIB from the
- specified context. If no <c>NotifyName</c> is specified (or
- if it is <c>""</c>), the notification is sent to all
- management targets (<c>Addresses</c> below). If no <c>ContextName</c>
- is specified, the default <c>""</c> context is used.
- </p>
+ management targets defined for <c>NotifyName</c> in the
+ <c>snmpNotifyTable</c> in SNMP-NOTIFICATION-MIB from the
+ specified context. </p>
+ <p>If no <c>NotifyName</c> is specified (or if it is <c>""</c>),
+ the notification is sent to all management targets
+ (<c>Addresses</c> below). </p>
+ <p>If no <c>ContextName</c> is specified, the default <c>""</c>
+ context is used. </p>
<p>The parameter <c>Receiver</c> specifies where information
- about delivery of Inform-Requests should be sent. The agent
- sends Inform-Requests and waits for acknowledgments from the
- managers. <c>Receiver</c> can have three values: </p>
+ about delivery of Inform-Requests should be sent. The agent
+ sends Inform-Requests and waits for acknowledgments from the
+ managers. <c>Receiver</c> can have three values: </p>
<list type="bulleted">
<item>
@@ -926,17 +1055,18 @@ snmp_agent:register_subagent(SA1,[1,2,3], SA2).
</item>
<item>
- <p><c>{Tag, Recv}</c> - The information is delivered either via messages
- or via a function call according to the value of <c>Recv</c>. </p>
- </item>
-
- <item>
<p><c>notification_delivery_info()</c> - The information is
delivered via a function call according to this data. See the
<seealso marker="#data_types">DATA TYPES</seealso> section
above for details. </p>
</item>
+ <item>
+ <p><c>{Tag, Recv}</c> - The information is delivered either via
+ messages or via a function call according to the value of
+ <c>Recv</c>. </p>
+ </item>
+
</list>
@@ -1064,86 +1194,20 @@ snmp_agent:register_subagent(SA1,[1,2,3], SA2).
(see SNMP-FRAMEWORK-MIB). </p>
</note>
-<!--
- <marker id="send_trap"></marker>
--->
- <marker id="discovery"></marker>
+ <p><c>ExtraInfo</c> is not normally used in any way by the agent.
+ It is intended to be passed along to the net-if process, which is
+ a component that a user can implement themself. The users own net-if
+ may then make use of ExtraInfo. The net-if provided with this
+ application does not process ExtraInfo. </p>
+ <p>There is one exception. <em>Any</em> tuple containing the atom
+ <c>snmpa_default_notification_extra_info</c> will, in this context,
+ be considered belonging to this application, and may be processed
+ by the agent. </p>
+
+ <marker id="discovery"></marker>
</desc>
</func>
-<!--
- <func>
- <name>send_trap(Agent,Trap,Community)</name>
- <name>send_trap(Agent,Trap,Community,Varbinds) -> void()</name>
- <fsummary>Send a trap</fsummary>
- <type>
- <v>Agent = pid() | atom()</v>
- <v>Trap = atom()</v>
- <v>Community = string()</v>
- <v>Varbinds = [Varbind]</v>
- <v>Varbind = {Variable, Value} | {Column, RowIndex, Value} | {OID, Value}</v>
- <v>Variable = atom()</v>
- <v>Column = atom()</v>
- <v>OID = oid()</v>
- <v>Value = term()</v>
- <v>RowIndex = [int()]</v>
- </type>
- <desc>
- <p>Note! This function is only kept for backwards
- compatibility reasons. Use <c>send_notification</c> instead.
- </p>
- <p>Sends the trap <c>Trap</c> to the managers defined for
- <c>Community</c> in the <c>intTrapDestTable</c> in
- OTP-SNMPEA-MIB. The optional argument <c>Varbinds</c> defines
- values for the objects in the trap. If no value is given for
- an object, the <c>Agent</c> performs a get-operation to
- retrieve the value.
- </p>
- <p><c>Varbinds</c> is a list of <c>Varbind</c>, where each
- <c>Varbind</c> is one of:
- </p>
- <list type="bulleted">
- <item><c>{Variable, Value}</c>, where <c>Variable</c> is the
- symbolic name of a scalar variable referred to in the trap
- specification.
- </item>
- <item><c>{Column, RowIndex, Value}</c>, where <c>Column</c>
- is the symbolic name of a column variable.
- <c>RowIndex</c> is a list of indices for the specified
- element. If this is the case, the OBJECT IDENTIFIER sent
- in the trap is the <c>RowIndex</c> appended to the OBJECT
- IDENTIFIER for the table column. This is the OBJECT
- IDENTIFIER which specifies the element.
- </item>
- <item><c>{OID, Value}</c>, where <c>OID</c> is the OBJECT
- IDENTIFIER for an instance of an object, scalar variable,
- or column variable.
- </item>
- </list>
- <p>For example, to specify that <c>sysLocation</c> should have the
- value <c>"upstairs"</c> in the trap, we could use one of:
- </p>
- <list type="bulleted">
- <item><c>{sysLocation, "upstairs"}</c> or</item>
- <item><c>{[1,3,6,1,2,1,1,6,0], "upstairs"}</c> or</item>
- <item><c>{?sysLocation_instance, "upstairs"}</c> (provided
- that the generated <c>.hrl</c> file is included)</item>
- </list>
- <p>If a variable in the trap is a table element, the
- <c>RowIndex</c> for the element must be given in the
- <c>Varbinds</c> list. In this case, the OBJECT IDENTIFIER sent
- in the trap is the OBJECT IDENTIFIER that identifies this
- element. This OBJECT IDENTIFIER could be used in a get
- operation later.
- </p>
- <p>This function is asynchronous, and does not return any
- information. If an error occurs, <c>snmp_error:user_err/2</c>
- is called and the trap is discarded. </p>
-
- <marker id="discovery"></marker>
- </desc>
- </func>
--->
<func>
<name>discovery(TargetName, Notification) -> {ok, ManagerEngineID} | {error, Reason}</name>
diff --git a/lib/snmp/doc/src/snmpa_conf.xml b/lib/snmp/doc/src/snmpa_conf.xml
index d873574c6e..a533c179ee 100644
--- a/lib/snmp/doc/src/snmpa_conf.xml
+++ b/lib/snmp/doc/src/snmpa_conf.xml
@@ -1,10 +1,10 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
<header>
<copyright>
- <year>2006</year><year>2010</year>
+ <year>2006</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -38,8 +38,21 @@
used for manipulating (write/append/read) the config files of the
SNMP agent. </p>
- <marker id="agent_entry"></marker>
+ <marker id="types"></marker>
</description>
+
+ <section>
+ <title>DATA TYPES</title>
+ <code type="none"><![CDATA[
+transportDomain() = transportDomainUdpIpv4 | transportDomainUdpIpv6
+transportAddressIPv4() = [integer()], length 4
+transportAddressIPv6() = [integer()], length 8
+transportAddressMask() = [integer()], length 0 (default), 6 (IPv4) or 10 (IPv6)
+ ]]></code>
+
+ <marker id="agent_entry"></marker>
+ </section>
+
<funcs>
<func>
<name>agent_entry(Tag, Val) -> agent_entry()</name>
@@ -381,17 +394,19 @@
<name>target_addr_entry(Name, Ip, TagList, ParamsName, EngineId, TMask) -> target_addr_entry()</name>
<name>target_addr_entry(Name, Ip, Udp, TagList, ParamsName, EngineId, TMask, MaxMessageSize) -> target_addr_entry()</name>
<name>target_addr_entry(Name, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize) -> target_addr_entry()</name>
+ <name>target_addr_entry(Name, Domain, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize) -> target_addr_entry()</name>
<fsummary>Create an target_addr entry</fsummary>
<type>
<v>Name = string()</v>
- <v>Ip = string()</v>
+ <v>Domain = transportDomain()</v>
+ <v>Ip = transportAddressIPv4() | transportAddressIPv6() (depends on Domain)</v>
<v>Udp = integer()</v>
<v>Timeout = integer()</v>
<v>RetryCount = integer()</v>
<v>TagList = string()</v>
<v>ParamsName = string()</v>
<v>EngineId = string()</v>
- <v>TMask = string()</v>
+ <v>TMask = transportAddressMask() (depends on Domain)</v>
<v>MaxMessageSize = integer()</v>
<v>target_addr_entry() = term()</v>
</type>
diff --git a/lib/snmp/doc/src/snmpm.xml b/lib/snmp/doc/src/snmpm.xml
index 1ee391d9ba..72849b9c9e 100644
--- a/lib/snmp/doc/src/snmpm.xml
+++ b/lib/snmp/doc/src/snmpm.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
@@ -63,6 +63,10 @@ value_type() = o ('OBJECT IDENTIFIER') |
c64 ('Counter64') |
tt ('TimeTicks')
value() = term()
+community() = string()
+sec_model() = any | v1 | v2c | usm
+sec_name() = string()
+sec_level() = noAuthNoPriv | authNoPriv | authPriv
]]></code>
<marker id="monitor"></marker>
@@ -482,11 +486,65 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<p>Get a list of all registered usm users with engine-id
<c>EngineID</c>.</p>
- <marker id="sync_get"></marker>
+ <marker id="sync_get2"></marker>
</desc>
</func>
<func>
+ <name>sync_get2(UserId, TargetName, Oids) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <name>sync_get2(UserId, TargetName, Oids, SendOpts) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <fsummary>Synchronous <c>get-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>Oids = [oid()]</v>
+ <v>SendOpts = send_opts()</v>
+ <v>send_opts() = [send_opt()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>SnmpReply = snmp_reply()</v>
+ <v>Remaining = integer()</v>
+ <v>Reason = {send_failed, ReqId, ActualReason} | {invalid_sec_info, SecInfo, SnmpInfo} | term()</v>
+ <v>ReqId = term()</v>
+ <v>ActualReason = term()</v>
+ <v>SecInfo = [sec_info()]</v>
+ <v>sec_info() = {sec_tag(), ExpectedValue, ReceivedValue}</v>
+ <v>sec_tag() = atom()</v>
+ <v>ExpectedValue = ReceivedValue = term()</v>
+ <v>SnmpInfo = term()</v>
+ </type>
+ <desc>
+ <p>Synchronous <c>get-request</c>. </p>
+
+ <p><c>Remaining</c> is the remaining time of the given (or default)
+ timeout time.</p>
+
+ <p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error.
+ <em>ActualReason</em> is the actual reason in this case. </p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a option (when using the built in
+ net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
+ <p>For <c>SnmpInfo</c>, see the user callback function
+ <seealso marker="snmpm_user#handle_report">handle_report</seealso>.</p>
+
+ <marker id="sync_get"></marker>
+ </desc>
+ </func>
+
+ <func>
<name>sync_get(UserId, TargetName, Oids) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
<name>sync_get(UserId, TargetName, ContextName, Oids) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
<name>sync_get(UserId, TargetName, Oids, Timeout) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
@@ -513,19 +571,63 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<desc>
<p>Synchronous <c>get-request</c>. </p>
<p><c>Remaining</c> is the remaining time of the given or
- default timeout time.</p>
+ default timeout time.</p>
<p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
- the net_if process failed to send the message. This could happen
- because of any number of reasons, i.e. encoding error. <em>R</em>
- is the actual reason in this case. </p>
- <p><c>ExtraInfo</c> is an opaque data structure passed on to
- the net-if process. The net-if process included in this
- application makes no use of this info, so the only use for it
- in such a configuration (when using the built in net-if) would
- be tracing.</p>
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error. <em>R</em>
+ is the actual reason in this case. </p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
<p>For <c>SnmpInfo</c>, see the user callback function
<seealso marker="snmpm_user#handle_report">handle_report</seealso>.</p>
+ <marker id="async_get2"></marker>
+ </desc>
+ </func>
+
+ <func>
+ <name>async_get2(UserId, TargetName, Oids) -> {ok, ReqId} | {error, Reason}</name>
+ <name>async_get2(UserId, TargetName, Oids, SendOpts) -> {ok, ReqId} | {error, Reason}</name>
+ <fsummary>Asynchronous <c>get-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>Oids = [oid()]</v>
+ <v>SendOpts = send_opts()</v>
+ <v>send_opts() = [send_opt()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>ReqId = term()</v>
+ <v>Reason = term()</v>
+ </type>
+ <desc>
+ <p>Asynchronous <c>get-request</c>.</p>
+
+ <p>The reply, if it arrives, will be delivered to the user
+ through a call to the snmpm_user callback function
+ <c>handle_pdu</c>.</p>
+
+ <p>The send option <c>timeout</c> specifies for how long the request is
+ valid (after which the manager is free to delete it).</p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a option (when using the built in
+ net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
<marker id="async_get"></marker>
</desc>
</func>
@@ -550,17 +652,73 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<desc>
<p>Asynchronous <c>get-request</c>.</p>
<p>The reply, if it arrives, will be delivered to the user
- through a call to the snmpm_user callback function
- <c>handle_pdu</c>.</p>
- <p>The <c>Expire</c> time indicates for how long the request is
- valid (after which the manager is free to delete it).</p>
- <p><c>ExtraInfo</c> is an opaque data structure passed on to
- the net-if process. The net-if process included in this
- application makes no use of this info, so the only use for it
- in such a configuration (when using the built in net-if) would
- be tracing.</p>
-
- <marker id="sync_get_next"></marker>
+ through a call to the snmpm_user callback function
+ <c>handle_pdu</c>.</p>
+ <p>The <c>Expire</c> time indicates for how long the request is
+ valid (after which the manager is free to delete it).</p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <marker id="sync_get_next2"></marker>
+ </desc>
+ </func>
+
+ <func>
+ <name>sync_get_next2(UserId, TargetName, Oids) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <name>sync_get_next2(UserId, TargetName, Oids, SendOpts) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <fsummary>Synchronous <c>get-next-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>Oids = [oid()]</v>
+ <v>SendOpts = send_opts()</v>
+ <v>send_opts() = [send_opt()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>SnmpReply = snmp_reply()</v>
+ <v>Remaining = integer()</v>
+ <v>Reason = {send_failed, ReqId, ActualReason} | {invalid_sec_info, SecInfo, SnmpInfo} | term()</v>
+ <v>ReqId = term()</v>
+ <v>ActualReason = term()</v>
+ <v>SecInfo = [sec_info()]</v>
+ <v>sec_info() = {sec_tag(), ExpectedValue, ReceivedValue}</v>
+ <v>sec_tag() = atom()</v>
+ <v>ExpectedValue = ReceivedValue = term()</v>
+ <v>SnmpInfo = term()</v>
+ </type>
+ <desc>
+ <p>Synchronous <c>get-next-request</c>. </p>
+
+ <p><c>Remaining</c> is the remaining time of the given (or default)
+ timeout time.</p>
+
+ <p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error.
+ <em>ActualReason</em> is the actual reason in this case. </p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a option (when using the built in
+ net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
+ <p>For <c>SnmpInfo</c>, see the user callback function
+ <seealso marker="snmpm_user#handle_report">handle_report</seealso>.</p>
+
+ <marker id="sync_get_next"></marker>
</desc>
</func>
@@ -587,16 +745,57 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<p>Synchronous <c>get-next-request</c>. </p>
<p><c>Remaining</c> time of the given or default timeout time.</p>
<p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
- the net_if process failed to send the message. This could happen
- because of any number of reasons, i.e. encoding error. <em>R</em>
- is the actual reason in this case. </p>
- <p><c>ExtraInfo</c> is an opaque data structure passed on to
- the net-if process. The net-if process included in this
- application makes no use of this info, so the only use for it
- in such a configuration (when using the built in net-if) would
- be tracing.</p>
-
- <marker id="async_get_next"></marker>
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error. <em>R</em>
+ is the actual reason in this case. </p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <marker id="async_get_next2"></marker>
+ </desc>
+ </func>
+
+ <func>
+ <name>async_get_next2(UserId, TargetName, Oids) -> {ok, ReqId} | {error, Reason}</name>
+ <name>async_get_next2(UserId, TargetName, Oids, SendOpts) -> {ok, ReqId} | {error, Reason}</name>
+ <fsummary>Asynchronous <c>get-next-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>Oids = [oid()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>ReqId = integer()</v>
+ <v>Reason = term()</v>
+ </type>
+ <desc>
+ <p>Asynchronous <c>get-next-request</c>. </p>
+
+ <p>The reply will be delivered to the user through a call
+ to the snmpm_user callback function <c>handle_pdu</c>.</p>
+
+ <p>The send option <c>timeout</c> specifies for how long the request is
+ valid (after which the manager is free to delete it).</p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a option (when using the built in
+ net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
+ <marker id="async_get_next"></marker>
</desc>
</func>
@@ -620,11 +819,75 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<desc>
<p>Asynchronous <c>get-next-request</c>. </p>
<p>The reply will be delivered to the user through a call
- to the snmpm_user callback function <c>handle_pdu</c>.</p>
+ to the snmpm_user callback function <c>handle_pdu</c>.</p>
<p>The <c>Expire</c> time indicates for how long the request is
- valid (after which the manager is free to delete it).</p>
+ valid (after which the manager is free to delete it).</p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <marker id="sync_set2"></marker>
+ </desc>
+ </func>
- <marker id="sync_set"></marker>
+ <func>
+ <name>sync_set2(UserId, TargetName, VarsAndVals) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <name>sync_set2(UserId, TargetName, VarsAndVals, SendOpts) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <fsummary>Synchronous <c>set-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>VarsAndVals = vars_and_vals()</v>
+ <v>SendOpts = send_opts()</v>
+ <v>send_opts() = [send_opt()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>SnmpReply = snmp_reply()</v>
+ <v>Remaining = integer()</v>
+ <v>Reason = {send_failed, ReqId, ActualReason} | {invalid_sec_info, SecInfo, SnmpInfo} | term()</v>
+ <v>ReqId = term()</v>
+ <v>ActualReason = term()</v>
+ <v>SecInfo = [sec_info()]</v>
+ <v>sec_info() = {sec_tag(), ExpectedValue, ReceivedValue}</v>
+ <v>sec_tag() = atom()</v>
+ <v>ExpectedValue = ReceivedValue = term()</v>
+ <v>SnmpInfo = term()</v>
+ </type>
+ <desc>
+ <p>Synchronous <c>set-request</c>. </p>
+
+ <p><c>Remaining</c> is the remaining time of the given (or default)
+ timeout time.</p>
+
+ <p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error.
+ <em>ActualReason</em> is the actual reason in this case. </p>
+
+ <p>When <em>var_and_val()</em> is <em>{oid(), value()}</em>, the
+ manager makes an educated guess based on the loaded mibs. </p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a option (when using the built in
+ net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
+ <p>For <c>SnmpInfo</c>, see the user callback function
+ <seealso marker="snmpm_user#handle_report">handle_report</seealso>.</p>
+
+ <marker id="sync_set"></marker>
</desc>
</func>
@@ -651,18 +914,64 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<p>Synchronous <c>set-request</c>. </p>
<p><c>Remaining</c> time of the given or default timeout time.</p>
<p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
- the net_if process failed to send the message. This could happen
- because of any number of reasons, i.e. encoding error. <em>R</em>
- is the actual reason in this case. </p>
- <p>When <em>var_and_val()</em> is <em>{oid(), value()}</em>, the
- manager makes an educated guess based on the loaded mibs. </p>
- <p><c>ExtraInfo</c> is an opaque data structure passed on to
- the net-if process. The net-if process included in this
- application makes no use of this info, so the only use for it
- in such a configuration (when using the built in net-if) would
- be tracing.</p>
-
- <marker id="async_set"></marker>
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error. <em>R</em>
+ is the actual reason in this case. </p>
+ <p>When <em>var_and_val()</em> is <em>{oid(), value()}</em>, the
+ manager makes an educated guess based on the loaded mibs. </p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <marker id="async_set2"></marker>
+ </desc>
+ </func>
+
+ <func>
+ <name>async_set2(UserId, TargetName, VarsAndVals) -> {ok, ReqId} | {error, Reason}</name>
+ <name>async_set2(UserId, TargetName, VarsAndVals, SendOpts) -> {ok, ReqId} | {error, Reason}</name>
+ <fsummary>Asynchronous <c>set-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>VarsAndVals = vars_and_vals()</v>
+ <v>SendOpts = send_opts()</v>
+ <v>send_opts() = [send_opt()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>ReqId = term()</v>
+ <v>Reason = term()</v>
+ </type>
+ <desc>
+ <p>Asynchronous <c>set-request</c>. </p>
+
+ <p>The reply will be delivered to the user through a call
+ to the snmpm_user callback function <c>handle_pdu</c>.</p>
+
+ <p>The send option <c>timeout</c> specifies for how long the request is
+ valid (after which the manager is free to delete it).</p>
+
+ <p>When <em>var_and_val()</em> is <em>{oid(), value()}</em>, the
+ manager makes an educated guess based on the loaded mibs. </p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a option (when using the built in
+ net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
+ <marker id="async_set"></marker>
</desc>
</func>
@@ -685,18 +994,76 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<desc>
<p>Asynchronous <c>set-request</c>. </p>
<p>The reply will be delivered to the user through a call
- to the snmpm_user callback function <c>handle_pdu</c>.</p>
+ to the snmpm_user callback function <c>handle_pdu</c>.</p>
<p>The <c>Expire</c> time indicates for how long the request is
- valid (after which the manager is free to delete it).</p>
- <p>When <em>var_and_val()</em> is <em>{oid(), value()}</em>, the
- manager makes an educated guess based on the loaded mibs. </p>
- <p><c>ExtraInfo</c> is an opaque data structure passed on to
- the net-if process. The net-if process included in this
- application makes no use of this info, so the only use for it
- in such a configuration (when using the built in net-if) would
- be tracing.</p>
-
- <marker id="sync_get_bulk"></marker>
+ valid (after which the manager is free to delete it).</p>
+ <p>When <em>var_and_val()</em> is <em>{oid(), value()}</em>, the
+ manager makes an educated guess based on the loaded mibs. </p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <marker id="sync_get_bulk2"></marker>
+ </desc>
+ </func>
+
+ <func>
+ <name>sync_get_bulk2(UserId, TragetName, NonRep, MaxRep, Oids) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <name>sync_get_bulk2(UserId, TragetName, NonRep, MaxRep, Oids, SendOpts) -> {ok, SnmpReply, Remaining} | {error, Reason}</name>
+ <fsummary>Synchronous <c>get-bulk-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>NonRep = integer()</v>
+ <v>MaxRep = integer()</v>
+ <v>Oids = [oid()]</v>
+ <v>SendOpts = send_opts()</v>
+ <v>send_opts() = [send_opt()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>SnmpReply = snmp_reply()</v>
+ <v>Remaining = integer()</v>
+ <v>Reason = {send_failed, ReqId, ActualReason} | {invalid_sec_info, SecInfo, SnmpInfo} | term()</v>
+ <v>ReqId = term()</v>
+ <v>ActualReason = term()</v>
+ <v>SecInfo = [sec_info()]</v>
+ <v>sec_info() = {sec_tag(), ExpectedValue, ReceivedValue}</v>
+ <v>sec_tag() = atom()</v>
+ <v>ExpectedValue = ReceivedValue = term()</v>
+ <v>SnmpInfo = term()</v>
+ </type>
+ <desc>
+ <p>Synchronous <c>get-bulk-request</c> (See RFC1905).</p>
+
+ <p><c>Remaining</c> is the remaining time of the given (or default)
+ timeout time.</p>
+
+ <p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error.
+ <em>ActualReason</em> is the actual reason in this case. </p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a option (when using the built in
+ net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
+ <p>For <c>SnmpInfo</c>, see the user callback function
+ <seealso marker="snmpm_user#handle_report">handle_report</seealso>.</p>
+
+ <marker id="sync_get_bulk"></marker>
</desc>
</func>
@@ -723,17 +1090,60 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<desc>
<p>Synchronous <c>get-bulk-request</c> (See RFC1905).</p>
<p><c>Remaining</c> time of the given or default timeout time.</p>
- <p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
- the net_if process failed to send the message. This could happen
- because of any number of reasons, i.e. encoding error. <em>R</em>
- is the actual reason in this case. </p>
- <p><c>ExtraInfo</c> is an opaque data structure passed on to
- the net-if process. The net-if process included in this
- application makes no use of this info, so the only use for it
- in such a configuration (when using the built in net-if) would
- be tracing.</p>
-
- <marker id="async_get_bulk"></marker>
+ <p>When <em>Reason</em> is <em>{send_failed, ...}</em> it means that
+ the net_if process failed to send the message. This could happen
+ because of any number of reasons, i.e. encoding error. <em>R</em>
+ is the actual reason in this case. </p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
+
+ <marker id="async_get_bulk2"></marker>
+ </desc>
+ </func>
+
+ <func>
+ <name>async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids) -> {ok, ReqId} | {error, Reason}</name>
+ <name>async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts) -> {ok, ReqId} | {error, Reason}</name>
+ <fsummary>Asynchronous <c>get-bulk-request</c></fsummary>
+ <type>
+ <v>UserId = term()</v>
+ <v>TargetName = target_name()</v>
+ <v>NonRep = integer()</v>
+ <v>MaxRep = integer()</v>
+ <v>Oids = [oid()]</v>
+ <v>SendOpts = send_opts()</v>
+ <v>send_opts() = [send_opt()]</v>
+ <v>send_opt() = {context, string()} | {timeout, pos_integer()} | {extra, term()} | {community, community()} | {sec_model, sec_model()} | {sec_name, string()} | {sec_level, sec_level()} | {max_message_size, pos_integer()}</v>
+ <v>ReqId = integer()</v>
+ <v>Reason = term()</v>
+ </type>
+ <desc>
+ <p>Asynchronous <c>get-bulk-request</c> (See RFC1905).</p>
+
+ <p>The reply will be delivered to the user through a call
+ to the snmpm_user callback function <c>handle_pdu</c>.</p>
+
+ <p>The send option <c>timeout</c> specifies for how long the request is
+ valid (after which the manager is free to delete it).</p>
+
+ <p>The send option <c>extra</c> specifies an opaque data structure
+ passed on to the net-if process. The net-if process included in this
+ application makes no use of this info, so the only use for it
+ in such a configuration (when using the built in net-if) would
+ be tracing.</p>
+
+ <p>Some of the send options (<c>community</c>, <c>sec_model</c>,
+ <c>sec_name</c>, <c>sec_level</c> and <c>max_message_size</c>)
+ are <c>override options</c>. That is,
+ for <em>this</em> request, they override any configuration done
+ when the agent was registered. </p>
+
+ <marker id="async_get_bulk"></marker>
</desc>
</func>
@@ -759,9 +1169,16 @@ priv_key = [integer()] (length is 16 if priv = usmDESPrivProtocol | usmAesCfb1
<desc>
<p>Asynchronous <c>get-bulk-request</c> (See RFC1905).</p>
<p>The reply will be delivered to the user through a call
- to the snmpm_user callback function <c>handle_pdu</c>.</p>
+ to the snmpm_user callback function <c>handle_pdu</c>.</p>
<p>The <c>Expire</c> time indicates for how long the request is
- valid (after which the manager is free to delete it).</p>
+ valid (after which the manager is free to delete it).</p>
+ <p><c>ExtraInfo</c> is an opaque data structure passed on to
+ the net-if process. The net-if process included in this
+ application makes, with one exception, no use of this info,
+ so the only use for it in such a configuration (when using the
+ built in net-if) would be tracing. The one usage exception is:
+ <em>Any</em> tuple with <c>snmpm_extra_info_tag</c> as its first
+ element is reserved for internal use. </p>
<marker id="cancel_async_request"></marker>
</desc>
diff --git a/lib/snmp/mibs/Makefile.in b/lib/snmp/mibs/Makefile.in
index 7aefb0ea34..3af74eca75 100644
--- a/lib/snmp/mibs/Makefile.in
+++ b/lib/snmp/mibs/Makefile.in
@@ -61,7 +61,8 @@ MIBS_A = \
SNMP-USER-BASED-SM-MIB \
SNMP-VIEW-BASED-ACM-MIB \
SNMP-USM-AES-MIB \
- INET-ADDRESS-MIB
+ INET-ADDRESS-MIB \
+ TRANSPORT-ADDRESS-MIB
MIBS_B = OTP-SNMPEA-MIB
diff --git a/lib/snmp/mibs/TRANSPORT-ADDRESS-MIB.mib b/lib/snmp/mibs/TRANSPORT-ADDRESS-MIB.mib
new file mode 100644
index 0000000000..7d450fbc2a
--- /dev/null
+++ b/lib/snmp/mibs/TRANSPORT-ADDRESS-MIB.mib
@@ -0,0 +1,417 @@
+TRANSPORT-ADDRESS-MIB DEFINITIONS ::= BEGIN
+
+IMPORTS
+ MODULE-IDENTITY, OBJECT-IDENTITY, mib-2 FROM SNMPv2-SMI
+ TEXTUAL-CONVENTION FROM SNMPv2-TC;
+
+transportAddressMIB MODULE-IDENTITY
+ LAST-UPDATED "200211010000Z"
+ ORGANIZATION
+ "IETF Operations and Management Area"
+ CONTACT-INFO
+ "Juergen Schoenwaelder (Editor)
+ TU Braunschweig
+ Bueltenweg 74/75
+ 38106 Braunschweig, Germany
+ Phone: +49 531 391-3289
+
+ Send comments to <[email protected]>."
+ DESCRIPTION
+ "This MIB module provides commonly used transport
+ address definitions.
+
+ Copyright (C) The Internet Society (2002). This version of
+ this MIB module is part of RFC 3419; see the RFC itself for
+ full legal notices."
+
+ -- Revision log
+
+ REVISION "200211010000Z"
+ DESCRIPTION
+ "Initial version, published as RFC 3419."
+ ::= { mib-2 100 }
+
+
+transportDomains OBJECT IDENTIFIER ::= { transportAddressMIB 1 }
+
+transportDomainUdpIpv4 OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The UDP over IPv4 transport domain. The corresponding
+ transport address is of type TransportAddressIPv4 for
+ global IPv4 addresses."
+ ::= { transportDomains 1 }
+
+transportDomainUdpIpv6 OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The UDP over IPv6 transport domain. The corresponding
+ transport address is of type TransportAddressIPv6 for
+ global IPv6 addresses."
+ ::= { transportDomains 2 }
+
+transportDomainUdpIpv4z OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The UDP over IPv4 transport domain. The corresponding
+ transport address is of type TransportAddressIPv4z for
+ scoped IPv4 addresses with a zone index."
+ ::= { transportDomains 3 }
+
+transportDomainUdpIpv6z OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The UDP over IPv6 transport domain. The corresponding
+ transport address is of type TransportAddressIPv6z for
+ scoped IPv6 addresses with a zone index."
+ ::= { transportDomains 4 }
+
+transportDomainTcpIpv4 OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The TCP over IPv4 transport domain. The corresponding
+ transport address is of type TransportAddressIPv4 for
+ global IPv4 addresses."
+ ::= { transportDomains 5 }
+
+transportDomainTcpIpv6 OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The TCP over IPv6 transport domain. The corresponding
+ transport address is of type TransportAddressIPv6 for
+ global IPv6 addresses."
+ ::= { transportDomains 6 }
+
+transportDomainTcpIpv4z OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The TCP over IPv4 transport domain. The corresponding
+ transport address is of type TransportAddressIPv4z for
+ scoped IPv4 addresses with a zone index."
+ ::= { transportDomains 7 }
+
+transportDomainTcpIpv6z OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The TCP over IPv6 transport domain. The corresponding
+ transport address is of type TransportAddressIPv6z for
+ scoped IPv6 addresses with a zone index."
+ ::= { transportDomains 8 }
+
+transportDomainSctpIpv4 OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The SCTP over IPv4 transport domain. The corresponding
+ transport address is of type TransportAddressIPv4 for
+ global IPv4 addresses. This transport domain usually
+ represents the primary address on multihomed SCTP
+ endpoints."
+ ::= { transportDomains 9 }
+
+transportDomainSctpIpv6 OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The SCTP over IPv6 transport domain. The corresponding
+ transport address is of type TransportAddressIPv6 for
+ global IPv6 addresses. This transport domain usually
+ represents the primary address on multihomed SCTP
+ endpoints."
+ ::= { transportDomains 10 }
+
+transportDomainSctpIpv4z OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The SCTP over IPv4 transport domain. The corresponding
+ transport address is of type TransportAddressIPv4z for
+ scoped IPv4 addresses with a zone index. This transport
+ domain usually represents the primary address on
+ multihomed SCTP endpoints."
+ ::= { transportDomains 11 }
+
+transportDomainSctpIpv6z OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The SCTP over IPv6 transport domain. The corresponding
+ transport address is of type TransportAddressIPv6z for
+ scoped IPv6 addresses with a zone index. This transport
+ domain usually represents the primary address on
+ multihomed SCTP endpoints."
+ ::= { transportDomains 12 }
+
+transportDomainLocal OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The Posix Local IPC transport domain. The corresponding
+ transport address is of type TransportAddressLocal.
+
+ The Posix Local IPC transport domain incorporates the
+ well-known UNIX domain sockets."
+ ::= { transportDomains 13 }
+
+transportDomainUdpDns OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The UDP transport domain using fully qualified domain
+ names. The corresponding transport address is of type
+ TransportAddressDns."
+ ::= { transportDomains 14 }
+
+transportDomainTcpDns OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The TCP transport domain using fully qualified domain
+ names. The corresponding transport address is of type
+ TransportAddressDns."
+ ::= { transportDomains 15 }
+
+transportDomainSctpDns OBJECT-IDENTITY
+ STATUS current
+ DESCRIPTION
+ "The SCTP transport domain using fully qualified domain
+ names. The corresponding transport address is of type
+ TransportAddressDns."
+ ::= { transportDomains 16 }
+
+TransportDomain ::= TEXTUAL-CONVENTION
+ STATUS current
+ DESCRIPTION
+ "A value that represents a transport domain.
+
+ Some possible values, such as transportDomainUdpIpv4, are
+ defined in this module. Other possible values can be
+ defined in other MIB modules."
+ SYNTAX OBJECT IDENTIFIER
+
+--
+-- The enumerated values of the textual convention below should
+-- be identical to the last sub-identifier of the OID registered
+-- for the same domain.
+--
+
+TransportAddressType ::= TEXTUAL-CONVENTION
+ STATUS current
+ DESCRIPTION
+ "A value that represents a transport domain. This is the
+ enumerated version of the transport domain registrations
+ in this MIB module. The enumerated values have the
+ following meaning:
+
+ unknown(0) unknown transport address type
+ udpIpv4(1) transportDomainUdpIpv4
+ udpIpv6(2) transportDomainUdpIpv6
+ udpIpv4z(3) transportDomainUdpIpv4z
+ udpIpv6z(4) transportDomainUdpIpv6z
+ tcpIpv4(5) transportDomainTcpIpv4
+ tcpIpv6(6) transportDomainTcpIpv6
+ tcpIpv4z(7) transportDomainTcpIpv4z
+ tcpIpv6z(8) transportDomainTcpIpv6z
+ sctpIpv4(9) transportDomainSctpIpv4
+ sctpIpv6(10) transportDomainSctpIpv6
+ sctpIpv4z(11) transportDomainSctpIpv4z
+ sctpIpv6z(12) transportDomainSctpIpv6z
+ local(13) transportDomainLocal
+ udpDns(14) transportDomainUdpDns
+ tcpDns(15) transportDomainTcpDns
+ sctpDns(16) transportDomainSctpDns
+
+ This textual convention can be used to represent transport
+ domains in situations where a syntax of TransportDomain is
+ unwieldy (for example, when used as an index).
+
+ The usage of this textual convention implies that additional
+ transport domains can only be supported by updating this MIB
+ module. This extensibility restriction does not apply for the
+ TransportDomain textual convention which allows MIB authors
+ to define additional transport domains independently in
+ other MIB modules."
+ SYNTAX INTEGER {
+ unknown(0),
+ udpIpv4(1),
+ udpIpv6(2),
+ udpIpv4z(3),
+ udpIpv6z(4),
+ tcpIpv4(5),
+ tcpIpv6(6),
+ tcpIpv4z(7),
+ tcpIpv6z(8),
+ sctpIpv4(9),
+ sctpIpv6(10),
+ sctpIpv4z(11),
+ sctpIpv6z(12),
+ local(13),
+ udpDns(14),
+ tcpDns(15),
+ sctpDns(16)
+ }
+
+TransportAddress ::= TEXTUAL-CONVENTION
+ STATUS current
+ DESCRIPTION
+ "Denotes a generic transport address.
+
+ A TransportAddress value is always interpreted within the
+ context of a TransportAddressType or TransportDomain value.
+ Every usage of the TransportAddress textual convention MUST
+ specify the TransportAddressType or TransportDomain object
+ which provides the context. Furthermore, MIB authors SHOULD
+ define a separate TransportAddressType or TransportDomain
+ object for each TransportAddress object. It is suggested that
+ the TransportAddressType or TransportDomain is logically
+ registered before the object(s) which use the
+ TransportAddress textual convention if they appear in the
+ same logical row.
+
+ The value of a TransportAddress object must always be
+ consistent with the value of the associated
+ TransportAddressType or TransportDomain object. Attempts
+ to set a TransportAddress object to a value which is
+ inconsistent with the associated TransportAddressType or
+ TransportDomain must fail with an inconsistentValue error.
+
+ When this textual convention is used as a syntax of an
+ index object, there may be issues with the limit of 128
+ sub-identifiers specified in SMIv2, STD 58. In this case,
+ the OBJECT-TYPE declaration MUST include a 'SIZE' clause
+ to limit the number of potential instance sub-identifiers."
+ SYNTAX OCTET STRING (SIZE (0..255))
+
+TransportAddressIPv4 ::= TEXTUAL-CONVENTION
+ DISPLAY-HINT "1d.1d.1d.1d:2d"
+ STATUS current
+ DESCRIPTION
+ "Represents a transport address consisting of an IPv4
+ address and a port number (as used for example by UDP,
+ TCP and SCTP):
+
+ octets contents encoding
+ 1-4 IPv4 address network-byte order
+ 5-6 port number network-byte order
+
+ This textual convention SHOULD NOT be used directly in object
+ definitions since it restricts addresses to a specific format.
+ However, if it is used, it MAY be used either on its own or
+ in conjunction with TransportAddressType or TransportDomain
+ as a pair."
+ SYNTAX OCTET STRING (SIZE (6))
+
+TransportAddressIPv6 ::= TEXTUAL-CONVENTION
+ DISPLAY-HINT "0a[2x:2x:2x:2x:2x:2x:2x:2x]0a:2d"
+ STATUS current
+ DESCRIPTION
+ "Represents a transport address consisting of an IPv6
+ address and a port number (as used for example by UDP,
+ TCP and SCTP):
+
+ octets contents encoding
+ 1-16 IPv6 address network-byte order
+ 17-18 port number network-byte order
+
+ This textual convention SHOULD NOT be used directly in object
+ definitions since it restricts addresses to a specific format.
+ However, if it is used, it MAY be used either on its own or
+ in conjunction with TransportAddressType or TransportDomain
+ as a pair."
+ SYNTAX OCTET STRING (SIZE (18))
+
+TransportAddressIPv4z ::= TEXTUAL-CONVENTION
+ DISPLAY-HINT "1d.1d.1d.1d%4d:2d"
+ STATUS current
+ DESCRIPTION
+ "Represents a transport address consisting of an IPv4
+ address, a zone index and a port number (as used for
+ example by UDP, TCP and SCTP):
+
+ octets contents encoding
+ 1-4 IPv4 address network-byte order
+ 5-8 zone index network-byte order
+ 9-10 port number network-byte order
+
+ This textual convention SHOULD NOT be used directly in object
+ definitions since it restricts addresses to a specific format.
+ However, if it is used, it MAY be used either on its own or
+ in conjunction with TransportAddressType or TransportDomain
+ as a pair."
+ SYNTAX OCTET STRING (SIZE (10))
+
+TransportAddressIPv6z ::= TEXTUAL-CONVENTION
+ DISPLAY-HINT "0a[2x:2x:2x:2x:2x:2x:2x:2x%4d]0a:2d"
+ STATUS current
+ DESCRIPTION
+ "Represents a transport address consisting of an IPv6
+ address, a zone index and a port number (as used for
+ example by UDP, TCP and SCTP):
+
+ octets contents encoding
+ 1-16 IPv6 address network-byte order
+ 17-20 zone index network-byte order
+ 21-22 port number network-byte order
+
+ This textual convention SHOULD NOT be used directly in object
+ definitions since it restricts addresses to a specific format.
+ However, if it is used, it MAY be used either on its own or
+ in conjunction with TransportAddressType or TransportDomain
+ as a pair."
+ SYNTAX OCTET STRING (SIZE (22))
+
+TransportAddressLocal ::= TEXTUAL-CONVENTION
+ DISPLAY-HINT "1a"
+ STATUS current
+ DESCRIPTION
+ "Represents a POSIX Local IPC transport address:
+
+ octets contents encoding
+ all POSIX Local IPC address string
+
+ The Posix Local IPC transport domain subsumes UNIX domain
+ sockets.
+
+ This textual convention SHOULD NOT be used directly in object
+ definitions since it restricts addresses to a specific format.
+ However, if it is used, it MAY be used either on its own or
+ in conjunction with TransportAddressType or TransportDomain
+ as a pair.
+
+ When this textual convention is used as a syntax of an
+ index object, there may be issues with the limit of 128
+ sub-identifiers specified in SMIv2, STD 58. In this case,
+ the OBJECT-TYPE declaration MUST include a 'SIZE' clause
+ to limit the number of potential instance sub-identifiers."
+ REFERENCE
+ "Protocol Independent Interfaces (IEEE POSIX 1003.1g)"
+ SYNTAX OCTET STRING (SIZE (1..255))
+
+TransportAddressDns ::= TEXTUAL-CONVENTION
+ DISPLAY-HINT "1a"
+ STATUS current
+ DESCRIPTION
+ "Represents a DNS domain name followed by a colon ':'
+ (ASCII character 0x3A) and a port number in ASCII.
+ The name SHOULD be fully qualified whenever possible.
+
+ Values of this textual convention are not directly useable as
+ transport-layer addressing information, and require runtime
+ resolution. As such, applications that write them must be
+ prepared for handling errors if such values are not
+ supported, or cannot be resolved (if resolution occurs at the
+ time of the management operation).
+
+ The DESCRIPTION clause of TransportAddress objects that may
+ have TransportAddressDns values must fully describe how (and
+ when) such names are to be resolved to IP addresses and vice
+ versa.
+
+ This textual convention SHOULD NOT be used directly in object
+ definitions since it restricts addresses to a specific format.
+ However, if it is used, it MAY be used either on its own or
+ in conjunction with TransportAddressType or TransportDomain
+ as a pair.
+
+ When this textual convention is used as a syntax of an
+ index object, there may be issues with the limit of 128
+ sub-identifiers specified in SMIv2, STD 58. In this case,
+ the OBJECT-TYPE declaration MUST include a 'SIZE' clause
+ to limit the number of potential instance sub-identifiers."
+ SYNTAX OCTET STRING (SIZE (1..255))
+
+END
diff --git a/lib/snmp/priv/conf/agent/target_addr.conf b/lib/snmp/priv/conf/agent/target_addr.conf
index 33a5d0d4c4..f48a6645a3 100644
--- a/lib/snmp/priv/conf/agent/target_addr.conf
+++ b/lib/snmp/priv/conf/agent/target_addr.conf
@@ -3,9 +3,13 @@
%% The data is inserted into the snmpTargetAddrTable defined
%% in SNMP-TARGET-MIB, and in the snmpTargeAddrExtTabke defined
%% in SNMP-COMMUNITY-MIB.
-%% Each row is a 9-tuple:
-%% {Name, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId,
-%% TMask, MaxMessageSize}.
+%% Each row is a 10 or 11-tuple (Domain is optional):
+%% {Name,
+%% Domain, Ip, Port,
+%% Timeout, RetryCount, TagList, ParamsName, EngineId,
+%% TMask, MaxMessageSize}.
+%% The value of Domain decide the format of the Ip and TMask values.
+%% If not present, classic Ipv4 is assumed.
%% The EngineId value is only used if Inform-Requests are sent to this
%% target. If Informs are not sent, this value is ignored, and can be
%% e.g. an empty string. However, if Informs are sent, it is essential
diff --git a/lib/snmp/src/agent/snmp_community_mib.erl b/lib/snmp/src/agent/snmp_community_mib.erl
index 5644a43345..3debe0a30e 100644
--- a/lib/snmp/src/agent/snmp_community_mib.erl
+++ b/lib/snmp/src/agent/snmp_community_mib.erl
@@ -25,7 +25,7 @@
snmpTargetAddrExtTable/3,
community2vacm/2, vacm2community/2,
get_target_addr_ext_mms/2]).
--export([add_community/5, delete_community/1]).
+-export([add_community/5, add_community/6, delete_community/1]).
-export([check_community/1]).
-include("SNMP-COMMUNITY-MIB.hrl").
@@ -128,12 +128,16 @@ read_community_config_files(Dir) ->
Comms.
check_community({Index, CommunityName, SecName, CtxName, TransportTag}) ->
+ EngineID = get_engine_id(),
+ check_community({Index, CommunityName, SecName,
+ EngineID, CtxName, TransportTag});
+check_community({Index, CommunityName, SecName,
+ EngineID, CtxName, TransportTag}) ->
snmp_conf:check_string(Index,{gt,0}),
snmp_conf:check_string(CommunityName),
snmp_conf:check_string(SecName),
snmp_conf:check_string(CtxName),
snmp_conf:check_string(TransportTag),
- EngineID = get_engine_id(),
Comm = {Index, CommunityName, SecName, EngineID, CtxName, TransportTag,
?'StorageType_nonVolatile', ?'RowStatus_active'},
{ok, Comm};
@@ -173,6 +177,13 @@ table_del_row(Tab, Key) ->
%% FIXME: does not work with mnesia
add_community(Idx, CommName, SecName, CtxName, TransportTag) ->
Community = {Idx, CommName, SecName, CtxName, TransportTag},
+ do_add_community(Community).
+
+add_community(Idx, CommName, SecName, EngineId, CtxName, TransportTag) ->
+ Community = {Idx, CommName, SecName, EngineId, CtxName, TransportTag},
+ do_add_community(Community).
+
+do_add_community(Community) ->
case (catch check_community(Community)) of
{ok, Row} ->
Key = element(1, Row),
diff --git a/lib/snmp/src/agent/snmp_notification_mib.erl b/lib/snmp/src/agent/snmp_notification_mib.erl
index 1cd69b430f..3da5766b44 100644
--- a/lib/snmp/src/agent/snmp_notification_mib.erl
+++ b/lib/snmp/src/agent/snmp_notification_mib.erl
@@ -273,9 +273,12 @@ find_targets(Key, TargAddrs, Db, Res) ->
get_targets([{TagList, Addr, TargetName, Params, Timeout, Retry}|T],
Tag, Type, Name) ->
case snmp_misc:is_tag_member(Tag, TagList) of
- true -> [{Name, {Addr, TargetName, Params, type(Type, Timeout, Retry)}}|
- get_targets(T, Tag, Type, Name)];
+ true ->
+ ?vtrace("tag ~w *is* member", [Tag]),
+ [{Name, {Addr, TargetName, Params, type(Type, Timeout, Retry)}}|
+ get_targets(T, Tag, Type, Name)];
false ->
+ ?vtrace("tag ~w is *not* member", [Tag]),
get_targets(T, Tag, Type, Name)
end;
get_targets([], _Tag, _Type, _Name) ->
diff --git a/lib/snmp/src/agent/snmp_target_mib.erl b/lib/snmp/src/agent/snmp_target_mib.erl
index 270a5fd5b6..b2f2417b02 100644
--- a/lib/snmp/src/agent/snmp_target_mib.erl
+++ b/lib/snmp/src/agent/snmp_target_mib.erl
@@ -26,16 +26,18 @@
snmpTargetParamsTable/1, snmpTargetParamsTable/3,
get_target_addrs/0, get_target_engine_id/1, set_target_engine_id/2,
is_valid_tag/3, get/3, table_next/2]).
--export([add_addr/10, delete_addr/1,
+-export([add_addr/10, add_addr/11, delete_addr/1,
add_params/5, delete_params/1]).
-export([check_target_addr/1, check_target_params/1]).
+-export([default_domain/0]).
--include("snmp_types.hrl").
--include("snmp_tables.hrl").
--include("SNMP-TARGET-MIB.hrl").
--include("SNMPv2-TC.hrl").
--include("SNMPv2-TM.hrl").
--include("SNMP-FRAMEWORK-MIB.hrl").
+-include_lib("snmp/include/snmp_types.hrl").
+-include_lib("snmp/include/snmp_tables.hrl").
+-include_lib("snmp/include/SNMP-TARGET-MIB.hrl").
+-include_lib("snmp/include/SNMPv2-TC.hrl").
+-include_lib("snmp/include/SNMPv2-TM.hrl").
+-include_lib("snmp/include/SNMP-FRAMEWORK-MIB.hrl").
+-include_lib("snmp/include/TRANSPORT-ADDRESS-MIB.hrl").
-define(VMODULE,"TARGET-MIB").
-include("snmp_verbosity.hrl").
@@ -49,6 +51,12 @@
%%-----------------------------------------------------------------
+
+default_domain() ->
+ snmpUDPDomain.
+
+
+%%-----------------------------------------------------------------
%% Func: configure/1
%% Args: Dir is the directory where the configuration files are found.
%% Purpose: If the tables doesn't exist, this function reads
@@ -139,39 +147,51 @@ read_target_config_files(Dir) ->
%% {Name, Ip, Udp, Timeout, RetryCount, TagList, Params, EngineId,
%% TMask, MMS}
%%-----------------------------------------------------------------
-check_target_addr({Name, Ip, Udp, Timeout, RetryCount, TagList,
- Params, EngineId, TMask, MMS}) ->
+
+check_target_addr({Name, Domain, Ip, Udp, Timeout, RetryCount, TagList,
+ Params, EngineId, TMask, MMS}) ->
?vtrace("check target address with:"
- "~n Name: ~s"
- "~n Ip: ~p"
- "~n Udp: ~p"
- "~n Timeout: ~p"
- "~n RetryCount: ~p"
- "~n TagList: ~p"
- "~n Params: ~p"
- "~n EngineId: ~p"
- "~n TMask: ~p"
- "~n MMS: ~p",
- [Name,Ip,Udp,Timeout,RetryCount,
- TagList,Params,EngineId,TMask,MMS]),
+ "~n Name: ~s"
+ "~n Domain: ~p"
+ "~n Ip: ~p"
+ "~n Udp: ~p"
+ "~n Timeout: ~p"
+ "~n RetryCount: ~p"
+ "~n TagList: ~p"
+ "~n Params: ~p"
+ "~n EngineId: ~p"
+ "~n TMask: ~p"
+ "~n MMS: ~p",
+ [Name,
+ Domain, Ip, Udp,
+ Timeout, RetryCount,
+ TagList, Params, EngineId, TMask, MMS]),
snmp_conf:check_string(Name,{gt,0}),
- snmp_conf:check_ip(Ip),
+ snmp_conf:check_domain(Domain),
+ snmp_conf:check_ip(Domain, Ip),
snmp_conf:check_integer(Udp, {gt, 0}),
snmp_conf:check_integer(Timeout, {gte, 0}),
snmp_conf:check_integer(RetryCount, {gte,0}),
snmp_conf:check_string(TagList),
snmp_conf:check_string(Params),
check_engine_id(EngineId),
- TAddr = Ip ++ [Udp div 256, Udp rem 256],
- check_mask(TMask, TAddr),
+ TAddress = snmp_conf:mk_taddress(Domain, Ip, Udp),
+ TDomain = snmp_conf:mk_tdomain(Domain),
+ check_tmask(TDomain, TMask, TAddress),
snmp_conf:check_packet_size(MMS),
?vtrace("check target address done",[]),
-
- Addr = {Name, ?snmpUDPDomain, TAddr, Timeout,
+ Addr = {Name, TDomain, TAddress, Timeout,
RetryCount, TagList, Params,
?'StorageType_nonVolatile', ?'RowStatus_active', EngineId,
TMask, MMS}, % Values for Augmenting table in SNMP-COMMUNITY-MIB
{ok, Addr};
+check_target_addr({Name, Ip, Udp, Timeout, RetryCount, TagList,
+ Params, EngineId, TMask, MMS}) ->
+ Domain = default_domain(),
+ check_target_addr({Name,
+ Domain, Ip, Udp,
+ Timeout, RetryCount, TagList,
+ Params, EngineId, TMask, MMS});
check_target_addr({Name, Ip, Udp, Timeout, RetryCount, TagList, Params,
EngineId}) ->
check_target_addr({Name, Ip, Udp, Timeout, RetryCount, TagList,
@@ -194,12 +214,13 @@ check_engine_id(discovery) ->
check_engine_id(EngineId) ->
snmp_conf:check_string(EngineId).
-check_mask([], _TAddr) ->
+
+check_tmask(_TDomain, [], _TAddress) ->
ok;
-check_mask(TMask, TAddr) when length(TMask) == length(TAddr) ->
- snmp_conf:check_taddress(TMask);
-check_mask(TMask, _TAddr) ->
- throw({error, {invalid_mask, TMask}}).
+check_tmask(TDomain, TMask, TAddress) when length(TMask) =:= length(TAddress) ->
+ snmp_conf:check_taddress(TDomain, TMask);
+check_tmask(_TDomain, TMask, _TAddr) ->
+ throw({error, {invalid_tmask, TMask}}).
%%-----------------------------------------------------------------
@@ -261,7 +282,13 @@ table_del_row(Tab, Key) ->
add_addr(Name, Ip, Port, Timeout, Retry, TagList,
Params, EngineId, TMask, MMS) ->
- Addr = {Name, Ip, Port, Timeout, Retry, TagList,
+ Domain = default_domain(),
+ add_addr(Name, Domain, Ip, Port, Timeout, Retry, TagList,
+ Params, EngineId, TMask, MMS).
+
+add_addr(Name, Domain, Ip, Port, Timeout, Retry, TagList,
+ Params, EngineId, TMask, MMS) ->
+ Addr = {Name, Domain, Ip, Port, Timeout, Retry, TagList,
Params, EngineId, TMask, MMS},
case (catch check_target_addr(Addr)) of
{ok, Row} ->
@@ -341,8 +368,11 @@ maybe_create_var(Var) ->
init_var(Var) -> ets:insert(snmp_agent_table, {Var, 0}).
vars() ->
- [snmpUnavailableContexts,
- snmpUnknownContexts].
+ [
+ snmpUnavailableContexts,
+ snmpUnknownContexts
+ ].
+
%%-----------------------------------------------------------------
%% API functions
@@ -562,6 +592,8 @@ snmpTargetAddrTable(print) ->
Prefix, element(?snmpTargetAddrTDomain, Row),
case element(?snmpTargetAddrTDomain, Row) of
?snmpUDPDomain -> udp;
+ ?transportDomainUdpIpv4 -> udpIpv4;
+ ?transportDomainUdpIpv6 -> udpIpv6;
_ -> undefined
end,
Prefix, element(?snmpTargetAddrTAddress, Row),
@@ -610,14 +642,14 @@ snmpTargetAddrTable(get, RowIndex, Cols) ->
snmpTargetAddrTable(get_next, RowIndex, Cols) ->
next(snmpTargetAddrTable, RowIndex, Cols);
snmpTargetAddrTable(set, RowIndex, Cols0) ->
- %% BMK BMK BMK
- case (catch verify_targetAddrTable_cols(Cols0, [])) of
+ %% BMK BMK
+ case (catch verify_targetAddrTable_cols(Cols0)) of
{ok, Cols} ->
snmp_notification_mib:invalidate_cache(),
%% Add columns for augmenting table snmpTargetAddrExtTable and for
- %% target engine ID. Target engine ID is set to "". The function
+ %% target engine ID. Target engine ID is set to "". The function
%% get_target_engine_id will return "" unless a value is set using
- %% set_target_engine_id. If it is "" Informs can't be sent to the
+ %% set_target_engine_id. If it is "" Informs can't be sent to the
%% target.
NCols = Cols ++ [{?snmpTargetAddrEngineId, ""},
{?snmpTargetAddrTMask, []},
@@ -628,12 +660,12 @@ snmpTargetAddrTable(set, RowIndex, Cols0) ->
Error
end;
snmpTargetAddrTable(is_set_ok, RowIndex, Cols0) ->
- case (catch verify_targetAddrTable_cols(Cols0, [])) of
+ case (catch verify_targetAddrTable_cols(Cols0)) of
{ok, Cols} ->
%% Add columns for augmenting table snmpTargetAddrExtTable and for
- %% target engine ID. Target engine ID is set to "". The function
+ %% target engine ID. Target engine ID is set to "". The function
%% get_target_engine_id will return "" unless a value is set using
- %% set_target_engine_id. If it is "" Informs can't be sent to the
+ %% set_target_engine_id. If it is "" Informs can't be sent to the
%% target.
NCols = Cols ++ [{?snmpTargetAddrEngineId, ""},
{?snmpTargetAddrTMask, []},
@@ -647,55 +679,83 @@ snmpTargetAddrTable(Op, Arg1, Arg2) ->
Db = db(snmpTargetAddrTable),
snmp_generic:table_func(Op, Arg1, Arg2, Db).
+verify_targetAddrTable_cols(Cols) ->
+ ValidCols0 = verify_targetAddrTable_cols(Cols, []),
+ %% Make a last pass to verify TDomain and TAddress.
+ ValidCols0.
+
verify_targetAddrTable_cols([], Cols) ->
{ok, lists:reverse(Cols)};
-verify_targetAddrTable_cols([{Col, Val0}|Cols], Acc) ->
- Val = verify_targetAddrTable_col(Col, Val0),
- verify_targetAddrTable_cols(Cols, [{Col, Val}|Acc]).
+verify_targetAddrTable_cols([{Col, Val0}|Cols], ValidCols) ->
+ Val = verify_targetAddrTable_col(Col, Val0, ValidCols),
+ verify_targetAddrTable_cols(Cols, [{Col, Val}|ValidCols]).
-verify_targetAddrTable_col(?snmpTargetAddrName, Name) ->
+verify_targetAddrTable_col(?snmpTargetAddrName, Name, _) ->
case (catch snmp_conf:check_string(Name)) of
ok ->
Name;
_ ->
wrongValue(?snmpTargetAddrName)
end;
-verify_targetAddrTable_col(?snmpTargetAddrTAddress, TAddr) ->
- case (catch snmp_conf:check_taddress(TAddr)) of
+verify_targetAddrTable_col(?snmpTargetAddrTDomain, TDomain, _) ->
+ case (catch snmp_conf:check_tdomain(TDomain)) of
ok ->
- TAddr;
+ TDomain;
_ ->
- wrongValue(?snmpTargetAddrTAddress)
+ wrongValue(?snmpTargetAddrTDomain)
+ end;
+%% In order to (properly) validate the TAddress,
+%% the TDomain must already have been validated
+%% (the format of TAddress depends on TDomain).
+verify_targetAddrTable_col(?snmpTargetAddrTAddress, TAddress, ValidCols) ->
+ case lists:keysearch(?snmpTargetAddrTDomain, 1, ValidCols) of
+ {value, {?snmpTargetAddrTDomain, TDomain}} ->
+ case (catch snmp_conf:check_taddress(TDomain, TAddress)) of
+ ok ->
+ TAddress;
+ _ ->
+ wrongValue(?snmpTargetAddrTAddress)
+ end;
+ false ->
+ %% The user did not provide us with a TDomain, which
+ %% must mean that he/she intends to use the old domain.
+ TDomain = snmp_conf:mk_tdomain(default_domain()),
+ case (catch snmp_conf:check_taddress(TDomain, TAddress)) of
+ ok ->
+ TAddress;
+ _ ->
+ wrongValue(?snmpTargetAddrTAddress)
+ end
end;
-verify_targetAddrTable_col(?snmpTargetAddrTimeout, Timeout) ->
+verify_targetAddrTable_col(?snmpTargetAddrTimeout, Timeout, _) ->
case (catch snmp_conf:check_integer(Timeout)) of
ok when Timeout >= 0 ->
Timeout;
_ ->
wrongValue(?snmpTargetAddrTimeout)
end;
-verify_targetAddrTable_col(?snmpTargetAddrRetryCount, Retry) ->
+verify_targetAddrTable_col(?snmpTargetAddrRetryCount, Retry, _) ->
case (catch snmp_conf:check_integer(Retry)) of
ok when Retry >= 0 ->
Retry;
_ ->
wrongValue(?snmpTargetAddrRetryCount)
end;
-verify_targetAddrTable_col(?snmpTargetAddrTagList, TagList) ->
+verify_targetAddrTable_col(?snmpTargetAddrTagList, TagList, _) ->
case (catch snmp_conf:check_string(TagList)) of
ok ->
TagList;
_ ->
wrongValue(?snmpTargetAddrTagList)
end;
-verify_targetAddrTable_col(?snmpTargetAddrParams, Params) ->
+verify_targetAddrTable_col(?snmpTargetAddrParams, Params, _) ->
case (catch snmp_conf:check_string(Params)) of
ok ->
Params;
_ ->
wrongValue(?snmpTargetAddrParams)
end;
-verify_targetAddrTable_col(_, Val) ->
+verify_targetAddrTable_col(_, Val, _) ->
Val.
diff --git a/lib/snmp/src/agent/snmpa.erl b/lib/snmp/src/agent/snmpa.erl
index 22fbd33add..b2e4f253ab 100644
--- a/lib/snmp/src/agent/snmpa.erl
+++ b/lib/snmp/src/agent/snmpa.erl
@@ -60,6 +60,7 @@
register_subagent/3, unregister_subagent/2,
+ send_notification2/3,
send_notification/3, send_notification/4, send_notification/5,
send_notification/6, send_notification/7,
send_trap/3, send_trap/4,
@@ -108,8 +109,9 @@
-export([print_mib_info/0, print_mib_tables/0, print_mib_variables/0]).
-include("snmpa_atl.hrl").
+-include("snmpa_internal.hrl").
--define(EXTRA_INFO, undefined).
+-define(DISCO_EXTRA_INFO, undefined).
%%-----------------------------------------------------------------
@@ -596,22 +598,56 @@ set_request_limit(Agent, NewLimit) ->
%% -
+send_notification2(Agent, Notification, SendOpts) ->
+ snmpa_agent:send_notification(Agent, Notification, SendOpts).
+
send_notification(Agent, Notification, Recv) ->
- send_notification(Agent, Notification, Recv, "", "", []).
+ SendOpts =
+ [
+ {receiver, Recv},
+ {varbinds, []},
+ {name, ""},
+ {context, ""},
+ {extra, ?DEFAULT_NOTIF_EXTRA_INFO}
+ ],
+ send_notification2(Agent, Notification, SendOpts).
send_notification(Agent, Notification, Recv, Varbinds) ->
- send_notification(Agent, Notification, Recv, "", "", Varbinds).
+ SendOpts =
+ [
+ {receiver, Recv},
+ {varbinds, Varbinds},
+ {name, ""},
+ {context, ""},
+ {extra, ?DEFAULT_NOTIF_EXTRA_INFO}
+ ],
+ send_notification2(Agent, Notification, SendOpts).
send_notification(Agent, Notification, Recv, NotifyName, Varbinds) ->
- send_notification(Agent, Notification, Recv, NotifyName, "", Varbinds).
+ SendOpts =
+ [
+ {receiver, Recv},
+ {varbinds, Varbinds},
+ {name, NotifyName},
+ {context, ""},
+ {extra, ?DEFAULT_NOTIF_EXTRA_INFO}
+ ],
+ send_notification2(Agent, Notification, SendOpts).
send_notification(Agent, Notification, Recv, NotifyName,
ContextName, Varbinds)
when (is_list(NotifyName) andalso
is_list(ContextName) andalso
is_list(Varbinds)) ->
- snmpa_agent:send_trap(Agent, Notification, NotifyName,
- ContextName, Recv, Varbinds).
+ SendOpts =
+ [
+ {receiver, Recv},
+ {varbinds, Varbinds},
+ {name, NotifyName},
+ {context, ContextName},
+ {extra, ?DEFAULT_NOTIF_EXTRA_INFO}
+ ],
+ send_notification2(Agent, Notification, SendOpts).
send_notification(Agent, Notification, Recv,
NotifyName, ContextName, Varbinds, LocalEngineID)
@@ -619,8 +655,16 @@ send_notification(Agent, Notification, Recv,
is_list(ContextName) andalso
is_list(Varbinds) andalso
is_list(LocalEngineID)) ->
- snmpa_agent:send_trap(Agent, Notification, NotifyName,
- ContextName, Recv, Varbinds, LocalEngineID).
+ SendOpts =
+ [
+ {receiver, Recv},
+ {varbinds, Varbinds},
+ {name, NotifyName},
+ {context, ContextName},
+ {extra, ?DEFAULT_NOTIF_EXTRA_INFO},
+ {local_engine_id, LocalEngineID}
+ ],
+ send_notification2(Agent, Notification, SendOpts).
%% Kept for backwards compatibility
send_trap(Agent, Trap, Community) ->
@@ -655,7 +699,7 @@ discovery(TargetName, Notification, Varbinds, DiscoHandler)
discovery(TargetName, Notification, ContextName, Varbinds, DiscoHandler).
discovery(TargetName, Notification, ContextName, Varbinds, DiscoHandler) ->
- ExtraInfo = ?EXTRA_INFO,
+ ExtraInfo = ?DISCO_EXTRA_INFO,
discovery(TargetName, Notification, ContextName, Varbinds, DiscoHandler,
ExtraInfo).
diff --git a/lib/snmp/src/agent/snmpa_acm.erl b/lib/snmp/src/agent/snmpa_acm.erl
index 6ad4f0b442..30bd34a205 100644
--- a/lib/snmp/src/agent/snmpa_acm.erl
+++ b/lib/snmp/src/agent/snmpa_acm.erl
@@ -62,11 +62,13 @@
%% {error, Reason} |
%% {discarded, Variable, Reason}
%% Types: Pdu = #pdu
-%% ACMData = acm_data() = {community, Community, Address} |
-%% {v3, MsgID, SecModel, SecName, SecLevel,
-%% ContextEngineID, ContextName, SecData}
+%% ACMData = acm_data() =
+%% {community, SecModel, Community, TDomain, TAddress} |
+%% {v3, MsgID, SecModel, SecName, SecLevel,
+%% ContextEngineID, ContextName, SecData}
%% Community = string()
-%% Address = ip() ++ udp() (list)
+%% TDomain = ?transportDomainUdpIpv4 | ?transportDomainUdpIpv6
+%% TAddress = ip() ++ udp() (list)
%% MsgID = integer() <not used>
%% SecModel = ?SEC_* (see snmp_types.hrl)
%% SecName = string()
@@ -114,7 +116,10 @@ error2status(_) -> genErr.
%% discarded: no error response is sent
%% authentication_failure: no error response is sent, a trap is generated
%%-----------------------------------------------------------------
-init_ca(Pdu, {community, SecModel, Community, TAddr}) ->
+init_ca(Pdu, {community, SecModel, Community, TAddress}) ->
+ TDomain = snmp_conf:mk_tdomain(snmp_target_mib:default_domain()),
+ init_ca(Pdu, {community, SecModel, Community, TDomain, TAddress});
+init_ca(Pdu, {community, SecModel, Community, TDomain, TAddress}) ->
%% This is a v1 or v2c request. Use SNMP-COMMUNITY-MIB to
%% map the community to vacm parameters.
?vtrace("check access for ~n"
@@ -126,18 +131,18 @@ init_ca(Pdu, {community, SecModel, Community, TAddr}) ->
_ -> read
end,
?vtrace("View type: ~p", [ViewType]),
- CaCacheKey = {Community, SecModel, TAddr, ViewType},
+ CaCacheKey = {Community, SecModel, TDomain, TAddress, ViewType},
case check_ca_cache(CaCacheKey) of
false ->
- case snmp_community_mib:community2vacm(Community,
- {?snmpUDPDomain,TAddr}) of
+ case snmp_community_mib:community2vacm(Community,
+ {TDomain, TAddress}) of
{SecName, _ContextEngineId, ContextName} ->
%% Maybe we should check that the contextEngineID
%% matches the local engineID?
%% It better, since we don't impl. proxy.
?vtrace("get mib view"
"~n Security name: ~p"
- "~n Context name: ~p",[SecName,ContextName]),
+ "~n Context name: ~p",[SecName, ContextName]),
case snmpa_vacm:get_mib_view(ViewType, SecModel, SecName,
?'SnmpSecurityLevel_noAuthNoPriv',
ContextName) of
@@ -153,7 +158,7 @@ init_ca(Pdu, {community, SecModel, Community, TAddr}) ->
end;
undefined ->
{authentication_failure, snmpInBadCommunityNames,
- {bad_community_name, TAddr, Community}}
+ {bad_community_name, TDomain, TAddress, Community}}
end;
Res ->
Res
@@ -219,6 +224,7 @@ upd_ca_cache(KeyVal) ->
invalidate_ca_cache() ->
erase(ca_cache).
+
%%-----------------------------------------------------------------
%% Func: check(Res) -> {ok, MibView} | {discarded, Variable, Reason}
%% Args: Res = {ok, AccessFunc} |
diff --git a/lib/snmp/src/agent/snmpa_agent.erl b/lib/snmp/src/agent/snmpa_agent.erl
index f70885b2ec..e4cfeddb6a 100644
--- a/lib/snmp/src/agent/snmpa_agent.erl
+++ b/lib/snmp/src/agent/snmpa_agent.erl
@@ -30,7 +30,7 @@
-export([subagent_set/2,
load_mibs/2, unload_mibs/2, which_mibs/1, whereis_mib/2, info/1,
register_subagent/3, unregister_subagent/2,
- send_trap/6, send_trap/7,
+ send_notification/3,
register_notification_filter/5,
unregister_notification_filter/2,
which_notification_filter/1,
@@ -62,10 +62,16 @@
-export([increment_counter/3]).
-export([restart_worker/1, restart_set_worker/1]).
+%% For backward compatibillity
+-export([send_trap/6, send_trap/7]).
+
%% Internal exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3, tr_var/2, tr_varbind/1,
- handle_pdu/7, worker/2, worker_loop/1, do_send_trap/7]).
+ handle_pdu/7, worker/2, worker_loop/1,
+ do_send_trap/7, do_send_trap/8]).
+
+-include("snmpa_internal.hrl").
-ifndef(default_verbosity).
-define(default_verbosity,silence).
@@ -527,6 +533,11 @@ which_notification_filter(Agent) ->
call(Agent, which_notification_filter).
+send_notification(Agent, Notification, SendOpts) ->
+ Msg = {send_notif, Notification, SendOpts},
+ maybe_call(Agent, Msg).
+
+%% <BACKWARD-COMPAT>
send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds) ->
?d("send_trap -> entry with"
"~n self(): ~p"
@@ -538,13 +549,33 @@ send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds) ->
"~n Varbinds: ~p",
[self(), Agent, wis(Agent),
Trap, NotifyName, CtxName, Recv, Varbinds]),
- Msg = {send_trap, Trap, NotifyName, CtxName, Recv, Varbinds},
- case (wis(Agent) =:= self()) of
- false ->
- call(Agent, Msg);
- true ->
- Agent ! Msg
- end.
+ SendOpts = [
+ {receiver, Recv},
+ {varbinds, Varbinds},
+ {name, NotifyName},
+ {context, CtxName},
+ {extra, ?DEFAULT_NOTIF_EXTRA_INFO}
+ ],
+ send_notification(Agent, Trap, SendOpts).
+
+%% send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds) ->
+%% ?d("send_trap -> entry with"
+%% "~n self(): ~p"
+%% "~n Agent: ~p [~p]"
+%% "~n Trap: ~p"
+%% "~n NotifyName: ~p"
+%% "~n CtxName: ~p"
+%% "~n Recv: ~p"
+%% "~n Varbinds: ~p",
+%% [self(), Agent, wis(Agent),
+%% Trap, NotifyName, CtxName, Recv, Varbinds]),
+%% Msg = {send_trap, Trap, NotifyName, CtxName, Recv, Varbinds},
+%% case (wis(Agent) =:= self()) of
+%% false ->
+%% call(Agent, Msg);
+%% true ->
+%% Agent ! Msg
+%% end.
send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID) ->
?d("send_trap -> entry with"
@@ -558,14 +589,38 @@ send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID) ->
"~n LocalEngineID: ~p",
[self(), Agent, wis(Agent),
Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID]),
- Msg =
- {send_trap, Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID},
- case (wis(Agent) =:= self()) of
- false ->
- call(Agent, Msg);
- true ->
- Agent ! Msg
- end.
+ SendOpts = [
+ {receiver, Recv},
+ {varbinds, Varbinds},
+ {name, NotifyName},
+ {context, CtxName},
+ {extra, ?DEFAULT_NOTIF_EXTRA_INFO},
+ {local_engine_id, LocalEngineID}
+ ],
+ send_notification(Agent, Trap, SendOpts).
+
+%% send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID) ->
+%% ?d("send_trap -> entry with"
+%% "~n self(): ~p"
+%% "~n Agent: ~p [~p]"
+%% "~n Trap: ~p"
+%% "~n NotifyName: ~p"
+%% "~n CtxName: ~p"
+%% "~n Recv: ~p"
+%% "~n Varbinds: ~p"
+%% "~n LocalEngineID: ~p",
+%% [self(), Agent, wis(Agent),
+%% Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID]),
+%% Msg =
+%% {send_trap, Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID},
+%% case (wis(Agent) =:= self()) of
+%% false ->
+%% call(Agent, Msg);
+%% true ->
+%% Agent ! Msg
+%% end.
+
+%% </BACKWARD-COMPAT>
%% -- Discovery functions --
@@ -655,7 +710,14 @@ wis(Atom) when is_atom(Atom) ->
forward_trap(Agent, TrapRecord, NotifyName, CtxName, Recv, Varbinds) ->
- Agent ! {forward_trap, TrapRecord, NotifyName, CtxName, Recv, Varbinds}.
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ forward_trap(Agent, TrapRecord, NotifyName, CtxName, Recv, Varbinds,
+ ExtraInfo).
+
+forward_trap(Agent, TrapRecord, NotifyName, CtxName, Recv, Varbinds,
+ ExtraInfo) ->
+ Agent ! {forward_trap, TrapRecord, NotifyName, CtxName, Recv, Varbinds,
+ ExtraInfo}.
%%-----------------------------------------------------------------
@@ -745,6 +807,22 @@ handle_info(worker_available, S) ->
?vdebug("worker available",[]),
{noreply, S#state{worker_state = ready}};
+handle_info({send_notif, Notification, SendOpts}, S) ->
+ ?vlog("[handle_info] send trap request:"
+ "~n Notification: ~p"
+ "~n SendOpts: ~p",
+ [Notification, SendOpts]),
+ case (catch handle_send_trap(cast, S, Notification, SendOpts)) of
+ {ok, NewS} ->
+ {noreply, NewS};
+ {'EXIT', R} ->
+ ?vinfo("Trap not sent:~n ~p", [R]),
+ {noreply, S};
+ _ ->
+ {noreply, S}
+ end;
+
+%% <BACKWARD-COMPAT>
handle_info({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds}, S) ->
?vlog("[handle_info] send trap request:"
"~n Trap: ~p"
@@ -753,9 +831,10 @@ handle_info({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds}, S) ->
"~n Recv: ~p"
"~n Varbinds: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds]),
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
- case catch handle_send_trap(S, Trap, NotifyName, ContextName,
- Recv, Varbinds, LocalEngineID) of
+ case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
+ Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
@@ -775,8 +854,9 @@ handle_info({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds,
"~n Varbinds: ~p"
"~n LocalEngineID: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds, LocalEngineID]),
- case catch handle_send_trap(S, Trap, NotifyName, ContextName,
- Recv, Varbinds, LocalEngineID) of
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
+ Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
@@ -785,8 +865,31 @@ handle_info({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds,
_ ->
{noreply, S}
end;
+%% </BACKWARD-COMPAT>
handle_info({forward_trap, TrapRecord, NotifyName, ContextName,
+ Recv, Varbinds, ExtraInfo}, S) ->
+ ?vlog("[handle_info] forward trap request:"
+ "~n TrapRecord: ~p"
+ "~n NotifyName: ~p"
+ "~n ContextName: ~p"
+ "~n Recv: ~p"
+ "~n Varbinds: ~p",
+ [TrapRecord, NotifyName, ContextName, Recv, Varbinds]),
+ LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
+ case (catch maybe_send_trap(S, TrapRecord, NotifyName, ContextName,
+ Recv, Varbinds, LocalEngineID, ExtraInfo)) of
+ {ok, NewS} ->
+ {noreply, NewS};
+ {'EXIT', R} ->
+ ?vinfo("Trap not sent:~n ~p", [R]),
+ {noreply, S};
+ _ ->
+ {noreply, S}
+ end;
+
+%% <BACKWARD-COMPAT>
+handle_info({forward_trap, TrapRecord, NotifyName, ContextName,
Recv, Varbinds}, S) ->
?vlog("[handle_info] forward trap request:"
"~n TrapRecord: ~p"
@@ -795,9 +898,10 @@ handle_info({forward_trap, TrapRecord, NotifyName, ContextName,
"~n Recv: ~p"
"~n Varbinds: ~p",
[TrapRecord, NotifyName, ContextName, Recv, Varbinds]),
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
case (catch maybe_send_trap(S, TrapRecord, NotifyName, ContextName,
- Recv, Varbinds, LocalEngineID)) of
+ Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
@@ -806,6 +910,7 @@ handle_info({forward_trap, TrapRecord, NotifyName, ContextName,
_ ->
{noreply, S}
end;
+%% </BACKWARD-COMPAT>
handle_info({backup_done, Reply}, #state{backup = {_, From}} = S) ->
?vlog("[handle_info] backup done:"
@@ -908,6 +1013,23 @@ handle_call(restart_set_worker, _From, #state{set_worker = Pid} = S) ->
end,
{reply, ok, S};
+handle_call({send_notif, Notification, SendOpts}, _From, S) ->
+ ?vlog("[handle_info] send trap request:"
+ "~n Notification: ~p"
+ "~n SendOpts: ~p",
+ [Notification, SendOpts]),
+ case (catch handle_send_trap(call, S, Notification, SendOpts)) of
+ {ok, NewS} ->
+ {reply, ok, NewS};
+ {'EXIT', Reason} ->
+ ?vinfo("Trap not sent:~n ~p", [Reason]),
+ {reply, {error, {send_failed, Reason}}, S};
+ _ ->
+ ?vinfo("Trap not sent", []),
+ {reply, {error, send_failed}, S}
+ end;
+
+%% <BACKWARD-COMPAT>
handle_call({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds},
_From, S) ->
?vlog("[handle_call] send trap request:"
@@ -917,19 +1039,20 @@ handle_call({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds},
"~n Recv: ~p"
"~n Varbinds: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds]),
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
LocalEngineID =
case S#state.type of
master_agent ->
?DEFAULT_LOCAL_ENGINE_ID;
_ ->
%% subagent -
- %% we don't need this, eventually the trap sent request
- %% will reach the master-agent and then it will look up
- %% the proper engine id.
+ %% we don't need this now, eventually the trap send
+ %% request will reach the master-agent and then it
+ %% will look up the proper engine id.
ignore
end,
case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
- Recv, Varbinds, LocalEngineID)) of
+ Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{reply, ok, NewS};
{'EXIT', Reason} ->
@@ -951,8 +1074,9 @@ handle_call({send_trap, Trap, NotifyName,
"~n Varbinds: ~p"
"~n LocalEngineID: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds, LocalEngineID]),
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
- Recv, Varbinds, LocalEngineID)) of
+ Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{reply, ok, NewS};
{'EXIT', Reason} ->
@@ -962,6 +1086,7 @@ handle_call({send_trap, Trap, NotifyName,
?vinfo("Trap not sent", []),
{reply, {error, send_failed}, S}
end;
+%% </BACKWARD-COMPAT>
handle_call({discovery,
TargetName, Notification, ContextName, Vbs, DiscoHandler,
@@ -1470,7 +1595,10 @@ handle_backup_res([{Who, Crap}|Results], Acc) ->
%% because we (for some reason) support the function
%% snmpa:current_community().
%%-----------------------------------------------------------------
-cheat({community, _SecModel, Community, _IpUdp}, Address, ContextName) ->
+cheat({community, SecModel, Community, _TAddress}, Address, ContextName) ->
+ {Community, Address, ContextName};
+cheat({community, _SecModel, Community, _TDomain, _TAddress},
+ Address, ContextName) ->
{Community, Address, ContextName};
cheat(_, Address, ContextName) ->
{"", Address, ContextName}.
@@ -1523,19 +1651,24 @@ spawn_thread(Vsn, Pdu, PduMS, ACMData, Address, Extra) ->
proc_lib:spawn_link(?MODULE, handle_pdu, Args).
spawn_trap_thread(TrapRec, NotifyName, ContextName, Recv, Vbs,
- LocalEngineID) ->
+ LocalEngineID, ExtraInfo) ->
Dict = get(),
proc_lib:spawn_link(?MODULE, do_send_trap,
[TrapRec, NotifyName, ContextName,
- Recv, Vbs, LocalEngineID, Dict]).
+ Recv, Vbs, LocalEngineID, ExtraInfo, Dict]).
do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
LocalEngineID, Dict) ->
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
+ LocalEngineID, ExtraInfo, Dict).
+do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
+ LocalEngineID, ExtraInfo, Dict) ->
lists:foreach(fun({Key, Val}) -> put(Key, Val) end, Dict),
put(sname,trap_sender_short_name(get(sname))),
?vlog("starting",[]),
snmpa_trap:send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
- LocalEngineID, get(net_if)).
+ LocalEngineID, ExtraInfo, get(net_if)).
worker(Master, Dict) ->
lists:foreach(fun({Key, Val}) -> put(Key, Val) end, Dict),
@@ -1550,21 +1683,34 @@ worker_loop(Master) ->
handle_pdu(Vsn, Pdu, PduMS, ACMData, Address, Extra),
Master ! worker_available;
- %% We don't trap exits!
+ %% We don't trap EXITs!
{TrapRec, NotifyName, ContextName, Recv, Vbs} ->
?vtrace("worker_loop -> send trap:"
"~n ~p", [TrapRec]),
snmpa_trap:send_trap(TrapRec, NotifyName,
- ContextName, Recv, Vbs, get(net_if)),
+ ContextName, Recv, Vbs,
+ ?DEFAULT_NOTIF_EXTRA_INFO,
+ get(net_if)),
Master ! worker_available;
- %% We don't trap exits!
+ %% We don't trap EXITs!
{send_trap,
TrapRec, NotifyName, ContextName, Recv, Vbs, LocalEngineID} ->
?vtrace("worker_loop -> send trap:"
"~n ~p", [TrapRec]),
snmpa_trap:send_trap(TrapRec, NotifyName,
- ContextName, Recv, Vbs, LocalEngineID,
+ ContextName, Recv, Vbs,
+ LocalEngineID, ?DEFAULT_NOTIF_EXTRA_INFO,
+ get(net_if)),
+ Master ! worker_available;
+
+ {send_trap,
+ TrapRec, NotifyName, ContextName, Recv, Vbs, LocalEngineID, ExtraInfo} ->
+ ?vtrace("worker_loop -> send trap:"
+ "~n ~p", [TrapRec]),
+ snmpa_trap:send_trap(TrapRec, NotifyName,
+ ContextName, Recv, Vbs,
+ LocalEngineID, ExtraInfo,
get(net_if)),
Master ! worker_available;
@@ -1713,34 +1859,79 @@ handle_acm_error(Vsn, Reason, Pdu, ACMData, Address, Extra) ->
ok
end.
+get_opt(Key, Default, SendOpts) ->
+ case lists:keysearch(Key, 1, SendOpts) of
+ {value, {Key, Value}} ->
+ Value;
+ false ->
+ Default
+ end.
-handle_send_trap(S, TrapName, NotifyName, ContextName, Recv, Varbinds,
- LocalEngineID) ->
+handle_send_trap(call, #state{type = master_agent} = S,
+ Notification, SendOpts) ->
+ SendOpts2 =
+ case lists:keymember(local_engine_id, 1, SendOpts) of
+ true ->
+ SendOpts;
+ false ->
+ [{local_engine_id, ?DEFAULT_LOCAL_ENGINE_ID}|SendOpts]
+ end,
+ handle_send_trap(S, Notification, SendOpts2);
+handle_send_trap(call, S, Notification, SendOpts) ->
+ SendOpts2 =
+ case lists:keymember(local_engine_id, 1, SendOpts) of
+ true ->
+ SendOpts;
+ false ->
+ %% subagent -
+ %% we don't need this now, eventually the trap send
+ %% request will reach the master-agent and then it
+ %% will look up the proper engine id.
+ [{local_engine_id, ignore}|SendOpts]
+ end,
+ handle_send_trap(S, Notification, SendOpts2);
+handle_send_trap(_, S, Notification, SendOpts) ->
+ handle_send_trap(S, Notification, SendOpts).
+
+handle_send_trap(S, Notification, SendOpts) ->
+ NotifyName = get_opt(name, "", SendOpts),
+ ContextName = get_opt(context, "", SendOpts),
+ Recv = get_opt(receiver, no_receiver, SendOpts),
+ Varbinds = get_opt(varbinds, [], SendOpts),
+ ExtraInfo = get_opt(extra, ?DEFAULT_NOTIF_EXTRA_INFO, SendOpts),
+ LocalEngineID =
+ get_opt(local_engine_id, ?DEFAULT_LOCAL_ENGINE_ID, SendOpts),
+ handle_send_trap(S, Notification, NotifyName, ContextName, Recv, Varbinds,
+ LocalEngineID, ExtraInfo).
+
+handle_send_trap(#state{type = Type} = S,
+ Notification, NotifyName, ContextName, Recv, Varbinds,
+ LocalEngineID, ExtraInfo) ->
?vtrace("handle_send_trap -> entry with"
- "~n S#state.type: ~p"
+ "~n Agent type: ~p"
"~n TrapName: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n LocalEngineID: ~p",
- [S#state.type, TrapName, NotifyName, ContextName, LocalEngineID]),
- case snmpa_trap:construct_trap(TrapName, Varbinds) of
+ [Type, Notification, NotifyName, ContextName, LocalEngineID]),
+ case snmpa_trap:construct_trap(Notification, Varbinds) of
{ok, TrapRecord, VarList} ->
?vtrace("handle_send_trap -> construction complete: "
"~n TrapRecord: ~p"
"~n VarList: ~p",
[TrapRecord, VarList]),
- case S#state.type of
+ case Type of
subagent ->
?vtrace("handle_send_trap -> [sub] forward trap",[]),
maybe_forward_trap(S, TrapRecord, NotifyName,
- ContextName, Recv, VarList),
+ ContextName, Recv, VarList, ExtraInfo),
{ok, S};
master_agent ->
?vtrace("handle_send_trap -> "
"[master] handle send trap",[]),
maybe_send_trap(S, TrapRecord, NotifyName,
ContextName, Recv, VarList,
- LocalEngineID)
+ LocalEngineID, ExtraInfo)
end;
error ->
error
@@ -1748,7 +1939,7 @@ handle_send_trap(S, TrapName, NotifyName, ContextName, Recv, Varbinds,
maybe_forward_trap(#state{parent = Parent, nfilters = NFs} = S,
- TrapRec, NotifyName, ContextName, Recv, V) ->
+ TrapRec, NotifyName, ContextName, Recv, V, ExtraInfo) ->
?vtrace("maybe_forward_trap -> entry with"
"~n NFs: ~p", [NFs]),
case filter_notification(NFs, [], TrapRec) of
@@ -1764,13 +1955,15 @@ maybe_forward_trap(#state{parent = Parent, nfilters = NFs} = S,
{send, [], TrapRec2} ->
?vtrace("maybe_forward_trap -> forward trap:"
"~n ~p", [TrapRec2]),
- forward_trap(Parent, TrapRec2, NotifyName, ContextName, Recv, V),
+ forward_trap(Parent, TrapRec2, NotifyName, ContextName, Recv, V,
+ ExtraInfo),
{ok, S};
{send, Removed, TrapRec2} ->
?vtrace("maybe_forward_trap -> forward trap:"
"~n ~p", [TrapRec2]),
- forward_trap(Parent, TrapRec2, NotifyName, ContextName, Recv, V),
+ forward_trap(Parent, TrapRec2, NotifyName, ContextName, Recv, V,
+ ExtraInfo),
NFs2 = del_notification_filter(Removed, NFs),
{ok, S#state{nfilters = NFs2}}
end.
@@ -1778,7 +1971,7 @@ maybe_forward_trap(#state{parent = Parent, nfilters = NFs} = S,
maybe_send_trap(#state{nfilters = NFs} = S,
TrapRec, NotifyName, ContextName, Recv, Varbinds,
- LocalEngineID) ->
+ LocalEngineID, ExtraInfo) ->
?vtrace("maybe_send_trap -> entry with"
"~n NFs: ~p", [NFs]),
case filter_notification(NFs, [], TrapRec) of
@@ -1796,7 +1989,7 @@ maybe_send_trap(#state{nfilters = NFs} = S,
"~n ~p", [TrapRec2]),
do_handle_send_trap(S, TrapRec2,
NotifyName, ContextName, Recv, Varbinds,
- LocalEngineID);
+ LocalEngineID, ExtraInfo);
{send, Removed, TrapRec2} ->
?vtrace("maybe_send_trap -> send trap:"
@@ -1804,36 +1997,37 @@ maybe_send_trap(#state{nfilters = NFs} = S,
NFs2 = del_notification_filter(Removed, NFs),
do_handle_send_trap(S#state{nfilters = NFs2}, TrapRec2,
NotifyName, ContextName, Recv, Varbinds,
- LocalEngineID)
+ LocalEngineID, ExtraInfo)
end.
do_handle_send_trap(S, TrapRec, NotifyName, ContextName, Recv, Varbinds,
- LocalEngineID) ->
+ LocalEngineID, ExtraInfo) ->
Vbs = snmpa_trap:try_initialise_vars(get(mibserver), Varbinds),
case S#state.type of
subagent ->
forward_trap(S#state.parent, TrapRec, NotifyName, ContextName,
- Recv, Vbs),
+ Recv, Vbs, ExtraInfo),
{ok, S};
master_agent when S#state.multi_threaded =:= false ->
?vtrace("do_handle_send_trap -> send trap:"
"~n ~p", [TrapRec]),
snmpa_trap:send_trap(TrapRec, NotifyName, ContextName,
- Recv, Vbs, LocalEngineID, get(net_if)),
+ Recv, Vbs, LocalEngineID, ExtraInfo,
+ get(net_if)),
{ok, S};
master_agent when S#state.worker_state =:= busy ->
%% Main worker busy => create new worker
?vtrace("do_handle_send_trap -> main worker busy: "
"spawn a trap sender", []),
spawn_trap_thread(TrapRec, NotifyName, ContextName, Recv, Vbs,
- LocalEngineID),
+ LocalEngineID, ExtraInfo),
{ok, S};
master_agent ->
%% Send to main worker
?vtrace("do_handle_send_trap -> send to main worker",[]),
S#state.worker ! {send_trap,
TrapRec, NotifyName, ContextName, Recv, Vbs,
- LocalEngineID},
+ LocalEngineID, ExtraInfo},
{ok, S#state{worker_state = busy}}
end.
@@ -1932,7 +2126,7 @@ send_discovery(S, From,
TargetName, Record, ContextName, InitVars,
DiscoHandler, ExtraInfo) ->
case snmpa_trap:send_discovery(TargetName, Record, ContextName,
- InitVars, get(net_if)) of
+ InitVars, get(net_if), ExtraInfo) of
{ok, Sender, SecLevel} ->
Disco = #disco{from = From,
rec = Record,
@@ -2009,9 +2203,12 @@ handle_discovery_response(#state{disco = #disco{target = TargetName,
#disco{rec = Record,
ctx = ContextName,
ivbs = InitVars} = Disco,
- case snmpa_trap:send_discovery(TargetName, Record,
+ case snmpa_trap:send_discovery(TargetName,
+ Record,
ContextName,
- InitVars, get(net_if)) of
+ InitVars,
+ get(net_if),
+ ExtraInfo) of
{ok, Sender, _SecLevel} ->
?vdebug("handle_discovery_response(1) -> "
"stage 2 trap sent", []),
@@ -3971,6 +4168,14 @@ user_err(F, A) ->
%% ---------------------------------------------------------------------
+maybe_call(Server, Req) ->
+ case (wis(Server) =:= self()) of
+ false ->
+ call(Server, Req);
+ true ->
+ Server ! Req
+ end.
+
call(Server, Req) ->
gen_server:call(Server, Req, infinity).
diff --git a/lib/snmp/src/agent/snmpa_authentication_service.erl b/lib/snmp/src/agent/snmpa_authentication_service.erl
index 572fab7fbf..d406c58ee4 100644
--- a/lib/snmp/src/agent/snmpa_authentication_service.erl
+++ b/lib/snmp/src/agent/snmpa_authentication_service.erl
@@ -29,11 +29,12 @@ behaviour_info(_) ->
%%-----------------------------------------------------------------
%% init_check_access(Pdu, ACMData)
%% Pdu = #pdu
-%% ACMData = acm_data() = {community, Community, Address} |
-%% {v3, MsgID, SecModel, SecName, SecLevel,
-%% ContextEngineID, ContextName, SecData}
+%% ACMData = acm_data() = {community, SecModel, Community, TDomain, TAddress} |
+%% {v3, MsgID, SecModel, SecName, SecLevel,
+%% ContextEngineID, ContextName, SecData}
%% Community = string()
-%% Address = ip() ++ udp() (list)
+%% TDomain = ?transportDomainUdpIpv4 | ?transportDomainUdpIpv6
+%% TAddress = ip() ++ udp() (list)
%% MsgID = integer() <not used>
%% SecModel = ?SEC_* (see snmp_types.hrl)
%% SecName = string()
diff --git a/lib/snmp/src/agent/snmpa_conf.erl b/lib/snmp/src/agent/snmpa_conf.erl
index b4fc716b3e..4e5aab5319 100644
--- a/lib/snmp/src/agent/snmpa_conf.erl
+++ b/lib/snmp/src/agent/snmpa_conf.erl
@@ -48,7 +48,7 @@
%% target_addr.conf
target_addr_entry/5, target_addr_entry/6,
- target_addr_entry/8, target_addr_entry/10,
+ target_addr_entry/8, target_addr_entry/10, target_addr_entry/11,
write_target_addr_config/2, write_target_addr_config/3,
append_target_addr_config/2,
read_target_addr_config/1,
@@ -447,7 +447,23 @@ target_addr_entry(Name,
EngineId,
TMask,
MaxMessageSize) ->
+ target_addr_entry(Name, snmp_target_mib:default_domain(), Ip, Udp,
+ Timeout, RetryCount, TagList, ParamsName,
+ TMask, MaxMessageSize).
+
+target_addr_entry(Name,
+ Domain,
+ Ip,
+ Udp,
+ Timeout,
+ RetryCount,
+ TagList,
+ ParamsName,
+ EngineId,
+ TMask,
+ MaxMessageSize) ->
{Name,
+ Domain,
Ip,
Udp,
Timeout,
@@ -465,9 +481,13 @@ write_target_addr_config(Dir, Conf) ->
"%% The data is inserted into the snmpTargetAddrTable defined\n"
"%% in SNMP-TARGET-MIB, and in the snmpTargetAddrExtTable defined\n"
"%% in SNMP-COMMUNITY-MIB.\n"
-"%% Each row is a 10-tuple:\n"
-"%% {Name, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId,\n"
-"%% TMask, MaxMessageSize}.\n"
+"%% Each row is a 10 or 11-tuple (Domain is optional):\n"
+"%% {Name, \n"
+"%% Domain, Ip, Port, \n"
+"%% Timeout, RetryCount, TagList, ParamsName, EngineId,\n"
+"%% TMask, MaxMessageSize}.\n"
+"%% The value of Domain decide the format of the Ip and TMask values. \n"
+"%% If not present, classic Ipv4 is assumed. \n"
"%% The EngineId value is only used if Inform-Requests are sent to this\n"
"%% target. If Informs are not sent, this value is ignored, and can be\n"
"%% e.g. an empty string. However, if Informs are sent, it is essential\n"
@@ -521,16 +541,31 @@ write_target_addr_conf(Fd, Hdr, Conf) ->
write_target_addr_conf(Fd, Conf) ->
Fun = fun(Entry) -> do_write_target_addr_conf(Fd, Entry) end,
- lists:foreach(Fun, Conf).
+ lists:foreach(Fun, Conf),
+ ok.
do_write_target_addr_conf(Fd,
- {Name, Ip, Udp,
+ {Name,
+ Ip, Udp,
+ Timeout, RetryCount, TagList,
+ ParamsName, EngineId,
+ TMask, MaxMessageSize}) ->
+ Domain = snmp_target_mib:default_domain(),
+ do_write_target_addr_conf(Fd,
+ {Name,
+ Domain, Ip, Udp,
+ Timeout, RetryCount, TagList,
+ ParamsName, EngineId,
+ TMask, MaxMessageSize});
+do_write_target_addr_conf(Fd,
+ {Name,
+ Domain, Ip, Udp,
Timeout, RetryCount, TagList,
ParamsName, EngineId,
TMask, MaxMessageSize}) ->
io:format(Fd,
- "{\"~s\", ~w, ~w, ~w, ~w, \"~s\", \"~s\", \"~s\", ~w, ~w}.~n",
- [Name, Ip, Udp, Timeout, RetryCount, TagList,
+ "{\"~s\", ~w, ~w, ~w, ~w, ~w, \"~s\", \"~s\", \"~s\", ~w, ~w}.~n",
+ [Name, Domain, Ip, Udp, Timeout, RetryCount, TagList,
ParamsName, EngineId, TMask, MaxMessageSize]);
do_write_target_addr_conf(_Fd, Crap) ->
error({bad_target_addr_config, Crap}).
@@ -546,13 +581,13 @@ target_params_entry(Name, Vsn) ->
target_params_entry(Name, Vsn, SecName, SecLevel).
target_params_entry(Name, Vsn, SecName, SecLevel) ->
- MPModel = if Vsn == v1 -> v1;
- Vsn == v2 -> v2c;
- Vsn == v3 -> v3
+ MPModel = if Vsn =:= v1 -> v1;
+ Vsn =:= v2 -> v2c;
+ Vsn =:= v3 -> v3
end,
- SecModel = if Vsn == v1 -> v1;
- Vsn == v2 -> v2c;
- Vsn == v3 -> usm
+ SecModel = if Vsn =:= v1 -> v1;
+ Vsn =:= v2 -> v2c;
+ Vsn =:= v3 -> usm
end,
target_params_entry(Name, MPModel, SecModel, SecName, SecLevel).
diff --git a/lib/snmp/src/agent/snmpa_internal.hrl b/lib/snmp/src/agent/snmpa_internal.hrl
index 9fa874f119..a91f30a4a6 100644
--- a/lib/snmp/src/agent/snmpa_internal.hrl
+++ b/lib/snmp/src/agent/snmpa_internal.hrl
@@ -23,6 +23,7 @@
-include_lib("snmp/src/app/snmp_internal.hrl").
-define(DEFAULT_LOCAL_ENGINE_ID, snmp_framework_mib:get_engine_id()).
+-define(DEFAULT_NOTIF_EXTRA_INFO, {snmpa_default_notification_extra_info}).
-define(snmpa_info(F, A), ?snmp_info("agent", F, A)).
-define(snmpa_warning(F, A), ?snmp_warning("agent", F, A)).
diff --git a/lib/snmp/src/agent/snmpa_mpd.erl b/lib/snmp/src/agent/snmpa_mpd.erl
index fd75b98f84..39a4246d26 100644
--- a/lib/snmp/src/agent/snmpa_mpd.erl
+++ b/lib/snmp/src/agent/snmpa_mpd.erl
@@ -115,8 +115,8 @@ reset() ->
%% Func: process_packet(Packet, TDomain, TAddress, State, Log) ->
%% {ok, SnmpVsn, Pdu, PduMS, ACMData} | {discarded, Reason}
%% Types: Packet = binary()
-%% TDomain = snmpUDPDomain | atom()
-%% TAddress = {Ip, Udp}
+%% TDomain = snmpUDPDomain | transportDomain()
+%% TAddress = {Ip, Udp} (*but* depends on TDomain)
%% State = #state
%% Purpose: This is the main Message Dispatching function. (see
%% section 4.2.1 in rfc2272)
@@ -182,24 +182,30 @@ discarded_pdu(Variable) -> inc(Variable).
%%-----------------------------------------------------------------
%% Handles a Community based message (v1 or v2c).
%%-----------------------------------------------------------------
-v1_v2c_proc(Vsn, NoteStore, Community, snmpUDPDomain,
+v1_v2c_proc(Vsn, NoteStore, Community, Domain,
{Ip, Udp}, LocalEngineID,
Data, HS, Log, Packet) ->
- TAddress = tuple_to_list(Ip) ++ [Udp div 256, Udp rem 256],
- AgentMS = get_engine_max_message_size(LocalEngineID),
- MgrMS = snmp_community_mib:get_target_addr_ext_mms(?snmpUDPDomain,
- TAddress),
- PduMS = case MgrMS of
- {ok, MMS} when MMS < AgentMS -> MMS - HS;
- _ -> AgentMS - HS
- end,
+ TDomain = snmp_conf:mk_tdomain(Domain),
+ TAddress = snmp_conf:mk_taddress(Domain, Ip, Udp),
+ AgentMS = get_engine_max_message_size(LocalEngineID),
+ MgrMS = snmp_community_mib:get_target_addr_ext_mms(TDomain, TAddress),
+ PduMS = case MgrMS of
+ {ok, MMS} when MMS < AgentMS -> MMS - HS;
+ _ -> AgentMS - HS
+ end,
case (catch snmp_pdus:dec_pdu(Data)) of
Pdu when is_record(Pdu, pdu) ->
Log(Pdu#pdu.type, Packet),
inc_snmp_in_vars(Pdu),
#pdu{request_id = ReqId} = Pdu,
- OkRes = {ok, Vsn, Pdu, PduMS,
- {community, sec_model(Vsn), Community, TAddress}},
+
+ %% <TDomain>
+ %% We have added TDomain, what are the consequences?
+ ACMData =
+ {community, sec_model(Vsn), Community, TDomain, TAddress},
+ OkRes = {ok, Vsn, Pdu, PduMS, ACMData},
+ %% </TDomain>
+
%% Make sure that we don't process duplicate SET request
%% twice. We don't know what could happen in that case.
%% The mgr does, so he has to generate a new SET request.
@@ -216,8 +222,6 @@ v1_v2c_proc(Vsn, NoteStore, Community, snmpUDPDomain,
snmp_note_store:set_note(NoteStore,
100, Key, true),
%% Uses ACMData that snmpa_acm knows of.
- %% snmpUDPDomain is implicit, since that's the only
- %% one we handle.
OkRes;
true ->
{discarded, duplicate_pdu}
@@ -275,12 +279,12 @@ v3_proc(NoteStore, Packet, LocalEngineID, V3Hdr, Data, Log) ->
"~n msgSecurityParameters = ~w",
[MsgID, MMS, MsgFlags, MsgSecurityModel, SecParams]),
%% 7.2.4
- SecModule = get_security_module(MsgSecurityModel),
+ SecModule = get_security_module(MsgSecurityModel),
%% 7.2.5
- SecLevel = check_sec_level(MsgFlags),
+ SecLevel = check_sec_level(MsgFlags),
IsReportable = snmp_misc:is_reportable(MsgFlags),
%% 7.2.6
- ?vtrace("v3_proc -> [7.2.6]"
+ ?vtrace("v3_proc -> [7.2.4-7.2.6]"
"~n SecModule = ~p"
"~n SecLevel = ~p"
"~n IsReportable = ~p",
@@ -531,7 +535,7 @@ check_sec_module_result(Res, V3Hdr, Data, LocalEngineID, IsReportable, Log) ->
?vdebug("security module result [7.2.6-b]:"
"~n Reason: ~p", [Reason]),
throw({discarded, {securityError, Reason}});
- {error, Reason, ErrorInfo} when IsReportable == true -> % case 7.2.6 a
+ {error, Reason, ErrorInfo} when IsReportable =:= true -> % case 7.2.6 a
?vdebug("security module result when reportable [7.2.6-a]:"
"~n Reason: ~p"
"~n ErrorInfo: ~p", [Reason, ErrorInfo]),
@@ -574,7 +578,7 @@ generate_response_msg(Vsn, RePdu, Type, ACMData, LocalEngineID, Log) ->
generate_response_msg(Vsn, RePdu, Type, ACMData, LocalEngineID, Log, 1).
generate_response_msg(Vsn, RePdu, Type,
- {community, _SecModel, Community, _IpUdp},
+ {community, _SecModel, Community, _TDomain, _TAddress},
LocalEngineID,
Log, _) ->
case catch snmp_pdus:enc_pdu(RePdu) of
diff --git a/lib/snmp/src/agent/snmpa_net_if.erl b/lib/snmp/src/agent/snmpa_net_if.erl
index 97a7a63dee..bbc5568cde 100644
--- a/lib/snmp/src/agent/snmpa_net_if.erl
+++ b/lib/snmp/src/agent/snmpa_net_if.erl
@@ -314,6 +314,14 @@ loop(S) ->
NewS = maybe_handle_send_pdu(S, Vsn, Pdu, MsgData, To, undefined),
loop(NewS);
+ %% We dont use the extra-info at this time, ...
+ {send_pdu, Vsn, Pdu, MsgData, To, _ExtraInfo} ->
+ ?vdebug("send pdu: "
+ "~n Pdu: ~p"
+ "~n To: ~p", [Pdu, To]),
+ NewS = maybe_handle_send_pdu(S, Vsn, Pdu, MsgData, To, undefined),
+ loop(NewS);
+
%% Informs
{send_pdu_req, Vsn, Pdu, MsgData, To, From} ->
?vdebug("send pdu request: "
@@ -324,7 +332,18 @@ loop(S) ->
NewS = maybe_handle_send_pdu(S, Vsn, Pdu, MsgData, To, From),
loop(NewS);
+ %% We dont use the extra-info at this time, ...
+ {send_pdu_req, Vsn, Pdu, MsgData, To, From, _ExtraInfo} ->
+ ?vdebug("send pdu request: "
+ "~n Pdu: ~p"
+ "~n To: ~p"
+ "~n From: ~p",
+ [Pdu, To, toname(From)]),
+ NewS = maybe_handle_send_pdu(S, Vsn, Pdu, MsgData, To, From),
+ loop(NewS);
+
%% Discovery Inform
+ %% <BACKWARD-COMPAT>
{send_discovery, Pdu, MsgData, To, From} ->
?vdebug("received send discovery request: "
"~n Pdu: ~p"
@@ -333,6 +352,18 @@ loop(S) ->
[Pdu, To, toname(From)]),
NewS = handle_send_discovery(S, Pdu, MsgData, To, From),
loop(NewS);
+ %% </BACKWARD-COMPAT>
+
+ %% Discovery Inform
+ {send_discovery, Pdu, MsgData, To, From, ExtraInfo} ->
+ ?vdebug("received send discovery request: "
+ "~n Pdu: ~p"
+ "~n To: ~p"
+ "~n From: ~p"
+ "~n ExtraInfo: ~p",
+ [Pdu, To, toname(From), ExtraInfo]),
+ NewS = handle_send_discovery(S, Pdu, MsgData, To, From),
+ loop(NewS);
{discarded_pdu, _Vsn, ReqId, _ACMData, Variable, _Extra} ->
?vdebug("discard PDU: ~p", [Variable]),
@@ -504,7 +535,6 @@ handle_discovery_response(_Ip, _Port, #pdu{request_id = ReqId} = Pdu,
S
end.
-
handle_recv(#state{usock = Sock,
mpd_state = MpdState,
note_store = NS,
@@ -513,7 +543,9 @@ handle_recv(#state{usock = Sock,
LogF = fun(Type, Data) ->
log(Log, Type, Data, Ip, Port)
end,
- case (catch snmpa_mpd:process_packet(Packet, snmpUDPDomain, {Ip, Port},
+ Domain = snmp_conf:which_domain(Ip), % What the ****...
+ case (catch snmpa_mpd:process_packet(Packet,
+ Domain, {Ip, Port},
MpdState, NS, LogF)) of
{ok, _Vsn, Pdu, _PduMS, {discovery, ManagerEngineId}} ->
handle_discovery_response(Ip, Port, Pdu, ManagerEngineId, S);
@@ -636,7 +668,6 @@ process_taddrs([{{_Domain, AddrAndPort}, _SecData}|T], Acc) ->
process_taddrs([{_Domain, AddrAndPort}|T], Acc) ->
process_taddrs(T, [AddrAndPort|Acc]).
-
merge_taddrs(To1, To2) ->
merge_taddrs(To1, To2, []).
@@ -776,15 +807,49 @@ handle_send_pdu1(#state{log = Log,
usock = Sock,
filter = FilterMod}, Type, Addresses) ->
SendFun =
- fun({snmpUDPDomain, {Ip, Port}, Packet}) when is_binary(Packet) ->
- ?vdebug("sending packet:"
+ fun({snmpUDPDomain, {Ip, Port}, Packet})
+ when is_binary(Packet) ->
+ ?vdebug("[snmpUDPDomain] sending packet:"
+ "~n size: ~p"
+ "~n to: ~p:~p",
+ [sz(Packet), Ip, Port]),
+ maybe_udp_send(FilterMod, Log, Type, Sock, Ip, Port, Packet);
+
+ ({snmpUDPDomain, {Ip, Port}, {Packet, _LogData}})
+ when is_binary(Packet) ->
+ ?vdebug("[snmpUDPDomain] sending encrypted packet:"
+ "~n size: ~p"
+ "~n to: ~p:~p",
+ [sz(Packet), Ip, Port]),
+ maybe_udp_send(FilterMod, Log, Type, Sock, Ip, Port, Packet);
+
+ ({transportDomainUdpIpv4, {Ip, Port}, Packet})
+ when is_binary(Packet) ->
+ ?vdebug("[transportDomainUdpIpv4] sending packet:"
+ "~n size: ~p"
+ "~n to: ~p:~p",
+ [sz(Packet), Ip, Port]),
+ maybe_udp_send(FilterMod, Log, Type, Sock, Ip, Port, Packet);
+
+ ({transportDomainUdpIpv4, {Ip, Port}, {Packet, _LogData}})
+ when is_binary(Packet) ->
+ ?vdebug("[transportDomainUdpIpv4] sending encrypted packet:"
+ "~n size: ~p"
+ "~n to: ~p:~p",
+ [sz(Packet), Ip, Port]),
+ maybe_udp_send(FilterMod, Log, Type, Sock, Ip, Port, Packet);
+
+ ({transportDomainUdpIpv6, {Ip, Port}, Packet})
+ when is_binary(Packet) ->
+ ?vdebug("[transportDomainUdpIpv6] sending packet:"
"~n size: ~p"
"~n to: ~p:~p",
[sz(Packet), Ip, Port]),
maybe_udp_send(FilterMod, Log, Type, Sock, Ip, Port, Packet);
- ({snmpUDPDomain, {Ip, Port}, {Packet, _LogData}}) when is_binary(Packet) ->
- ?vdebug("sending encrypted packet:"
+ ({transportDomainUdpIpv6, {Ip, Port}, {Packet, _LogData}})
+ when is_binary(Packet) ->
+ ?vdebug("[transportDomainUdpIpv6] sending encrypted packet:"
"~n size: ~p"
"~n to: ~p:~p",
[sz(Packet), Ip, Port]),
diff --git a/lib/snmp/src/agent/snmpa_trap.erl b/lib/snmp/src/agent/snmpa_trap.erl
index 450cb2e9f4..3c7ae804a5 100644
--- a/lib/snmp/src/agent/snmpa_trap.erl
+++ b/lib/snmp/src/agent/snmpa_trap.erl
@@ -24,27 +24,34 @@
%% External exports
-export([construct_trap/2,
try_initialise_vars/2,
- send_trap/6, send_trap/7]).
--export([send_discovery/5]).
+ send_trap/6, send_trap/7, send_trap/8]).
+-export([send_discovery/6]).
%% Internal exports
--export([init_v2_inform/9,
- init_v3_inform/9, init_v3_inform/10,
+-export([init_v2_inform/9, init_v2_inform/10,
+ init_v3_inform/9, init_v3_inform/10, init_v3_inform/11,
send_inform/6]).
--export([init_discovery_inform/12, send_discovery_inform/5]).
-
--include("snmp_types.hrl").
--include("snmpa_internal.hrl").
--include("SNMPv2-MIB.hrl").
--include("SNMPv2-TM.hrl").
--include("SNMPv2-TC.hrl").
--include("SNMP-FRAMEWORK-MIB.hrl").
--include("SNMP-TARGET-MIB.hrl").
+-export([init_discovery_inform/13, send_discovery_inform/5]).
+
+%% <BACKWARD-COMPAT>
+-export([send_discovery/5,
+ init_discovery_inform/12]).
+%% </BACKWARD-COMPAT>
+
+-include_lib("snmp/include/snmp_types.hrl").
+-include_lib("snmp/src/agent/snmpa_internal.hrl").
+-include_lib("snmp/include/SNMPv2-MIB.hrl").
+-include_lib("snmp/include/SNMPv2-TM.hrl").
+-include_lib("snmp/include/SNMPv2-TC.hrl").
+-include_lib("snmp/include/SNMP-FRAMEWORK-MIB.hrl").
+-include_lib("snmp/include/SNMP-TARGET-MIB.hrl").
+-include_lib("snmp/include/TRANSPORT-ADDRESS-MIB.hrl").
-define(enterpriseSpecific, 6).
-define(VMODULE,"TRAP").
-include("snmp_verbosity.hrl").
+-include("snmpa_internal.hrl").
%%-----------------------------------------------------------------
@@ -335,25 +342,36 @@ make_varbind_list(Varbinds) ->
%% SnmpTargetAddrTable (using the Tag).
%%-----------------------------------------------------------------
send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs, NetIf) ->
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
+ send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
+ LocalEngineID, ExtraInfo, NetIf).
+
+send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs, ExtraInfo, NetIf) ->
LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
- LocalEngineID, NetIf).
+ LocalEngineID, ExtraInfo, NetIf).
-send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs, LocalEngineID, NetIf) ->
+send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs, LocalEngineID,
+ ExtraInfo, NetIf) ->
(catch do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
- LocalEngineID, NetIf)).
+ LocalEngineID, ExtraInfo, NetIf)).
do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
- LocalEngineID, NetIf) ->
+ LocalEngineID, ExtraInfo, NetIf) ->
VarbindList = make_varbind_list(Vbs),
Dests = find_dests(NotifyName),
send_trap_pdus(Dests, ContextName, {TrapRec, VarbindList}, [], [], [],
- Recv, LocalEngineID, NetIf).
+ Recv, LocalEngineID, ExtraInfo, NetIf).
send_discovery(TargetName, Record, ContextName, Vbs, NetIf) ->
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ send_discovery(TargetName, Record, ContextName, Vbs, NetIf, ExtraInfo).
+send_discovery(TargetName, Record, ContextName, Vbs, NetIf, ExtraInfo) ->
case find_dest(TargetName) of
{ok, Dest} ->
- send_discovery_pdu(Dest, Record, ContextName, Vbs, NetIf);
+ send_discovery_pdu(Dest, Record, ContextName, Vbs, NetIf,
+ ExtraInfo);
Error ->
Error
end.
@@ -440,11 +458,13 @@ split_variables([]) -> {[], []}.
%% NOTE: This function is executed in the master agent's context
%%-----------------------------------------------------------------
find_dests("") ->
+ ?vtrace("find destinations", []),
snmp_notification_mib:get_targets();
find_dests(NotifyName) ->
+ ?vtrace("find destinations for ~p", [NotifyName]),
case snmp_notification_mib:get_targets(NotifyName) of
[] ->
- ?vlog("No dests found for snmpNotifyName: ~p",[NotifyName]),
+ ?vlog("No dests found for NotifyName: ~p", [NotifyName]),
[];
Dests ->
Dests
@@ -529,7 +549,8 @@ find_dest(TargetName) ->
send_discovery_pdu({Dest, TargetName, {SecModel, SecName, SecLevel},
Timeout, Retry},
- Record, ContextName, Vbs, NetIf) ->
+ Record, ContextName, Vbs, NetIf,
+ ExtraInfo) ->
?vdebug("send_discovery_pdu -> entry with "
"~n Destination address: ~p"
"~n Target name: ~p"
@@ -539,9 +560,10 @@ send_discovery_pdu({Dest, TargetName, {SecModel, SecName, SecLevel},
"~n Timeout: ~p"
"~n Retry: ~p"
"~n Record: ~p"
- "~n ContextName: ~p",
+ "~n ContextName: ~p"
+ "~n ExtraInfo: ~p",
[Dest, TargetName, SecModel, SecName, SecLevel,
- Timeout, Retry, Record, ContextName]),
+ Timeout, Retry, Record, ContextName, ExtraInfo]),
case get_mib_view(SecModel, SecName, SecLevel, ContextName) of
{ok, MibView} ->
case check_all_varbinds(Record, Vbs, MibView) of
@@ -551,7 +573,7 @@ send_discovery_pdu({Dest, TargetName, {SecModel, SecName, SecLevel},
SecModel, SecName, SecLevel,
TargetName, ContextName,
Timeout, Retry,
- SysUpTime, NetIf);
+ SysUpTime, NetIf, ExtraInfo);
false ->
{error, {mibview_validation_failed, Vbs, MibView}}
end;
@@ -561,7 +583,7 @@ send_discovery_pdu({Dest, TargetName, {SecModel, SecName, SecLevel},
send_discovery_pdu(Record, Dest, Vbs,
SecModel, SecName, SecLevel, TargetName,
- ContextName, Timeout, Retry, SysUpTime, NetIf) ->
+ ContextName, Timeout, Retry, SysUpTime, NetIf, ExtraInfo) ->
{_Oid, IVbs} = mk_v2_trap(Record, Vbs, SysUpTime), % v2 refers to SMIv2;
Sender = proc_lib:spawn_link(?MODULE, init_discovery_inform,
[self(),
@@ -570,13 +592,25 @@ send_discovery_pdu(Record, Dest, Vbs,
ContextName,
Timeout, Retry,
IVbs, NetIf,
- get(verbosity)]),
+ get(verbosity),
+ ExtraInfo]),
{ok, Sender, SecLevel}.
init_discovery_inform(Parent,
Dest,
SecModel, SecName, SecLevel, TargetName,
ContextName, Timeout, Retry, Vbs, NetIf, Verbosity) ->
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ init_discovery_inform(Parent,
+ Dest,
+ SecModel, SecName, SecLevel, TargetName,
+ ContextName, Timeout, Retry, Vbs, NetIf,
+ Verbosity, ExtraInfo).
+init_discovery_inform(Parent,
+ Dest,
+ SecModel, SecName, SecLevel, TargetName,
+ ContextName, Timeout, Retry, Vbs, NetIf,
+ Verbosity, ExtraInfo) ->
put(verbosity, Verbosity),
put(sname, madis),
Pdu = make_discovery_pdu(Vbs),
@@ -584,7 +618,7 @@ init_discovery_inform(Parent,
SecLevelFlag = mk_flag(SecLevel),
SecData = {SecModel, SecName, SecLevelFlag, TargetName},
MsgData = {SecData, ContextEngineId, ContextName},
- Msg = {send_discovery, Pdu, MsgData, Dest, self()},
+ Msg = {send_discovery, Pdu, MsgData, Dest, self(), ExtraInfo},
?MODULE:send_discovery_inform(Parent, Timeout*10, Retry, Msg, NetIf).
%% note_timeout(Timeout, Retry)
@@ -628,11 +662,11 @@ send_discovery_inform(Parent, Timeout, Retry, Msg, NetIf) ->
%% should be used for the target, and determine the message
%% specific parameters to be used.
%%-----------------------------------------------------------------
-send_trap_pdus([{DestAddr, TargetName, {MpModel, SecModel, SecName, SecLevel},
- Type} | T],
+send_trap_pdus([{DestAddr, TargetName,
+ {MpModel, SecModel, SecName, SecLevel}, Type} | T],
ContextName,
{TrapRec, Vbs}, V1Res, V2Res, V3Res, Recv,
- LocalEngineID, NetIf) ->
+ LocalEngineID, ExtraInfo, NetIf) ->
?vdebug("send trap pdus: "
"~n Destination address: ~p"
"~n Target name: ~p"
@@ -658,13 +692,13 @@ send_trap_pdus([{DestAddr, TargetName, {MpModel, SecModel, SecName, SecLevel},
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
[{DestAddr, Community} | V1Res],
V2Res, V3Res, Recv,
- LocalEngineID, NetIf);
+ LocalEngineID, ExtraInfo, NetIf);
undefined ->
?vdebug("No community found for v1 dest: ~p",
[element(2, DestAddr)]),
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
V1Res, V2Res, V3Res, Recv,
- LocalEngineID, NetIf)
+ LocalEngineID, ExtraInfo, NetIf)
end;
true when MpModel =:= ?MP_V2C ->
?vtrace("send_trap_pdus -> v2c mp model",[]),
@@ -679,13 +713,14 @@ send_trap_pdus([{DestAddr, TargetName, {MpModel, SecModel, SecName, SecLevel},
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
V1Res,
[{DestAddr, Community, Type}|V2Res],
- V3Res, Recv, LocalEngineID, NetIf);
+ V3Res, Recv,
+ LocalEngineID, ExtraInfo, NetIf);
undefined ->
?vdebug("No community found for v2c dest: ~p",
[element(2, DestAddr)]),
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
V1Res, V2Res, V3Res, Recv,
- LocalEngineID, NetIf)
+ LocalEngineID, ExtraInfo, NetIf)
end;
true when MpModel =:= ?MP_V3 ->
?vtrace("send_trap_pdus -> v3 mp model",[]),
@@ -694,20 +729,20 @@ send_trap_pdus([{DestAddr, TargetName, {MpModel, SecModel, SecName, SecLevel},
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
V1Res, V2Res,
[{DestAddr, MsgData, Type} | V3Res],
- Recv, LocalEngineID, NetIf);
+ Recv, LocalEngineID, ExtraInfo, NetIf);
true ->
?vlog("bad MpModel ~p for dest ~p",
[MpModel, element(2, DestAddr)]),
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
V1Res, V2Res, V3Res, Recv,
- LocalEngineID, NetIf);
+ LocalEngineID, ExtraInfo, NetIf);
_ ->
?vlog("no access for dest: "
"~n ~p in target ~p",
[element(2, DestAddr), TargetName]),
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
V1Res, V2Res, V3Res, Recv,
- LocalEngineID, NetIf)
+ LocalEngineID, ExtraInfo, NetIf)
end;
{discarded, Reason} ->
?vlog("mib view error ~p for"
@@ -715,24 +750,27 @@ send_trap_pdus([{DestAddr, TargetName, {MpModel, SecModel, SecName, SecLevel},
"~n SecName: ~w",
[Reason, element(2, DestAddr), SecName]),
send_trap_pdus(T, ContextName, {TrapRec, Vbs},
- V1Res, V2Res, V3Res, Recv, LocalEngineID, NetIf)
+ V1Res, V2Res, V3Res, Recv,
+ LocalEngineID, ExtraInfo, NetIf)
end;
-send_trap_pdus([], ContextName, {TrapRec, Vbs}, V1Res, V2Res, V3Res,
- Recv, LocalEngineID, NetIf) ->
+send_trap_pdus([], ContextName, {TrapRec, Vbs},
+ V1Res, V2Res, V3Res, Recv,
+ LocalEngineID, ExtraInfo,
+ NetIf) ->
SysUpTime = snmp_standard_mib:sys_up_time(),
?vdebug("send trap pdus with sysUpTime ~p", [SysUpTime]),
InformRecvs = get_inform_recvs(V2Res ++ V3Res),
InformTargets = [Addr || {Addr, _, _, _} <- InformRecvs],
deliver_recv(Recv, snmp_targets, InformTargets),
- send_v1_trap(TrapRec, V1Res, Vbs, NetIf, SysUpTime),
- send_v2_trap(TrapRec, V2Res, Vbs, Recv, NetIf, SysUpTime),
- send_v3_trap(TrapRec, V3Res, Vbs, Recv, LocalEngineID, NetIf,
+ send_v1_trap(TrapRec, V1Res, Vbs, ExtraInfo, NetIf, SysUpTime),
+ send_v2_trap(TrapRec, V2Res, Vbs, Recv, ExtraInfo, NetIf, SysUpTime),
+ send_v3_trap(TrapRec, V3Res, Vbs, Recv, LocalEngineID, ExtraInfo, NetIf,
SysUpTime, ContextName).
-send_v1_trap(_TrapRec, [], _Vbs, _NetIf, _SysUpTime) ->
+send_v1_trap(_TrapRec, [], _Vbs, _ExtraInfo, _NetIf, _SysUpTime) ->
ok;
send_v1_trap(#trap{enterpriseoid = Enter, specificcode = Spec},
- V1Res, Vbs, NetIf, SysUpTime) ->
+ V1Res, Vbs, ExtraInfo, NetIf, SysUpTime) ->
?vdebug("prepare to send v1 trap "
"~n '~p'"
"~n with"
@@ -744,9 +782,10 @@ send_v1_trap(#trap{enterpriseoid = Enter, specificcode = Spec},
lists:foreach(fun({Community, Addrs}) ->
?vtrace("send v1 trap pdu to ~p",[Addrs]),
NetIf ! {send_pdu, 'version-1', TrapPdu,
- {community, Community}, Addrs}
+ {community, Community}, Addrs, ExtraInfo}
end, AddrCommunities);
-send_v1_trap(#notification{oid = Oid}, V1Res, Vbs, NetIf, SysUpTime) ->
+send_v1_trap(#notification{oid = Oid}, V1Res, Vbs, ExtraInfo, NetIf,
+ SysUpTime) ->
%% Use alg. in rfc2089 to map a v2 trap to a v1 trap
% delete Counter64 objects from vbs
?vdebug("prepare to send v1 trap '~p'",[Oid]),
@@ -768,31 +807,31 @@ send_v1_trap(#notification{oid = Oid}, V1Res, Vbs, NetIf, SysUpTime) ->
lists:foreach(fun({Community, Addrs}) ->
?vtrace("send v1 trap to ~p",[Addrs]),
NetIf ! {send_pdu, 'version-1', TrapPdu,
- {community, Community}, Addrs}
+ {community, Community}, Addrs, ExtraInfo}
end, AddrCommunities).
-send_v2_trap(_TrapRec, [], _Vbs, _Recv, _NetIf, _SysUpTime) ->
+send_v2_trap(_TrapRec, [], _Vbs, _Recv, _ExtraInfo, _NetIf, _SysUpTime) ->
ok;
-send_v2_trap(TrapRec, V2Res, Vbs, Recv, NetIf, SysUpTime) ->
+send_v2_trap(TrapRec, V2Res, Vbs, Recv, ExtraInfo, NetIf, SysUpTime) ->
?vdebug("prepare to send v2 trap",[]),
{_Oid, IVbs} = mk_v2_trap(TrapRec, Vbs, SysUpTime),
- TrapRecvs = get_trap_recvs(V2Res),
- InformRecvs = get_inform_recvs(V2Res),
- do_send_v2_trap(TrapRecvs, IVbs, NetIf),
- do_send_v2_inform(InformRecvs, IVbs, Recv, NetIf).
+ TrapRecvs = get_trap_recvs(V2Res),
+ InformRecvs = get_inform_recvs(V2Res),
+ do_send_v2_trap(TrapRecvs, IVbs, ExtraInfo, NetIf),
+ do_send_v2_inform(InformRecvs, IVbs, Recv, ExtraInfo, NetIf).
-send_v3_trap(_TrapRec, [], _Vbs, _Recv, _LocalEngineID,
+send_v3_trap(_TrapRec, [], _Vbs, _Recv, _LocalEngineID, _ExtraInfo,
_NetIf, _SysUpTime, _ContextName) ->
ok;
-send_v3_trap(TrapRec, V3Res, Vbs, Recv, LocalEngineID,
+send_v3_trap(TrapRec, V3Res, Vbs, Recv, LocalEngineID, ExtraInfo,
NetIf, SysUpTime, ContextName) ->
?vdebug("prepare to send v3 trap",[]),
{_Oid, IVbs} = mk_v2_trap(TrapRec, Vbs, SysUpTime), % v2 refers to SMIv2;
TrapRecvs = get_trap_recvs(V3Res), % same SMI for v3
InformRecvs = get_inform_recvs(V3Res),
- do_send_v3_trap(TrapRecvs, ContextName, IVbs, NetIf),
+ do_send_v3_trap(TrapRecvs, ContextName, IVbs, ExtraInfo, NetIf),
do_send_v3_inform(InformRecvs, ContextName, IVbs, Recv,
- LocalEngineID, NetIf).
+ LocalEngineID, ExtraInfo, NetIf).
mk_v2_trap(#notification{oid = Oid}, Vbs, SysUpTime) ->
@@ -830,60 +869,70 @@ get_inform_recvs(InformRecvs) ->
[{Addr, MsgData, Timeout, Retry} ||
{Addr, MsgData, {inform, Timeout, Retry}} <- InformRecvs].
-do_send_v2_trap([], _Vbs, _NetIf) ->
+do_send_v2_trap([], _Vbs, _ExtraInfo, _NetIf) ->
ok;
-do_send_v2_trap(Recvs, Vbs, NetIf) ->
+do_send_v2_trap(Recvs, Vbs, ExtraInfo, NetIf) ->
TrapPdu = make_v2_notif_pdu(Vbs, 'snmpv2-trap'),
AddrCommunities = mk_addr_communities(Recvs),
lists:foreach(fun({Community, Addrs}) ->
?vtrace("~n send v2 trap to ~p",[Addrs]),
NetIf ! {send_pdu, 'version-2', TrapPdu,
- {community, Community}, Addrs}
+ {community, Community}, Addrs, ExtraInfo}
end, AddrCommunities),
ok.
-do_send_v2_inform([], _Vbs, _Recv, _NetIf) ->
+do_send_v2_inform([], _Vbs, _Recv, _ExtraInfo, _NetIf) ->
ok;
-do_send_v2_inform(Recvs, Vbs, Recv, NetIf) ->
+do_send_v2_inform(Recvs, Vbs, Recv, ExtraInfo, NetIf) ->
lists:foreach(
fun({Addr, Community, Timeout, Retry}) ->
?vtrace("~n start inform sender to send v2 inform to ~p",
[Addr]),
proc_lib:spawn_link(?MODULE, init_v2_inform,
[Addr, Timeout, Retry, Vbs,
- Recv, NetIf, Community,
+ Recv, ExtraInfo, NetIf, Community,
get(verbosity), get(sname)])
end,
Recvs).
-do_send_v3_trap([], _ContextName, _Vbs, _NetIf) ->
+do_send_v3_trap([], _ContextName, _Vbs, _ExtraInfo, _NetIf) ->
ok;
-do_send_v3_trap(Recvs, ContextName, Vbs, NetIf) ->
+do_send_v3_trap(Recvs, ContextName, Vbs, ExtraInfo, NetIf) ->
TrapPdu = make_v2_notif_pdu(Vbs, 'snmpv2-trap'), % Yes, v2
ContextEngineId = snmp_framework_mib:get_engine_id(),
lists:foreach(fun(Recv) ->
?vtrace("~n send v3 notif to ~p",[Recv]),
NetIf ! {send_pdu, 'version-3', TrapPdu,
- {v3, ContextEngineId, ContextName}, [Recv]}
+ {v3, ContextEngineId, ContextName},
+ [Recv], ExtraInfo}
end, Recvs),
ok.
-do_send_v3_inform([], _ContextName, _Vbs, _Recv, _LocalEngineID, _NetIf) ->
+do_send_v3_inform([], _ContextName, _Vbs, _Recv,
+ _LocalEngineID, _ExtraInfo, _NetIf) ->
ok;
-do_send_v3_inform(Recvs, ContextName, Vbs, Recv, LocalEngineID, NetIf) ->
+do_send_v3_inform(Recvs, ContextName, Vbs, Recv,
+ LocalEngineID, ExtraInfo, NetIf) ->
lists:foreach(
fun({Addr, MsgData, Timeout, Retry}) ->
?vtrace("~n start inform sender to send v3 inform to ~p",
[Addr]),
proc_lib:spawn_link(?MODULE, init_v3_inform,
[{Addr, MsgData}, Timeout, Retry, Vbs,
- Recv, LocalEngineID, NetIf, ContextName,
+ Recv, LocalEngineID, ExtraInfo,
+ NetIf, ContextName,
get(verbosity), get(sname)])
end,
Recvs).
%% New process
-init_v2_inform(Addr, Timeout, Retry, Vbs, Recv, NetIf, Community,V,S) ->
+init_v2_inform(Addr, Timeout, Retry, Vbs, Recv, NetIf, Community, V, S) ->
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ init_v2_inform(Addr, Timeout, Retry, Vbs, Recv, ExtraInfo, NetIf,
+ Community, V, S).
+
+init_v2_inform(Addr, Timeout, Retry, Vbs, Recv, ExtraInfo, NetIf,
+ Community, V, S) ->
%% Make a new Inform for each recipient; they need unique
%% request-ids!
put(verbosity,V),
@@ -892,17 +941,26 @@ init_v2_inform(Addr, Timeout, Retry, Vbs, Recv, NetIf, Community,V,S) ->
[Timeout,Retry]),
InformPdu = make_v2_notif_pdu(Vbs, 'inform-request'),
Msg = {send_pdu_req, 'version-2', InformPdu, {community, Community},
- [Addr], self()},
+ [Addr], self(), ExtraInfo},
?MODULE:send_inform(Addr, Timeout*10, Retry, Msg, Recv, NetIf).
%% New process
init_v3_inform(Addr, Timeout, Retry, Vbs, Recv, NetIf, ContextName, V, S) ->
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
- init_v3_inform(Addr, Timeout, Retry, Vbs, Recv, LocalEngineID,
+ init_v3_inform(Addr, Timeout, Retry, Vbs, Recv,
+ LocalEngineID, ExtraInfo,
+ NetIf, ContextName, V, S).
+
+init_v3_inform(Addr, Timeout, Retry, Vbs, Recv, LocalEngineID, NetIf,
+ ContextName, V, S) ->
+ ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
+ init_v3_inform(Addr, Timeout, Retry, Vbs, Recv,
+ LocalEngineID, ExtraInfo,
NetIf, ContextName, V, S).
-init_v3_inform(Addr, Timeout, Retry, Vbs, Recv, LocalEngineID,
+init_v3_inform(Addr, Timeout, Retry, Vbs, Recv, LocalEngineID, ExtraInfo,
NetIf, ContextName, V, S) ->
%% Make a new Inform for each recipient; they need unique
%% request-ids!
@@ -913,7 +971,7 @@ init_v3_inform(Addr, Timeout, Retry, Vbs, Recv, LocalEngineID,
InformPdu = make_v2_notif_pdu(Vbs, 'inform-request'), % Yes, v2
ContextEngineId = LocalEngineID,
Msg = {send_pdu_req, 'version-3', InformPdu,
- {v3, ContextEngineId, ContextName}, [Addr], self()},
+ {v3, ContextEngineId, ContextName}, [Addr], self(), ExtraInfo},
?MODULE:send_inform(Addr, Timeout*10, Retry, Msg, Recv, NetIf).
send_inform(Addr, _Timeout, -1, _Msg, Recv, _NetIf) ->
@@ -1001,9 +1059,27 @@ transform_taddr({?snmpUDPDomain, [A1, A2, A3, A4, P1, P2]}) -> % v2
Addr = {A1, A2, A3, A4},
Port = P1 bsl 8 + P2,
{Addr, Port};
+transform_taddr({?transportDomainUdpIpv4, [A1, A2, A3, A4, P1, P2]}) -> % v2
+ Addr = {A1, A2, A3, A4},
+ Port = P1 bsl 8 + P2,
+ {Addr, Port};
+transform_taddr({?transportDomainUdpIpv6,
+ [A1, A2, A3, A4, A5, A6, A7, A8, P1, P2]}) -> % v2
+ Addr = {A1, A2, A3, A4, A5, A6, A7, A8},
+ Port = P1 bsl 8 + P2,
+ {Addr, Port};
transform_taddr({{?snmpUDPDomain, [A1, A2, A3, A4, P1, P2]}, _MsgData}) -> % v3
Addr = {A1, A2, A3, A4},
Port = P1 bsl 8 + P2,
+ {Addr, Port};
+transform_taddr({{?transportDomainUdpIpv4, [A1, A2, A3, A4, P1, P2]}, _MsgData}) -> % v3
+ Addr = {A1, A2, A3, A4},
+ Port = P1 bsl 8 + P2,
+ {Addr, Port};
+transform_taddr({{?transportDomainUdpIpv6,
+ [A1, A2, A3, A4, A5, A6, A7, A8, P1, P2]}, _MsgData}) -> % v3
+ Addr = {A1, A2, A3, A4, A5, A6, A7, A8},
+ Port = P1 bsl 8 + P2,
{Addr, Port}.
@@ -1053,13 +1129,14 @@ mk_addr_communities(Recvs) ->
[{Addr, Comm} | T] = lists:keysort(2, Recvs),
mic(T, Comm, [Addr], []).
-mic([{Addr, Comm} | T], CurComm, AddrList, Res) when Comm == CurComm ->
+mic([{Addr, Comm} | T], CurComm, AddrList, Res) when Comm =:= CurComm ->
mic(T, CurComm, [Addr | AddrList], Res);
mic([{Addr, Comm} | T], CurComm, AddrList, Res) ->
mic(T, Comm, [Addr], [{CurComm, AddrList} | Res]);
mic([], CurComm, AddrList, Res) ->
[{CurComm, AddrList} | Res].
+
%%-----------------------------------------------------------------
%% Convert the SecurityLevel into a flag value used by snmpa_mpd
%%-----------------------------------------------------------------
diff --git a/lib/snmp/src/agent/snmpa_usm.erl b/lib/snmp/src/agent/snmpa_usm.erl
index f35d1f1916..6f54307f9f 100644
--- a/lib/snmp/src/agent/snmpa_usm.erl
+++ b/lib/snmp/src/agent/snmpa_usm.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1999-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1999-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
@@ -330,7 +330,6 @@ non_authoritative(SecName,
end
end.
-
is_auth(?usmNoAuthProtocol, _, _, _, SecName, _, _, _, _) -> % 3.2.5
error(usmStatsUnsupportedSecLevels,
?usmStatsUnsupportedSecLevels_instance, SecName); % OTP-5464
@@ -613,8 +612,7 @@ authenticate_outgoing(Message, UsmSecParams,
end,
?vtrace("authenticate_outgoing -> encode message only",[]),
snmp_pdus:enc_message_only(Message2).
-
-
+
%%-----------------------------------------------------------------
%% Auth and priv algorithms
@@ -753,14 +751,19 @@ set_engine_latest_time(SnmpEngineID, EngineTime) ->
%%-----------------------------------------------------------------
%% Utility functions
%%-----------------------------------------------------------------
+-spec error(term()) -> no_return().
error(Reason) ->
throw({error, Reason}).
+-spec error(term(), term()) -> no_return().
error(Reason, ErrorInfo) ->
throw({error, Reason, ErrorInfo}).
+-spec error(term(), term(), term()) -> no_return().
error(Variable, Oid, SecName) ->
error(Variable, Oid, SecName, []).
+
+-spec error(term(), term(), term(), [term()]) -> no_return().
error(Variable, Oid, SecName, Opts) ->
Val = inc(Variable),
ErrorInfo = {#varbind{oid = Oid,
@@ -772,7 +775,6 @@ error(Variable, Oid, SecName, Opts) ->
inc(Name) -> ets:update_counter(snmp_agent_table, Name, 1).
-
get_counter(Name) ->
case (catch ets:lookup(snmp_agent_table, Name)) of
[{_, Val}] ->
@@ -780,8 +782,3 @@ get_counter(Name) ->
_ ->
0
end.
-
-
-
-
-
diff --git a/lib/snmp/src/app/snmp.appup.src b/lib/snmp/src/app/snmp.appup.src
index de0e5d6e14..5deb40be0f 100644
--- a/lib/snmp/src/app/snmp.appup.src
+++ b/lib/snmp/src/app/snmp.appup.src
@@ -22,10 +22,56 @@
%% ----- U p g r a d e -------------------------------------------------------
[
+ {"4.19",
+ [
+ {load_module, snmpa, soft_purge, soft_purge, []},
+ {load_module, snmpm, soft_purge, soft_purge, [snmpm_server]},
+ {load_module, snmpa_usm, soft_purge, soft_purge, []},
+ {load_module, snmpm_usm, soft_purge, soft_purge, []},
+ {load_module, snmp_log, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
+ {load_module, snmp_conf, soft_purge, soft_purge, []},
+ {load_module, snmpa_conf, soft_purge, soft_purge, [snmp_conf]},
+ {load_module, snmp_misc, soft_purge, soft_purge, []},
+ {load_module, snmp_config, soft_purge, soft_purge, []},
+ {load_module, snmpa_mpd, soft_purge, soft_purge, [snmp_conf]},
+ {load_module, snmpa_trap, soft_purge, soft_purge,
+ [snmpa_mpd, snmp_notification_mib, snmp_target_mib, snmpa_net_if]},
+ {load_module, snmpa_acm, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd, snmp_target_mib]},
+ {load_module, snmpa_conf, soft_purge, soft_purge,
+ [snmp_notification_mib]},
+ {load_module, snmp_notification_mib, soft_purge, soft_purge,
+ [snmp_conf, snmp_target_mib]},
+ {load_module, snmp_community_mib, soft_purge, soft_purge, []},
+ {load_module, snmp_target_mib, soft_purge, soft_purge,
+ [snmp_conf]},
+ {update, snmpm_net_if, soft, soft_purge, soft_purge, []},
+ {update, snmpm_server, soft, soft_purge, soft_purge, [snmpm_net_if]},
+ {update, snmpa_net_if, soft, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd]},
+ {update, snmpa_agent, soft, soft_purge, soft_purge,
+ [snmpa_acm, snmpa_mpd, snmpa_trap]}
+ ]
+ },
{"4.18",
[
+ {load_module, snmpa, soft_purge, soft_purge, []},
+ {load_module, snmpm, soft_purge, soft_purge, [snmpm_server]},
+ {load_module, snmpa_usm, soft_purge, soft_purge, []},
+ {load_module, snmpm_usm, soft_purge, soft_purge, []},
{load_module, snmp_misc, soft_purge, soft_purge, []},
+ {load_module, snmp_log, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
+ {load_module, snmp_conf, soft_purge, soft_purge, []},
+ {load_module, snmp_config, soft_purge, soft_purge, [snmp_conf]},
+ {load_module, snmpa_conf, soft_purge, soft_purge, []},
+ {load_module, snmpa_mpd, soft_purge, soft_purge, [snmp_conf]},
{load_module, snmpa_vacm, soft_purge, soft_purge, []},
+ {load_module, snmpa_trap, soft_purge, soft_purge,
+ [snmpa_mpd, snmp_notification_mib, snmp_target_mib, snmpa_net_if]},
+ {load_module, snmpa_acm, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd, snmp_target_mib]},
{load_module, snmpa, soft_purge, soft_purge,
[snmp_community_mib,
snmp_framework_mib,
@@ -33,6 +79,8 @@
snmp_target_mib,
snmp_user_based_sm_mib,
snmp_view_based_acm_mib]},
+ {load_module, snmp_notification_mib, soft_purge, soft_purge,
+ [snmp_conf, snmp_target_mib, snmpa_mib_lib]},
{load_module, snmp_community_mib, soft_purge, soft_purge,
[snmpa_mib_lib]},
{load_module, snmp_framework_mib, soft_purge, soft_purge,
@@ -45,7 +93,15 @@
[snmpa_mib_lib]},
{load_module, snmp_view_based_acm_mib, soft_purge, soft_purge,
[snmpa_mib_lib, snmpa_vacm]},
- {load_module, snmpa_mib_lib, soft_purge, soft_purge, []}
+ {load_module, snmpa_mib_lib, soft_purge, soft_purge, []},
+
+ {update, snmpm_net_if, soft, soft_purge, soft_purge, []},
+ {update, snmpm_server, soft, soft_purge, soft_purge, [snmpm_net_if]},
+
+ {update, snmpa_net_if, soft, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd]},
+ {update, snmpa_agent, soft, soft_purge, soft_purge,
+ [snmpa_acm, snmpa_mpd, snmpa_trap]}
]
}
],
@@ -53,10 +109,58 @@
%% ------D o w n g r a d e ---------------------------------------------------
[
+ {"4.19",
+ [
+ {load_module, snmpa, soft_purge, soft_purge, []},
+ {load_module, snmpm, soft_purge, soft_purge, [snmpm_server]},
+ {load_module, snmpa_usm, soft_purge, soft_purge, []},
+ {load_module, snmpm_usm, soft_purge, soft_purge, []},
+ {load_module, snmp_log, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
+ {load_module, snmp_conf, soft_purge, soft_purge, []},
+ {load_module, snmpa_conf, soft_purge, soft_purge, [snmp_conf]},
+ {load_module, snmp_misc, soft_purge, soft_purge, []},
+ {load_module, snmp_config, soft_purge, soft_purge, []},
+ {load_module, snmpa_mpd, soft_purge, soft_purge, [snmp_conf]},
+ {load_module, snmpa_trap, soft_purge, soft_purge,
+ [snmpa_mpd, snmp_notification_mib, snmp_target_mib, snmpa_net_if]},
+ {load_module, snmpa_acm, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd, snmp_target_mib]},
+ {load_module, snmpa_conf, soft_purge, soft_purge,
+ [snmp_notification_mib]},
+ {load_module, snmp_notification_mib, soft_purge, soft_purge,
+ [snmp_conf, snmp_target_mib]},
+ {load_module, snmp_community_mib, soft_purge, soft_purge, []},
+ {load_module, snmp_target_mib, soft_purge, soft_purge,
+ [snmp_conf]},
+
+ {update, snmpm_net_if, soft, soft_purge, soft_purge, []},
+ {update, snmpm_server, soft, soft_purge, soft_purge, [snmpm_net_if]},
+
+ {update, snmpa_net_if, soft, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd]},
+ {update, snmpa_agent, soft, soft_purge, soft_purge,
+ [snmpa_acm, snmpa_mpd, snmpa_trap]}
+ ]
+ },
{"4.18",
[
+ {load_module, snmpa, soft_purge, soft_purge, []},
+ {load_module, snmpm, soft_purge, soft_purge, [snmpm_server]},
+ {load_module, snmpa_usm, soft_purge, soft_purge, []},
+ {load_module, snmpm_usm, soft_purge, soft_purge, []},
{load_module, snmp_misc, soft_purge, soft_purge, []},
+ {load_module, snmp_log, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
+ {load_module, snmp_conf, soft_purge, soft_purge, []},
+ {load_module, snmpa_conf, soft_purge, soft_purge, [snmp_conf]},
+ {load_module, snmp_config, soft_purge, soft_purge, []},
+ {load_module, snmpa_mpd, soft_purge, soft_purge, [snmp_conf]},
{load_module, snmpa_vacm, soft_purge, soft_purge, []},
+ {load_module, snmpa_trap, soft_purge, soft_purge,
+ [snmpa_mpd, snmp_notification_mib, snmp_target_mib, snmpa_net_if]},
+ {load_module, snmpa_acm, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd, snmp_target_mib]},
{load_module, snmpa, soft_purge, soft_purge,
[snmp_community_mib,
snmp_framework_mib,
@@ -64,6 +168,8 @@
snmp_target_mib,
snmp_user_based_sm_mib,
snmp_view_based_acm_mib]},
+ {load_module, snmp_notification_mib, soft_purge, soft_purge,
+ [snmp_conf, snmp_target_mib, snmpa_mib_lib]},
{load_module, snmp_community_mib, soft_purge, soft_purge,
[snmpa_mib_lib]},
{load_module, snmp_framework_mib, soft_purge, soft_purge,
@@ -76,7 +182,15 @@
[snmpa_mib_lib]},
{load_module, snmp_view_based_acm_mib, soft_purge, soft_purge,
[snmpa_mib_lib, snmpa_vacm]},
- {load_module, snmpa_mib_lib, soft_purge, soft_purge, []}
+ {load_module, snmpa_mib_lib, soft_purge, soft_purge, []},
+
+ {update, snmpm_net_if, soft, soft_purge, soft_purge, []},
+ {update, snmpm_server, soft, soft_purge, soft_purge, [snmpm_net_if]},
+
+ {update, snmpa_net_if, soft, soft_purge, soft_purge,
+ [snmp_conf, snmpa_mpd]},
+ {update, snmpa_agent, soft, soft_purge, soft_purge,
+ [snmpa_acm, snmpa_mpd, snmpa_trap]}
]
}
]
diff --git a/lib/snmp/src/manager/snmpm.erl b/lib/snmp/src/manager/snmpm.erl
index 5b6321b4c3..e457d3b47a 100644
--- a/lib/snmp/src/manager/snmpm.erl
+++ b/lib/snmp/src/manager/snmpm.erl
@@ -57,15 +57,16 @@
usm_user_info/3, update_usm_user_info/4,
%%
- %% Basic SNMP API
- sync_get/3, sync_get/4, sync_get/5, sync_get/6,
- async_get/3, async_get/4, async_get/5, async_get/6,
- sync_get_next/3, sync_get_next/4, sync_get_next/5, sync_get_next/6,
- async_get_next/3, async_get_next/4, async_get_next/5, async_get_next/6,
- sync_set/3, sync_set/4, sync_set/5, sync_set/6,
- async_set/3, async_set/4, async_set/5, async_set/6,
- sync_get_bulk/5, sync_get_bulk/6, sync_get_bulk/7, sync_get_bulk/8,
- async_get_bulk/5, async_get_bulk/6, async_get_bulk/7, async_get_bulk/8,
+ %% Basic SNMP API (version "3").
+ sync_get2/3, sync_get2/4,
+ async_get2/3, async_get2/4,
+ sync_get_next2/3, sync_get_next2/4,
+ async_get_next2/3, async_get_next2/4,
+ sync_set2/3, sync_set2/4,
+ async_set2/3, async_set2/4,
+ sync_get_bulk2/5, sync_get_bulk2/6,
+ async_get_bulk2/5, async_get_bulk2/6,
+
cancel_async_request/2,
%%
@@ -91,7 +92,61 @@
-export([format_reason/1, format_reason/2]).
-%% Backward compatibillity exports
+%% Backward compatibility exports (API version "2")
+-export([
+ sync_get/3, sync_get/4, sync_get/5, sync_get/6,
+ async_get/3, async_get/4, async_get/5, async_get/6,
+ sync_get_next/3, sync_get_next/4, sync_get_next/5, sync_get_next/6,
+ async_get_next/3, async_get_next/4, async_get_next/5, async_get_next/6,
+ sync_set/3, sync_set/4, sync_set/5, sync_set/6,
+ async_set/3, async_set/4, async_set/5, async_set/6,
+ sync_get_bulk/5, sync_get_bulk/6, sync_get_bulk/7, sync_get_bulk/8,
+ async_get_bulk/5, async_get_bulk/6, async_get_bulk/7, async_get_bulk/8
+ ]).
+
+%% Backward compatibility exports (API version "1")
+-deprecated({agent_info, 3}).
+-deprecated({update_agent_info, 5}).
+-deprecated({g, 3}).
+-deprecated({g, 4}).
+-deprecated({g, 5}).
+-deprecated({g, 6}).
+-deprecated({g, 7}).
+-deprecated({ag, 3}).
+-deprecated({ag, 4}).
+-deprecated({ag, 5}).
+-deprecated({ag, 6}).
+-deprecated({ag, 7}).
+-deprecated({gn, 3}).
+-deprecated({gn, 4}).
+-deprecated({gn, 5}).
+-deprecated({gn, 6}).
+-deprecated({gn, 7}).
+-deprecated({agn, 3}).
+-deprecated({agn, 4}).
+-deprecated({agn, 5}).
+-deprecated({agn, 6}).
+-deprecated({agn, 7}).
+-deprecated({gb, 5}).
+-deprecated({gb, 6}).
+-deprecated({gb, 7}).
+-deprecated({gb, 8}).
+-deprecated({gb, 9}).
+-deprecated({agb, 5}).
+-deprecated({agb, 6}).
+-deprecated({agb, 7}).
+-deprecated({agb, 8}).
+-deprecated({agb, 9}).
+-deprecated({s, 3}).
+-deprecated({s, 4}).
+-deprecated({s, 5}).
+-deprecated({s, 6}).
+-deprecated({s, 7}).
+-deprecated({as, 3}).
+-deprecated({as, 4}).
+-deprecated({as, 5}).
+-deprecated({as, 6}).
+-deprecated({as, 7}).
-export([
agent_info/3, update_agent_info/5,
g/3, g/4, g/5, g/6, g/7,
@@ -108,12 +163,12 @@
-export([start_link/3, snmpm_start_verify/2, snmpm_start_verify/3]).
--include("snmp_debug.hrl").
+-include_lib("snmp/src/misc/snmp_debug.hrl").
+-include_lib("snmp/include/snmp_types.hrl").
-include("snmpm_atl.hrl").
--include("snmp_types.hrl").
+-include("snmpm_internal.hrl").
-define(DEFAULT_AGENT_PORT, 161).
--define(DEFAULT_CONTEXT, "").
%% This function is called when the snmp application
@@ -332,23 +387,23 @@ register_agent(UserId, TargetName, Config)
is_list(Config)) ->
do_register_agent(UserId, TargetName, [{reg_type, target_name} | Config]);
-%% Backward compatibillity
+%% Backward compatibility
%% Note that the agent engine id is a mandatory config option,
%% so this function *will* fail!
register_agent(UserId, Addr, Port) when is_integer(Port) ->
register_agent(UserId, Addr, Port, []);
-%% Backward compatibillity
+%% Backward compatibility
register_agent(UserId, Addr, Config) when is_list(Config) ->
register_agent(UserId, Addr, ?DEFAULT_AGENT_PORT, Config).
-%% Backward compatibillity
+%% Backward compatibility
%% Note that the agent engine id is a mandatory config option,
%% so this function *will* fail!
register_agent(UserId, Addr) ->
register_agent(UserId, Addr, ?DEFAULT_AGENT_PORT, []).
-%% Backward compatibillity
+%% Backward compatibility
register_agent(UserId, Addr, Port, Config0) ->
case lists:keymember(target_name, 1, Config0) of
false ->
@@ -368,7 +423,7 @@ register_agent(UserId, Addr, Port, Config0) ->
unregister_agent(UserId, TargetName) when is_list(TargetName) ->
snmpm_config:unregister_agent(UserId, TargetName);
-%% Backward compatibillity functions
+%% Backward compatibility functions
unregister_agent(UserId, Addr) ->
unregister_agent(UserId, Addr, ?DEFAULT_AGENT_PORT).
@@ -383,7 +438,7 @@ unregister_agent(UserId, Addr, Port) ->
agent_info(TargetName, Item) ->
snmpm_config:agent_info(TargetName, Item).
-%% Backward compatibillity
+%% Backward compatibility
agent_info(Addr, Port, Item) ->
case target_name(Addr, Port) of
{ok, TargetName} ->
@@ -393,24 +448,12 @@ agent_info(Addr, Port, Item) ->
end.
update_agent_info(UserId, TargetName, Item, Val) ->
-%% p("update_agent_info -> entry with"
-%% "~n UserId: ~p"
-%% "~n TargetName: ~p"
-%% "~n Item: ~p"
-%% "~n Val: ~p", [UserId, TargetName, Item, Val]),
snmpm_config:update_agent_info(UserId, TargetName, Item, Val).
-%% Backward compatibillity functions
+%% Backward compatibility functions
update_agent_info(UserId, Addr, Port, Item, Val) ->
-%% p("update_agent_info -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Port: ~p"
-%% "~n Item: ~p"
-%% "~n Val: ~p", [UserId, Addr, Port, Item, Val]),
case target_name(Addr, Port) of
{ok, TargetName} ->
-%% p("update_agent_info -> TargetName: ~p", [TargetName]),
update_agent_info(UserId, TargetName, Item, Val);
Error ->
Error
@@ -472,94 +515,54 @@ which_usm_users(EngineID) when is_list(EngineID) ->
%% --- synchroneous get-request ---
%%
+sync_get2(UserId, TargetName, Oids) ->
+ sync_get2(UserId, TargetName, Oids, []).
+
+sync_get2(UserId, TargetName, Oids, SendOpts)
+ when is_list(Oids) andalso is_list(SendOpts) ->
+ snmpm_server:sync_get2(UserId, TargetName, Oids, SendOpts).
+
+%% <BACKWARD-COMPAT>
sync_get(UserId, TargetName, Oids) ->
-%% p("sync_get -> entry with"
-%% "~n UserId: ~p"
-%% "~n TargetName: ~p"
-%% "~n Oids: ~p", [UserId, TargetName, Oids]),
- sync_get(UserId, TargetName, ?DEFAULT_CONTEXT, Oids).
-
-sync_get(UserId, TargetName, Context, Oids) when is_list(Oids) ->
-%% p("sync_get -> entry with"
-%% "~n UserId: ~p"
-%% "~n TargetName: ~p"
-%% "~n Context: ~p"
-%% "~n Oids: ~p", [UserId, TargetName, Context, Oids]),
- snmpm_server:sync_get(UserId, TargetName, Context, Oids);
-
-sync_get(UserId, TargetName, Oids, Timeout) when is_integer(Timeout) ->
-%% p("sync_get -> entry with"
-%% "~n UserId: ~p"
-%% "~n TargetName: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p", [UserId, TargetName, Oids, Timeout]),
- sync_get(UserId, TargetName, ?DEFAULT_CONTEXT, Oids, Timeout).
+ sync_get2(UserId, TargetName, Oids).
+
+sync_get(UserId, TargetName, Oids, Timeout)
+ when is_list(Oids) andalso is_integer(Timeout) ->
+ SendOpts = [{timeout, Timeout}],
+ sync_get2(UserId, TargetName, Oids, SendOpts);
+sync_get(UserId, TargetName, Context, [OH|_] = Oids)
+ when is_list(Context) andalso is_list(OH) ->
+ SendOpts = [{context, Context}],
+ sync_get2(UserId, TargetName, Oids, SendOpts).
sync_get(UserId, TargetName, Context, Oids, Timeout) ->
-%% p("sync_get -> entry with"
-%% "~n UserId: ~p"
-%% "~n TargetName: ~p"
-%% "~n Context: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p", [UserId, TargetName, Context, Oids, Timeout]),
- snmpm_server:sync_get(UserId, TargetName, Context, Oids, Timeout).
+ SendOpts = [{context, Context}, {timeout, Timeout}],
+ sync_get2(UserId, TargetName, Oids, SendOpts).
sync_get(UserId, TargetName, Context, Oids, Timeout, ExtraInfo) ->
-%% p("sync_get -> entry with"
-%% "~n UserId: ~p"
-%% "~n TargetName: ~p"
-%% "~n Context: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p"
-%% "~n ExtraInfo: ~p",
-%% [UserId, TargetName, Context, Oids, Timeout, ExtraInfo]),
- snmpm_server:sync_get(UserId, TargetName, Context, Oids, Timeout,
- ExtraInfo).
+ SendOpts = [{context, Context}, {timeout, Timeout}, {extra, ExtraInfo}],
+ sync_get2(UserId, TargetName, Oids, SendOpts).
+%% </BACKWARD-COMPAT>
+%% <DEPRECATED>
g(UserId, Addr, Oids) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Oids: ~p", [UserId, Addr, Oids]),
g(UserId, Addr, ?DEFAULT_AGENT_PORT, Oids).
g(UserId, Addr, CtxName, Oids) when is_list(CtxName) andalso is_list(Oids) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n CtxName: ~p"
-%% "~n Oids: ~p", [UserId, Addr, CtxName, Oids]),
g(UserId, Addr, ?DEFAULT_AGENT_PORT, CtxName, Oids);
g(UserId, Addr, Port, Oids) when is_integer(Port) andalso is_list(Oids) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Port: ~p"
-%% "~n Oids: ~p", [UserId, Addr, Port, Oids]),
g(UserId, Addr, Port, ?DEFAULT_CONTEXT, Oids);
g(UserId, Addr, Oids, Timeout)
when is_list(Oids) andalso is_integer(Timeout) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p", [UserId, Addr, Oids, Timeout]),
g(UserId, Addr, ?DEFAULT_AGENT_PORT, Oids, Timeout).
g(UserId, Addr, Port, CtxName, Oids)
when is_integer(Port) andalso is_list(CtxName) andalso is_list(Oids) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Port: ~p"
-%% "~n Context: ~p"
-%% "~n Oids: ~p", [UserId, Addr, Port, CtxName, Oids]),
case target_name(Addr, Port) of
{ok, TargetName} ->
-%% p("g -> TargetName: ~p", [TargetName]),
sync_get(UserId, TargetName, CtxName, Oids);
Error ->
Error
@@ -567,59 +570,28 @@ g(UserId, Addr, Port, CtxName, Oids)
g(UserId, Addr, Port, Oids, Timeout)
when is_integer(Port) andalso is_list(Oids) andalso is_integer(Timeout) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p",
-%% [UserId, Addr, Oids, Timeout]),
g(UserId, Addr, Port, ?DEFAULT_CONTEXT, Oids, Timeout);
g(UserId, Addr, CtxName, Oids, Timeout)
when is_list(CtxName) andalso is_list(Oids) andalso is_integer(Timeout) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n CtxName: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p",
-%% [UserId, Addr, CtxName, Oids, Timeout]),
g(UserId, Addr, ?DEFAULT_AGENT_PORT, CtxName, Oids, Timeout).
g(UserId, Addr, Port, CtxName, Oids, Timeout) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Port: ~p"
-%% "~n CtxName: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p",
-%% [UserId, Addr, Port, CtxName, Oids, Timeout]),
case target_name(Addr, Port) of
{ok, TargetName} ->
-%% p("g -> TargetName: ~p", [TargetName]),
sync_get(UserId, TargetName, CtxName, Oids, Timeout);
Error ->
Error
end.
g(UserId, Addr, Port, CtxName, Oids, Timeout, ExtraInfo) ->
-%% p("g -> entry with"
-%% "~n UserId: ~p"
-%% "~n Addr: ~p"
-%% "~n Port: ~p"
-%% "~n CtxName: ~p"
-%% "~n Oids: ~p"
-%% "~n Timeout: ~p"
-%% "~n ExtraInfo: ~p",
-%% [UserId, Addr, Port, CtxName, Oids, Timeout, ExtraInfo]),
case target_name(Addr, Port) of
{ok, TargetName} ->
-%% p("g -> TargetName: ~p", [TargetName]),
sync_get(UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo);
Error ->
Error
end.
+%% </DEPRECATED>
@@ -629,23 +601,36 @@ g(UserId, Addr, Port, CtxName, Oids, Timeout, ExtraInfo) ->
%% through a call to handle_pdu/5
%%
-async_get(UserId, TargetName, Oids) ->
- async_get(UserId, TargetName, ?DEFAULT_CONTEXT, Oids).
+async_get2(UserId, TargetName, Oids) ->
+ async_get2(UserId, TargetName, Oids, []).
+
+async_get2(UserId, TargetName, Oids, SendOpts)
+ when is_list(Oids) andalso is_list(SendOpts) ->
+ snmpm_server:async_get2(UserId, TargetName, Oids, SendOpts).
-async_get(UserId, TargetName, Context, Oids) when is_list(Oids) ->
- snmpm_server:async_get(UserId, TargetName, Context, Oids);
+%% <BACKWARD-COMPAT>
+async_get(UserId, TargetName, Oids) ->
+ async_get2(UserId, TargetName, Oids).
async_get(UserId, TargetName, Oids, Expire) when is_integer(Expire) ->
- async_get(UserId, TargetName, ?DEFAULT_CONTEXT, Oids, Expire).
+ SendOpts = [{timeout, Expire}],
+ async_get2(UserId, TargetName, Oids, SendOpts);
+async_get(UserId, TargetName, Context, Oids)
+ when is_list(Context) andalso is_list(Oids) ->
+ SendOpts = [{context, Context}],
+ async_get2(UserId, TargetName, Oids, SendOpts).
async_get(UserId, TargetName, Context, Oids, Expire) ->
- snmpm_server:async_get(UserId, TargetName, Context, Oids, Expire).
+ SendOpts = [{timeout, Expire}, {context, Context}],
+ async_get2(UserId, TargetName, Oids, SendOpts).
async_get(UserId, TargetName, Context, Oids, Expire, ExtraInfo) ->
- snmpm_server:async_get(UserId, TargetName, Context, Oids, Expire,
- ExtraInfo).
+ SendOpts = [{timeout, Expire}, {context, Context}, {extra, ExtraInfo}],
+ async_get2(UserId, TargetName, Oids, SendOpts).
+%% </BACKWARD-COMPAT>
+%% <DEPRECATED>
ag(UserId, Addr, Oids) ->
ag(UserId, Addr, ?DEFAULT_AGENT_PORT, Oids).
@@ -690,31 +675,44 @@ ag(UserId, Addr, Port, CtxName, Oids, Expire, ExtraInfo) ->
Error ->
Error
end.
+%% </DEPRECATED>
%% --- synchroneous get_next-request ---
%%
-sync_get_next(UserId, TargetName, Oids) ->
- sync_get_next(UserId, TargetName, ?DEFAULT_CONTEXT, Oids).
+sync_get_next2(UserId, TargetName, Oids) ->
+ sync_get_next2(UserId, TargetName, Oids, []).
-sync_get_next(UserId, TargetName, Context, Oids)
- when is_list(Context) andalso is_list(Oids) ->
- snmpm_server:sync_get_next(UserId, TargetName, Context, Oids);
+sync_get_next2(UserId, TargetName, Oids, SendOpts)
+ when is_list(Oids) andalso is_list(SendOpts) ->
+ snmpm_server:sync_get_next2(UserId, TargetName, Oids, SendOpts).
+
+%% <BACKWARD-COMPAT>
+sync_get_next(UserId, TargetName, Oids) ->
+ sync_get_next2(UserId, TargetName, Oids).
sync_get_next(UserId, TargetName, Oids, Timeout)
when is_list(Oids) andalso is_integer(Timeout) ->
- sync_get_next(UserId, TargetName, ?DEFAULT_CONTEXT, Oids, Timeout).
+ SendOpts = [{timeout, Timeout}],
+ sync_get_next2(UserId, TargetName, Oids, SendOpts);
+sync_get_next(UserId, TargetName, Context, Oids)
+ when is_list(Context) andalso is_list(Oids) ->
+ SendOpts = [{context, Context}],
+ sync_get_next2(UserId, TargetName, Oids, SendOpts).
sync_get_next(UserId, TargetName, Context, Oids, Timeout) ->
- snmpm_server:sync_get_next(UserId, TargetName, Context, Oids, Timeout).
+ SendOpts = [{timeout, Timeout}, {context, Context}],
+ sync_get_next2(UserId, TargetName, Oids, SendOpts).
sync_get_next(UserId, TargetName, Context, Oids, Timeout, ExtraInfo) ->
- snmpm_server:sync_get_next(UserId, TargetName, Context, Oids, Timeout,
- ExtraInfo).
+ SendOpts = [{timeout, Timeout}, {context, Context}, {extra, ExtraInfo}],
+ sync_get_next2(UserId, TargetName, Oids, SendOpts).
+%% </BACKWARD-COMPAT>
+%% <DEPRECATED>
gn(UserId, Addr, Oids) ->
gn(UserId, Addr, ?DEFAULT_AGENT_PORT, Oids).
@@ -759,30 +757,44 @@ gn(UserId, Addr, Port, CtxName, Oids, Timeout, ExtraInfo) ->
Error ->
Error
end.
+%% </DEPRECATED>
%% --- asynchroneous get_next-request ---
%%
+async_get_next2(UserId, TargetName, Oids) ->
+ async_get_next2(UserId, TargetName, Oids, []).
+
+async_get_next2(UserId, TargetName, Oids, SendOpts)
+ when is_list(Oids) andalso is_list(SendOpts) ->
+ snmpm_server:async_get_next2(UserId, TargetName, Oids, SendOpts).
+
+%% <BACKWARD-COMPAT>
async_get_next(UserId, TargetName, Oids) ->
- async_get_next(UserId, TargetName, ?DEFAULT_CONTEXT, Oids).
+ async_get_next2(UserId, TargetName, Oids).
+async_get_next(UserId, TargetName, Oids, Expire)
+ when is_list(Oids) andalso is_integer(Expire) ->
+ SendOpts = [{timeout, Expire}],
+ async_get_next2(UserId, TargetName, Oids, SendOpts);
async_get_next(UserId, TargetName, Context, Oids)
when is_list(Context) andalso is_list(Oids) ->
- snmpm_server:async_get_next(UserId, TargetName, Context, Oids);
+ SendOpts = [{context, Context}],
+ async_get_next2(UserId, TargetName, Oids, SendOpts).
-async_get_next(UserId, TargetName, Oids, Timeout)
- when is_list(Oids) andalso is_integer(Timeout) ->
- async_get_next(UserId, TargetName, ?DEFAULT_CONTEXT, Oids, Timeout).
+async_get_next(UserId, TargetName, Context, Oids, Expire) ->
+ SendOpts = [{timeout, Expire}, {context, Context}],
+ async_get_next2(UserId, TargetName, Oids, SendOpts).
-async_get_next(UserId, TargetName, Context, Oids, Timeout) ->
- snmpm_server:async_get_next(UserId, TargetName, Context, Oids, Timeout).
+async_get_next(UserId, TargetName, Context, Oids, Expire, ExtraInfo) ->
+ SendOpts = [{timeout, Expire}, {context, Context}, {extra, ExtraInfo}],
+ async_get_next2(UserId, TargetName, Oids, SendOpts).
+%% </BACKWARD-COMPAT>
-async_get_next(UserId, TargetName, Context, Oids, Timeout, ExtraInfo) ->
- snmpm_server:async_get_next(UserId, TargetName, Context, Oids, Timeout,
- ExtraInfo).
+%% <DEPRECATED>
agn(UserId, Addr, Oids) ->
agn(UserId, Addr, ?DEFAULT_AGENT_PORT, Oids).
@@ -828,31 +840,44 @@ agn(UserId, Addr, Port, CtxName, Oids, Expire, ExtraInfo) ->
Error ->
Error
end.
+%% </DEPRECATED>
%% --- synchroneous set-request ---
%%
-sync_set(UserId, TargetName, VarsAndVals) ->
- sync_set(UserId, TargetName, ?DEFAULT_CONTEXT, VarsAndVals).
+sync_set2(UserId, TargetName, VarsAndVals) ->
+ sync_set2(UserId, TargetName, VarsAndVals, []).
-sync_set(UserId, TargetName, Context, VarsAndVals)
- when is_list(Context) andalso is_list(VarsAndVals) ->
- snmpm_server:sync_set(UserId, TargetName, Context, VarsAndVals);
+sync_set2(UserId, TargetName, VarsAndVals, SendOpts)
+ when is_list(VarsAndVals) andalso is_list(SendOpts) ->
+ snmpm_server:sync_set2(UserId, TargetName, VarsAndVals, SendOpts).
+
+%% <BACKWARD-COMPAT>
+sync_set(UserId, TargetName, VarsAndVals) ->
+ sync_set2(UserId, TargetName, VarsAndVals).
sync_set(UserId, TargetName, VarsAndVals, Timeout)
when is_list(VarsAndVals) andalso is_integer(Timeout) ->
- sync_set(UserId, TargetName, ?DEFAULT_CONTEXT, VarsAndVals, Timeout).
+ SendOpts = [{timeout, Timeout}],
+ sync_set2(UserId, TargetName, VarsAndVals, SendOpts);
+sync_set(UserId, TargetName, Context, VarsAndVals)
+ when is_list(Context) andalso is_list(VarsAndVals) ->
+ SendOpts = [{context, Context}],
+ sync_set2(UserId, TargetName, VarsAndVals, SendOpts).
sync_set(UserId, TargetName, Context, VarsAndVals, Timeout) ->
- snmpm_server:sync_set(UserId, TargetName, Context, VarsAndVals, Timeout).
+ SendOpts = [{timeout, Timeout}, {context, Context}],
+ sync_set2(UserId, TargetName, VarsAndVals, SendOpts).
sync_set(UserId, TargetName, Context, VarsAndVals, Timeout, ExtraInfo) ->
- snmpm_server:sync_set(UserId, TargetName, Context, VarsAndVals, Timeout,
- ExtraInfo).
+ SendOpts = [{timeout, Timeout}, {context, Context}, {extra, ExtraInfo}],
+ sync_set2(UserId, TargetName, VarsAndVals, SendOpts).
+%% </BACKWARD-COMPAT>
+%% <DEPRECATED>
s(UserId, Addr, VarsAndVals) ->
s(UserId, Addr, ?DEFAULT_AGENT_PORT, VarsAndVals).
@@ -906,31 +931,44 @@ s(UserId, Addr, Port, CtxName, VarsAndVals, Timeout, ExtraInfo) ->
Error ->
Error
end.
+%% </DEPRECATED>
%% --- asynchroneous set-request ---
%%
-async_set(UserId, TargetName, VarsAndVals) ->
- async_set(UserId, TargetName, ?DEFAULT_CONTEXT, VarsAndVals).
+async_set2(UserId, TargetName, VarsAndVals) ->
+ async_set2(UserId, TargetName, VarsAndVals, []).
-async_set(UserId, TargetName, Context, VarsAndVals)
- when is_list(Context) andalso is_list(VarsAndVals) ->
- snmpm_server:async_set(UserId, TargetName, Context, VarsAndVals);
+async_set2(UserId, TargetName, VarsAndVals, SendOpts)
+ when is_list(VarsAndVals) andalso is_list(SendOpts) ->
+ snmpm_server:async_set2(UserId, TargetName, VarsAndVals, SendOpts).
+
+%% <BACKWARD-COMPAT>
+async_set(UserId, TargetName, VarsAndVals) ->
+ async_set2(UserId, TargetName, VarsAndVals).
async_set(UserId, TargetName, VarsAndVals, Expire)
when is_list(VarsAndVals) andalso is_integer(Expire) ->
- async_set(UserId, TargetName, ?DEFAULT_CONTEXT, VarsAndVals, Expire).
+ SendOpts = [{timeout, Expire}],
+ async_set2(UserId, TargetName, VarsAndVals, SendOpts);
+async_set(UserId, TargetName, Context, VarsAndVals)
+ when is_list(Context) andalso is_list(VarsAndVals) ->
+ SendOpts = [{context, Context}],
+ async_set2(UserId, TargetName, VarsAndVals, SendOpts).
async_set(UserId, TargetName, Context, VarsAndVals, Expire) ->
- snmpm_server:async_set(UserId, TargetName, Context, VarsAndVals, Expire).
+ SendOpts = [{timeout, Expire}, {context, Context}],
+ async_set2(UserId, TargetName, VarsAndVals, SendOpts).
async_set(UserId, TargetName, Context, VarsAndVals, Expire, ExtraInfo) ->
- snmpm_server:async_set(UserId, TargetName, Context, VarsAndVals, Expire,
- ExtraInfo).
+ SendOpts = [{timeout, Expire}, {context, Context}, {extra, ExtraInfo}],
+ async_set2(UserId, TargetName, VarsAndVals, SendOpts).
+%% </BACKWARD-COMPAT>
+%% <DEPRECATED>
as(UserId, Addr, VarsAndVals) ->
as(UserId, Addr, ?DEFAULT_AGENT_PORT, VarsAndVals).
@@ -984,44 +1022,77 @@ as(UserId, Addr, Port, CtxName, VarsAndVals, Expire, ExtraInfo) ->
Error ->
Error
end.
-
-
+%% </DEPRECATED>
%% --- synchroneous get-bulk ---
%%
-sync_get_bulk(UserId, TargetName, NonRep, MaxRep, Oids) ->
- sync_get_bulk(UserId, TargetName, NonRep, MaxRep, ?DEFAULT_CONTEXT, Oids).
+sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids) ->
+ sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, []).
-sync_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids)
+sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts)
when is_integer(NonRep) andalso
is_integer(MaxRep) andalso
- is_list(Context) andalso
- is_list(Oids) ->
- snmpm_server:sync_get_bulk(UserId, TargetName,
- NonRep, MaxRep,
- Context, Oids);
+ is_list(Oids) andalso
+ is_list(SendOpts) ->
+ %% p("sync_get_bulk -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n TargetName: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n Oids: ~p"
+ %% "~n SendOpts: ~p",
+ %% [UserId, TargetName, NonRep, MaxRep, Oids, SendOpts]),
+ snmpm_server:sync_get_bulk2(UserId, TargetName,
+ NonRep, MaxRep, Oids, SendOpts).
+
+%% <BACKWARD-COMPAT>
+sync_get_bulk(UserId, TargetName, NonRep, MaxRep, Oids) ->
+ sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids).
sync_get_bulk(UserId, TargetName, NonRep, MaxRep, Oids, Timeout)
when is_integer(NonRep) andalso
is_integer(MaxRep) andalso
is_list(Oids) andalso
is_integer(Timeout) ->
- sync_get_bulk(UserId, TargetName, NonRep, MaxRep,
- ?DEFAULT_CONTEXT, Oids, Timeout).
+ SendOpts = [{timeout, Timeout}],
+ sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts);
+sync_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids)
+ when is_integer(NonRep) andalso
+ is_integer(MaxRep) andalso
+ is_list(Context) andalso
+ is_list(Oids) ->
+ %% p("sync_get_bulk -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n TargetName: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n Context: ~p"
+ %% "~n Oids: ~p", [UserId, TargetName, NonRep, MaxRep, Context, Oids]),
+ SendOpts = [{context, Context}],
+ sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
sync_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids, Timeout) ->
- snmpm_server:sync_get_bulk(UserId, TargetName, NonRep, MaxRep,
- Context, Oids, Timeout).
+ SendOpts = [{timeout, Timeout}, {context, Context}],
+ sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
sync_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids, Timeout,
ExtraInfo) ->
- snmpm_server:sync_get_bulk(UserId, TargetName, NonRep, MaxRep,
- Context, Oids, Timeout, ExtraInfo).
+ SendOpts = [{timeout, Timeout}, {context, Context}, {extra, ExtraInfo}],
+ sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
+%% </BACKWARD-COMPAT>
+%% <DEPRECATED>
gb(UserId, Addr, NonRep, MaxRep, Oids) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n Oids: ~p",
+ %% [UserId, Addr, NonRep, MaxRep, Oids]),
gb(UserId, Addr, ?DEFAULT_AGENT_PORT, NonRep, MaxRep, Oids).
gb(UserId, Addr, Port, NonRep, MaxRep, Oids)
@@ -1029,6 +1100,14 @@ gb(UserId, Addr, Port, NonRep, MaxRep, Oids)
is_integer(NonRep) andalso
is_integer(MaxRep) andalso
is_list(Oids) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n Port: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n Oids: ~p",
+ %% [UserId, Addr, Port, NonRep, MaxRep, Oids]),
gb(UserId, Addr, Port, NonRep, MaxRep, ?DEFAULT_CONTEXT, Oids);
gb(UserId, Addr, NonRep, MaxRep, CtxName, Oids)
@@ -1036,6 +1115,14 @@ gb(UserId, Addr, NonRep, MaxRep, CtxName, Oids)
is_integer(MaxRep) andalso
is_list(CtxName) andalso
is_list(Oids) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n CtxName: ~p"
+ %% "~n Oids: ~p",
+ %% [UserId, Addr, NonRep, MaxRep, CtxName, Oids]),
gb(UserId, Addr, ?DEFAULT_AGENT_PORT, NonRep, MaxRep, CtxName, Oids);
gb(UserId, Addr, NonRep, MaxRep, Oids, Timeout)
@@ -1043,6 +1130,14 @@ gb(UserId, Addr, NonRep, MaxRep, Oids, Timeout)
is_integer(MaxRep) andalso
is_list(Oids) andalso
is_integer(Timeout) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n Oids: ~p"
+ %% "~n Timeout: ~p",
+ %% [UserId, Addr, NonRep, MaxRep, Oids, Timeout]),
gb(UserId, Addr, ?DEFAULT_AGENT_PORT, NonRep, MaxRep, Oids, Timeout).
gb(UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids)
@@ -1051,8 +1146,18 @@ gb(UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids)
is_integer(MaxRep) andalso
is_list(CtxName) andalso
is_list(Oids) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n Port: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n CtxName: ~p"
+ %% "~n Oids: ~p",
+ %% [UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids]),
case target_name(Addr, Port) of
{ok, TargetName} ->
+ %% p("gb -> TargetName: ~p", [TargetName]),
sync_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids);
Error ->
Error
@@ -1064,6 +1169,15 @@ gb(UserId, Addr, Port, NonRep, MaxRep, Oids, Timeout)
is_integer(MaxRep) andalso
is_list(Oids) andalso
is_integer(Timeout) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n Port: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n Oids: ~p"
+ %% "~n Timeout: ~p",
+ %% [UserId, Addr, Port, NonRep, MaxRep, Oids, Timeout]),
gb(UserId, Addr, Port, NonRep, MaxRep, ?DEFAULT_CONTEXT, Oids, Timeout);
gb(UserId, Addr, NonRep, MaxRep, CtxName, Oids, Timeout)
@@ -1072,10 +1186,29 @@ gb(UserId, Addr, NonRep, MaxRep, CtxName, Oids, Timeout)
is_list(CtxName) andalso
is_list(Oids) andalso
is_integer(Timeout) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n CtxName: ~p"
+ %% "~n Oids: ~p"
+ %% "~n Timeout: ~p",
+ %% [UserId, Addr, NonRep, MaxRep, CtxName, Oids, Timeout]),
gb(UserId, Addr, ?DEFAULT_AGENT_PORT, NonRep, MaxRep, CtxName, Oids,
Timeout).
gb(UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids, Timeout) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n Port: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n CtxName: ~p"
+ %% "~n Oids: ~p"
+ %% "~n Timeout: ~p",
+ %% [UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids, Timeout]),
case target_name(Addr, Port) of
{ok, TargetName} ->
sync_get_bulk(UserId, TargetName,
@@ -1085,6 +1218,17 @@ gb(UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids, Timeout) ->
end.
gb(UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids, Timeout, ExtraInfo) ->
+ %% p("gb -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n Addr: ~p"
+ %% "~n Port: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n CtxName: ~p"
+ %% "~n Oids: ~p"
+ %% "~n Timeout: ~p"
+ %% "~n ExtraInfo: ~p",
+ %% [UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids, Timeout, ExtraInfo]),
case target_name(Addr, Port) of
{ok, TargetName} ->
sync_get_bulk(UserId, TargetName,
@@ -1092,42 +1236,55 @@ gb(UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids, Timeout, ExtraInfo) ->
Error ->
Error
end.
+%% </DEPRECATED>
%% --- asynchroneous get-bulk ---
%%
-async_get_bulk(UserId, TargetName, NonRep, MaxRep, Oids) ->
- async_get_bulk(UserId, TargetName, NonRep, MaxRep, ?DEFAULT_CONTEXT, Oids).
+async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids) ->
+ async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, []).
-async_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids)
+async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts)
when is_integer(NonRep) andalso
is_integer(MaxRep) andalso
- is_list(Context) andalso
- is_list(Oids) ->
- snmpm_server:async_get_bulk(UserId, TargetName,
- NonRep, MaxRep, Context, Oids);
+ is_list(Oids) andalso
+ is_list(SendOpts) ->
+ snmpm_server:async_get_bulk2(UserId, TargetName,
+ NonRep, MaxRep, Oids, SendOpts).
+
+%% <BACKWARD-COMPAT>
+async_get_bulk(UserId, TargetName, NonRep, MaxRep, Oids) ->
+ async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids).
async_get_bulk(UserId, TargetName, NonRep, MaxRep, Oids, Expire)
when is_integer(NonRep) andalso
is_integer(MaxRep) andalso
is_list(Oids) andalso
is_integer(Expire) ->
- async_get_bulk(UserId, TargetName,
- NonRep, MaxRep, ?DEFAULT_CONTEXT, Oids, Expire).
+ SendOpts = [{timeout, Expire}],
+ async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts);
+async_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids)
+ when is_integer(NonRep) andalso
+ is_integer(MaxRep) andalso
+ is_list(Context) andalso
+ is_list(Oids) ->
+ SendOpts = [{context, Context}],
+ async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
async_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids, Expire) ->
- snmpm_server:async_get_bulk(UserId, TargetName,
- NonRep, MaxRep, Context, Oids, Expire).
+ SendOpts = [{timeout, Expire}, {context, Context}],
+ async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
async_get_bulk(UserId, TargetName, NonRep, MaxRep, Context, Oids, Expire,
ExtraInfo) ->
- snmpm_server:async_get_bulk(UserId, TargetName,
- NonRep, MaxRep,
- Context, Oids, Expire, ExtraInfo).
+ SendOpts = [{timeout, Expire}, {context, Context}, {extra, ExtraInfo}],
+ async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
+%% </BACKWARD-COMPAT>
+%% <DEPRECATED>
agb(UserId, Addr, NonRep, MaxRep, Oids) ->
agb(UserId, Addr, ?DEFAULT_AGENT_PORT, NonRep, MaxRep, Oids).
@@ -1200,6 +1357,7 @@ agb(UserId, Addr, Port, NonRep, MaxRep, CtxName, Oids, Expire, ExtraInfo) ->
Error ->
Error
end.
+%% </DEPRECATED>
cancel_async_request(UserId, ReqId) ->
@@ -1207,7 +1365,7 @@ cancel_async_request(UserId, ReqId) ->
%%%-----------------------------------------------------------------
-%%% Audit Trail Log functions (for backward compatibillity)
+%%% Audit Trail Log functions (for backward compatibility)
%%%-----------------------------------------------------------------
log_to_txt(LogDir, Mibs) ->
OutFile = "snmpm_log.txt",
diff --git a/lib/snmp/src/manager/snmpm_internal.hrl b/lib/snmp/src/manager/snmpm_internal.hrl
index 5d9b32e3f6..53ad41c6b0 100644
--- a/lib/snmp/src/manager/snmpm_internal.hrl
+++ b/lib/snmp/src/manager/snmpm_internal.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2006-2009. All Rights Reserved.
+%% 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
@@ -20,6 +20,11 @@
-ifndef(snmpm_internal).
-define(snmpm_internal, true).
+-define(DEFAULT_CONTEXT, "").
+-define(SNMPM_EXTRA_INFO_TAG, snmpm_extra_info_tag).
+-define(DEFAULT_EXTRA_INFO, {?SNMPM_EXTRA_INFO_TAG}).
+
+
-include_lib("snmp/src/app/snmp_internal.hrl").
-define(snmpm_info(F, A), ?snmp_info("manager", F, A)).
diff --git a/lib/snmp/src/manager/snmpm_net_if.erl b/lib/snmp/src/manager/snmpm_net_if.erl
index 07156dacd9..3d248fff57 100644
--- a/lib/snmp/src/manager/snmpm_net_if.erl
+++ b/lib/snmp/src/manager/snmpm_net_if.erl
@@ -99,7 +99,7 @@ stop(Pid) ->
call(Pid, stop).
send_pdu(Pid, Pdu, Vsn, MsgData, Addr, Port) ->
- send_pdu(Pid, Pdu, Vsn, MsgData, Addr, Port, undefined).
+ send_pdu(Pid, Pdu, Vsn, MsgData, Addr, Port, ?DEFAULT_EXTRA_INFO).
send_pdu(Pid, Pdu, Vsn, MsgData, Addr, Port, ExtraInfo)
when is_record(Pdu, pdu) ->
@@ -380,13 +380,14 @@ handle_call(Req, From, State) ->
%% {noreply, State, Timeout} |
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
-handle_cast({send_pdu, Pdu, Vsn, MsgData, Addr, Port, _ExtraInfo}, State) ->
+handle_cast({send_pdu, Pdu, Vsn, MsgData, Addr, Port, ExtraInfo}, State) ->
?vlog("received send_pdu message with"
"~n Pdu: ~p"
"~n Vsn: ~p"
"~n MsgData: ~p"
"~n Addr: ~p"
"~n Port: ~p", [Pdu, Vsn, MsgData, Addr, Port]),
+ maybe_process_extra_info(ExtraInfo),
maybe_handle_send_pdu(Pdu, Vsn, MsgData, Addr, Port, State),
{noreply, State};
@@ -999,6 +1000,19 @@ pdu_type_of(TrapPdu) when is_record(TrapPdu, trappdu) ->
%% -------------------------------------------------------------------
+%% At this point this function is used during testing
+maybe_process_extra_info(?DEFAULT_EXTRA_INFO) ->
+ ok;
+maybe_process_extra_info({?SNMPM_EXTRA_INFO_TAG, Fun})
+ when is_function(Fun, 0) ->
+ (catch Fun()),
+ ok;
+maybe_process_extra_info(_ExtraInfo) ->
+ ok.
+
+
+%% -------------------------------------------------------------------
+
t() ->
{A,B,C} = erlang:now(),
A*1000000000+B*1000+(C div 1000).
diff --git a/lib/snmp/src/manager/snmpm_server.erl b/lib/snmp/src/manager/snmpm_server.erl
index d64b5b1d53..b8d7cf6375 100644
--- a/lib/snmp/src/manager/snmpm_server.erl
+++ b/lib/snmp/src/manager/snmpm_server.erl
@@ -32,14 +32,14 @@
register_user/4, register_user_monitor/4, unregister_user/1,
- sync_get/4, sync_get/5, sync_get/6,
- async_get/4, async_get/5, async_get/6,
- sync_get_next/4, sync_get_next/5, sync_get_next/6,
- async_get_next/4, async_get_next/5, async_get_next/6,
- sync_get_bulk/6, sync_get_bulk/7, sync_get_bulk/8,
- async_get_bulk/6, async_get_bulk/7, async_get_bulk/8,
- sync_set/4, sync_set/5, sync_set/6,
- async_set/4, async_set/5, async_set/6,
+ sync_get2/4,
+ async_get2/4,
+ sync_get_next2/4,
+ async_get_next2/4,
+ sync_get_bulk2/6,
+ async_get_bulk2/6,
+ sync_set2/4,
+ async_set2/4,
cancel_async_request/2,
%% discovery/2, discovery/3, discovery/4, discovery/5, discovery/6,
@@ -55,6 +55,20 @@
]).
+%% <BACKWARD-COMPAT>
+-export([sync_get/4, sync_get/5, sync_get/6,
+ async_get/4, async_get/5, async_get/6,
+ sync_get_next/4, sync_get_next/5, sync_get_next/6,
+ async_get_next/4, async_get_next/5, async_get_next/6,
+ sync_get_bulk/6, sync_get_bulk/7, sync_get_bulk/8,
+ async_get_bulk/6, async_get_bulk/7, async_get_bulk/8,
+ sync_set/4, sync_set/5, sync_set/6,
+ async_set/4, async_set/5, async_set/6
+ ]).
+%% </BACKWARD-COMPAT>
+
+
+
%% Internal exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
code_change/3, terminate/2]).
@@ -75,13 +89,39 @@
-define(SERVER, ?MODULE).
--define(SYNC_GET_TIMEOUT, 5000).
--define(SYNC_SET_TIMEOUT, 5000).
--define(DEFAULT_ASYNC_EXPIRE, 5000).
--define(EXTRA_INFO, undefined).
-
--define(SNMP_AGENT_PORT, 161).
-
+-define(DEFAULT_SYNC_TIMEOUT, timer:seconds(5)).
+-define(DEFAULT_SYNC_GET_TIMEOUT, ?DEFAULT_SYNC_TIMEOUT).
+-define(DEFAULT_SYNC_GET_NEXT_TIMEOUT, ?DEFAULT_SYNC_TIMEOUT).
+-define(DEFAULT_SYNC_GET_BULK_TIMEOUT, ?DEFAULT_SYNC_TIMEOUT).
+-define(DEFAULT_SYNC_SET_TIMEOUT, ?DEFAULT_SYNC_TIMEOUT).
+
+-define(DEFAULT_ASYNC_TIMEOUT, timer:seconds(5)).
+-define(DEFAULT_ASYNC_GET_TIMEOUT, ?DEFAULT_ASYNC_TIMEOUT).
+-define(DEFAULT_ASYNC_GET_NEXT_TIMEOUT, ?DEFAULT_ASYNC_TIMEOUT).
+-define(DEFAULT_ASYNC_GET_BULK_TIMEOUT, ?DEFAULT_ASYNC_TIMEOUT).
+-define(DEFAULT_ASYNC_SET_TIMEOUT, ?DEFAULT_ASYNC_TIMEOUT).
+
+-define(SNMP_AGENT_PORT, 161).
+
+-define(SYNC_GET_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_SYNC_GET_TIMEOUT, SendOpts)).
+-define(SYNC_GET_NEXT_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_SYNC_GET_NEXT_TIMEOUT, SendOpts)).
+-define(SYNC_GET_BULK_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_SYNC_GET_BULK_TIMEOUT, SendOpts)).
+-define(SYNC_SET_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_SYNC_SET_TIMEOUT, SendOpts)).
+
+-define(ASYNC_GET_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_ASYNC_GET_TIMEOUT, SendOpts)).
+-define(ASYNC_GET_NEXT_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_ASYNC_GET_NEXT_TIMEOUT, SendOpts)).
+-define(ASYNC_GET_BULK_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_ASYNC_GET_BULK_TIMEOUT, SendOpts)).
+-define(ASYNC_SET_TIMEOUT(SendOpts),
+ get_opt(timeout, ?DEFAULT_ASYNC_SET_TIMEOUT, SendOpts)).
+
+-define(GET_EXTRA(SendOpts), get_opt(extra, ?DEFAULT_EXTRA_INFO, SendOpts)).
-ifdef(snmp_debug).
-define(GS_START_LINK(Args),
@@ -192,82 +232,140 @@ unregister_user(UserId) ->
%% -- [sync] get --
+%% The reason why we have a sync_get2 is to simplify backward
+%% compatibillity.
+
+%% sync_get2(UserId, TargetName, Oids) ->
+%% sync_get2(UserId, TargetName, Oids, []).
+sync_get2(UserId, TargetName, Oids, Opts) ->
+ call({sync_get, self(), UserId, TargetName, Oids, Opts}).
+
+
+%% <BACKWARD-COMPAT>
sync_get(UserId, TargetName, CtxName, Oids) ->
sync_get(UserId, TargetName, CtxName, Oids,
- ?SYNC_GET_TIMEOUT).
+ ?DEFAULT_SYNC_GET_TIMEOUT).
sync_get(UserId, TargetName, CtxName, Oids, Timeout) ->
- sync_get(UserId, TargetName, CtxName, Oids, Timeout, ?EXTRA_INFO).
+ sync_get(UserId, TargetName, CtxName, Oids, Timeout, ?DEFAULT_EXTRA_INFO).
sync_get(UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo)
when is_list(TargetName) andalso
is_list(CtxName) andalso
is_list(Oids) andalso
is_integer(Timeout) ->
- call({sync_get, self(), UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo}).
+ Opts = [{context, CtxName}, {timeout, Timeout}, {extra, ExtraInfo}],
+ sync_get2(UserId, TargetName, Oids, Opts).
+%% </BACKWARD-COMPAT>
+
+
%% -- [async] get --
+%% async_get2(UserId, TargetName, Oids) ->
+%% async_get2(UserId, TargetName, Oids, []).
+async_get2(UserId, TargetName, Oids, SendOpts) ->
+ call({async_get, self(), UserId, TargetName, Oids, SendOpts}).
+
+
+%% <BACKWARD-COMPAT>
async_get(UserId, TargetName, CtxName, Oids) ->
async_get(UserId, TargetName, CtxName, Oids,
- ?DEFAULT_ASYNC_EXPIRE, ?EXTRA_INFO).
+ ?DEFAULT_ASYNC_GET_TIMEOUT, ?DEFAULT_EXTRA_INFO).
async_get(UserId, TargetName, CtxName, Oids, Expire) ->
- async_get(UserId, TargetName, CtxName, Oids, Expire, ?EXTRA_INFO).
+ async_get(UserId, TargetName, CtxName, Oids, Expire, ?DEFAULT_EXTRA_INFO).
async_get(UserId, TargetName, CtxName, Oids, Expire, ExtraInfo)
when (is_list(TargetName) andalso
is_list(CtxName) andalso
is_list(Oids) andalso
is_integer(Expire) andalso (Expire >= 0)) ->
- call({async_get, self(), UserId, TargetName, CtxName, Oids, Expire,
- ExtraInfo}).
+ SendOpts = [{context, CtxName}, {expire, Expire}, {extra, ExtraInfo}],
+ async_get2(UserId, TargetName, Oids, SendOpts).
+%% </BACKWARD-COMPAT>
+
+
%% -- [sync] get-next --
+%% sync_get_next2(UserId, TargetName, Oids) ->
+%% sync_get_next2(UserId, TargetName, Oids, []).
+sync_get_next2(UserId, TargetName, Oids, SendOpts) ->
+ call({sync_get_next, self(), UserId, TargetName, Oids, SendOpts}).
+
+
+%% <BACKWARD-COMPAT>
sync_get_next(UserId, TargetName, CtxName, Oids) ->
- sync_get_next(UserId, TargetName, CtxName, Oids, ?SYNC_GET_TIMEOUT,
- ?EXTRA_INFO).
+ sync_get_next(UserId, TargetName, CtxName, Oids,
+ ?DEFAULT_SYNC_GET_TIMEOUT, ?DEFAULT_EXTRA_INFO).
sync_get_next(UserId, TargetName, CtxName, Oids, Timeout) ->
- sync_get_next(UserId, TargetName, CtxName, Oids, Timeout, ?EXTRA_INFO).
+ sync_get_next(UserId, TargetName, CtxName, Oids, Timeout,
+ ?DEFAULT_EXTRA_INFO).
sync_get_next(UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo)
when is_list(TargetName) andalso
is_list(CtxName) andalso
is_list(Oids) andalso
is_integer(Timeout) ->
- call({sync_get_next, self(), UserId, TargetName, CtxName, Oids, Timeout,
- ExtraInfo}).
+ SendOpts = [{context, CtxName}, {timeout, Timeout}, {extra, ExtraInfo}],
+ sync_get_next2(UserId, TargetName, Oids, SendOpts).
+%% <BACKWARD-COMPAT>
+
+
%% -- [async] get-next --
+%% async_get_next2(UserId, TargetName, Oids) ->
+%% async_get_next2(UserId, TargetName, Oids, []).
+async_get_next2(UserId, TargetName, Oids, SendOpts) ->
+ call({async_get_next, self(), UserId, TargetName, Oids, SendOpts}).
+
+
async_get_next(UserId, TargetName, CtxName, Oids) ->
async_get_next(UserId, TargetName, CtxName, Oids,
- ?DEFAULT_ASYNC_EXPIRE, ?EXTRA_INFO).
+ ?DEFAULT_ASYNC_GET_NEXT_TIMEOUT, ?DEFAULT_EXTRA_INFO).
async_get_next(UserId, TargetName, CtxName, Oids, Expire) ->
- async_get_next(UserId, TargetName, CtxName, Oids, Expire, ?EXTRA_INFO).
+ async_get_next(UserId, TargetName, CtxName, Oids, Expire,
+ ?DEFAULT_EXTRA_INFO).
async_get_next(UserId, TargetName, CtxName, Oids, Expire, ExtraInfo)
when (is_list(TargetName) andalso
is_list(CtxName) andalso
is_list(Oids) andalso
is_integer(Expire) andalso (Expire >= 0)) ->
- call({async_get_next, self(), UserId, TargetName, CtxName, Oids,
- Expire, ExtraInfo}).
+ SendOpts = [{context, CtxName}, {expire, Expire}, {extra, ExtraInfo}],
+ async_get_next2(UserId, TargetName, Oids, SendOpts).
+
+
%% -- [sync] get-bulk --
+%% sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids) ->
+%% sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, []).
+sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts) ->
+ %% p("sync_get_bulk2 -> entry with"
+ %% "~n UserId: ~p"
+ %% "~n TargetName: ~p"
+ %% "~n NonRep: ~p"
+ %% "~n MaxRep: ~p"
+ %% "~n Oids: ~p"
+ %% "~n SendOpts: ~p",
+ %% [UserId, TargetName, NonRep, MaxRep, Oids, SendOpts]),
+ call({sync_get_bulk, self(), UserId, TargetName,
+ NonRep, MaxRep, Oids, SendOpts}).
+
sync_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids) ->
sync_get_bulk(UserId, TargetName,
NonRep, MaxRep, CtxName, Oids,
- ?SYNC_GET_TIMEOUT, ?EXTRA_INFO).
+ ?DEFAULT_SYNC_GET_TIMEOUT, ?DEFAULT_EXTRA_INFO).
sync_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids, Timeout) ->
sync_get_bulk(UserId, TargetName,
NonRep, MaxRep, CtxName, Oids,
- Timeout, ?EXTRA_INFO).
+ Timeout, ?DEFAULT_EXTRA_INFO).
sync_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids, Timeout,
ExtraInfo)
@@ -277,20 +375,28 @@ sync_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids, Timeout,
is_list(CtxName) andalso
is_list(Oids) andalso
is_integer(Timeout) ->
- call({sync_get_bulk, self(), UserId, TargetName,
- NonRep, MaxRep, CtxName, Oids, Timeout, ExtraInfo}).
+ SendOpts = [{context, CtxName}, {timeout, Timeout}, {extra, ExtraInfo}],
+ sync_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
+
%% -- [async] get-bulk --
+%% async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids) ->
+%% async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, []).
+async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts) ->
+ call({async_get_bulk, self(), UserId, TargetName, NonRep, MaxRep,
+ Oids, SendOpts}).
+
+
async_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids) ->
async_get_bulk(UserId, TargetName,
NonRep, MaxRep, CtxName, Oids,
- ?DEFAULT_ASYNC_EXPIRE, ?EXTRA_INFO).
+ ?DEFAULT_ASYNC_GET_BULK_TIMEOUT, ?DEFAULT_EXTRA_INFO).
async_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids, Expire) ->
async_get_bulk(UserId, TargetName,
NonRep, MaxRep, CtxName, Oids,
- Expire, ?EXTRA_INFO).
+ Expire, ?DEFAULT_EXTRA_INFO).
async_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids, Expire,
ExtraInfo)
@@ -300,45 +406,61 @@ async_get_bulk(UserId, TargetName, NonRep, MaxRep, CtxName, Oids, Expire,
is_list(CtxName) andalso
is_list(Oids) andalso
is_integer(Expire) ->
- call({async_get_bulk, self(), UserId, TargetName,
- NonRep, MaxRep, CtxName, Oids, Expire, ExtraInfo}).
+ SendOpts = [{context, CtxName}, {expire, Expire}, {extra, ExtraInfo}],
+ async_get_bulk2(UserId, TargetName, NonRep, MaxRep, Oids, SendOpts).
+
+
%% -- [sync] set --
%% VarsAndValues is: {PlainOid, o|s|i, Value} (unknown mibs) | {Oid, Value}
+%% sync_set2(UserId, TargetName, VarsAndVals) ->
+%% sync_set2(UserId, TargetName, VarsAndVals, []).
+sync_set2(UserId, TargetName, VarsAndVals, SendOpts) ->
+ call({sync_set, self(), UserId, TargetName, VarsAndVals, SendOpts}).
+
+
sync_set(UserId, TargetName, CtxName, VarsAndVals) ->
sync_set(UserId, TargetName, CtxName, VarsAndVals,
- ?SYNC_SET_TIMEOUT, ?EXTRA_INFO).
+ ?DEFAULT_SYNC_SET_TIMEOUT, ?DEFAULT_EXTRA_INFO).
sync_set(UserId, TargetName, CtxName, VarsAndVals, Timeout) ->
sync_set(UserId, TargetName, CtxName, VarsAndVals,
- Timeout, ?EXTRA_INFO).
+ Timeout, ?DEFAULT_EXTRA_INFO).
sync_set(UserId, TargetName, CtxName, VarsAndVals, Timeout, ExtraInfo)
when is_list(TargetName) andalso
is_list(CtxName) andalso
is_list(VarsAndVals) andalso
is_integer(Timeout) ->
- call({sync_set, self(), UserId, TargetName,
- CtxName, VarsAndVals, Timeout, ExtraInfo}).
+ SendOpts = [{context, CtxName}, {timeout, Timeout}, {extra, ExtraInfo}],
+ sync_set2(UserId, TargetName, VarsAndVals, SendOpts).
+
+
%% -- [async] set --
+%% async_set2(UserId, TargetName, VarsAndVals) ->
+%% async_set2(UserId, TargetName, VarsAndVals, []).
+async_set2(UserId, TargetName, VarsAndVals, SendOpts) ->
+ call({async_set, self(), UserId, TargetName, VarsAndVals, SendOpts}).
+
+
async_set(UserId, TargetName, CtxName, VarsAndVals) ->
async_set(UserId, TargetName, CtxName, VarsAndVals,
- ?DEFAULT_ASYNC_EXPIRE, ?EXTRA_INFO).
+ ?DEFAULT_ASYNC_SET_TIMEOUT, ?DEFAULT_EXTRA_INFO).
async_set(UserId, TargetName, CtxName, VarsAndVals, Expire) ->
async_set(UserId, TargetName, CtxName, VarsAndVals,
- Expire, ?EXTRA_INFO).
+ Expire, ?DEFAULT_EXTRA_INFO).
async_set(UserId, TargetName, CtxName, VarsAndVals, Expire, ExtraInfo)
when (is_list(TargetName) andalso
is_list(CtxName) andalso
is_list(VarsAndVals) andalso
is_integer(Expire) andalso (Expire >= 0)) ->
- call({async_set, self(), UserId, TargetName,
- CtxName, VarsAndVals, Expire, ExtraInfo}).
+ SendOpts = [{context, CtxName}, {expire, Expire}, {extra, ExtraInfo}],
+ async_set2(UserId, TargetName, VarsAndVals, SendOpts).
cancel_async_request(UserId, ReqId) ->
@@ -571,9 +693,26 @@ handle_call({unregister_user, UserId}, _From, State) ->
%% We will reply to this request later, when the reply comes in from the
%% agent, or when the timeout hits (unless we get an error now).
-handle_call({sync_get, Pid, UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo},
+handle_call({sync_get, Pid, UserId, TargetName, Oids, SendOpts},
+ From, State) ->
+ ?vlog("[~p,~p] received sync_get request for: "
+ "~n ~p", [UserId, TargetName, Oids]),
+ case (catch handle_sync_get(Pid,
+ UserId, TargetName, Oids, SendOpts,
+ From, State)) of
+ ok ->
+ {noreply, State};
+ Error ->
+ {reply, Error, State}
+ end;
+
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
+handle_call({sync_get,
+ Pid, UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo},
From, State) ->
- ?vlog("received sync_get [~p] request", [CtxName]),
+ ?vlog("[~p,~p,~p] received sync_get request for: "
+ "~n ~p", [UserId, TargetName, CtxName, Oids]),
case (catch handle_sync_get(Pid,
UserId, TargetName, CtxName, Oids,
Timeout, ExtraInfo, From, State)) of
@@ -582,10 +721,30 @@ handle_call({sync_get, Pid, UserId, TargetName, CtxName, Oids, Timeout, ExtraInf
Error ->
{reply, Error, State}
end;
+%% </BACKWARD-COMPAT>
+
+
+handle_call({sync_get_next, Pid, UserId, TargetName, Oids, SendOpts},
+ From, State) ->
+ ?vlog("[~p,~p] received sync_get_next request for: "
+ "~n ~p", [UserId, TargetName, SendOpts]),
+ case (catch handle_sync_get_next(Pid,
+ UserId, TargetName, Oids, SendOpts,
+ From, State)) of
+ ok ->
+ {noreply, State};
+ Error ->
+ {reply, Error, State}
+ end;
-handle_call({sync_get_next, Pid, UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo}, From, State) ->
- ?vlog("received sync_get_next [~p] request", [CtxName]),
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
+handle_call({sync_get_next,
+ Pid, UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo},
+ From, State) ->
+ ?vlog("[~p,~p,~p] received sync_get_next request for"
+ "~n ~p", [UserId, TargetName, CtxName, Oids]),
case (catch handle_sync_get_next(Pid,
UserId, TargetName, CtxName, Oids,
Timeout, ExtraInfo, From, State)) of
@@ -594,13 +753,31 @@ handle_call({sync_get_next, Pid, UserId, TargetName, CtxName, Oids, Timeout, Ext
Error ->
{reply, Error, State}
end;
+%% </BACKWARD-COMPAT>
%% Check agent version? This op not in v1
+handle_call({sync_get_bulk,
+ Pid, UserId, TargetName, NonRep, MaxRep, Oids, SendOpts},
+ From, State) ->
+ ?vlog("[~p,~p] received sync_get_bulk request for: "
+ "~n ~p", [UserId, TargetName, Oids]),
+ case (catch handle_sync_get_bulk(Pid,
+ UserId, TargetName, NonRep, MaxRep, Oids,
+ SendOpts, From, State)) of
+ ok ->
+ {noreply, State};
+ Error ->
+ {reply, Error, State}
+ end;
+
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
handle_call({sync_get_bulk, Pid, UserId, TargetName,
NonRep, MaxRep, CtxName, Oids, Timeout, ExtraInfo},
From, State) ->
- ?vlog("received sync_get_bulk [~p] request", [CtxName]),
+ ?vlog("[~p,~p] received sync_get_bulk request for: ~p"
+ "~n ~p", [UserId, TargetName, CtxName, Oids]),
case (catch handle_sync_get_bulk(Pid,
UserId, TargetName, CtxName,
NonRep, MaxRep, Oids,
@@ -610,12 +787,31 @@ handle_call({sync_get_bulk, Pid, UserId, TargetName,
Error ->
{reply, Error, State}
end;
+%% </BACKWARD-COMPAT>
+
+
+handle_call({sync_set,
+ Pid, UserId, TargetName, VarsAndVals, SendOpts},
+ From, State) ->
+ ?vlog("[~p,~p] received sync_set request for: "
+ "~n ~p", [UserId, TargetName, VarsAndVals]),
+ case (catch handle_sync_set(Pid,
+ UserId, TargetName, VarsAndVals, SendOpts,
+ From, State)) of
+ ok ->
+ {noreply, State};
+ Error ->
+ {reply, Error, State}
+ end;
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
handle_call({sync_set, Pid, UserId, TargetName,
CtxName, VarsAndVals, Timeout, ExtraInfo},
From, State) ->
- ?vlog("received sync_set [~p] request", [CtxName]),
+ ?vlog("[~p,~p,~p] received sync_set request for: "
+ "~n ~p", [UserId, TargetName, CtxName, VarsAndVals]),
case (catch handle_sync_set(Pid,
UserId, TargetName, CtxName, VarsAndVals,
Timeout, ExtraInfo, From, State)) of
@@ -624,45 +820,105 @@ handle_call({sync_set, Pid, UserId, TargetName,
Error ->
{reply, Error, State}
end;
+%% </BACKWARD-COMPAT>
+handle_call({async_get, Pid, UserId, TargetName, Oids, SendOpts},
+ _From, State) ->
+ ?vlog("[~p,~p] received async_get request for: "
+ "~n ~p", [UserId, TargetName, Oids]),
+ Reply = (catch handle_async_get(Pid,
+ UserId, TargetName, Oids, SendOpts,
+ State)),
+ {reply, Reply, State};
+
+
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
handle_call({async_get, Pid, UserId, TargetName,
CtxName, Oids, Expire, ExtraInfo},
_From, State) ->
- ?vlog("received async_get [~p] request", [CtxName]),
+ ?vlog("[~p,~p,~p] received async_get request for: "
+ "~n ~p", [UserId, TargetName, CtxName, Oids]),
Reply = (catch handle_async_get(Pid, UserId, TargetName, CtxName, Oids,
Expire, ExtraInfo, State)),
{reply, Reply, State};
+%% </BACKWARD-COMPAT>
+
+
+handle_call({async_get_next, Pid, UserId, TargetName, Oids, SendOpts},
+ _From, State) ->
+ ?vlog("[~p,~p] received async_get_next request for: "
+ "~n ~p", [UserId, TargetName, Oids]),
+ Reply = (catch handle_async_get_next(Pid,
+ UserId, TargetName, Oids, SendOpts,
+ State)),
+ {reply, Reply, State};
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
handle_call({async_get_next, Pid, UserId, TargetName,
CtxName, Oids, Expire, ExtraInfo},
_From, State) ->
- ?vlog("received async_get_next [~p] request", [CtxName]),
+ ?vlog("[~p,~p,~p] received async_get_next request for: ",
+ [UserId, TargetName, CtxName, Oids]),
Reply = (catch handle_async_get_next(Pid, UserId, TargetName, CtxName,
Oids, Expire, ExtraInfo, State)),
{reply, Reply, State};
+%% </BACKWARD-COMPAT>
%% Check agent version? This op not in v1
+handle_call({async_get_bulk,
+ Pid, UserId, TargetName, NonRep, MaxRep, Oids, SendOpts},
+ _From, State) ->
+ ?vlog("[~p,~p] received async_get_bulk request for: "
+ "~n ~p", [UserId, TargetName, Oids]),
+ Reply = (catch handle_async_get_bulk(Pid,
+ UserId, TargetName,
+ NonRep, MaxRep, Oids, SendOpts,
+ State)),
+ {reply, Reply, State};
+
+
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
handle_call({async_get_bulk, Pid, UserId, TargetName,
NonRep, MaxRep, CtxName, Oids, Expire, ExtraInfo},
_From, State) ->
- ?vlog("received async_get_bulk [~p] request", [CtxName]),
+ ?vlog("[~p,~p,~p] received async_get_bulk request for: "
+ "~n ~p", [UserId, TargetName, CtxName, Oids]),
Reply = (catch handle_async_get_bulk(Pid,
UserId, TargetName, CtxName,
NonRep, MaxRep, Oids,
Expire, ExtraInfo, State)),
{reply, Reply, State};
+%% </BACKWARD-COMPAT>
+
+
+handle_call({async_set,
+ Pid, UserId, TargetName, VarsAndVals, SendOpts},
+ _From, State) ->
+ ?vlog("[~p,~p] received async_set request for: "
+ "~n ~p", [UserId, TargetName, VarsAndVals]),
+ Reply = (catch handle_async_set(Pid,
+ UserId, TargetName, VarsAndVals, SendOpts,
+ State)),
+ {reply, Reply, State};
+%% <BACKWARD-COMPAT>
+%% The only case where this would be called is during code upgrade
handle_call({async_set, Pid, UserId, TargetName,
CtxName, VarsAndVals, Expire, ExtraInfo},
_From, State) ->
- ?vlog("received async_set [~p] request", [CtxName]),
+ ?vlog("[~p,~p,~p] received async_set request for: "
+ "~n ~p", [UserId, TargetName, CtxName, VarsAndVals]),
Reply = (catch handle_async_set(Pid, UserId, TargetName, CtxName,
VarsAndVals, Expire, ExtraInfo, State)),
{reply, Reply, State};
+%% </BACKWARD-COMPAT>
handle_call({cancel_async_request, UserId, ReqId}, _From, State) ->
@@ -901,36 +1157,46 @@ terminate(Reason, #state{gct = GCT}) ->
handle_sync_get(Pid, UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo,
From, State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Timeout},
+ {extra, ExtraInfo}
+ ],
+ handle_sync_get(Pid, UserId, TargetName, Oids, SendOpts, From, State).
+
+handle_sync_get(Pid, UserId, TargetName, Oids, SendOpts, From, State) ->
?vtrace("handle_sync_get -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n Oids: ~p"
- "~n Timeout: ~p"
+ "~n SendOpts: ~p"
"~n From: ~p",
- [Pid, UserId, TargetName, CtxName, Oids, Timeout, From]),
- case agent_data(TargetName, CtxName) of
+ [Pid, UserId, TargetName, Oids, SendOpts, From]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_sync_get -> send a ~p message", [Vsn]),
- ReqId = send_get_request(Oids, Vsn, MsgData, Addr, Port,
- ExtraInfo, State),
+ Extra = ?GET_EXTRA(SendOpts),
+ ReqId = send_get_request(Oids, Vsn, MsgData,
+ Addr, Port, Extra, State),
?vdebug("handle_sync_get -> ReqId: ~p", [ReqId]),
- Msg = {sync_timeout, ReqId, From},
- Ref = erlang:send_after(Timeout, self(), Msg),
- MonRef = erlang:monitor(process, Pid),
+ Msg = {sync_timeout, ReqId, From},
+ Timeout = ?SYNC_GET_TIMEOUT(SendOpts),
+ Ref = erlang:send_after(Timeout, self(), Msg),
+ MonRef = erlang:monitor(process, Pid),
?vtrace("handle_sync_get -> MonRef: ~p", [MonRef]),
- Req = #request{id = ReqId,
- user_id = UserId,
- reg_type = RegType,
- target = TargetName,
- addr = Addr,
- port = Port,
- type = get,
- data = MsgData,
- ref = Ref,
- mon = MonRef,
- from = From},
+ Req = #request{id = ReqId,
+ user_id = UserId,
+ reg_type = RegType,
+ target = TargetName,
+ addr = Addr,
+ port = Port,
+ type = get,
+ data = MsgData,
+ ref = Ref,
+ mon = MonRef,
+ from = From},
ets:insert(snmpm_request_table, Req),
ok;
Error ->
@@ -940,39 +1206,49 @@ handle_sync_get(Pid, UserId, TargetName, CtxName, Oids, Timeout, ExtraInfo,
Error
end.
-
handle_sync_get_next(Pid, UserId, TargetName, CtxName, Oids, Timeout,
ExtraInfo, From, State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Timeout},
+ {extra, ExtraInfo}
+ ],
+ handle_sync_get_next(Pid, UserId, TargetName, Oids, SendOpts, From, State).
+
+handle_sync_get_next(Pid, UserId, TargetName, Oids, SendOpts,
+ From, State) ->
?vtrace("handle_sync_get_next -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n Oids: ~p"
- "~n Timeout: ~p"
+ "~n SendOpts: ~p"
"~n From: ~p",
- [Pid, UserId, TargetName, CtxName, Oids, Timeout, From]),
- case agent_data(TargetName, CtxName) of
+ [Pid, UserId, TargetName, Oids, SendOpts, From]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_sync_get_next -> send a ~p message", [Vsn]),
- ReqId = send_get_next_request(Oids, Vsn, MsgData,
- Addr, Port, ExtraInfo, State),
+ Extra = ?GET_EXTRA(SendOpts),
+ ReqId = send_get_next_request(Oids, Vsn, MsgData,
+ Addr, Port, Extra, State),
?vdebug("handle_sync_get_next -> ReqId: ~p", [ReqId]),
- Msg = {sync_timeout, ReqId, From},
- Ref = erlang:send_after(Timeout, self(), Msg),
- MonRef = erlang:monitor(process, Pid),
+ Msg = {sync_timeout, ReqId, From},
+ Timeout = ?SYNC_GET_NEXT_TIMEOUT(SendOpts),
+ Ref = erlang:send_after(Timeout, self(), Msg),
+ MonRef = erlang:monitor(process, Pid),
?vtrace("handle_sync_get_next -> MonRef: ~p", [MonRef]),
- Req = #request{id = ReqId,
- user_id = UserId,
- reg_type = RegType,
- target = TargetName,
- addr = Addr,
- port = Port,
- type = get_next,
- data = MsgData,
- ref = Ref,
- mon = MonRef,
- from = From},
+ Req = #request{id = ReqId,
+ user_id = UserId,
+ reg_type = RegType,
+ target = TargetName,
+ addr = Addr,
+ port = Port,
+ type = get_next,
+ data = MsgData,
+ ref = Ref,
+ mon = MonRef,
+ from = From},
ets:insert(snmpm_request_table, Req),
ok;
@@ -987,39 +1263,50 @@ handle_sync_get_next(Pid, UserId, TargetName, CtxName, Oids, Timeout,
handle_sync_get_bulk(Pid, UserId, TargetName, CtxName,
NonRep, MaxRep, Oids, Timeout,
ExtraInfo, From, State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Timeout},
+ {extra, ExtraInfo}
+ ],
+ handle_sync_get_bulk(Pid, UserId, TargetName, NonRep, MaxRep, Oids,
+ SendOpts, From, State).
+
+handle_sync_get_bulk(Pid, UserId, TargetName, NonRep, MaxRep, Oids, SendOpts,
+ From, State) ->
?vtrace("handle_sync_get_bulk -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n NonRep: ~p"
"~n MaxRep: ~p"
"~n Oids: ~p"
- "~n Timeout: ~p"
+ "~n SendOpts: ~p"
"~n From: ~p",
- [Pid, UserId, TargetName, CtxName, NonRep, MaxRep, Oids,
- Timeout, From]),
- case agent_data(TargetName, CtxName) of
+ [Pid, UserId, TargetName, NonRep, MaxRep, Oids, SendOpts, From]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_sync_get_bulk -> send a ~p message", [Vsn]),
- ReqId = send_get_bulk_request(Oids, Vsn, MsgData, Addr, Port,
- NonRep, MaxRep, ExtraInfo, State),
+ Extra = ?GET_EXTRA(SendOpts),
+ ReqId = send_get_bulk_request(Oids, Vsn, MsgData, Addr, Port,
+ NonRep, MaxRep, Extra, State),
?vdebug("handle_sync_get_bulk -> ReqId: ~p", [ReqId]),
- Msg = {sync_timeout, ReqId, From},
- Ref = erlang:send_after(Timeout, self(), Msg),
- MonRef = erlang:monitor(process, Pid),
+ Msg = {sync_timeout, ReqId, From},
+ Timeout = ?SYNC_GET_BULK_TIMEOUT(SendOpts),
+ Ref = erlang:send_after(Timeout, self(), Msg),
+ MonRef = erlang:monitor(process, Pid),
?vtrace("handle_sync_get_bulk -> MonRef: ~p", [MonRef]),
- Req = #request{id = ReqId,
- user_id = UserId,
- reg_type = RegType,
- target = TargetName,
- addr = Addr,
- port = Port,
- type = get_bulk,
- data = MsgData,
- ref = Ref,
- mon = MonRef,
- from = From},
+ Req = #request{id = ReqId,
+ user_id = UserId,
+ reg_type = RegType,
+ target = TargetName,
+ addr = Addr,
+ port = Port,
+ type = get_bulk,
+ data = MsgData,
+ ref = Ref,
+ mon = MonRef,
+ from = From},
ets:insert(snmpm_request_table, Req),
ok;
@@ -1033,36 +1320,47 @@ handle_sync_get_bulk(Pid, UserId, TargetName, CtxName,
handle_sync_set(Pid, UserId, TargetName, CtxName, VarsAndVals, Timeout,
ExtraInfo, From, State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Timeout},
+ {extra, ExtraInfo}
+ ],
+ handle_sync_set(Pid, UserId, TargetName, VarsAndVals, SendOpts,
+ From, State).
+
+handle_sync_set(Pid, UserId, TargetName, VarsAndVals, SendOpts, From, State) ->
?vtrace("handle_sync_set -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n VarsAndVals: ~p"
- "~n Timeout: ~p"
+ "~n SendOpts: ~p"
"~n From: ~p",
- [Pid, UserId, TargetName, CtxName, VarsAndVals, Timeout, From]),
- case agent_data(TargetName, CtxName) of
+ [Pid, UserId, TargetName, VarsAndVals, From]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_sync_set -> send a ~p message", [Vsn]),
- ReqId = send_set_request(VarsAndVals, Vsn, MsgData,
- Addr, Port, ExtraInfo, State),
+ Extra = ?GET_EXTRA(SendOpts),
+ ReqId = send_set_request(VarsAndVals, Vsn, MsgData,
+ Addr, Port, Extra, State),
?vdebug("handle_sync_set -> ReqId: ~p", [ReqId]),
- Msg = {sync_timeout, ReqId, From},
- Ref = erlang:send_after(Timeout, self(), Msg),
- MonRef = erlang:monitor(process, Pid),
+ Msg = {sync_timeout, ReqId, From},
+ Timeout = ?SYNC_SET_TIMEOUT(SendOpts),
+ Ref = erlang:send_after(Timeout, self(), Msg),
+ MonRef = erlang:monitor(process, Pid),
?vtrace("handle_sync_set -> MonRef: ~p", [MonRef]),
- Req = #request{id = ReqId,
- user_id = UserId,
- reg_type = RegType,
- target = TargetName,
- addr = Addr,
- port = Port,
- type = set,
- data = MsgData,
- ref = Ref,
- mon = MonRef,
- from = From},
+ Req = #request{id = ReqId,
+ user_id = UserId,
+ reg_type = RegType,
+ target = TargetName,
+ addr = Addr,
+ port = Port,
+ type = set,
+ data = MsgData,
+ ref = Ref,
+ mon = MonRef,
+ from = From},
ets:insert(snmpm_request_table, Req),
ok;
@@ -1076,20 +1374,30 @@ handle_sync_set(Pid, UserId, TargetName, CtxName, VarsAndVals, Timeout,
handle_async_get(Pid, UserId, TargetName, CtxName, Oids, Expire, ExtraInfo,
State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Expire},
+ {extra, ExtraInfo}
+ ],
+ handle_async_get(Pid, UserId, TargetName, Oids, SendOpts, State).
+
+handle_async_get(Pid, UserId, TargetName, Oids, SendOpts, State) ->
?vtrace("handle_async_get -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n Oids: ~p"
- "~n Expire: ~p",
- [Pid, UserId, TargetName, CtxName, Oids, Expire]),
- case agent_data(TargetName, CtxName) of
+ "~n SendOpts: ~p",
+ [Pid, UserId, TargetName, Oids, SendOpts]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_async_get -> send a ~p message", [Vsn]),
+ Extra = ?GET_EXTRA(SendOpts),
ReqId = send_get_request(Oids, Vsn, MsgData, Addr, Port,
- ExtraInfo, State),
+ Extra, State),
?vdebug("handle_async_get -> ReqId: ~p", [ReqId]),
+ Expire = ?ASYNC_GET_TIMEOUT(SendOpts),
Req = #request{id = ReqId,
user_id = UserId,
reg_type = RegType,
@@ -1114,20 +1422,30 @@ handle_async_get(Pid, UserId, TargetName, CtxName, Oids, Expire, ExtraInfo,
handle_async_get_next(Pid, UserId, TargetName, CtxName, Oids, Expire,
ExtraInfo, State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Expire},
+ {extra, ExtraInfo}
+ ],
+ handle_async_get_next(Pid, UserId, TargetName, Oids, SendOpts, State).
+
+handle_async_get_next(Pid, UserId, TargetName, Oids, SendOpts, State) ->
?vtrace("handle_async_get_next -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n Oids: ~p"
- "~n Expire: ~p",
- [Pid, UserId, TargetName, CtxName, Oids, Expire]),
- case agent_data(TargetName, CtxName) of
+ "~n SendOpts: ~p",
+ [Pid, UserId, TargetName, Oids, SendOpts]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_async_get_next -> send a ~p message", [Vsn]),
+ Extra = ?GET_EXTRA(SendOpts),
ReqId = send_get_next_request(Oids, Vsn, MsgData,
- Addr, Port, ExtraInfo, State),
+ Addr, Port, Extra, State),
?vdebug("handle_async_get_next -> ReqId: ~p", [ReqId]),
+ Expire = ?ASYNC_GET_NEXT_TIMEOUT(SendOpts),
Req = #request{id = ReqId,
user_id = UserId,
reg_type = RegType,
@@ -1153,22 +1471,36 @@ handle_async_get_next(Pid, UserId, TargetName, CtxName, Oids, Expire,
handle_async_get_bulk(Pid, UserId, TargetName, CtxName,
NonRep, MaxRep, Oids, Expire,
ExtraInfo, State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Expire},
+ {extra, ExtraInfo}
+ ],
+ handle_async_get_bulk(Pid,
+ UserId, TargetName, NonRep, MaxRep, Oids, SendOpts,
+ State).
+
+handle_async_get_bulk(Pid,
+ UserId, TargetName, NonRep, MaxRep, Oids, SendOpts,
+ State) ->
?vtrace("handle_async_get_bulk -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n NonRep: ~p"
"~n MaxRep: ~p"
"~n Oids: ~p"
- "~n Expire: ~p",
- [Pid, UserId, TargetName, CtxName, NonRep, MaxRep, Oids, Expire]),
- case agent_data(TargetName, CtxName) of
+ "~n SendOpts: ~p",
+ [Pid, UserId, TargetName, NonRep, MaxRep, Oids, SendOpts]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_async_get_bulk -> send a ~p message", [Vsn]),
+ Extra = ?GET_EXTRA(SendOpts),
ReqId = send_get_bulk_request(Oids, Vsn, MsgData, Addr, Port,
- NonRep, MaxRep, ExtraInfo, State),
+ NonRep, MaxRep, Extra, State),
?vdebug("handle_async_get_bulk -> ReqId: ~p", [ReqId]),
+ Expire = ?ASYNC_GET_BULK_TIMEOUT(SendOpts),
Req = #request{id = ReqId,
user_id = UserId,
reg_type = RegType,
@@ -1192,20 +1524,30 @@ handle_async_get_bulk(Pid, UserId, TargetName, CtxName,
handle_async_set(Pid, UserId, TargetName, CtxName, VarsAndVals, Expire,
ExtraInfo, State) ->
+ SendOpts =
+ [
+ {context, CtxName},
+ {timeout, Expire},
+ {extra, ExtraInfo}
+ ],
+ handle_async_set(Pid, UserId, TargetName, VarsAndVals, SendOpts, State).
+
+handle_async_set(Pid, UserId, TargetName, VarsAndVals, SendOpts, State) ->
?vtrace("handle_async_set -> entry with"
"~n Pid: ~p"
"~n UserId: ~p"
"~n TargetName: ~p"
- "~n CtxName: ~p"
"~n VarsAndVals: ~p"
- "~n Expire: ~p",
- [Pid, UserId, TargetName, CtxName, VarsAndVals, Expire]),
- case agent_data(TargetName, CtxName) of
+ "~n SendOpts: ~p",
+ [Pid, UserId, TargetName, VarsAndVals, SendOpts]),
+ case agent_data(TargetName, SendOpts) of
{ok, RegType, Addr, Port, Vsn, MsgData} ->
?vtrace("handle_async_set -> send a ~p message", [Vsn]),
+ Extra = ?GET_EXTRA(SendOpts),
ReqId = send_set_request(VarsAndVals, Vsn, MsgData,
- Addr, Port, ExtraInfo, State),
+ Addr, Port, Extra, State),
?vdebug("handle_async_set -> ReqId: ~p", [ReqId]),
+ Expire = ?ASYNC_SET_TIMEOUT(SendOpts),
Req = #request{id = ReqId,
user_id = UserId,
reg_type = RegType,
@@ -2798,10 +3140,7 @@ request_id() ->
%%----------------------------------------------------------------------
-agent_data(TargetName, CtxName) ->
- agent_data(TargetName, CtxName, []).
-
-agent_data(TargetName, CtxName, Config) ->
+agent_data(TargetName, SendOpts) ->
case snmpm_config:agent_info(TargetName, all) of
{ok, Info} ->
Version = agent_data_item(version, Info),
@@ -2813,15 +3152,18 @@ agent_data(TargetName, CtxName, Config) ->
DefSecLevel = agent_data_item(sec_level, Info),
EngineId = agent_data_item(engine_id, Info),
+ CtxName = agent_data_item(context,
+ SendOpts,
+ ?DEFAULT_CONTEXT),
SecModel = agent_data_item(sec_model,
- Config,
+ SendOpts,
DefSecModel),
SecName = agent_data_item(sec_name,
- Config,
+ SendOpts,
DefSecName),
SecLevel = agent_data_item(sec_level,
- Config,
+ SendOpts,
DefSecLevel),
{SecModel, SecName, mk_sec_level_flag(SecLevel),
@@ -2831,10 +3173,10 @@ agent_data(TargetName, CtxName, Config) ->
DefSecModel = agent_data_item(sec_model, Info),
Comm = agent_data_item(community,
- Config,
+ SendOpts,
DefComm),
SecModel = agent_data_item(sec_model,
- Config,
+ SendOpts,
DefSecModel),
{Comm, SecModel}
@@ -3003,6 +3345,12 @@ default_agent_config() ->
%%----------------------------------------------------------------------
+get_opt(Key, Default, Opts) ->
+ proplists:get_value(Key, Opts, Default).
+
+
+%%----------------------------------------------------------------------
+
is_started(#state{net_if = _Pid, net_if_mod = _Mod}) ->
%% Mod:is_started(Pid) and snmpm_config:is_started().
case snmpm_config:is_started() of
diff --git a/lib/snmp/src/manager/snmpm_usm.erl b/lib/snmp/src/manager/snmpm_usm.erl
index 449127844a..ef2070a90e 100644
--- a/lib/snmp/src/manager/snmpm_usm.erl
+++ b/lib/snmp/src/manager/snmpm_usm.erl
@@ -476,14 +476,19 @@ set_engine_latest_time(SnmpEngineID, EngineTime) ->
%%-----------------------------------------------------------------
%% Utility functions
%%-----------------------------------------------------------------
+-spec error(term()) -> no_return().
error(Reason) ->
throw({error, Reason}).
+-spec error(term(), term()) -> no_return().
error(Reason, ErrorInfo) ->
throw({error, Reason, ErrorInfo}).
+-spec error(term(), term(), term()) -> no_return().
error(Variable, Oid, SecName) ->
error(Variable, Oid, SecName, []).
+
+-spec error(term(), term(), term(), [term()]) -> no_return().
error(Variable, Oid, SecName, Opts) ->
Val = inc(Variable),
ErrorInfo = {#varbind{oid = Oid,
diff --git a/lib/snmp/src/misc/snmp_conf.erl b/lib/snmp/src/misc/snmp_conf.erl
index 4d2f5d8f92..cb5b3bbfbd 100644
--- a/lib/snmp/src/misc/snmp_conf.erl
+++ b/lib/snmp/src/misc/snmp_conf.erl
@@ -37,7 +37,13 @@
check_timer/1,
- check_ip/1, check_taddress/1,
+ check_domain/1,
+ check_tdomain/1,
+ mk_tdomain/1,
+ which_domain/1,
+ check_ip/1, check_ip/2,
+ check_taddress/1, check_taddress/2,
+ mk_taddress/3,
check_packet_size/1,
@@ -52,8 +58,10 @@
-define(SNMP_USE_V3, true).
--include("snmp_types.hrl").
--include("SNMP-FRAMEWORK-MIB.hrl").
+-include_lib("snmp/include/snmp_types.hrl").
+-include_lib("snmp/include/SNMP-FRAMEWORK-MIB.hrl").
+-include_lib("snmp/include/TRANSPORT-ADDRESS-MIB.hrl").
+-include_lib("snmp/include/SNMPv2-TM.hrl").
-define(VMODULE,"CONF").
-include("snmp_verbosity.hrl").
@@ -338,15 +346,96 @@ check_sec_level(BadSecLevel) ->
%% ---------
-check_taddress(X) when is_list(X) andalso (length(X) =:= 6) ->
+check_tdomain(TDomain) ->
+ SupportedTDomains =
+ [
+ ?snmpUDPDomain,
+ ?transportDomainUdpIpv4,
+ ?transportDomainUdpIpv6
+ ],
+ AllTDomains =
+ [
+ ?transportDomainUdpIpv4,
+ ?transportDomainUdpIpv6,
+ ?transportDomainUdpIpv4z,
+ ?transportDomainUdpIpv6z,
+ ?transportDomainTcpIpv4,
+ ?transportDomainTcpIpv6,
+ ?transportDomainTcpIpv4z,
+ ?transportDomainTcpIpv6z,
+ ?transportDomainSctpIpv4,
+ ?transportDomainSctpIpv6,
+ ?transportDomainSctpIpv4z,
+ ?transportDomainSctpIpv6z,
+ ?transportDomainLocal,
+ ?transportDomainUdpDns,
+ ?transportDomainTcpDns,
+ ?transportDomainSctpDns
+ ],
+ case lists:member(TDomain, SupportedTDomains) of
+ true ->
+ ok;
+ false ->
+ case lists:member(TDomain, AllTDomains) of
+ true ->
+ error({unsupported_tdomain, TDomain});
+ false ->
+ error({unknown_tdomain, TDomain})
+ end
+ end.
+
+
+%% ---------
+
+mk_tdomain(snmpUDPDomain) ->
+ ?snmpUDPDomain;
+mk_tdomain(transportDomainUdpIpv4) ->
+ ?transportDomainUdpIpv4;
+mk_tdomain(transportDomainUdpIpv6) ->
+ ?transportDomainUdpIpv6;
+mk_tdomain(BadDomain) ->
+ error({bad_domain, BadDomain}).
+
+
+%% ---------
+
+check_taddress(X) ->
+ check_taddress(snmpUDPDomain, X).
+
+check_taddress(?snmpUDPDomain, X) ->
+ check_taddress(transportDomainUdpIpv4, X);
+check_taddress(snmpUDPDomain, X) ->
+ check_taddress(transportDomainUdpIpv4, X);
+
+check_taddress(?transportDomainUdpIpv4, X) ->
+ check_taddress(transportDomainUdpIpv4, X);
+check_taddress(transportDomainUdpIpv4, X)
+ when is_list(X) andalso (length(X) =:= 6) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_taddress, X})
end;
-check_taddress(X) ->
- error({invalid_taddress, X}).
+check_taddress(transportDomainUdpIpv4, X) ->
+ error({invalid_taddress, X});
+
+check_taddress(?transportDomainUdpIpv6, X) ->
+ check_taddress(transportDomainUdpIpv6, X);
+check_taddress(transportDomainUdpIpv6, X)
+ when is_list(X) andalso (length(X) =:= 10) ->
+ case (catch all_integer(X)) of
+ true ->
+ ok;
+ false ->
+ error({invalid_taddress, X})
+ end;
+check_taddress(transportDomainUdpIpv6, X) ->
+ error({invalid_taddress, X});
+
+check_taddress(BadDomain, _X) ->
+ error({invalid_tdomain, BadDomain}).
+
%% ---------
@@ -385,15 +474,115 @@ do_check_timer(WaitFor, Factor, Incr, Retry) ->
%% ---------
-check_ip(X) when is_list(X) andalso (length(X) =:= 4) ->
+check_domain(Domain) ->
+ SupportedDomains =
+ [
+ snmpUDPDomain,
+ transportDomainUdpIpv4,
+ transportDomainUdpIpv6
+ ],
+ AllDomains =
+ [
+ transportDomainUdpIpv4,
+ transportDomainUdpIpv6,
+ transportDomainUdpIpv4z,
+ transportDomainUdpIpv6z,
+ transportDomainTcpIpv4,
+ transportDomainTcpIpv6,
+ transportDomainTcpIpv4z,
+ transportDomainTcpIpv6z,
+ transportDomainSctpIpv4,
+ transportDomainSctpIpv6,
+ transportDomainSctpIpv4z,
+ transportDomainSctpIpv6z,
+ transportDomainLocal,
+ transportDomainUdpDns,
+ transportDomainTcpDns,
+ transportDomainSctpDns
+ ],
+ case lists:member(Domain, SupportedDomains) of
+ true ->
+ ok;
+ false ->
+ case lists:member(Domain, AllDomains) of
+ true ->
+ error({unsupported_domain, Domain});
+ false ->
+ error({unknown_domain, Domain})
+ end
+ end.
+
+
+%% ---------
+
+%% The values of Ip and Port has both been checked at this
+%% point, so we dont need to do that again.
+mk_taddress(snmpUDPDomain, Ip, Port) ->
+ mk_taddress(transportDomainUdpIpv4, Ip, Port);
+mk_taddress(transportDomainUdpIpv4, Ip, Port) when is_list(Ip) ->
+ Ip ++ [Port div 256, Port rem 256];
+mk_taddress(transportDomainUdpIpv4 = Domain, Ip, Port) when is_tuple(Ip) ->
+ mk_taddress(Domain, tuple_to_list(Ip), Port);
+mk_taddress(transportDomainUdpIpv6, Ip, Port) when is_list(Ip) ->
+ Ip ++ [Port div 256, Port rem 256];
+mk_taddress(transportDomainUdpIpv6 = Domain, Ip, Port) when is_tuple(Ip) ->
+ mk_taddress(Domain, tuple_to_list(Ip), Port);
+
+%% These are just for convenience
+mk_taddress(?snmpUDPDomain, Ip, Port) ->
+ mk_taddress(snmpUDPDomain, Ip, Port);
+mk_taddress(?transportDomainUdpIpv4, Ip, Port) ->
+ mk_taddress(transportDomainUdpIpv4, Ip, Port);
+mk_taddress(?transportDomainUdpIpv6, Ip, Port) ->
+ mk_taddress(transportDomainUdpIpv6, Ip, Port);
+
+%% Bad domain
+mk_taddress(BadDomain, _Ip, _Port) ->
+ error({bad_domain, BadDomain}).
+
+
+%% ---------
+
+which_domain(Ip) when is_list(Ip) andalso (length(Ip) =:= 4) ->
+ transportDomainUdpIpv4;
+which_domain(Ip) when is_tuple(Ip) andalso (size(Ip) =:= 4) ->
+ transportDomainUdpIpv4;
+which_domain(Ip) when is_list(Ip) andalso (length(Ip) =:= 8) ->
+ transportDomainUdpIpv6;
+which_domain(Ip) when is_tuple(Ip) andalso (size(Ip) =:= 8) ->
+ transportDomainUdpIpv6.
+
+
+%% ---------
+
+check_ip(X) ->
+ check_ip(snmpUDPDomain, X).
+
+check_ip(snmpUDPDomain, X) ->
+ check_ip(transportDomainUdpIpv4, X);
+check_ip(transportDomainUdpIpv4, X) when is_list(X) andalso (length(X) =:= 4) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_ip_address, X})
end;
-check_ip(X) ->
- error({invalid_ip_address, X}).
+check_ip(transportDomainUdpIpv4, X) ->
+ error({invalid_ip_address, X});
+
+check_ip(transportDomainUdpIpv6, X) when is_list(X) andalso (length(X) =:= 8) ->
+ case (catch all_integer(X)) of
+ true ->
+ ok;
+ false ->
+ error({invalid_ip_address, X})
+ end;
+check_ip(transportDomainUdpIpv6, X) ->
+ error({invalid_ip_address, X});
+
+check_ip(BadDomain, _X) ->
+ error({invalid_domain, BadDomain}).
+
%% ---------
diff --git a/lib/snmp/src/misc/snmp_config.erl b/lib/snmp/src/misc/snmp_config.erl
index 25350e08cb..813942225e 100644
--- a/lib/snmp/src/misc/snmp_config.erl
+++ b/lib/snmp/src/misc/snmp_config.erl
@@ -491,6 +491,9 @@ config_agent_snmp(Dir, Vsns) ->
Host = host(),
AgentIP = ask("5. IP address for the agent (only used as id ~n"
" when sending traps)", Host, fun verify_address/1),
+ %% We intentionally skip TDomain...
+ %% If the user wish to use IPv6, the user must create an dummy entry here
+ %% and then manually edit these entries later.
ManagerIP = ask("6. IP address for the manager (only this manager ~n"
" will have access to the agent, traps are sent ~n"
" to this one)", Host, fun verify_address/1),
@@ -1062,9 +1065,19 @@ verify_sec_type(ST) -> {error, "invalid security type: " ++ ST}.
verify_address(A) ->
- case (catch snmp_misc:ip(A)) of
+ verify_address(A, snmpUDPDomain).
+
+verify_address(A, snmpUDPDomain = _Domain) ->
+ do_verify_address(A, inet);
+verify_address(A, transportDomainUdpIpv4 = _Domain) ->
+ do_verify_address(A, inet);
+verify_address(A, transportDomainUdpIpv6 = _Domain) ->
+ do_verify_address(A, inet6).
+
+do_verify_address(A, Family) ->
+ case (catch snmp_misc:ip(A, Family)) of
{ok, IP} ->
- {ok, tuple_to_list(IP)};
+ {ok, tuple_to_list(IP)};
{error, _} ->
{error, "invalid address: " ++ A};
_E ->
@@ -1721,10 +1734,12 @@ write_agent_snmp_target_addr_conf(Dir, ManagerIp, UDP,
Hdr = header() ++ Comment,
F = fun(v1 = Vsn, Acc) ->
[{mk_ip(ManagerIp, Vsn),
+ snmp_target_mib:default_domain(),
ManagerIp, UDP, Timeout, RetryCount,
"std_trap", mk_param(Vsn), "", [], 2048}| Acc];
(v2 = Vsn, Acc) ->
[{mk_ip(ManagerIp, Vsn),
+ snmp_target_mib:default_domain(),
ManagerIp, UDP, Timeout, RetryCount,
"std_trap", mk_param(Vsn), "", [], 2048},
{lists:flatten(io_lib:format("~s.2",[mk_ip(ManagerIp, Vsn)])),
@@ -1732,6 +1747,7 @@ write_agent_snmp_target_addr_conf(Dir, ManagerIp, UDP,
"std_inform", mk_param(Vsn), "", [], 2048}| Acc];
(v3 = Vsn, Acc) ->
[{mk_ip(ManagerIp, Vsn),
+ snmp_target_mib:default_domain(),
ManagerIp, UDP, Timeout, RetryCount,
"std_trap", mk_param(Vsn), "", [], 2048},
{lists:flatten(io_lib:format("~s.3",[mk_ip(ManagerIp, Vsn)])),
diff --git a/lib/snmp/src/misc/snmp_log.erl b/lib/snmp/src/misc/snmp_log.erl
index f9aa911817..7930e37c66 100644
--- a/lib/snmp/src/misc/snmp_log.erl
+++ b/lib/snmp/src/misc/snmp_log.erl
@@ -266,9 +266,6 @@ validate_loop(eof, _Log, _Validatior, _PrevTS, _PrevSN) ->
ok;
validate_loop({error, _} = Error, _Log, _Validator, _PrevTS, _PrevSN) ->
Error;
-validate_loop({corrupt_log_file, _} = Reason,
- _Log, _Validator, _PrevTS, _PrevSN) ->
- {error, Reason};
validate_loop({Cont, Terms}, Log, Validator, PrevTS, PrevSN) ->
?vtrace("validate_loop -> entry with"
"~n Terms: ~p"
@@ -508,8 +505,6 @@ loop(eof, _Log, _Write) ->
ok;
loop({error, _} = Error, _Log, _Write) ->
Error;
-loop({corrupt_log_file, _} = Reason, _Log, _Write) ->
- {error, Reason};
loop({Cont, Terms}, Log, Write) ->
case (catch lists:foreach(Write, Terms)) of
{'EXIT', Reason} ->
diff --git a/lib/snmp/src/misc/snmp_misc.erl b/lib/snmp/src/misc/snmp_misc.erl
index 1b535743a4..6adef06ab9 100644
--- a/lib/snmp/src/misc/snmp_misc.erl
+++ b/lib/snmp/src/misc/snmp_misc.erl
@@ -40,7 +40,7 @@
get_option/2,
get_option/3,
get_sec_level/1,
- ip/1,
+ ip/1, ip/2,
is_auth/1,
is_BitString/1,
is_oid/1,
@@ -347,10 +347,15 @@ bits_to_int([Kibble|Ks],Kibbles,Res) ->
%%----------------------------------------------------------------------
-%% Returns: {ok, {int(),int(),int(),int()}} | {error, Reason}
+%% Returns: {ok, {int(),int(),int(),int()}} |
+%% {ok, {int(),int(),int(),int()},int(),int(),int(),int()} |
+%% {error, Reason}
%%----------------------------------------------------------------------
ip(Host) ->
- inet:getaddr(Host, inet).
+ ip(Host, inet).
+
+ip(Host, Family) ->
+ inet:getaddr(Host, Family).
ensure_trailing_dir_delimiter([]) -> "/";
ensure_trailing_dir_delimiter(DirSuggestion) ->
diff --git a/lib/snmp/src/misc/snmp_pdus.erl b/lib/snmp/src/misc/snmp_pdus.erl
index dc8900c8cd..82618a0b86 100644
--- a/lib/snmp/src/misc/snmp_pdus.erl
+++ b/lib/snmp/src/misc/snmp_pdus.erl
@@ -269,24 +269,35 @@ dec_value([64 | Bytes]) ->
{Value, Rest} = dec_oct_str_notag(Bytes),
{{'IpAddress', Value}, Rest};
dec_value([65 | Bytes]) ->
+ %% Counter32 is an unsigned 32 but is actually encoded as
+ %% a signed integer 32 (INTEGER).
{Value, Rest} = dec_integer_notag(Bytes),
- if Value >= 0, Value =< 4294967295 ->
- {{'Counter32', Value}, Rest};
- true ->
- exit({error, {bad_counter32, Value}})
- end;
+ Value2 =
+ if
+ (Value >= 0) andalso (Value =< 16#ffffffff) ->
+ %% We accept value above 16#7fffffff
+ %% in order to be backward bug-compatible
+ Value;
+ (Value < 0) ->
+ 16#ffffffff + Value + 1;
+ true ->
+ exit({error, {bad_counter32, Value}})
+ end,
+ {{'Counter32', Value2}, Rest};
dec_value([66 | Bytes]) ->
{Value, Rest} = dec_integer_notag(Bytes),
- if Value >= 0, Value =< 4294967295 ->
+ if
+ (Value >= 0) andalso (Value =< 4294967295) ->
{{'Unsigned32', Value}, Rest};
- true ->
+ true ->
exit({error, {bad_unsigned32, Value}})
end;
dec_value([67 | Bytes]) ->
{Value, Rest} = dec_integer_notag(Bytes),
- if Value >= 0, Value =< 4294967295 ->
+ if
+ (Value >= 0) andalso (Value =< 4294967295) ->
{{'TimeTicks', Value}, Rest};
- true ->
+ true ->
exit({error, {bad_timeticks, Value}})
end;
dec_value([68 | Bytes]) ->
@@ -642,6 +653,21 @@ enc_value(_Type, endOfMibView) ->
[130,0];
enc_value('NULL', _Val) ->
[5,0];
+enc_value('Counter32', Val) ->
+ Val2 =
+ if
+ Val > 16#ffffffff ->
+ exit({error, {bad_counter32, Val}});
+ Val >= 16#80000000 ->
+ (Val band 16#7fffffff) - 16#80000000;
+ Val >= 0 ->
+ Val;
+ true ->
+ exit({error, {bad_counter32, Val}})
+ end,
+ Bytes2 = enc_integer_notag(Val2),
+ Len2 = elength(length(Bytes2)),
+ lists:append([65 | Len2],Bytes2);
enc_value('Counter64', Val) ->
Val2 =
if
diff --git a/lib/snmp/test/Makefile b/lib/snmp/test/Makefile
index b7975024b4..0e9c73081d 100644
--- a/lib/snmp/test/Makefile
+++ b/lib/snmp/test/Makefile
@@ -145,9 +145,12 @@ endif
# ----------------------------------------------------
EBIN = .
-ERL_COMPILE_FLAGS += -I../src \
+ERL_COMPILE_FLAGS += -I../../snmp/src/app \
+ -I../../snmp/src/misc \
+ -I../../snmp/src/agent \
+ -I../../snmp/src/manager \
-I$(ERL_TOP)/lib/test_server/include \
- -I../include \
+ -I../../snmp/include \
-Dsnmp_test_data=snmp_test_data \
-Dversion=\"$(VSN)$(PRE_VSN)\" \
+'{parse_transform,sys_pre_attributes}' \
diff --git a/lib/snmp/test/snmp_agent_test.erl b/lib/snmp/test/snmp_agent_test.erl
index 692d29fda0..acf62f5646 100644
--- a/lib/snmp/test/snmp_agent_test.erl
+++ b/lib/snmp/test/snmp_agent_test.erl
@@ -81,13 +81,12 @@
case get(vsn) of
v1 -> V1;
v2 -> V2;
- _ -> V3
+ _ -> V3
end).
all() ->
- Reqs = [mnesia, distribution, {local_slave_nodes, 2},
- {time, 360}],
+ %% Reqs = [mnesia, distribution, {local_slave_nodes, 2}, {time, 360}],
Conf1 = [{group, all_tcs}],
Conf2 = [{group, tickets2}],
Conf1 ++ Conf2.
@@ -95,67 +94,138 @@ all() ->
groups() ->
[{all_tcs, [], cases()},
{mib_storage, [],
- [{group, mib_storage_ets}, {group, mib_storage_dets},
+ [
+ {group, mib_storage_ets},
+ {group, mib_storage_dets},
{group, mib_storage_mnesia},
{group, mib_storage_size_check_ets},
{group, mib_storage_size_check_dets},
{group, mib_storage_size_check_mnesia},
{group, mib_storage_varm_dets},
- {group, mib_storage_varm_mnesia}]},
- {mib_storage_ets, [], mib_storage_ets_cases()},
- {mib_storage_dets, [], mib_storage_dets_cases()},
- {mib_storage_mnesia, [], mib_storage_mnesia_cases()},
- {mib_storage_size_check_ets, [],
- mse_size_check_cases()},
- {mib_storage_size_check_dets, [],
- msd_size_check_cases()},
- {mib_storage_size_check_mnesia, [],
- msm_size_check_cases()},
- {mib_storage_varm_dets, [],
- varm_mib_storage_dets_cases()},
- {mib_storage_varm_mnesia, [],
- varm_mib_storage_mnesia_cases()},
- {misc, [], misc_cases()}, {test_v1, [], v1_cases()},
- {test_v2, [], v2_cases()},
- {test_v1_v2, [], v1_v2_cases()},
- {test_v3, [], v3_cases()},
- {test_multi_threaded, [], mt_cases()},
- {multiple_reqs, [], mul_cases()},
- {multiple_reqs_2, [], mul_cases_2()},
- {v2_inform, [], [v2_inform_i]},
+ {group, mib_storage_varm_mnesia}
+ ]
+ },
+ {mib_storage_ets, [], mib_storage_ets_cases()},
+ {mib_storage_dets, [], mib_storage_dets_cases()},
+ {mib_storage_mnesia, [], mib_storage_mnesia_cases()},
+ {mib_storage_size_check_ets, [], mse_size_check_cases()},
+ {mib_storage_size_check_dets, [], msd_size_check_cases()},
+ {mib_storage_size_check_mnesia, [], msm_size_check_cases()},
+ {mib_storage_varm_dets, [], varm_mib_storage_dets_cases()},
+ {mib_storage_varm_mnesia, [], varm_mib_storage_mnesia_cases()},
+ {misc, [], misc_cases()},
+ {test_v1, [], v1_cases()},
+ {test_v2, [], v2_cases()},
+ {test_v1_v2, [], v1_v2_cases()},
+ {test_v3, [], v3_cases()},
+ {test_multi_threaded, [], mt_cases()},
+ {multiple_reqs, [], mul_cases()},
+ {multiple_reqs_2, [], mul_cases_2()},
+ {v2_inform, [],
+ [
+ v2_inform_i
+ ]
+ },
{v3_security, [],
- [v3_crypto_basic, v3_md5_auth, v3_sha_auth,
- v3_des_priv]},
+ [
+ v3_crypto_basic,
+ v3_md5_auth,
+ v3_sha_auth,
+ v3_des_priv
+ ]
+ },
{standard_mibs, [],
- [snmp_standard_mib, snmp_community_mib,
- snmp_framework_mib, snmp_target_mib,
- snmp_notification_mib, snmp_view_based_acm_mib]},
+ [
+ snmp_standard_mib,
+ snmp_community_mib,
+ snmp_framework_mib,
+ snmp_target_mib,
+ snmp_notification_mib,
+ snmp_view_based_acm_mib
+ ]
+ },
{standard_mibs_2, [],
- [snmpv2_mib_2, snmp_community_mib_2,
- snmp_framework_mib_2, snmp_target_mib_2,
- snmp_notification_mib_2, snmp_view_based_acm_mib_2]},
+ [
+ snmpv2_mib_2,
+ snmp_community_mib_2,
+ snmp_framework_mib_2,
+ snmp_target_mib_2,
+ snmp_notification_mib_2,
+ snmp_view_based_acm_mib_2
+ ]
+ },
{standard_mibs_3, [],
- [snmpv2_mib_3, snmp_framework_mib_3, snmp_mpd_mib_3,
- snmp_target_mib_3, snmp_notification_mib_3,
- snmp_view_based_acm_mib_3, snmp_user_based_sm_mib_3]},
+ [
+ snmpv2_mib_3,
+ snmp_framework_mib_3,
+ snmp_mpd_mib_3,
+ snmp_target_mib_3,
+ snmp_notification_mib_3,
+ snmp_view_based_acm_mib_3,
+ snmp_user_based_sm_mib_3
+ ]
+ },
{reported_bugs, [],
- [otp_1128, otp_1129, otp_1131, otp_1162, otp_1222,
- otp_1298, otp_1331, otp_1338, otp_1342, otp_2776,
- otp_2979, otp_3187, otp_3725]},
+ [
+ otp_1128,
+ otp_1129,
+ otp_1131,
+ otp_1162,
+ otp_1222,
+ otp_1298,
+ otp_1331,
+ otp_1338,
+ otp_1342,
+ otp_2776,
+ otp_2979,
+ otp_3187,
+ otp_3725
+ ]
+ },
{reported_bugs_2, [],
- [otp_1128_2, otp_1129_2, otp_1131_2, otp_1162_2,
- otp_1222_2, otp_1298_2, otp_1331_2, otp_1338_2,
- otp_1342_2, otp_2776_2, otp_2979_2, otp_3187_2]},
+ [
+ otp_1128_2,
+ otp_1129_2,
+ otp_1131_2,
+ otp_1162_2,
+ otp_1222_2,
+ otp_1298_2,
+ otp_1331_2,
+ otp_1338_2,
+ otp_1342_2,
+ otp_2776_2,
+ otp_2979_2,
+ otp_3187_2
+ ]
+ },
{reported_bugs_3, [],
- [otp_1128_3, otp_1129_3, otp_1131_3, otp_1162_3,
- otp_1222_3, otp_1298_3, otp_1331_3, otp_1338_3,
- otp_1342_3, otp_2776_3, otp_2979_3, otp_3187_3,
- otp_3542]},
- {tickets1, [], [{group, otp_4394}, {group, otp_7157}]},
+ [
+ otp_1128_3,
+ otp_1129_3,
+ otp_1131_3,
+ otp_1162_3,
+ otp_1222_3,
+ otp_1298_3,
+ otp_1331_3,
+ otp_1338_3,
+ otp_1342_3,
+ otp_2776_3,
+ otp_2979_3,
+ otp_3187_3,
+ otp_3542
+ ]
+ },
+ {tickets1, [],
+ [
+ {group, otp_4394},
+ {group, otp_7157}
+ ]
+ },
{tickets2, [], [otp8395]},
{otp_4394, [], [otp_4394_test]},
- {otp_7157, [],
- begin Reqs = [], Conf = [otp_7157_test], Conf end}].
+ {otp_7157, [], [otp_7157_test]
+ }
+ ].
init_per_group(all_tcs, Config) ->
init_all(Config);
@@ -378,17 +448,29 @@ end_per_testcase2(_Case, Config) ->
cases() ->
-case ?OSTYPE() of
- vxworks ->
- [{group, misc}, {group, test_v1}, {group, test_v2},
- {group, test_v1_v2}, {group, test_multi_threaded},
- {group, mib_storage}, {group, tickets1}];
- _Else ->
- [{group, misc}, {group, test_v1}, {group, test_v2},
- {group, test_v1_v2}, {group, test_v3},
- {group, test_multi_threaded}, {group, mib_storage},
- {group, tickets1}]
-end.
+ case ?OSTYPE() of
+ vxworks ->
+ [
+ {group, misc},
+ {group, test_v1},
+ {group, test_v2},
+ {group, test_v1_v2},
+ {group, test_multi_threaded},
+ {group, mib_storage},
+ {group, tickets1}
+ ];
+ _Else ->
+ [
+ {group, misc},
+ {group, test_v1},
+ {group, test_v2},
+ {group, test_v1_v2},
+ {group, test_v3},
+ {group, test_multi_threaded},
+ {group, mib_storage},
+ {group, tickets1}
+ ]
+ end.
%%%-----------------------------------------------------------------
@@ -1071,11 +1153,29 @@ app_dir(App) ->
%v1_cases() -> [loop_mib];
v1_cases() ->
-[simple, db_notify_client, v1_processing, big, big2,
- loop_mib, api, subagent, mnesia, {group, multiple_reqs},
- sa_register, v1_trap, sa_error, next_across_sa, undo,
- {group, reported_bugs}, {group, standard_mibs},
- sparse_table, cnt_64, opaque, change_target_addr_config].
+ [
+ simple,
+ db_notify_client,
+ v1_processing,
+ big,
+ big2,
+ loop_mib,
+ api,
+ subagent,
+ mnesia,
+ {group, multiple_reqs},
+ sa_register,
+ v1_trap,
+ sa_error,
+ next_across_sa,
+ undo,
+ {group, reported_bugs},
+ {group, standard_mibs},
+ sparse_table,
+ cnt_64,
+ opaque,
+ change_target_addr_config
+ ].
init_v1(Config) when is_list(Config) ->
?line SaNode = ?config(snmp_sa, Config),
@@ -1094,12 +1194,31 @@ finish_v1(Config) when is_list(Config) ->
v2_cases() ->
-[simple_2, v2_processing, big_2, big2_2, loop_mib_2,
- api_2, subagent_2, mnesia_2, {group, multiple_reqs_2},
- sa_register_2, v2_trap, {group, v2_inform}, sa_error_2,
- next_across_sa_2, undo_2, {group, reported_bugs_2},
- {group, standard_mibs_2}, v2_types, implied,
- sparse_table_2, cnt_64_2, opaque_2, v2_caps].
+ [
+ simple_2,
+ v2_processing,
+ big_2,
+ big2_2,
+ loop_mib_2,
+ api_2,
+ subagent_2,
+ mnesia_2,
+ {group, multiple_reqs_2},
+ sa_register_2,
+ v2_trap,
+ {group, v2_inform},
+ sa_error_2,
+ next_across_sa_2,
+ undo_2,
+ {group, reported_bugs_2},
+ {group, standard_mibs_2},
+ v2_types,
+ implied,
+ sparse_table_2,
+ cnt_64_2,
+ opaque_2,
+ v2_caps
+ ].
init_v2(Config) when is_list(Config) ->
SaNode = ?config(snmp_sa, Config),
@@ -1118,7 +1237,7 @@ finish_v2(Config) when is_list(Config) ->
v1_v2_cases() ->
-[simple_bi].
+ [simple_bi].
init_v1_v2(Config) when is_list(Config) ->
SaNode = ?config(snmp_sa, Config),
@@ -1137,13 +1256,32 @@ finish_v1_v2(Config) when is_list(Config) ->
v3_cases() ->
-[simple_3, v3_processing, big_3, big2_3, api_3,
- subagent_3, mnesia_3, loop_mib_3, multiple_reqs_3,
- sa_register_3, v3_trap, v3_inform, sa_error_3,
- next_across_sa_3, undo_3, {group, reported_bugs_3},
- {group, standard_mibs_3}, {group, v3_security},
- v2_types_3, implied_3, sparse_table_3, cnt_64_3,
- opaque_3, v2_caps_3].
+ [
+ simple_3,
+ v3_processing,
+ big_3,
+ big2_3,
+ api_3,
+ subagent_3,
+ mnesia_3,
+ loop_mib_3,
+ multiple_reqs_3,
+ sa_register_3,
+ v3_trap,
+ v3_inform,
+ sa_error_3,
+ next_across_sa_3,
+ undo_3,
+ {group, reported_bugs_3},
+ {group, standard_mibs_3},
+ {group, v3_security},
+ v2_types_3,
+ implied_3,
+ sparse_table_3,
+ cnt_64_3,
+ opaque_3,
+ v2_caps_3
+ ].
init_v3(Config) when is_list(Config) ->
%% Make sure crypto works, otherwise start_agent will fail
diff --git a/lib/snmp/test/snmp_agent_test_lib.erl b/lib/snmp/test/snmp_agent_test_lib.erl
index 9e89aa889c..3ae2409997 100644
--- a/lib/snmp/test/snmp_agent_test_lib.erl
+++ b/lib/snmp/test/snmp_agent_test_lib.erl
@@ -1311,10 +1311,12 @@ rewrite_target_addr_conf(Dir, NewPort) ->
"~n NewPort: ~p", [NewPort]),
TAFile = filename:join(Dir, "target_addr.conf"),
case file:read_file_info(TAFile) of
- {ok, _} -> ok;
- {error, R} -> ?ERR("failure reading file info of "
- "target address config file: ~p",[R]),
- ok
+ {ok, _} ->
+ ok;
+ {error, R} ->
+ ?ERR("failure reading file info of "
+ "target address config file: ~p",[R]),
+ ok
end,
?line [TrapAddr|Addrs] =
@@ -1335,8 +1337,9 @@ rewrite_target_addr_conf(Dir, NewPort) ->
rewrite_target_addr_conf_check(O) ->
{ok,O}.
-rewrite_target_addr_conf2(NewPort,{Name,Ip,_Port,Timeout,Retry,
- "std_trap",EngineId}) ->
+rewrite_target_addr_conf2(NewPort,
+ {Name, Ip, _Port, Timeout, Retry,
+ "std_trap", EngineId}) ->
?LOG("rewrite_target_addr_conf2 -> entry with std_trap",[]),
{Name,Ip,NewPort,Timeout,Retry,"std_trap",EngineId};
rewrite_target_addr_conf2(_NewPort,O) ->
diff --git a/lib/snmp/test/snmp_manager_test.erl b/lib/snmp/test/snmp_manager_test.erl
index 50836db731..6bd62df655 100644
--- a/lib/snmp/test/snmp_manager_test.erl
+++ b/lib/snmp/test/snmp_manager_test.erl
@@ -37,13 +37,16 @@
-include_lib("snmp/include/snmp_types.hrl").
-include_lib("snmp/include/STANDARD-MIB.hrl").
+-include_lib("snmp/src/manager/snmpm_internal.hrl").
%%----------------------------------------------------------------------
%% External exports
%%----------------------------------------------------------------------
-export([
- all/0,groups/0,init_per_group/2,end_per_group/2,
+ all/0,
+ groups/0,
+ init_per_group/2, end_per_group/2,
init_per_testcase/2, end_per_testcase/2,
@@ -54,49 +57,45 @@
notify_started01/1,
notify_started02/1,
-
register_user1/1,
-
register_agent1/1,
register_agent2/1,
-
info/1,
-
-
-
simple_sync_get1/1,
simple_sync_get2/1,
+ simple_sync_get3/1,
simple_async_get1/1,
simple_async_get2/1,
-
+ simple_async_get3/1,
simple_sync_get_next1/1,
simple_sync_get_next2/1,
+ simple_sync_get_next3/1,
simple_async_get_next1/1,
simple_async_get_next2/1,
-
+ simple_async_get_next3/1,
simple_sync_set1/1,
simple_sync_set2/1,
+ simple_sync_set3/1,
simple_async_set1/1,
simple_async_set2/1,
-
+ simple_async_set3/1,
simple_sync_get_bulk1/1,
simple_sync_get_bulk2/1,
+ simple_sync_get_bulk3/1,
simple_async_get_bulk1/1,
simple_async_get_bulk2/1,
-
+ simple_async_get_bulk3/1,
misc_async1/1,
misc_async2/1,
discovery/1,
-
-
trap1/1,
trap2/1,
@@ -109,8 +108,6 @@
report/1,
-
-
otp8015_1/1,
otp8395_1/1
@@ -220,7 +217,7 @@ init_per_testcase2(Case, Config) ->
Conf2.
init_per_testcase3(Case, Config) ->
- OldApiCases =
+ ApiCases01 =
[
simple_sync_get1,
simple_async_get1,
@@ -232,7 +229,7 @@ init_per_testcase3(Case, Config) ->
simple_async_get_bulk1,
misc_async1
],
- NewApiCases =
+ ApiCases02 =
[
simple_sync_get2,
simple_async_get2,
@@ -245,6 +242,17 @@ init_per_testcase3(Case, Config) ->
misc_async2,
otp8395_1
],
+ ApiCases03 =
+ [
+ simple_sync_get3,
+ simple_async_get3,
+ simple_sync_get_next3,
+ simple_async_get_next3,
+ simple_sync_set3,
+ simple_async_set3,
+ simple_sync_get_bulk3,
+ simple_async_get_bulk3
+ ],
Cases =
[
trap1,
@@ -256,8 +264,9 @@ init_per_testcase3(Case, Config) ->
inform_swarm,
report
] ++
- OldApiCases ++
- NewApiCases,
+ ApiCases01 ++
+ ApiCases02 ++
+ ApiCases03,
case lists:member(Case, Cases) of
true ->
NoAutoInformCases = [inform1, inform2, inform3, inform_swarm],
@@ -279,7 +288,7 @@ init_per_testcase3(Case, Config) ->
Conf2 = init_agent(Conf1),
Conf3 = init_manager(AutoInform, Conf2),
Conf4 = init_mgr_user(Conf3),
- case lists:member(Case, NewApiCases) of
+ case lists:member(Case, ApiCases02 ++ ApiCases03) of
true ->
init_mgr_user_data2(Conf4);
false ->
@@ -301,7 +310,7 @@ end_per_testcase(Case, Config) when is_list(Config) ->
Conf2.
end_per_testcase2(Case, Config) ->
- OldApiCases =
+ ApiCases01 =
[
simple_sync_get1,
simple_async_get1,
@@ -313,7 +322,7 @@ end_per_testcase2(Case, Config) ->
simple_async_get_bulk1,
misc_async1
],
- NewApiCases =
+ ApiCases02 =
[
simple_sync_get2,
simple_async_get2,
@@ -326,6 +335,17 @@ end_per_testcase2(Case, Config) ->
misc_async2,
otp8395_1
],
+ ApiCases03 =
+ [
+ simple_sync_get3,
+ simple_async_get3,
+ simple_sync_get_next3,
+ simple_async_get_next3,
+ simple_sync_set3,
+ simple_async_set3,
+ simple_sync_get_bulk3,
+ simple_async_get_bulk3
+ ],
Cases =
[
trap1,
@@ -337,11 +357,12 @@ end_per_testcase2(Case, Config) ->
inform_swarm,
report
] ++
- OldApiCases ++
- NewApiCases,
+ ApiCases01 ++
+ ApiCases02 ++
+ ApiCases03,
case lists:member(Case, Cases) of
true ->
- Conf1 = case lists:member(Case, NewApiCases) of
+ Conf1 = case lists:member(Case, ApiCases02 ++ ApiCases03) of
true ->
fin_mgr_user_data2(Config);
false ->
@@ -360,42 +381,129 @@ end_per_testcase2(Case, Config) ->
%%======================================================================
all() ->
-[{group, start_and_stop_tests}, {group, misc_tests},
- {group, user_tests}, {group, agent_tests},
- {group, request_tests}, {group, event_tests}, discovery,
- {group, tickets}].
+ [
+ {group, start_and_stop_tests},
+ {group, misc_tests},
+ {group, user_tests},
+ {group, agent_tests},
+ {group, request_tests},
+ {group, event_tests},
+ discovery,
+ {group, tickets}
+ ].
groups() ->
- [{start_and_stop_tests, [],
- [simple_start_and_stop1, simple_start_and_stop2,
- simple_start_and_monitor_crash1,
- simple_start_and_monitor_crash2, notify_started01,
- notify_started02]},
- {misc_tests, [], [info]},
- {user_tests, [], [register_user1]},
- {agent_tests, [], [register_agent1, register_agent2]},
- {request_tests, [],
- [{group, get_tests}, {group, get_next_tests},
- {group, set_tests}, {group, bulk_tests},
- {group, misc_request_tests}]},
- {get_tests, [],
- [simple_sync_get1, simple_sync_get2, simple_async_get1,
- simple_async_get2]},
- {get_next_tests, [],
- [simple_sync_get_next1, simple_sync_get_next2,
- simple_async_get_next1, simple_async_get_next2]},
- {set_tests, [],
- [simple_sync_set1, simple_sync_set2, simple_async_set1,
- simple_async_set2]},
- {bulk_tests, [],
- [simple_sync_get_bulk1, simple_sync_get_bulk2,
- simple_async_get_bulk1, simple_async_get_bulk2]},
- {misc_request_tests, [], [misc_async1, misc_async2]},
- {event_tests, [],
- [trap1, trap2, inform1, inform2, inform3, inform4,
- inform_swarm, report]},
- {tickets, [], [{group, otp8015}, {group, otp8395}]},
- {otp8015, [], [otp8015_1]}, {otp8395, [], [otp8395_1]}].
+ [
+ {start_and_stop_tests, [],
+ [
+ simple_start_and_stop1,
+ simple_start_and_stop2,
+ simple_start_and_monitor_crash1,
+ simple_start_and_monitor_crash2,
+ notify_started01,
+ notify_started02
+ ]
+ },
+ {misc_tests, [],
+ [
+ info
+ ]
+ },
+ {user_tests, [],
+ [
+ register_user1
+ ]
+ },
+ {agent_tests, [],
+ [
+ register_agent1,
+ register_agent2
+ ]
+ },
+ {request_tests, [],
+ [
+ {group, get_tests},
+ {group, get_next_tests},
+ {group, set_tests},
+ {group, bulk_tests},
+ {group, misc_request_tests}
+ ]
+ },
+ {get_tests, [],
+ [
+ simple_sync_get1,
+ simple_sync_get2,
+ simple_sync_get3,
+ simple_async_get1,
+ simple_async_get2,
+ simple_async_get3
+ ]
+ },
+ {get_next_tests, [],
+ [
+ simple_sync_get_next1,
+ simple_sync_get_next2,
+ simple_sync_get_next3,
+ simple_async_get_next1,
+ simple_async_get_next2,
+ simple_async_get_next3
+ ]
+ },
+ {set_tests, [],
+ [
+ simple_sync_set1,
+ simple_sync_set2,
+ simple_sync_set3,
+ simple_async_set1,
+ simple_async_set2,
+ simple_async_set3
+ ]
+ },
+ {bulk_tests, [],
+ [
+ simple_sync_get_bulk1,
+ simple_sync_get_bulk2,
+ simple_sync_get_bulk3,
+ simple_async_get_bulk1,
+ simple_async_get_bulk2,
+ simple_async_get_bulk3
+ ]
+ },
+ {misc_request_tests, [],
+ [
+ misc_async1,
+ misc_async2
+ ]
+ },
+ {event_tests, [],
+ [
+ trap1,
+ trap2,
+ inform1,
+ inform2,
+ inform3,
+ inform4,
+ inform_swarm,
+ report
+ ]
+ },
+ {tickets, [],
+ [
+ {group, otp8015},
+ {group, otp8395}
+ ]
+ },
+ {otp8015, [],
+ [
+ otp8015_1
+ ]
+ },
+ {otp8395, [],
+ [
+ otp8395_1
+ ]
+ }
+ ].
init_per_group(_GroupName, Config) ->
Config.
@@ -404,21 +512,6 @@ end_per_group(_GroupName, Config) ->
Config.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
%%======================================================================
%% Test functions
%%======================================================================
@@ -1319,15 +1412,15 @@ simple_sync_get1(Config) when is_list(Config) ->
p("issue get-request without loading the mib"),
Oids1 = [?sysObjectID_instance, ?sysDescr_instance, ?sysUpTime_instance],
- ?line ok = do_simple_get(Node, Addr, Port, Oids1),
+ ?line ok = do_simple_sync_get(Node, Addr, Port, Oids1),
p("issue get-request after first loading the mibs"),
?line ok = mgr_user_load_mib(Node, std_mib()),
Oids2 = [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
- ?line ok = do_simple_get(Node, Addr, Port, Oids2),
+ ?line ok = do_simple_sync_get(Node, Addr, Port, Oids2),
ok.
-do_simple_get(Node, Addr, Port, Oids) ->
+do_simple_sync_get(Node, Addr, Port, Oids) ->
?line {ok, Reply, Rem} = mgr_user_sync_get(Node, Addr, Port, Oids),
?DBG("~n Reply: ~p"
@@ -1360,14 +1453,22 @@ do_simple_get(Node, Addr, Port, Oids) ->
%%======================================================================
-simple_sync_get2(doc) -> ["Simple sync get-request - New style (TargetName)"];
+simple_sync_get2(doc) ->
+ ["Simple sync get-request - Version 2 API (TargetName)"];
simple_sync_get2(suite) -> [];
simple_sync_get2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
put(tname, ssg2),
- do_simple_get(Config).
+ do_simple_sync_get2(Config).
-do_simple_get(Config) ->
+do_simple_sync_get2(Config) ->
+ Get = fun(Node, TargetName, Oids) ->
+ mgr_user_sync_get(Node, TargetName, Oids)
+ end,
+ PostVerify = fun() -> ok end,
+ do_simple_sync_get2(Config, Get, PostVerify).
+
+do_simple_sync_get2(Config, Get, PostVerify) ->
p("starting with Config: ~p~n", [Config]),
Node = ?config(manager_node, Config),
@@ -1375,20 +1476,21 @@ do_simple_get(Config) ->
p("issue get-request without loading the mib"),
Oids1 = [?sysObjectID_instance, ?sysDescr_instance, ?sysUpTime_instance],
- ?line ok = do_simple_get(Node, TargetName, Oids1),
+ ?line ok = do_simple_sync_get2(Node, TargetName, Oids1, Get, PostVerify),
p("issue get-request after first loading the mibs"),
?line ok = mgr_user_load_mib(Node, std_mib()),
Oids2 = [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
- ?line ok = do_simple_get(Node, TargetName, Oids2),
+ ?line ok = do_simple_sync_get2(Node, TargetName, Oids2, Get, PostVerify),
ok.
-
-do_simple_get(Node, TargetName, Oids) ->
- ?line {ok, Reply, Rem} = mgr_user_sync_get(Node, TargetName, Oids),
+
+do_simple_sync_get2(Node, TargetName, Oids, Get, PostVerify)
+ when is_function(Get, 3) andalso is_function(PostVerify, 0) ->
+ ?line {ok, Reply, Rem} = Get(Node, TargetName, Oids),
?DBG("~n Reply: ~p"
"~n Rem: ~w", [Reply, Rem]),
-
+
%% verify that the operation actually worked:
%% The order should be the same, so no need to seach
?line ok = case Reply of
@@ -1403,7 +1505,7 @@ do_simple_get(Node, TargetName, Oids) ->
"~n SysDescr: ~s"
"~n SysUpTime: ~w",
[SysObjectID, SysDescr, SysUpTime]),
- ok;
+ PostVerify();
{noError, 0, Vbs} ->
p("unexpected varbinds: ~n~p", [Vbs]),
{error, {unexpected_vbs, Vbs}};
@@ -1416,6 +1518,38 @@ do_simple_get(Node, TargetName, Oids) ->
%%======================================================================
+simple_sync_get3(doc) ->
+ ["Simple sync get-request - Version 3 API (TargetName and send-opts)"];
+simple_sync_get3(suite) -> [];
+simple_sync_get3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, ssg3),
+ do_simple_sync_get3(Config).
+
+do_simple_sync_get3(Config) ->
+ Self = self(),
+ Msg = simple_sync_get3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+ Get = fun(Node, TargetName, Oids) ->
+ mgr_user_sync_get2(Node, TargetName, Oids, SendOpts)
+ end,
+ PostVerify =
+ fun() ->
+ receive
+ Msg ->
+ ok
+ end
+ end,
+ do_simple_sync_get2(Config, Get, PostVerify).
+
+
+%%======================================================================
+
simple_async_get1(doc) -> ["Simple (async) get-request - "
"Old style (Addr & Port)"];
simple_async_get1(suite) -> [];
@@ -1435,40 +1569,41 @@ simple_async_get1(Config) when is_list(Config) ->
?line ok = agent_load_mib(AgentNode, Test2Mib),
Exec = fun(Data) ->
- async_g_exec1(MgrNode, Addr, Port, Data)
+ async_g_exec1(MgrNode, Addr, Port, Data)
end,
- Requests = [
- { 1,
- [?sysObjectID_instance],
- Exec,
- fun(X) -> sag_verify(X, [?sysObjectID_instance]) end},
- { 2,
- [?sysDescr_instance, ?sysUpTime_instance],
- Exec,
- fun(X) ->
- sag_verify(X, [?sysObjectID_instance,
- ?sysUpTime_instance])
- end},
- { 3,
- [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
- Exec,
- fun(X) ->
- sag_verify(X, [?sysObjectID_instance,
- ?sysDescr_instance,
- ?sysUpTime_instance])
- end},
- { 4,
- [?sysObjectID_instance,
- ?sysDescr_instance,
- ?sysUpTime_instance],
- Exec,
- fun(X) ->
- sag_verify(X, [?sysObjectID_instance,
- ?sysDescr_instance,
- ?sysUpTime_instance])
- end}
- ],
+ Requests =
+ [
+ { 1,
+ [?sysObjectID_instance],
+ Exec,
+ fun(X) -> sag_verify(X, [?sysObjectID_instance]) end },
+ { 2,
+ [?sysDescr_instance, ?sysUpTime_instance],
+ Exec,
+ fun(X) ->
+ sag_verify(X, [?sysObjectID_instance,
+ ?sysUpTime_instance])
+ end },
+ { 3,
+ [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
+ Exec,
+ fun(X) ->
+ sag_verify(X, [?sysObjectID_instance,
+ ?sysDescr_instance,
+ ?sysUpTime_instance])
+ end },
+ { 4,
+ [?sysObjectID_instance,
+ ?sysDescr_instance,
+ ?sysUpTime_instance],
+ Exec,
+ fun(X) ->
+ sag_verify(X, [?sysObjectID_instance,
+ ?sysDescr_instance,
+ ?sysUpTime_instance])
+ end }
+ ],
p("manager info when starting test: ~n~p", [mgr_info(MgrNode)]),
p("agent info when starting test: ~n~p", [agent_info(AgentNode)]),
@@ -1516,66 +1651,76 @@ sag_verify_vbs([Vb|_], [E|_]) ->
%%======================================================================
-simple_async_get2(doc) -> ["Simple (async) get-request - "
- "New style (TargetName)"];
+simple_async_get2(doc) ->
+ ["Simple (async) get-request - Version 2 API (TargetName)"];
simple_async_get2(suite) -> [];
simple_async_get2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
put(tname, sag2),
p("starting with Config: ~p~n", [Config]),
-
MgrNode = ?config(manager_node, Config),
AgentNode = ?config(agent_node, Config),
TargetName = ?config(manager_agent_target_name, Config),
+ Get = fun(Oids) -> async_g_exec2(MgrNode, TargetName, Oids) end,
+ PostVerify = fun(Res) -> Res end,
+ do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify).
+do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify) ->
?line ok = mgr_user_load_mib(MgrNode, std_mib()),
Test2Mib = test2_mib(Config),
?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
?line ok = agent_load_mib(AgentNode, Test2Mib),
-
- Exec = fun(Data) ->
- async_g_exec2(MgrNode, TargetName, Data)
- end,
-
- Requests = [
- { 1,
- [?sysObjectID_instance],
- Exec,
- fun(X) -> sag_verify(X, [?sysObjectID_instance]) end},
- { 2,
- [?sysDescr_instance, ?sysUpTime_instance],
- Exec,
- fun(X) ->
- sag_verify(X, [?sysObjectID_instance,
- ?sysUpTime_instance])
- end},
- { 3,
- [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
- Exec,
- fun(X) ->
- sag_verify(X, [?sysObjectID_instance,
- ?sysDescr_instance,
- ?sysUpTime_instance])
- end},
- { 4,
- [?sysObjectID_instance,
- ?sysDescr_instance,
- ?sysUpTime_instance],
- Exec,
- fun(X) ->
- sag_verify(X, [?sysObjectID_instance,
- ?sysDescr_instance,
- ?sysUpTime_instance])
- end}
- ],
+ do_simple_async_sync_get2(fun() -> mgr_info(MgrNode) end,
+ fun() -> agent_info(AgentNode) end,
+ Get, PostVerify).
+
+do_simple_async_sync_get2(MgrInfo, AgentInfo, Get, PostVerify)
+ when is_function(MgrInfo, 0) andalso
+ is_function(AgentInfo, 0) andalso
+ is_function(Get, 1) andalso
+ is_function(PostVerify, 1) ->
+ Requests =
+ [
+ { 1,
+ [?sysObjectID_instance],
+ Get,
+ fun(X) ->
+ PostVerify(sag_verify(X, [?sysObjectID_instance])) end},
+ { 2,
+ [?sysDescr_instance, ?sysUpTime_instance],
+ Get,
+ fun(X) ->
+ PostVerify(sag_verify(X, [?sysObjectID_instance,
+ ?sysUpTime_instance]))
+ end},
+ { 3,
+ [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],
+ Get,
+ fun(X) ->
+ PostVerify(sag_verify(X, [?sysObjectID_instance,
+ ?sysDescr_instance,
+ ?sysUpTime_instance]))
+
+ end},
+ { 4,
+ [?sysObjectID_instance,
+ ?sysDescr_instance,
+ ?sysUpTime_instance],
+ Get,
+ fun(X) ->
+ PostVerify(sag_verify(X, [?sysObjectID_instance,
+ ?sysDescr_instance,
+ ?sysUpTime_instance]))
+ end}
+ ],
- p("manager info when starting test: ~n~p", [mgr_info(MgrNode)]),
- p("agent info when starting test: ~n~p", [agent_info(AgentNode)]),
+ p("manager info when starting test: ~n~p", [MgrInfo()]),
+ p("agent info when starting test: ~n~p", [AgentInfo()]),
?line ok = async_exec(Requests, []),
- p("manager info when ending test: ~n~p", [mgr_info(MgrNode)]),
- p("agent info when ending test: ~n~p", [agent_info(AgentNode)]),
+ p("manager info when ending test: ~n~p", [MgrInfo()]),
+ p("agent info when ending test: ~n~p", [AgentInfo()]),
ok.
@@ -1585,6 +1730,36 @@ async_g_exec2(Node, TargetName, Oids) ->
%%======================================================================
+simple_async_get3(doc) ->
+ ["Simple (async) get-request - Version 3 API (TargetName and send-opts)"];
+simple_async_get3(suite) -> [];
+simple_async_get3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, sag3),
+ p("starting with Config: ~p~n", [Config]),
+ MgrNode = ?config(manager_node, Config),
+ AgentNode = ?config(agent_node, Config),
+ TargetName = ?config(manager_agent_target_name, Config),
+ Self = self(),
+ Msg = simple_async_get3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+ Get = fun(Oids) -> async_g_exec3(MgrNode, TargetName, Oids, SendOpts) end,
+ PostVerify = fun(ok) -> receive Msg -> ok end;
+ (Error) -> Error
+ end,
+ do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify).
+
+async_g_exec3(Node, TargetName, Oids, SendOpts) ->
+ mgr_user_async_get2(Node, TargetName, Oids, SendOpts).
+
+
+%%======================================================================
+
simple_sync_get_next1(doc) -> ["Simple (sync) get_next-request - "
"Old style (Addr & Port)"];
simple_sync_get_next1(suite) -> [];
@@ -1722,23 +1897,33 @@ check_ssgn_vbs([Vb|_], [E|_]) ->
%%======================================================================
-simple_sync_get_next2(doc) -> ["Simple (sync) get_next-request - "
- "New style (TargetName)"];
+simple_sync_get_next2(doc) ->
+ ["Simple (sync) get_next-request - Version 2 API (TargetName)"];
simple_sync_get_next2(suite) -> [];
simple_sync_get_next2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
- put(tname, ssgn),
+ put(tname, ssgn2),
p("starting with Config: ~p~n", [Config]),
- MgrNode = ?config(manager_node, Config),
- AgentNode = ?config(agent_node, Config),
+ GetNext = fun(Node, TargetName, Oids) ->
+ mgr_user_sync_get_next(Node, TargetName, Oids)
+ end,
+ PostVerify = fun(Res) -> Res end,
+ do_simple_sync_get_next2(Config, GetNext, PostVerify).
+
+do_simple_sync_get_next2(Config, GetNext, PostVerify)
+ when is_function(GetNext, 3) andalso is_function(PostVerify, 1) ->
+
+ MgrNode = ?config(manager_node, Config),
+ AgentNode = ?config(agent_node, Config),
TargetName = ?config(manager_agent_target_name, Config),
%% -- 1 --
Oids01 = [[1,3,7,1]],
VF01 = fun(X) -> verify_ssgn_reply1(X, [{[1,3,7,1],endOfMibView}]) end,
?line ok = do_simple_get_next(1,
- MgrNode, TargetName, Oids01, VF01),
+ MgrNode, TargetName, Oids01, VF01,
+ GetNext, PostVerify),
?line ok = mgr_user_load_mib(MgrNode, std_mib()),
@@ -1748,7 +1933,8 @@ simple_sync_get_next2(Config) when is_list(Config) ->
verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView])
end,
?line ok = do_simple_get_next(2,
- MgrNode, TargetName, Oids02, VF02),
+ MgrNode, TargetName, Oids02, VF02,
+ GetNext, PostVerify),
Test2Mib = test2_mib(Config),
?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
@@ -1761,7 +1947,8 @@ simple_sync_get_next2(Config) when is_list(Config) ->
verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}])
end,
?line ok = do_simple_get_next(3,
- MgrNode, TargetName, Oids03, VF03),
+ MgrNode, TargetName, Oids03, VF03,
+ GetNext, PostVerify),
%% -- 4 --
Oids04 = [[TCnt2, 2]],
@@ -1769,7 +1956,8 @@ simple_sync_get_next2(Config) when is_list(Config) ->
verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}])
end,
?line ok = do_simple_get_next(4,
- MgrNode, TargetName, Oids04, VF04),
+ MgrNode, TargetName, Oids04, VF04,
+ GetNext, PostVerify),
%% -- 5 --
?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),
@@ -1778,7 +1966,8 @@ simple_sync_get_next2(Config) when is_list(Config) ->
verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]})
end,
?line ok = do_simple_get_next(5,
- MgrNode, TargetName, Oids05, VF05),
+ MgrNode, TargetName, Oids05, VF05,
+ GetNext, PostVerify),
%% -- 6 --
?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),
@@ -1787,7 +1976,8 @@ simple_sync_get_next2(Config) when is_list(Config) ->
verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]})
end,
?line ok = do_simple_get_next(6,
- MgrNode, TargetName, Oids06, VF06),
+ MgrNode, TargetName, Oids06, VF06,
+ GetNext, PostVerify),
%% -- 7 --
?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),
@@ -1797,7 +1987,8 @@ simple_sync_get_next2(Config) when is_list(Config) ->
[?sysDescr, TGenErr3]})
end,
?line ok = do_simple_get_next(7,
- MgrNode, TargetName, Oids07, VF07),
+ MgrNode, TargetName, Oids07, VF07,
+ GetNext, PostVerify),
%% -- 8 --
?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),
@@ -1806,18 +1997,19 @@ simple_sync_get_next2(Config) when is_list(Config) ->
verify_ssgn_reply2(X, {tooBig, 0, []})
end,
?line ok = do_simple_get_next(8,
- MgrNode, TargetName, Oids08, VF08),
+ MgrNode, TargetName, Oids08, VF08,
+ GetNext, PostVerify),
ok.
-do_simple_get_next(N, Node, TargetName, Oids, Verify) ->
+do_simple_get_next(N, Node, TargetName, Oids, Verify, GetNext, PostVerify) ->
p("issue get-next command ~w", [N]),
- case mgr_user_sync_get_next(Node, TargetName, Oids) of
+ case GetNext(Node, TargetName, Oids) of
{ok, Reply, Rem} ->
?DBG("get-next ok:"
"~n Reply: ~p"
"~n Rem: ~w", [Reply, Rem]),
- Verify(Reply);
+ PostVerify(Verify(Reply));
Error ->
{error, {unexpected_reply, Error}}
@@ -1826,6 +2018,33 @@ do_simple_get_next(N, Node, TargetName, Oids, Verify) ->
%%======================================================================
+simple_sync_get_next3(doc) ->
+ ["Simple (sync) get_next-request - "
+ "Version 3 API (TargetName with send-opts)"];
+simple_sync_get_next3(suite) -> [];
+simple_sync_get_next3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, ssgn3),
+ p("starting with Config: ~p~n", [Config]),
+ Self = self(),
+ Msg = simple_sync_get_next3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+ GetNext = fun(Node, TargetName, Oids) ->
+ mgr_user_sync_get_next2(Node, TargetName, Oids, SendOpts)
+ end,
+ PostVerify = fun(ok) -> receive Msg -> ok end;
+ (Error) -> Error
+ end,
+ do_simple_sync_get_next2(Config, GetNext, PostVerify).
+
+
+%%======================================================================
+
simple_async_get_next1(doc) -> ["Simple (async) get_next-request - "
"Old style (Addr & Port)"];
simple_async_get_next1(suite) -> [];
@@ -1923,8 +2142,8 @@ async_gn_exec1(Node, Addr, Port, Oids) ->
%%======================================================================
-simple_async_get_next2(doc) -> ["Simple (async) get_next-request - "
- "New style (TargetName)"];
+simple_async_get_next2(doc) ->
+ ["Simple (async) get_next-request - Version 2 API (TargetName)"];
simple_async_get_next2(suite) -> [];
simple_async_get_next2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
@@ -1939,11 +2158,14 @@ simple_async_get_next2(Config) when is_list(Config) ->
Test2Mib = test2_mib(Config),
?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
?line ok = agent_load_mib(AgentNode, Test2Mib),
-
- Exec = fun(X) ->
- async_gn_exec2(MgrNode, TargetName, X)
- end,
-
+ GetNext = fun(Oids) ->
+ async_gn_exec2(MgrNode, TargetName, Oids)
+ end,
+ PostVerify = fun(Res) -> Res end,
+ do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify).
+
+do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify)
+ when is_function(GetNext, 1) andalso is_function(PostVerify, 1) ->
?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),
?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),
?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),
@@ -1954,51 +2176,60 @@ simple_async_get_next2(Config) when is_list(Config) ->
[
{1,
[[1,3,7,1]],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply1(X, [{[1,3,7,1], endOfMibView}])
+ PostVerify(
+ verify_ssgn_reply1(X, [{[1,3,7,1], endOfMibView}]))
+
end},
{2,
[[sysDescr], [1,3,7,1]],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView])
+ PostVerify(
+ verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView]))
end},
{3,
[[TCnt2, 1]],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}])
+ PostVerify(
+ verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}]))
end},
{4,
[[TCnt2, 2]],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}])
+ PostVerify(
+ verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}]))
end},
{5,
[TGenErr1],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]})
+ PostVerify(
+ verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}))
end},
{6,
[TGenErr2],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]})
+ PostVerify(
+ verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}))
end},
{7,
[[sysDescr], TGenErr3],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]})
+ PostVerify(
+ verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]}))
end},
{8,
[TTooBig],
- Exec,
+ GetNext,
fun(X) ->
- verify_ssgn_reply2(X, {tooBig, 0, []})
+ PostVerify(
+ verify_ssgn_reply2(X, {tooBig, 0, []}))
end}
],
@@ -2019,6 +2250,48 @@ async_gn_exec2(Node, TargetName, Oids) ->
%%======================================================================
+simple_async_get_next3(doc) ->
+ ["Simple (async) get_next-request - "
+ "Version 3 API (TargetName with send-opts)"];
+simple_async_get_next3(suite) -> [];
+simple_async_get_next3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, ssgn2),
+ p("starting with Config: ~p~n", [Config]),
+
+ MgrNode = ?config(manager_node, Config),
+ AgentNode = ?config(agent_node, Config),
+ TargetName = ?config(manager_agent_target_name, Config),
+
+ ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
+ Test2Mib = test2_mib(Config),
+ ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
+ ?line ok = agent_load_mib(AgentNode, Test2Mib),
+
+ Self = self(),
+ Msg = simple_async_get_next3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+
+ GetNext = fun(Oids) ->
+ async_gn_exec3(MgrNode, TargetName, Oids, SendOpts)
+ end,
+ PostVerify = fun(ok) -> receive Msg -> ok end;
+ (Error) -> Error
+ end,
+
+ do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify).
+
+async_gn_exec3(Node, TargetName, Oids, SendOpts) ->
+ mgr_user_async_get_next2(Node, TargetName, Oids, SendOpts).
+
+
+%%======================================================================
+
simple_sync_set1(doc) -> ["Simple (sync) set-request - "
"Old style (Addr & Port)"];
simple_sync_set1(suite) -> [];
@@ -2088,14 +2361,25 @@ value_of_vavs([{_Oid, Val}|VAVs], Acc) ->
%%======================================================================
-simple_sync_set2(doc) -> ["Simple (sync) set-request - New style (TargetName)"];
+simple_sync_set2(doc) ->
+ ["Simple (sync) set-request - Version 2 API (TargetName)"];
simple_sync_set2(suite) -> [];
simple_sync_set2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
put(tname, sss2),
p("starting with Config: ~p~n", [Config]),
- Node = ?config(manager_node, Config),
+ Set = fun(Node, TargetName, VAVs) ->
+ mgr_user_sync_set(Node, TargetName, VAVs)
+ end,
+ PostVerify = fun() -> ok end,
+
+ do_simple_sync_set2(Config, Set, PostVerify).
+
+do_simple_sync_set2(Config, Set, PostVerify)
+ when is_function(Set, 3) andalso is_function(PostVerify, 0) ->
+
+ Node = ?config(manager_node, Config),
TargetName = ?config(manager_agent_target_name, Config),
p("issue set-request without loading the mib"),
@@ -2105,7 +2389,7 @@ simple_sync_set2(Config) when is_list(Config) ->
{?sysName_instance, s, Val11},
{?sysLocation_instance, s, Val12}
],
- ?line ok = do_simple_set2(Node, TargetName, VAVs1),
+ ?line ok = do_simple_set2(Node, TargetName, VAVs1, Set, PostVerify),
p("issue set-request after first loading the mibs"),
?line ok = mgr_user_load_mib(Node, std_mib()),
@@ -2115,12 +2399,12 @@ simple_sync_set2(Config) when is_list(Config) ->
{[sysName, 0], Val21},
{[sysLocation, 0], Val22}
],
- ?line ok = do_simple_set2(Node, TargetName, VAVs2),
+ ?line ok = do_simple_set2(Node, TargetName, VAVs2, Set, PostVerify),
ok.
-do_simple_set2(Node, TargetName, VAVs) ->
+do_simple_set2(Node, TargetName, VAVs, Set, PostVerify) ->
[SysName, SysLoc] = value_of_vavs(VAVs),
- ?line {ok, Reply, Rem} = mgr_user_sync_set(Node, TargetName, VAVs),
+ ?line {ok, Reply, Rem} = Set(Node, TargetName, VAVs),
?DBG("~n Reply: ~p"
"~n Rem: ~w", [Reply, Rem]),
@@ -2133,7 +2417,7 @@ do_simple_set2(Node, TargetName, VAVs) ->
value = SysName},
#varbind{oid = ?sysLocation_instance,
value = SysLoc}]} ->
- ok;
+ PostVerify();
{noError, 0, Vbs} ->
{error, {unexpected_vbs, Vbs}};
Else ->
@@ -2145,6 +2429,33 @@ do_simple_set2(Node, TargetName, VAVs) ->
%%======================================================================
+simple_sync_set3(doc) ->
+ ["Simple (sync) set-request - Version 3 API (TargetName with send-opts)"];
+simple_sync_set3(suite) -> [];
+simple_sync_set3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, sss3),
+ p("starting with Config: ~p~n", [Config]),
+
+ Self = self(),
+ Msg = simple_sync_set3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+
+ Set = fun(Node, TargetName, VAVs) ->
+ mgr_user_sync_set2(Node, TargetName, VAVs, SendOpts)
+ end,
+ PostVerify = fun() -> receive Msg -> ok end end,
+
+ do_simple_sync_set2(Config, Set, PostVerify).
+
+
+%%======================================================================
+
simple_async_set1(doc) -> ["Simple (async) set-request - "
"Old style (Addr & Port)"];
simple_async_set1(suite) -> [];
@@ -2237,8 +2548,8 @@ sas_verify_vbs([Vb|_], [E|_]) ->
%%======================================================================
-simple_async_set2(doc) -> ["Simple (async) set-request - "
- "New style (TargetName)"];
+simple_async_set2(doc) ->
+ ["Simple (async) set-request - Version 2 API (TargetName)"];
simple_async_set2(suite) -> [];
simple_async_set2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
@@ -2254,31 +2565,40 @@ simple_async_set2(Config) when is_list(Config) ->
?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
?line ok = agent_load_mib(AgentNode, Test2Mib),
- Exec = fun(X) ->
- async_s_exec2(MgrNode, TargetName, X)
- end,
+ Set =
+ fun(Oids) ->
+ async_s_exec2(MgrNode, TargetName, Oids)
+ end,
+ PostVerify = fun(Res) -> Res end,
+
+ do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify).
+do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify) ->
Requests =
[
{1,
[{?sysName_instance, s, "Arne Anka"}],
- Exec,
+ Set,
fun(X) ->
- sas_verify(X, [?sysName_instance])
+ PostVerify(sas_verify(X, [?sysName_instance]))
end},
{2,
[{?sysLocation_instance, s, "Stockholm"},
{?sysName_instance, s, "Arne Anka"}],
- Exec,
+ Set,
fun(X) ->
- sas_verify(X, [?sysLocation_instance, ?sysName_instance])
+ PostVerify(sas_verify(X,
+ [?sysLocation_instance,
+ ?sysName_instance]))
end},
{3,
[{[sysName, 0], "Gothenburg"},
{[sysLocation, 0], "Sune Anka"}],
- Exec,
+ Set,
fun(X) ->
- sas_verify(X, [?sysName_instance, ?sysLocation_instance])
+ PostVerify(sas_verify(X,
+ [?sysName_instance,
+ ?sysLocation_instance]))
end}
],
@@ -2299,6 +2619,48 @@ async_s_exec2(Node, TargetName, VAVs) ->
%%======================================================================
+simple_async_set3(doc) ->
+ ["Simple (async) set-request - Version 3 API (TargetName with send-opts)"];
+simple_async_set3(suite) -> [];
+simple_async_set3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, sas3),
+ p("starting with Config: ~p~n", [Config]),
+
+ MgrNode = ?config(manager_node, Config),
+ AgentNode = ?config(agent_node, Config),
+ TargetName = ?config(manager_agent_target_name, Config),
+
+ ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
+ Test2Mib = test2_mib(Config),
+ ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
+ ?line ok = agent_load_mib(AgentNode, Test2Mib),
+
+ Self = self(),
+ Msg = simple_async_set3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+
+ Set =
+ fun(Oids) ->
+ async_s_exec3(MgrNode, TargetName, Oids, SendOpts)
+ end,
+ PostVerify = fun(ok) -> receive Msg -> ok end;
+ (Res) -> Res
+ end,
+
+ do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify).
+
+async_s_exec3(Node, TargetName, VAVs, SendOpts) ->
+ mgr_user_async_set2(Node, TargetName, VAVs, SendOpts).
+
+
+%%======================================================================
+
simple_sync_get_bulk1(doc) -> ["Simple (sync) get_bulk-request - "
"Old style (Addr & Port)"];
simple_sync_get_bulk1(suite) -> [];
@@ -2470,8 +2832,8 @@ check_ssgb_vbs([R|_], [E|_]) ->
%%======================================================================
-simple_sync_get_bulk2(doc) -> ["Simple (sync) get_bulk-request - "
- "New style (TargetName)"];
+simple_sync_get_bulk2(doc) ->
+ ["Simple (sync) get_bulk-request - Version 2 API (TargetName)"];
simple_sync_get_bulk2(suite) -> [];
simple_sync_get_bulk2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
@@ -2482,20 +2844,33 @@ simple_sync_get_bulk2(Config) when is_list(Config) ->
AgentNode = ?config(agent_node, Config),
TargetName = ?config(manager_agent_target_name, Config),
+ GetBulk =
+ fun(NonRep, MaxRep, Oids) ->
+ mgr_user_sync_get_bulk(MgrNode, TargetName,
+ NonRep, MaxRep, Oids)
+ end,
+ PostVerify = fun(Res) -> Res end,
+
+ do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify).
+
+do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify) ->
%% -- 1 --
?line ok = do_simple_get_bulk2(1,
- MgrNode, TargetName, 1, 1, [],
- fun verify_ssgb_reply1/1),
+ 1, 1, [],
+ fun verify_ssgb_reply1/1,
+ GetBulk, PostVerify),
%% -- 2 --
?line ok = do_simple_get_bulk2(2,
- MgrNode, TargetName, -1, 1, [],
- fun verify_ssgb_reply1/1),
+ -1, 1, [],
+ fun verify_ssgb_reply1/1,
+ GetBulk, PostVerify),
%% -- 3 --
?line ok = do_simple_get_bulk2(3,
- MgrNode, TargetName, -1, -1, [],
- fun verify_ssgb_reply1/1),
+ -1, -1, [],
+ fun verify_ssgb_reply1/1,
+ GetBulk, PostVerify),
?line ok = mgr_user_load_mib(MgrNode, std_mib()),
%% -- 4 --
@@ -2503,13 +2878,13 @@ simple_sync_get_bulk2(Config) when is_list(Config) ->
verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView])
end,
?line ok = do_simple_get_bulk2(4,
- MgrNode, TargetName,
- 2, 0, [[sysDescr],[1,3,7,1]], VF04),
+ 2, 0, [[sysDescr],[1,3,7,1]], VF04,
+ GetBulk, PostVerify),
%% -- 5 --
?line ok = do_simple_get_bulk2(5,
- MgrNode, TargetName,
- 1, 2, [[sysDescr],[1,3,7,1]], VF04),
+ 1, 2, [[sysDescr],[1,3,7,1]], VF04,
+ GetBulk, PostVerify),
%% -- 6 --
VF06 = fun(X) ->
@@ -2518,8 +2893,8 @@ simple_sync_get_bulk2(Config) when is_list(Config) ->
?sysObjectID_instance, endOfMibView])
end,
?line ok = do_simple_get_bulk2(6,
- MgrNode, TargetName,
- 0, 2, [[sysDescr],[1,3,7,1]], VF06),
+ 0, 2, [[sysDescr],[1,3,7,1]], VF06,
+ GetBulk, PostVerify),
%% -- 7 --
VF07 = fun(X) ->
@@ -2529,10 +2904,10 @@ simple_sync_get_bulk2(Config) when is_list(Config) ->
?sysObjectID_instance, endOfMibView])
end,
?line ok = do_simple_get_bulk2(7,
- MgrNode, TargetName,
2, 2,
[[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]],
- VF07),
+ VF07,
+ GetBulk, PostVerify),
Test2Mib = test2_mib(Config),
?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
@@ -2545,17 +2920,17 @@ simple_sync_get_bulk2(Config) when is_list(Config) ->
?sysDescr_instance])
end,
?line ok = do_simple_get_bulk2(8,
- MgrNode, TargetName,
1, 2,
[[sysDescr],[sysDescr],[tTooBig]],
- VF08),
+ VF08,
+ GetBulk, PostVerify),
%% -- 9 --
?line ok = do_simple_get_bulk2(9,
- MgrNode, TargetName,
1, 12,
[[tDescr2], [sysDescr]],
- fun verify_ssgb_reply1/1),
+ fun verify_ssgb_reply1/1,
+ GetBulk, PostVerify),
%% -- 10 --
VF10 = fun(X) ->
@@ -2566,13 +2941,13 @@ simple_sync_get_bulk2(Config) when is_list(Config) ->
{?sysDescr, 'NULL'}])
end,
?line ok = do_simple_get_bulk2(10,
- MgrNode, TargetName,
2, 2,
[[sysDescr],
[sysObjectID],
[tGenErr1],
[sysDescr]],
- VF10),
+ VF10,
+ GetBulk, PostVerify),
%% -- 11 --
?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),
@@ -2583,20 +2958,25 @@ simple_sync_get_bulk2(Config) when is_list(Config) ->
{fl([TCnt2,2]), endOfMibView}])
end,
?line ok = do_simple_get_bulk2(11,
- MgrNode, TargetName,
0, 2,
- [[TCnt2, 1]], VF11),
+ [[TCnt2, 1]], VF11,
+ GetBulk, PostVerify),
ok.
-do_simple_get_bulk2(N, Node, TargetName, NonRep, MaxRep, Oids, Verify) ->
+do_simple_get_bulk2(N,
+ NonRep, MaxRep, Oids,
+ Verify, GetBulk, PostVerify)
+ when is_function(Verify, 1) andalso
+ is_function(GetBulk, 3) andalso
+ is_function(PostVerify) ->
p("issue get-bulk command ~w", [N]),
- case mgr_user_sync_get_bulk(Node, TargetName, NonRep, MaxRep, Oids) of
+ case GetBulk(NonRep, MaxRep, Oids) of
{ok, Reply, Rem} ->
?DBG("get-bulk ok:"
"~n Reply: ~p"
"~n Rem: ~w", [Reply, Rem]),
- Verify(Reply);
+ PostVerify(Verify(Reply));
Error ->
{error, {unexpected_reply, Error}}
@@ -2605,6 +2985,42 @@ do_simple_get_bulk2(N, Node, TargetName, NonRep, MaxRep, Oids, Verify) ->
%%======================================================================
+simple_sync_get_bulk3(doc) ->
+ ["Simple (sync) get_bulk-request - "
+ "Version 3 API (TargetName with send-opts)"];
+simple_sync_get_bulk3(suite) -> [];
+simple_sync_get_bulk3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, ssgb3),
+ p("starting with Config: ~p~n", [Config]),
+
+ MgrNode = ?config(manager_node, Config),
+ AgentNode = ?config(agent_node, Config),
+ TargetName = ?config(manager_agent_target_name, Config),
+
+ Self = self(),
+ Msg = simple_async_set3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+
+ GetBulk =
+ fun(NonRep, MaxRep, Oids) ->
+ mgr_user_sync_get_bulk2(MgrNode, TargetName,
+ NonRep, MaxRep, Oids, SendOpts)
+ end,
+ PostVerify = fun(ok) -> receive Msg -> ok end;
+ (Res) -> Res
+ end,
+
+ do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify).
+
+
+%%======================================================================
+
simple_async_get_bulk1(doc) -> ["Simple (async) get_bulk-request - "
"Old style (Addr & Port)"];
simple_async_get_bulk1(suite) -> [];
@@ -2748,8 +3164,8 @@ async_gb_exec1(Node, Addr, Port, {NR, MR, Oids}) ->
%%======================================================================
-simple_async_get_bulk2(doc) -> ["Simple (async) get_bulk-request - "
- "New style (TargetName)"];
+simple_async_get_bulk2(doc) ->
+ ["Simple (async) get_bulk-request - Version 2 API (TargetName)"];
simple_async_get_bulk2(suite) -> [];
simple_async_get_bulk2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
@@ -2765,111 +3181,122 @@ simple_async_get_bulk2(Config) when is_list(Config) ->
?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
?line ok = agent_load_mib(AgentNode, Test2Mib),
- Exec = fun(Data) ->
- async_gb_exec2(MgrNode, TargetName, Data)
- end,
+ GetBulk =
+ fun(Data) ->
+ async_gb_exec2(MgrNode, TargetName, Data)
+ end,
+ PostVerify = fun(Res) -> Res end,
+ do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify).
+
+do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify) ->
%% We re-use the verification functions from the ssgb test-case
VF04 = fun(X) ->
- verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView])
+ PostVerify(
+ verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]))
end,
VF06 = fun(X) ->
- verify_ssgb_reply2(X,
- [?sysDescr_instance, endOfMibView,
- ?sysObjectID_instance, endOfMibView])
+ PostVerify(
+ verify_ssgb_reply2(X,
+ [?sysDescr_instance, endOfMibView,
+ ?sysObjectID_instance, endOfMibView]))
end,
VF07 = fun(X) ->
- verify_ssgb_reply2(X,
- [?sysDescr_instance, endOfMibView,
- ?sysDescr_instance, endOfMibView,
- ?sysObjectID_instance, endOfMibView])
+ PostVerify(
+ verify_ssgb_reply2(X,
+ [?sysDescr_instance, endOfMibView,
+ ?sysDescr_instance, endOfMibView,
+ ?sysObjectID_instance, endOfMibView]))
end,
VF08 = fun(X) ->
- verify_ssgb_reply2(X,
- [?sysDescr_instance,
- ?sysDescr_instance])
+ PostVerify(
+ verify_ssgb_reply2(X,
+ [?sysDescr_instance,
+ ?sysDescr_instance]))
end,
VF10 = fun(X) ->
- verify_ssgb_reply3(X,
- [{?sysDescr, 'NULL'},
- {?sysObjectID, 'NULL'},
- {?tGenErr1, 'NULL'},
- {?sysDescr, 'NULL'}])
+ PostVerify(
+ verify_ssgb_reply3(X,
+ [{?sysDescr, 'NULL'},
+ {?sysObjectID, 'NULL'},
+ {?tGenErr1, 'NULL'},
+ {?sysDescr, 'NULL'}]))
end,
?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),
VF11 = fun(X) ->
- verify_ssgb_reply2(X,
- [{fl([TCnt2,2]), 100},
- {fl([TCnt2,2]), endOfMibView}])
+ PostVerify(
+ verify_ssgb_reply2(X,
+ [{fl([TCnt2,2]), 100},
+ {fl([TCnt2,2]), endOfMibView}]))
end,
Requests = [
{ 1,
{1, 1, []},
- Exec,
- fun verify_ssgb_reply1/1},
+ GetBulk,
+ fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
{ 2,
{-1, 1, []},
- Exec,
- fun verify_ssgb_reply1/1},
+ GetBulk,
+ fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
{ 3,
{-1, -1, []},
- Exec,
- fun verify_ssgb_reply1/1},
+ GetBulk,
+ fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
{ 4,
{2, 0, [[sysDescr],[1,3,7,1]]},
- Exec,
+ GetBulk,
VF04},
{ 5,
{1, 2, [[sysDescr],[1,3,7,1]]},
- Exec,
+ GetBulk,
VF04},
{ 6,
{0, 2, [[sysDescr],[1,3,7,1]]},
- Exec,
+ GetBulk,
VF06},
{ 7,
{2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]},
- Exec,
+ GetBulk,
VF07},
{ 8,
{1, 2, [[sysDescr],[sysDescr],[tTooBig]]},
- Exec,
+ GetBulk,
VF08},
{ 9,
{1, 12, [[tDescr2], [sysDescr]]},
- Exec,
- fun verify_ssgb_reply1/1},
+ GetBulk,
+ fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
{10,
{2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]},
- Exec,
+ GetBulk,
VF10},
{11,
{0, 2, [[TCnt2, 1]]},
- Exec,
+ GetBulk,
VF11},
{12,
{2, 0, [[sysDescr],[1,3,7,1]]},
- Exec,
+ GetBulk,
VF04},
{13,
{1, 12, [[tDescr2], [sysDescr]]},
- Exec,
- fun verify_ssgb_reply1/1},
+ GetBulk,
+ fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},
{14,
{2, 2, [[sysDescr],[sysObjectID],[tGenErr1],[sysDescr]]},
- Exec,
+ GetBulk,
VF10},
{15,
{0, 2, [[TCnt2, 1]]},
- Exec,
+ GetBulk,
VF11},
{16,
{2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]},
- Exec,
+ GetBulk,
VF07},
{17,
{2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]},
- Exec,
+ GetBulk,
VF10}
],
@@ -2890,6 +3317,49 @@ async_gb_exec2(Node, TargetName, {NR, MR, Oids}) ->
%%======================================================================
+simple_async_get_bulk3(doc) ->
+ ["Simple (async) get_bulk-request - "
+ "Version 3 API (TargetName with send-opts)"];
+simple_async_get_bulk3(suite) -> [];
+simple_async_get_bulk3(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ put(tname, sagb3),
+ p("starting with Config: ~p~n", [Config]),
+
+ MgrNode = ?config(manager_node, Config),
+ AgentNode = ?config(agent_node, Config),
+ TargetName = ?config(manager_agent_target_name, Config),
+
+ ?line ok = mgr_user_load_mib(MgrNode, std_mib()),
+ Test2Mib = test2_mib(Config),
+ ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),
+ ?line ok = agent_load_mib(AgentNode, Test2Mib),
+
+ Self = self(),
+ Msg = simple_async_get_bulk3,
+ Fun = fun() -> Self ! Msg end,
+ Extra = {?SNMPM_EXTRA_INFO_TAG, Fun},
+ SendOpts =
+ [
+ {extra, Extra}
+ ],
+
+ GetBulk =
+ fun(Data) ->
+ async_gb_exec3(MgrNode, TargetName, Data, SendOpts)
+ end,
+ PostVerify = fun(ok) -> receive Msg -> ok end;
+ (Res) -> Res
+ end,
+
+ do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify).
+
+async_gb_exec3(Node, TargetName, {NR, MR, Oids}, SendOpts) ->
+ mgr_user_async_get_bulk2(Node, TargetName, NR, MR, Oids, SendOpts).
+
+
+%%======================================================================
+
misc_async1(doc) -> ["Misc (async) request(s) - "
"Old style (Addr & Port)"];
misc_async1(suite) -> [];
@@ -3079,8 +3549,8 @@ misc_async1(Config) when is_list(Config) ->
%%======================================================================
-misc_async2(doc) -> ["Misc (async) request(s) - "
- "New style (TargetName)"];
+misc_async2(doc) ->
+ ["Misc (async) request(s) - Version 2 API (TargetName)"];
misc_async2(suite) -> [];
misc_async2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
@@ -4440,7 +4910,7 @@ otp8395_1(suite) -> [];
otp8395_1(Config) when is_list(Config) ->
process_flag(trap_exit, true),
put(tname, otp8395_1),
- do_simple_get(Config).
+ do_simple_sync_get2(Config).
%%======================================================================
@@ -4986,6 +5456,9 @@ mgr_user_sync_get(Node, Addr_or_TargetName, Oids) ->
mgr_user_sync_get(Node, Addr, Port, Oids) ->
rcall(Node, snmp_manager_user, sync_get, [Addr, Port, Oids]).
+mgr_user_sync_get2(Node, TargetName, Oids, SendOpts) ->
+ rcall(Node, snmp_manager_user, sync_get2, [TargetName, Oids, SendOpts]).
+
%% mgr_user_async_get(Node, Oids) ->
%% mgr_user_async_get(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).
mgr_user_async_get(Node, Addr_or_TargetName, Oids) ->
@@ -4993,6 +5466,9 @@ mgr_user_async_get(Node, Addr_or_TargetName, Oids) ->
mgr_user_async_get(Node, Addr, Port, Oids) ->
rcall(Node, snmp_manager_user, async_get, [Addr, Port, Oids]).
+mgr_user_async_get2(Node, TargetName, Oids, SendOpts) ->
+ rcall(Node, snmp_manager_user, async_get2, [TargetName, Oids, SendOpts]).
+
%% mgr_user_sync_get_next(Node, Oids) ->
%% mgr_user_sync_get_next(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).
mgr_user_sync_get_next(Node, Addr_or_TargetName, Oids) ->
@@ -5000,6 +5476,9 @@ mgr_user_sync_get_next(Node, Addr_or_TargetName, Oids) ->
mgr_user_sync_get_next(Node, Addr, Port, Oids) ->
rcall(Node, snmp_manager_user, sync_get_next, [Addr, Port, Oids]).
+mgr_user_sync_get_next2(Node, TargetName, Oids, SendOpts) ->
+ rcall(Node, snmp_manager_user, sync_get_next2, [TargetName, Oids, SendOpts]).
+
%% mgr_user_async_get_next(Node, Oids) ->
%% mgr_user_async_get_next(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).
mgr_user_async_get_next(Node, Addr_or_TargetName, Oids) ->
@@ -5007,6 +5486,9 @@ mgr_user_async_get_next(Node, Addr_or_TargetName, Oids) ->
mgr_user_async_get_next(Node, Addr, Port, Oids) ->
rcall(Node, snmp_manager_user, async_get_next, [Addr, Port, Oids]).
+mgr_user_async_get_next2(Node, TargetName, Oids, SendOpts) ->
+ rcall(Node, snmp_manager_user, async_get_next2, [TargetName, Oids, SendOpts]).
+
%% mgr_user_sync_set(Node, VAV) ->
%% mgr_user_sync_set(Node, ?LOCALHOST(), ?AGENT_PORT, VAV).
mgr_user_sync_set(Node, Addr_or_TargetName, VAV) ->
@@ -5014,6 +5496,9 @@ mgr_user_sync_set(Node, Addr_or_TargetName, VAV) ->
mgr_user_sync_set(Node, Addr, Port, VAV) ->
rcall(Node, snmp_manager_user, sync_set, [Addr, Port, VAV]).
+mgr_user_sync_set2(Node, TargetName, VAV, SendOpts) ->
+ rcall(Node, snmp_manager_user, sync_set2, [TargetName, VAV, SendOpts]).
+
%% mgr_user_async_set(Node, VAV) ->
%% mgr_user_async_set(Node, ?LOCALHOST(), ?AGENT_PORT, VAV).
mgr_user_async_set(Node, Addr_or_TargetName, VAV) ->
@@ -5021,26 +5506,37 @@ mgr_user_async_set(Node, Addr_or_TargetName, VAV) ->
mgr_user_async_set(Node, Addr, Port, VAV) ->
rcall(Node, snmp_manager_user, async_set, [Addr, Port, VAV]).
+mgr_user_async_set2(Node, TargetName, VAV, SendOpts) ->
+ rcall(Node, snmp_manager_user, async_set2, [TargetName, VAV, SendOpts]).
+
%% mgr_user_sync_get_bulk(Node, NonRep, MaxRep, Oids) ->
%% mgr_user_sync_get_bulk(Node, ?LOCALHOST(), ?AGENT_PORT,
%% NonRep, MaxRep, Oids).
mgr_user_sync_get_bulk(Node, Addr_or_TargetName, NonRep, MaxRep, Oids) ->
rcall(Node, snmp_manager_user, sync_get_bulk,
- [Addr_or_TargetName, NonRep, MaxRep, Oids]).
+ [Addr_or_TargetName, NonRep, MaxRep, Oids]).
mgr_user_sync_get_bulk(Node, Addr, Port, NonRep, MaxRep, Oids) ->
rcall(Node, snmp_manager_user, sync_get_bulk,
[Addr, Port, NonRep, MaxRep, Oids]).
+mgr_user_sync_get_bulk2(Node, TargetName, NonRep, MaxRep, Oids, SendOpts) ->
+ rcall(Node, snmp_manager_user, sync_get_bulk2,
+ [TargetName, NonRep, MaxRep, Oids, SendOpts]).
+
%% mgr_user_async_get_bulk(Node, NonRep, MaxRep, Oids) ->
%% mgr_user_async_get_bulk(Node, ?LOCALHOST(), ?AGENT_PORT,
%% NonRep, MaxRep, Oids).
mgr_user_async_get_bulk(Node, Addr_or_TargetName, NonRep, MaxRep, Oids) ->
rcall(Node, snmp_manager_user, async_get_bulk,
- [Addr_or_TargetName, NonRep, MaxRep, Oids]).
+ [Addr_or_TargetName, NonRep, MaxRep, Oids]).
mgr_user_async_get_bulk(Node, Addr, Port, NonRep, MaxRep, Oids) ->
rcall(Node, snmp_manager_user, async_get_bulk,
[Addr, Port, NonRep, MaxRep, Oids]).
+mgr_user_async_get_bulk2(Node, TargetName, NonRep, MaxRep, Oids, SendOpts) ->
+ rcall(Node, snmp_manager_user, async_get_bulk2,
+ [TargetName, NonRep, MaxRep, Oids, SendOpts]).
+
mgr_user_purify_oid(Node, Oid) ->
rcall(Node, snmp_manager_user, purify_oid, [Oid]).
diff --git a/lib/snmp/test/snmp_manager_user.erl b/lib/snmp/test/snmp_manager_user.erl
index b0e192344d..30b5dd1fc7 100644
--- a/lib/snmp/test/snmp_manager_user.erl
+++ b/lib/snmp/test/snmp_manager_user.erl
@@ -50,14 +50,14 @@
update_agent_info/3, update_agent_info/4,
which_all_agents/0, which_own_agents/0,
load_mib/1, unload_mib/1,
- sync_get/1, sync_get/2, sync_get/3,
- async_get/1, async_get/2, async_get/3,
- sync_get_next/1, sync_get_next/2, sync_get_next/3,
- async_get_next/1, async_get_next/2, async_get_next/3,
- sync_set/1, sync_set/2, sync_set/3,
- async_set/1, async_set/2, async_set/3,
- sync_get_bulk/3, sync_get_bulk/4, sync_get_bulk/5,
- async_get_bulk/3, async_get_bulk/4, async_get_bulk/5,
+ sync_get/1, sync_get/2, sync_get/3, sync_get2/3,
+ async_get/1, async_get/2, async_get/3, async_get2/3,
+ sync_get_next/1, sync_get_next/2, sync_get_next/3, sync_get_next2/3,
+ async_get_next/1, async_get_next/2, async_get_next/3, async_get_next2/3,
+ sync_set/1, sync_set/2, sync_set/3, sync_set2/3,
+ async_set/1, async_set/2, async_set/3, async_set2/3,
+ sync_get_bulk/3, sync_get_bulk/4, sync_get_bulk/5, sync_get_bulk2/5,
+ async_get_bulk/3, async_get_bulk/4, async_get_bulk/5, async_get_bulk2/5,
name_to_oid/1, oid_to_name/1,
purify_oid/1
]).
@@ -171,6 +171,10 @@ sync_get(Addr_or_TargetName, Oids) ->
sync_get(Addr, Port, Oids) ->
call({sync_get, Addr, Port, Oids}).
+sync_get2(TargetName, Oids, SendOpts) ->
+ call({sync_get2, TargetName, Oids, SendOpts}).
+
+
%% --
async_get(Oids) ->
@@ -182,6 +186,9 @@ async_get(Addr_or_TargetName, Oids) ->
async_get(Addr, Port, Oids) ->
call({async_get, Addr, Port, Oids}).
+async_get2(TargetName, Oids, SendOpts) ->
+ call({async_get2, TargetName, Oids, SendOpts}).
+
%% --
sync_get_next(Oids) ->
@@ -193,6 +200,9 @@ sync_get_next(Addr_or_TargetName, Oids) ->
sync_get_next(Addr, Port, Oids) ->
call({sync_get_next, Addr, Port, Oids}).
+sync_get_next2(TargetName, Oids, SendOpts) ->
+ call({sync_get_next2, TargetName, Oids, SendOpts}).
+
%% --
async_get_next(Oids) ->
@@ -204,6 +214,9 @@ async_get_next(Addr_or_TargetName, Oids) ->
async_get_next(Addr, Port, Oids) ->
call({async_get_next, Addr, Port, Oids}).
+async_get_next2(TargetName, Oids, SendOpts) ->
+ call({async_get_next2, TargetName, Oids, SendOpts}).
+
%% --
sync_set(VAV) ->
@@ -215,6 +228,9 @@ sync_set(Addr_or_TargetName, VAV) ->
sync_set(Addr, Port, VAV) ->
call({sync_set, Addr, Port, VAV}).
+sync_set2(TargetName, VAV, SendOpts) ->
+ call({sync_set2, TargetName, VAV, SendOpts}).
+
%% --
async_set(VAV) ->
@@ -226,6 +242,9 @@ async_set(Addr_or_TargetName, VAV) ->
async_set(Addr, Port, VAV) ->
call({async_set, Addr, Port, VAV}).
+async_set2(TargetName, VAV, SendOpts) ->
+ call({async_set2, TargetName, VAV, SendOpts}).
+
%% --
sync_get_bulk(NonRep, MaxRep, Oids) ->
@@ -237,6 +256,9 @@ sync_get_bulk(Addr_or_TargetName, NonRep, MaxRep, Oids) ->
sync_get_bulk(Addr, Port, NonRep, MaxRep, Oids) ->
call({sync_get_bulk, Addr, Port, NonRep, MaxRep, Oids}).
+sync_get_bulk2(TargetName, NonRep, MaxRep, Oids, SendOpts) ->
+ call({sync_get_bulk2, TargetName, NonRep, MaxRep, Oids, SendOpts}).
+
%% --
async_get_bulk(NonRep, MaxRep, Oids) ->
@@ -248,6 +270,9 @@ async_get_bulk(Addr_or_TargetName, NonRep, MaxRep, Oids) ->
async_get_bulk(Addr, Port, NonRep, MaxRep, Oids) ->
call({async_get_bulk, Addr, Port, NonRep, MaxRep, Oids}).
+async_get_bulk2(TargetName, NonRep, MaxRep, Oids, SendOpts) ->
+ call({async_get_bulk2, TargetName, NonRep, MaxRep, Oids, SendOpts}).
+
%% --
name_to_oid(Name) ->
@@ -400,6 +425,16 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (sync) get-request --
%%
+ {{sync_get2, TargetName, Oids, SendOpts}, From, Ref}
+ when is_list(TargetName) ->
+ d("loop -> received sync_get2 request with"
+ "~n TargetName: ~p"
+ "~n Oids: ~p"
+ "~n SendOpts: ~p", [TargetName, Oids, SendOpts]),
+ Res = snmpm:sync_get2(Id, TargetName, Oids, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
%% No agent specified, so send it to all of them
{{sync_get, Oids}, From, Ref} ->
d("loop -> received sync_get request "
@@ -439,6 +474,16 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (async) get-request --
%%
+ {{async_get2, TargetName, Oids, SendOpts}, From, Ref}
+ when is_list(TargetName) ->
+ d("loop -> received async_get2 request with"
+ "~n TargetName: ~p"
+ "~n Oids: ~p"
+ "~n SendOpts: ~p", [TargetName, Oids, SendOpts]),
+ Res = snmpm:async_get2(Id, TargetName, Oids, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
%% No agent specified, so send it to all of them
{{async_get, Oids}, From, Ref} ->
d("loop -> received async_get request"),
@@ -472,6 +517,16 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (sync) get_next-request --
%%
+ {{sync_get_next2, TargetName, Oids, SendOpts}, From, Ref}
+ when is_list(TargetName) ->
+ d("loop -> received sync_get_next2 request with"
+ "~n TargetName: ~p"
+ "~n Oids: ~p"
+ "~n SendOpts: ~p", [TargetName, Oids, SendOpts]),
+ Res = snmpm:sync_get_next2(Id, TargetName, Oids, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
%% No agent specified, so send it to all of them
{{sync_get_next, Oids}, From, Ref} ->
d("loop -> received sync_get_next request"),
@@ -505,6 +560,16 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (async) get_next-request --
%%
+ {{async_get_next2, TargetName, Oids, SendOpts}, From, Ref}
+ when is_list(TargetName) ->
+ d("loop -> received async_get_next2 request with"
+ "~n TargetName: ~p"
+ "~n Oids: ~p"
+ "~n SendOpts: ~p", [TargetName, Oids, SendOpts]),
+ Res = snmpm:async_get_next2(Id, TargetName, Oids, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
%% No agent specified, so send it to all of them
{{async_get_next, Oids}, From, Ref} ->
d("loop -> received async_get_next request"),
@@ -538,6 +603,16 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (sync) set-request --
%%
+ {{sync_set2, TargetName, VAV, SendOpts}, From, Ref}
+ when is_list(TargetName) ->
+ d("loop -> received sync_set2 request with"
+ "~n TargetName: ~p"
+ "~n VAV: ~p"
+ "~n SendOpts: ~p", [TargetName, VAV, SendOpts]),
+ Res = snmpm:sync_set2(Id, TargetName, VAV, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
{{sync_set, VAV}, From, Ref} ->
d("loop -> received sync_set request"),
Res = [snmpm:sync_set(Id, TargetName, VAV) ||
@@ -568,6 +643,16 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (async) set-request --
%%
+ {{async_set2, TargetName, VAV, SendOpts}, From, Ref}
+ when is_list(TargetName) ->
+ d("loop -> received async_set2 request with"
+ "~n TargetName: ~p"
+ "~n VAV: ~p"
+ "~n SendOpts: ~p", [TargetName, VAV, SendOpts]),
+ Res = snmpm:async_set2(Id, TargetName, VAV, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
{{async_set, VAV}, From, Ref} ->
d("loop -> received async_set request"),
Res = [snmpm:async_set(Id, TargetName, VAV) ||
@@ -598,6 +683,20 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (sync) get-bulk-request --
%%
+ {{sync_get_bulk2, TargetName, NonRep, MaxRep, Oids, SendOpts}, From, Ref}
+ when is_list(TargetName) ->
+ d("loop -> received sync_get_bulk request with"
+ "~n TargetName: ~p"
+ "~n NonRep: ~w"
+ "~n MaxRep: ~w"
+ "~n Oids: ~p"
+ "~n SendOpts: ~p",
+ [TargetName, NonRep, MaxRep, Oids, SendOpts]),
+ Res = snmpm:sync_get_bulk2(Id, TargetName,
+ NonRep, MaxRep, Oids, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
%% No agent specified, so send it to all of them
{{sync_get_bulk, NonRep, MaxRep, Oids}, From, Ref} ->
d("loop -> received sync_get_bulk request with"
@@ -645,6 +744,20 @@ loop(#state{parent = Parent, id = Id} = S) ->
%% -- (async) get-bulk-request --
%%
+ {{async_get_bulk2, TargetName, NonRep, MaxRep, Oids, SendOpts},
+ From, Ref} when is_list(TargetName) ->
+ d("loop -> received async_get_bulk2 request with"
+ "~n TargetName: ~p"
+ "~n NonRep: ~w"
+ "~n MaxRep: ~w"
+ "~n Oids: ~p"
+ "~n SendOpts: ~p",
+ [TargetName, NonRep, MaxRep, Oids, SendOpts]),
+ Res = snmpm:async_get_bulk2(Id, TargetName,
+ NonRep, MaxRep, Oids, SendOpts),
+ reply(From, Res, Ref),
+ loop(S);
+
%% No agent specified, so send it to all of them
{{async_get_bulk, NonRep, MaxRep, Oids}, From, Ref} ->
d("loop -> received async_get_bulk request with"
@@ -847,7 +960,11 @@ call(Req, To) when is_integer(To) ->
{error, timeout}
end.
-reply(Pid, Reply, Ref) ->
+reply(Pid, Reply, Ref) ->
+ d("reply -> entry with"
+ "~n Pid: ~p"
+ "~n Reply: ~p"
+ "~n Ref: ~p", [Pid, Reply, Ref]),
Pid ! {Reply, Ref}.
cast(Msg) ->
diff --git a/lib/snmp/test/snmp_pdus_test.erl b/lib/snmp/test/snmp_pdus_test.erl
index ef510ad62e..197797c816 100644
--- a/lib/snmp/test/snmp_pdus_test.erl
+++ b/lib/snmp/test/snmp_pdus_test.erl
@@ -38,6 +38,8 @@
otp7575/1,
otp8563/1,
+ otp9022/1,
+
init_per_testcase/2, end_per_testcase/2
]).
@@ -75,7 +77,7 @@ all() ->
[{group, tickets}].
groups() ->
- [{tickets, [], [otp7575, otp8563]}].
+ [{tickets, [], [otp7575, otp8563, otp9022]}].
init_per_group(_GroupName, Config) ->
Config.
@@ -169,7 +171,56 @@ otp8563(Config) when is_list(Config) ->
Unexpected7 ->
exit({unexpected_encode_result, Unexpected7, Val7})
end,
-
+
+ ok.
+
+
+otp9022(suite) -> [];
+otp9022(doc) -> ["OTP-9022"];
+otp9022(Config) when is_list(Config) ->
+ Val1 = 16#7fffffff,
+ io:format("try encode and decode ~w~n", [Val1]),
+ Enc1 = snmp_pdus:enc_value('Counter32', Val1),
+ {{'Counter32', Val1}, []} = snmp_pdus:dec_value(Enc1),
+
+ Val2 = Val1 + 1,
+ io:format("try encode and decode ~w~n", [Val2]),
+ Enc2 = snmp_pdus:enc_value('Counter32', Val2),
+ {{'Counter32', Val2}, []} = snmp_pdus:dec_value(Enc2),
+
+ Val3 = Val2 + 1,
+ io:format("try encode and decode ~w~n", [Val3]),
+ Enc3 = snmp_pdus:enc_value('Counter32', Val3),
+ {{'Counter32', Val3}, []} = snmp_pdus:dec_value(Enc3),
+
+ Val4 = 16#fffffffe,
+ io:format("try encode and decode ~w~n", [Val4]),
+ Enc4 = snmp_pdus:enc_value('Counter32', Val4),
+ {{'Counter32', Val4}, []} = snmp_pdus:dec_value(Enc4),
+
+ Val5 = Val4 + 1,
+ io:format("try encode and decode ~w~n", [Val5]),
+ Enc5 = snmp_pdus:enc_value('Counter32', Val5),
+ {{'Counter32', Val5}, []} = snmp_pdus:dec_value(Enc5),
+
+ Val6 = 16#ffffffff + 1,
+ io:format("try and fail to encode ~w~n", [Val6]),
+ case (catch snmp_pdus:enc_value('Counter32', Val6)) of
+ {'EXIT', {error, {bad_counter32, Val6}}} ->
+ ok;
+ Unexpected6 ->
+ exit({unexpected_encode_result, Unexpected6, Val6})
+ end,
+
+ Val7 = -1,
+ io:format("try and fail to encode ~w~n", [Val7]),
+ case (catch snmp_pdus:enc_value('Counter32', Val7)) of
+ {'EXIT', {error, {bad_counter32, Val7}}} ->
+ ok;
+ Unexpected7 ->
+ exit({unexpected_encode_result, Unexpected7, Val7})
+ end,
+
ok.
diff --git a/lib/snmp/vsn.mk b/lib/snmp/vsn.mk
index e70c97dcb8..29228fc59b 100644
--- a/lib/snmp/vsn.mk
+++ b/lib/snmp/vsn.mk
@@ -17,6 +17,6 @@
#
# %CopyrightEnd%
-SNMP_VSN = 4.19
+SNMP_VSN = 4.20
PRE_VSN =
APP_VSN = "snmp-$(SNMP_VSN)$(PRE_VSN)"
diff --git a/lib/ssh/doc/src/notes.xml b/lib/ssh/doc/src/notes.xml
index 4f546a37ed..71f3941577 100644
--- a/lib/ssh/doc/src/notes.xml
+++ b/lib/ssh/doc/src/notes.xml
@@ -29,6 +29,20 @@
<file>notes.xml</file>
</header>
+<section><title>Ssh 2.0.7</title>
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ An unexpected message would crash the ssh_connection_handler and close
+ the connection. Now an error message is generated instead.</p>
+ <p>
+ Own Id: OTP-9273</p>
+ </item>
+ </list>
+ </section>
+</section>
+
<section><title>Ssh 2.0.6</title>
<section><title>Fixed Bugs and Malfunctions</title>
<list>
diff --git a/lib/ssh/src/ssh.appup.src b/lib/ssh/src/ssh.appup.src
index 37f24e2463..974145836c 100644
--- a/lib/ssh/src/ssh.appup.src
+++ b/lib/ssh/src/ssh.appup.src
@@ -19,10 +19,12 @@
{"%VSN%",
[
+ {"2.0.6", [{load_module, ssh_userreg, soft_purge, soft_purge, []}]},
{"2.0.5", [{load_module, ssh_userreg, soft_purge, soft_purge, []},
{load_module, ssh_connection_handler, soft_purge, soft_purge, [ssh_userreg]}]}
],
[
+ {"2.0.6", [{load_module, ssh_userreg, soft_purge, soft_purge, []}]},
{"2.0.5", [{load_module, ssh_userreg, soft_purge, soft_purge, []},
{load_module, ssh_connection_handler, soft_purge, soft_purge, [ssh_userreg]}]}
]
diff --git a/lib/ssh/src/ssh_connection_handler.erl b/lib/ssh/src/ssh_connection_handler.erl
index 3193be2510..00b30e5434 100644
--- a/lib/ssh/src/ssh_connection_handler.erl
+++ b/lib/ssh/src/ssh_connection_handler.erl
@@ -569,7 +569,19 @@ handle_info({CloseTag, _Socket}, _StateName,
#state{transport_close_tag = CloseTag, %%manager = Pid,
ssh_params = #ssh{role = _Role, opts = _Opts}} = State) ->
%%ok = ssh_connection_manager:delivered(Pid),
- {stop, normal, State}.
+ {stop, normal, State};
+handle_info(UnexpectedMessage, StateName, #state{ssh_params = SshParams} = State) ->
+ Msg = lists:flatten(io_lib:format(
+ "Unexpected message '~p' received in state '~p'\n"
+ "Role: ~p\n"
+ "Peer: ~p\n"
+ "Local Address: ~p\n", [UnexpectedMessage, StateName,
+ SshParams#ssh.role, SshParams#ssh.peer,
+ proplists:get_value(address, SshParams#ssh.opts)])),
+ error_logger:info_report(Msg),
+ {next_state, StateName, State}.
+
+
%%--------------------------------------------------------------------
%% Function: terminate(Reason, StateName, State) -> void()
%% Description:This function is called by a gen_fsm when it is about
diff --git a/lib/ssh/test/Makefile b/lib/ssh/test/Makefile
new file mode 100644
index 0000000000..5a2a6de24a
--- /dev/null
+++ b/lib/ssh/test/Makefile
@@ -0,0 +1,121 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2004-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%
+#
+
+include $(ERL_TOP)/make/target.mk
+include $(ERL_TOP)/make/$(TARGET)/otp.mk
+
+# ----------------------------------------------------
+# Application version
+# ----------------------------------------------------
+include ../vsn.mk
+VSN=$(GS_VSN)
+
+# ----------------------------------------------------
+# Target Specs
+# ----------------------------------------------------
+
+MODULES= \
+ ssh_test_lib \
+ ssh_SUITE \
+ ssh_basic_SUITE \
+ ssh_to_openssh_SUITE \
+ ssh_sftp_SUITE \
+ ssh_sftpd_SUITE \
+ ssh_sftpd_erlclient_SUITE
+
+HRL_FILES_NEEDED_IN_TEST= \
+ $(ERL_TOP)/lib/ssh/src/ssh.hrl \
+ $(ERL_TOP)/lib/ssh/src/ssh_xfer.hrl
+
+ERL_FILES= $(MODULES:%=%.erl)
+
+TARGET_FILES= $(MODULES:%=$(EBIN)/%.$(EMULATOR))
+
+DATA_DIRS = $(MODULES:%=%_data)
+
+INCLUDES = -I$(ERL_TOP)/lib/test_server/include \
+ -I$(ERL_TOP)/lib/ssh/src \
+
+EMAKEFILE=Emakefile
+MAKE_EMAKE = $(wildcard $(ERL_TOP)/make/make_emakefile)
+
+ifeq ($(MAKE_EMAKE),)
+BUILDTARGET = $(TARGET_FILES)
+RELTEST_FILES = $(INETS_SPECS) $(SOURCE)
+else
+BUILDTARGET = emakebuild
+RELTEST_FILES = $(EMAKEFILE) $(INETS_SPECS) $(SOURCE)
+endif
+
+# ----------------------------------------------------
+# Release directory specification
+# ----------------------------------------------------
+RELSYSDIR = $(RELEASE_PATH)/ssh_test
+
+# ----------------------------------------------------
+# FLAGS
+# The path to the test_server ebin dir is needed when
+# running the target "targets".
+# ----------------------------------------------------
+ERL_COMPILE_FLAGS += -pa ../../../internal_tools/test_server/ebin \
+ $(INCLUDES)
+
+EBIN = .
+
+# ----------------------------------------------------
+# Targets
+# ----------------------------------------------------
+tests debug opt: $(BUILDTARGET)
+
+targets: $(TARGET_FILES)
+
+.PHONY: emakebuild
+
+emakebuild: $(EMAKEFILE)
+
+$(EMAKEFILE):
+ $(MAKE_EMAKE) $(ERL_COMPILE_FLAGS) -o$(EBIN) '*_SUITE_make' | grep -v Warning > $(EMAKEFILE)
+ $(MAKE_EMAKE) $(ERL_COMPILE_FLAGS) -o$(EBIN) $(MODULES) | grep -v Warning >> $(EMAKEFILE)
+
+clean:
+ rm -f $(EMAKEFILE)
+ rm -f $(TARGET_FILES)
+ rm -f core
+docs:
+
+info:
+ @echo "TARGET_FILES = $(TARGET_FILES)"
+ @echo "DATA_DIRS = $(DATA_DIRS)"
+
+# ----------------------------------------------------
+# Release Target
+# ----------------------------------------------------
+include $(ERL_TOP)/make/otp_release_targets.mk
+
+release_spec: opt
+
+release_tests_spec: opt
+ $(INSTALL_DIR) $(RELSYSDIR)
+ $(INSTALL_DATA) $(ERL_FILES) $(RELSYSDIR)
+ $(INSTALL_DATA) ssh.spec ssh.cover $(RELSYSDIR)
+ $(INSTALL_DATA) $(HRL_FILES_NEEDED_IN_TEST) $(RELSYSDIR)
+ chmod -f -R u+w $(RELSYSDIR)
+ @tar cf - *_SUITE_data | (cd $(RELSYSDIR); tar xf -)
+
+release_docs_spec:
diff --git a/lib/ssh/test/ssh.cover b/lib/ssh/test/ssh.cover
new file mode 100644
index 0000000000..a4221fbbbe
--- /dev/null
+++ b/lib/ssh/test/ssh.cover
@@ -0,0 +1,2 @@
+{incl_app,ssh,details}.
+
diff --git a/lib/ssh/test/ssh.spec b/lib/ssh/test/ssh.spec
new file mode 100644
index 0000000000..8de0fe44e4
--- /dev/null
+++ b/lib/ssh/test/ssh.spec
@@ -0,0 +1,7 @@
+{suites,"../ssh_test",all}.
+{skip_cases,"../ssh_test",ssh_ssh_SUITE,
+ [ssh],
+ "Current implementation is timingdependent and\nhence will succeed/fail on a whim"}.
+{skip_cases,"../ssh_test",ssh_ssh_SUITE,
+ [ssh_compressed],
+ "Current implementation is timingdependent hence will succeed/fail on a whim"}.
diff --git a/lib/ssh/test/ssh.spec.vxworks b/lib/ssh/test/ssh.spec.vxworks
new file mode 100644
index 0000000000..81f665283c
--- /dev/null
+++ b/lib/ssh/test/ssh.spec.vxworks
@@ -0,0 +1,3 @@
+{topcase, {dir, "../ssh_test"}}.
+{require_nodenames, 1}.
+%{skip, {M, F, "Not yet implemented"}}.
diff --git a/lib/ssh/test/ssh_SUITE.erl b/lib/ssh/test/ssh_SUITE.erl
new file mode 100644
index 0000000000..953c9080f9
--- /dev/null
+++ b/lib/ssh/test/ssh_SUITE.erl
@@ -0,0 +1,72 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2004-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%
+%%
+
+%%
+%%%----------------------------------------------------------------
+%%% Purpose:ssh application test suite.
+%%%-----------------------------------------------------------------
+-module(ssh_SUITE).
+-include_lib("common_test/include/ct.hrl").
+-include("test_server_line.hrl").
+
+% Default timetrap timeout (set in init_per_testcase).
+-define(default_timeout, ?t:minutes(1)).
+-define(application, ssh).
+
+% Test server specific exports
+-export([all/0,groups/0,init_per_group/2,end_per_group/2]).
+-export([init_per_testcase/2, end_per_testcase/2]).
+
+% Test cases must be exported.
+-export([app_test/1]).
+-define(cases, [app_test]).
+
+%%
+%% all/1
+%%
+all() ->
+ [app_test].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+init_per_testcase(_Case, Config) ->
+ Dog=test_server:timetrap(?default_timeout),
+ [{watchdog, Dog}|Config].
+end_per_testcase(_Case, Config) ->
+ Dog=?config(watchdog, Config),
+ test_server:timetrap_cancel(Dog),
+ ok.
+%
+% Test cases starts here.
+%
+app_test(suite) ->
+ [];
+app_test(doc) ->
+ ["Application consistency test."];
+app_test(Config) when is_list(Config) ->
+ ?t:app_test(?application),
+ ok.
diff --git a/lib/ssh/test/ssh_basic_SUITE.erl b/lib/ssh/test/ssh_basic_SUITE.erl
new file mode 100644
index 0000000000..5ea0d98980
--- /dev/null
+++ b/lib/ssh/test/ssh_basic_SUITE.erl
@@ -0,0 +1,389 @@
+%%
+%% %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%
+%%
+
+%%
+
+-module(ssh_basic_SUITE).
+
+-include_lib("common_test/include/ct.hrl").
+-include("test_server_line.hrl").
+
+%% Note: This directive should only be used in test suites.
+-compile(export_all).
+
+-define(NEWLINE, <<"\r\n">>).
+
+%%--------------------------------------------------------------------
+%% Function: init_per_suite(Config) -> Config
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Initialization before the whole suite
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%%--------------------------------------------------------------------
+init_per_suite(Config) ->
+ case catch crypto:start() of
+ ok ->
+ Dir = ?config(priv_dir, Config),
+ {ok, _} = ssh_test_lib:get_id_keys(Dir),
+ ssh_test_lib:make_dsa_files(Config),
+ Config;
+ _Else ->
+ {skip, "Crypto could not be started!"}
+ end.
+
+%%--------------------------------------------------------------------
+%% Function: end_per_suite(Config) -> _
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after the whole suite
+%%--------------------------------------------------------------------
+end_per_suite(Config) ->
+ Dir = ?config(priv_dir, Config),
+ crypto:stop(),
+ ssh_test_lib:remove_id_keys(Dir),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: init_per_testcase(TestCase, Config) -> Config
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%%
+%% Description: Initialization before each test case
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%% Description: Initialization before each test case
+%%--------------------------------------------------------------------
+init_per_testcase(_TestCase, Config) ->
+ ssh_test_lib:known_hosts(backup),
+ ssh:start(),
+ Config.
+
+%%--------------------------------------------------------------------
+%% Function: end_per_testcase(TestCase, Config) -> _
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after each test case
+%%--------------------------------------------------------------------
+end_per_testcase(_TestCase, _Config) ->
+ ssh:stop(),
+ ssh_test_lib:known_hosts(restore),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: all(Clause) -> TestCases
+%% Clause - atom() - suite | doc
+%% TestCases - [Case]
+%% Case - atom()
+%% Name of a test case.
+%% Description: Returns a list of all test cases in this test suite
+%%--------------------------------------------------------------------
+all() ->
+ [exec, exec_compressed, shell, daemon_already_started,
+ server_password_option, server_userpassword_option,
+ known_hosts].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+%% Test cases starts here.
+%%--------------------------------------------------------------------
+sign_and_verify_rsa(doc) ->
+ ["Test api function ssh:sign_data and ssh:verify_data"];
+
+sign_and_verify_rsa(suite) ->
+ [];
+sign_and_verify_rsa(Config) when is_list(Config) ->
+ Data = ssh:sign_data(<<"correct data">>, "ssh-rsa"),
+ ok = ssh:verify_data(<<"correct data">>, Data, "ssh-rsa"),
+ {error,invalid_signature} = ssh:verify_data(<<"incorrect data">>, Data,"ssh-rsa").
+
+
+exec(doc) ->
+ ["Test api function ssh_connection:exec"];
+
+exec(suite) ->
+ [];
+
+exec(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ SystemDir = ?config(data_dir, Config),
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+ ConnectionRef =
+ ssh_test_lib:connect(Host, Port, [{silently_accept_hosts, true},
+ {user_interaction, false}]),
+ {ok, ChannelId0} = ssh_connection:session_channel(ConnectionRef, infinity),
+ success = ssh_connection:exec(ConnectionRef, ChannelId0,
+ "1+1.", infinity),
+ Data0 = {ssh_cm, ConnectionRef, {data, ChannelId0, 0, <<"2\n">>}},
+ case ssh_test_lib:receive_exec_result(Data0) of
+ expected ->
+ ok;
+ Other0 ->
+ test_server:fail(Other0)
+ end,
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId0),
+
+ %% Test that it is possible to start a new channel and
+ %% run an other exec on the same connection.
+ {ok, ChannelId1} = ssh_connection:session_channel(ConnectionRef, infinity),
+ success = ssh_connection:exec(ConnectionRef, ChannelId1,
+ "2+2.", infinity),
+ Data1 = {ssh_cm, ConnectionRef, {data, ChannelId1, 0, <<"4\n">>}},
+ case ssh_test_lib:receive_exec_result(Data1) of
+ expected ->
+ ok;
+ Other1 ->
+ test_server:fail(Other1)
+ end,
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId1),
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+exec_compressed(doc) ->
+ ["Test that compression option works"];
+
+exec_compressed(suite) ->
+ [];
+
+exec_compressed(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ SystemDir = ?config(data_dir, Config),
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {compression, zlib},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+
+ ConnectionRef =
+ ssh_test_lib:connect(Host, Port, [{silently_accept_hosts, true},
+ {user_interaction, false}]),
+ {ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity),
+ success = ssh_connection:exec(ConnectionRef, ChannelId,
+ "1+1.", infinity),
+ Data = {ssh_cm, ConnectionRef, {data, ChannelId, 0, <<"2\n">>}},
+ case ssh_test_lib:receive_exec_result(Data) of
+ expected ->
+ ok;
+ Other ->
+ test_server:fail(Other)
+ end,
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId),
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+
+shell(doc) ->
+ ["Test that ssh:shell/2 works"];
+
+shell(suite) ->
+ [];
+
+shell(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ SystemDir = ?config(data_dir, Config),
+ {_Pid, _Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+ test_server:sleep(500),
+
+ IO = ssh_test_lib:start_io_server(),
+ Shell = ssh_test_lib:start_shell(Port, IO),
+ receive
+ ErlShellStart ->
+ test_server:format("Erlang shell start: ~p~n", [ErlShellStart])
+ end,
+ receive
+ ErlPrompt0 ->
+ test_server:format("Erlang prompt: ~p~n", [ErlPrompt0])
+ end,
+ IO ! {input, self(), "1+1.\r\n"},
+ receive
+ Echo0 ->
+ test_server:format("Echo: ~p ~n", [Echo0])
+ end,
+ receive
+ ?NEWLINE ->
+ ok
+ end,
+ receive
+ Result0 = <<"2">> ->
+ test_server:format("Result: ~p~n", [Result0])
+ end,
+ receive
+ ?NEWLINE ->
+ ok
+ end,
+ receive
+ ErlPrompt1 ->
+ test_server:format("Erlang prompt: ~p~n", [ErlPrompt1])
+ end,
+ exit(Shell, kill),
+ %% Does not seem to work in the testserver!
+ %% IO ! {input, self(), "q().\r\n"},
+ %% receive
+ %% ?NEWLINE ->
+ %% ok
+ %% end,
+ %% receive
+ %% Echo1 ->
+ %% test_server:format("Echo: ~p ~n", [Echo1])
+ %% end,
+ %% receive
+ %% ?NEWLINE ->
+ %% ok
+ %% end,
+ %% receive
+ %% Result1 ->
+ %% test_server:format("Result: ~p~n", [Result1])
+ %% end,
+ receive
+ {'EXIT', Shell, killed} ->
+ ok
+ end.
+
+%%--------------------------------------------------------------------
+daemon_already_started(doc) ->
+ ["Test that get correct error message if you try to start a daemon",
+ "on an adress that already runs a daemon see also seq10667" ];
+
+daemon_already_started(suite) ->
+ [];
+
+daemon_already_started(Config) when is_list(Config) ->
+ SystemDir = ?config(data_dir, Config),
+ {Pid, _Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+ {error, eaddrinuse} = ssh_test_lib:daemon(Port, [{system_dir, SystemDir},
+ {failfun,
+ fun ssh_test_lib:failfun/2}]),
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+server_password_option(doc) ->
+ ["validate to server that uses the 'password' option"];
+server_password_option(suite) ->
+ [];
+server_password_option(Config) when is_list(Config) ->
+ UserDir = ?config(data_dir, Config), % to make sure we don't use
+ SysDir = ?config(data_dir, Config), % public-key-auth
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SysDir},
+ {password, "morot"}]),
+
+ ConnectionRef =
+ ssh_test_lib:connect(Host, Port, [{silently_accept_hosts, true},
+ {user, "foo"},
+ {password, "morot"},
+ {user_interaction, false},
+ {user_dir, UserDir}]),
+ {error, Reason} =
+ ssh_test_lib:connect(Host, Port, [{silently_accept_hosts, true},
+ {user, "vego"},
+ {password, "foo"},
+ {user_interaction, false},
+ {user_dir, UserDir}]),
+
+ test_server:format("Test of wrong password: Error msg: ~p ~n", [Reason]),
+
+ ssh:close(ConnectionRef),
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+
+server_userpassword_option(doc) ->
+ ["validate to server that uses the 'password' option"];
+server_userpassword_option(suite) ->
+ [];
+server_userpassword_option(Config) when is_list(Config) ->
+ UserDir = ?config(data_dir, Config), % to make sure we don't use
+ SysDir = ?config(data_dir, Config), % public-key-auth
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SysDir},
+ {user_passwords, [{"vego", "morot"}]}]),
+
+ ConnectionRef =
+ ssh_test_lib:connect(Host, Port, [{silently_accept_hosts, true},
+ {user, "vego"},
+ {password, "morot"},
+ {user_interaction, false},
+ {user_dir, UserDir}]),
+ ssh:close(ConnectionRef),
+
+ {error, Reason0} =
+ ssh_test_lib:connect(Host, Port, [{silently_accept_hosts, true},
+ {user, "foo"},
+ {password, "morot"},
+ {user_interaction, false},
+ {user_dir, UserDir}]),
+
+ test_server:format("Test of user foo that does not exist. "
+ "Error msg: ~p ~n", [Reason0]),
+
+ {error, Reason1} =
+ ssh_test_lib:connect(Host, Port, [{silently_accept_hosts, true},
+ {user, "vego"},
+ {password, "foo"},
+ {user_interaction, false},
+ {user_dir, UserDir}]),
+ test_server:format("Test of wrong Password. "
+ "Error msg: ~p ~n", [Reason1]),
+
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+known_hosts(doc) ->
+ ["check that known_hosts is updated correctly"];
+known_hosts(suite) ->
+ [];
+known_hosts(Config) when is_list(Config) ->
+ SystemDir = ?config(data_dir, Config),
+ UserDir = ?config(priv_dir, Config),
+
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+
+ KnownHosts = filename:join(UserDir, "known_hosts"),
+ file:delete(KnownHosts),
+ {error, enoent} = file:read_file(KnownHosts),
+ ConnectionRef =
+ ssh_test_lib:connect(Host, Port, [{user_dir, UserDir},
+ {user_interaction, false},
+ silently_accept_hosts]),
+ {ok, _Channel} = ssh_connection:session_channel(ConnectionRef, infinity),
+ ok = ssh:close(ConnectionRef),
+ {ok, Binary} = file:read_file(KnownHosts),
+ Lines = string:tokens(binary_to_list(Binary), "\n"),
+ [Line] = Lines,
+ [HostAndIp, Alg, _KeyData] = string:tokens(Line, " "),
+ [Host, _Ip] = string:tokens(HostAndIp, ","),
+ "ssh-" ++ _ = Alg,
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+%% Internal functions
+%%--------------------------------------------------------------------
diff --git a/lib/ssh/test/ssh_sftp_SUITE.erl b/lib/ssh/test/ssh_sftp_SUITE.erl
new file mode 100644
index 0000000000..c96b6de3ea
--- /dev/null
+++ b/lib/ssh/test/ssh_sftp_SUITE.erl
@@ -0,0 +1,543 @@
+%%
+%% %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%
+%%
+
+%%
+-module(ssh_sftp_SUITE).
+
+%% Note: This directive should only be used in test suites.
+-compile(export_all).
+
+-include_lib("common_test/include/ct.hrl").
+-include("test_server_line.hrl").
+
+-include_lib("kernel/include/file.hrl").
+
+% Default timetrap timeout
+-define(default_timeout, ?t:minutes(1)).
+
+-define(SFPD_PORT, 9999).
+-define(USER, "Alladin").
+-define(PASSWD, "Sesame").
+
+%% Test server callback functions
+%%--------------------------------------------------------------------
+%% Function: init_per_suite(Config) -> Config
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Initiation before the whole suite
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%%--------------------------------------------------------------------
+init_per_suite(Config) ->
+ case {catch crypto:start(),catch ssh:start()} of
+ {ok,ok} ->
+ Dir = ?config(priv_dir, Config),
+ {ok, _} = ssh_test_lib:get_id_keys(Dir),
+ ssh_test_lib:make_dsa_files(Config),
+ Config;
+ {ok,_} ->
+ {skip,"Could not start ssh!"};
+ {_,ok} ->
+ {skip,"Could not start crypto!"};
+ {_,_} ->
+ {skip,"Could not start crypto and ssh!"}
+ end.
+
+%%--------------------------------------------------------------------
+%% Function: end_per_suite(Config) -> _
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after the whole suite
+%%--------------------------------------------------------------------
+end_per_suite(Config) ->
+ crypto:stop(),
+ Dir = ?config(priv_dir, Config),
+ ssh_test_lib:remove_id_keys(Dir),
+ Config.
+
+%%--------------------------------------------------------------------
+%% Function: init_per_testcase(TestCase, Config) -> Config
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%%
+%% Description: Initiation before each test case
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%% Description: Initiation before each test case
+%%--------------------------------------------------------------------
+init_per_testcase(_Case, Config) ->
+ prep(Config),
+ TmpConfig0 = lists:keydelete(watchdog, 1, Config),
+ TmpConfig = lists:keydelete(sftp, 1, TmpConfig0),
+ Dog = test_server:timetrap(?default_timeout),
+ Dir = ?config(priv_dir, Config),
+ SysDir = ?config(data_dir, Config),
+ Host = ssh_test_lib:hostname(),
+
+ Sftp = case (catch ssh_sftp:start_channel(Host,
+ [{user_dir, Dir},
+ {user_interaction, false},
+ {silently_accept_hosts, true}])) of
+ {ok, ChannelPid, Connection} ->
+ {ChannelPid, Connection};
+ _Error ->
+ {_Sftpd, _Host, _Port} =
+ ssh_test_lib:daemon(Host, ?SFPD_PORT,
+ [{system_dir, SysDir},
+ {user_passwords,
+ [{?USER, ?PASSWD}]},
+ {failfun,
+ fun ssh_test_lib:failfun/2}]),
+ Result = (catch ssh_sftp:start_channel(Host, ?SFPD_PORT,
+ [{user, ?USER},
+ {password, ?PASSWD},
+ {user_interaction, false},
+ {silently_accept_hosts, true}])),
+ {ok, ChannelPid, Connection} = Result,
+ {ChannelPid, Connection}
+ end,
+
+ [{sftp, Sftp}, {watchdog, Dog} | TmpConfig].
+
+%%--------------------------------------------------------------------
+%% Function: end_per_testcase(TestCase, Config) -> _
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after each test case
+%%--------------------------------------------------------------------
+end_per_testcase(_Case, Config) ->
+ {Sftp, Connection} = ?config(sftp, Config),
+ ssh_sftp:stop_channel(Sftp),
+ ssh:close(Connection),
+ Dog = ?config(watchdog, Config),
+ test_server:timetrap_cancel(Dog),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: all(Clause) -> TestCases
+%% Clause - atom() - suite | doc
+%% TestCases - [Case]
+%% Case - atom()
+%% Name of a test case.
+%% Description: Returns a list of all test cases in this test suite
+%%--------------------------------------------------------------------
+all() ->
+ [open_close_file, open_close_dir, read_file, read_dir,
+ write_file, rename_file, mk_rm_dir, remove_file, links,
+ retrieve_attributes, set_attributes, async_read,
+ async_write, position, pos_read, pos_write].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%% Test cases starts here.
+%%--------------------------------------------------------------------
+open_close_file(doc) ->
+ ["Test API functions open/3 and close/2"];
+open_close_file(suite) ->
+ [];
+open_close_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ ok = open_close_file(Sftp, FileName, [read]),
+ ok = open_close_file(Sftp, FileName, [write]),
+ ok = open_close_file(Sftp, FileName, [write, creat]),
+ ok = open_close_file(Sftp, FileName, [write, trunc]),
+ ok = open_close_file(Sftp, FileName, [append]),
+ ok = open_close_file(Sftp, FileName, [read, binary]),
+
+ ok.
+
+open_close_file(Server, File, Mode) ->
+ {ok, Handle} = ssh_sftp:open(Server, File, Mode),
+ ok = ssh_sftp:close(Server, Handle),
+ ok.
+
+
+%%--------------------------------------------------------------------
+open_close_dir(doc) ->
+ ["Test API functions opendir/2 and close/2"];
+open_close_dir(suite) ->
+ [];
+open_close_dir(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ {Sftp, _} = ?config(sftp, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+
+ {ok, Handle} = ssh_sftp:opendir(Sftp, PrivDir),
+ ok = ssh_sftp:close(Sftp, Handle),
+ {error, _} = ssh_sftp:opendir(Sftp, FileName),
+
+ ok.
+%%--------------------------------------------------------------------
+read_file(doc) ->
+ ["Test API funtion read_file/2"];
+read_file(suite) ->
+ [];
+read_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok, Data} = ssh_sftp:read_file(Sftp, FileName),
+
+ {ok, Data} = file:read_file(FileName),
+
+ ok.
+%%--------------------------------------------------------------------
+read_dir(doc) ->
+ ["Test API function list_dir/2"];
+read_dir(suite) ->
+ [];
+read_dir(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ {Sftp, _} = ?config(sftp, Config),
+ {ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
+ test_server:format("sftp list dir: ~p~n", [Files]),
+ ok.
+
+%%--------------------------------------------------------------------
+write_file(doc) ->
+ ["Test API function write_file/2"];
+write_file(suite) ->
+ [];
+write_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ Data = list_to_binary("Hej hopp!"),
+
+ ssh_sftp:write_file(Sftp, FileName, [Data]),
+
+ {ok, Data} = file:read_file(FileName),
+
+ ok.
+
+%%--------------------------------------------------------------------
+remove_file(doc) ->
+ ["Test API function delete/2"];
+remove_file(suite) ->
+ [];
+remove_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
+
+ true = lists:member(filename:basename(FileName), Files),
+
+ ok = ssh_sftp:delete(Sftp, FileName),
+
+ {ok, NewFiles} = ssh_sftp:list_dir(Sftp, PrivDir),
+
+ false = lists:member(filename:basename(FileName), NewFiles),
+
+ {error, _} = ssh_sftp:delete(Sftp, FileName),
+
+ ok.
+
+%%--------------------------------------------------------------------
+rename_file(doc) ->
+ ["Test API function rename_file/2"];
+rename_file(suite) ->
+ [];
+rename_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+ NewFileName = filename:join(PrivDir, "test.txt"),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
+
+ test_server:format("FileName: ~p, Files: ~p~n", [FileName, Files]),
+
+ true = lists:member(filename:basename(FileName), Files),
+ false = lists:member(filename:basename(NewFileName), Files),
+
+ ok = ssh_sftp:rename(Sftp, FileName, NewFileName),
+
+ {ok, NewFiles} = ssh_sftp:list_dir(Sftp, PrivDir),
+
+ test_server:format("FileName: ~p, Files: ~p~n", [FileName, NewFiles]),
+
+ false = lists:member(filename:basename(FileName), NewFiles),
+ true = lists:member(filename:basename(NewFileName), NewFiles),
+
+ ok.
+
+%%--------------------------------------------------------------------
+mk_rm_dir(doc) ->
+ ["Test API functions make_dir/2, del_dir/2"];
+mk_rm_dir(suite) ->
+ [];
+mk_rm_dir(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ {Sftp, _} = ?config(sftp, Config),
+ DirName = filename:join(PrivDir, "test"),
+
+ ok = ssh_sftp:make_dir(Sftp, DirName),
+ ok = ssh_sftp:del_dir(Sftp, DirName),
+
+ NewDirName = filename:join(PrivDir, "foo/bar"),
+
+ {error, _} = ssh_sftp:make_dir(Sftp, NewDirName),
+ {error, _} = ssh_sftp:del_dir(Sftp, PrivDir),
+
+ ok.
+
+%%--------------------------------------------------------------------
+links(doc) ->
+ ["Tests API function make_symlink/3"];
+links(suite) ->
+ [];
+links(Config) when is_list(Config) ->
+ case test_server:os_type() of
+ {win32, _} ->
+ {skip, "Links are not fully supported by windows"};
+ _ ->
+ {Sftp, _} = ?config(sftp, Config),
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+ LinkFileName = filename:join(PrivDir, "link_test.txt"),
+
+ ok = ssh_sftp:make_symlink(Sftp, FileName, LinkFileName),
+ {ok, FileName} = ssh_sftp:read_link(Sftp, LinkFileName),
+ ok
+ end.
+
+%%--------------------------------------------------------------------
+retrieve_attributes(doc) ->
+ ["Test API function read_file_info/3"];
+retrieve_attributes(suite) ->
+ [];
+retrieve_attributes(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok, FileInfo} = ssh_sftp:read_file_info(Sftp, FileName),
+
+ {ok, NewFileInfo} = file:read_file_info(FileName),
+
+ %% TODO comparison. There are some differences now is that ok?
+ test_server:format("SFTP: ~p FILE: ~p~n", [FileInfo, NewFileInfo]),
+ ok.
+
+%%--------------------------------------------------------------------
+set_attributes(doc) ->
+ ["Test API function write_file_info/3"];
+set_attributes(suite) ->
+ [];
+set_attributes(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok,Fd} = file:open(FileName, write),
+ io:put_chars(Fd,"foo"),
+
+ ok = ssh_sftp:write_file_info(Sftp, FileName, #file_info{mode=8#400}),
+ {error, eacces} = file:write_file(FileName, "hello again"),
+ ssh_sftp:write_file_info(Sftp, FileName, #file_info{mode=8#600}),
+ ok = file:write_file(FileName, "hello again"),
+
+ ok.
+
+%%--------------------------------------------------------------------
+
+async_read(doc) ->
+ ["Test API aread/3"];
+async_read(suite) ->
+ [];
+async_read(Config) when is_list(Config) ->
+ {Sftp, _} = ?config(sftp, Config),
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "sftp.txt"),
+ {ok, Handle} = ssh_sftp:open(Sftp, FileName, [read]),
+ {async, Ref} = ssh_sftp:aread(Sftp, Handle, 20),
+
+ receive
+ {async_reply, Ref, {ok, Data}} ->
+ test_server:format("Data: ~p~n", [Data]),
+ ok;
+ Msg ->
+ test_server:fail(Msg)
+ end,
+ ok.
+%%--------------------------------------------------------------------
+async_write(doc) ->
+ ["Test API awrite/3"];
+async_write(suite) ->
+ [];
+async_write(Config) when is_list(Config) ->
+ {Sftp, _} = ?config(sftp, Config),
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ {ok, Handle} = ssh_sftp:open(Sftp, FileName, [write]),
+ Data = list_to_binary("foobar"),
+ {async, Ref} = ssh_sftp:awrite(Sftp, Handle, Data),
+
+ receive
+ {async_reply, Ref, ok} ->
+ {ok, Data} = file:read_file(FileName);
+ Msg ->
+ test_server:fail(Msg)
+ end,
+ ok.
+
+%%--------------------------------------------------------------------
+
+position(doc) ->
+ ["Test API functions position/3"];
+position(suite) ->
+ [];
+position(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ {Sftp, _} = ?config(sftp, Config),
+
+ Data = list_to_binary("1234567890"),
+ ssh_sftp:write_file(Sftp, FileName, [Data]),
+
+ {ok, Handle} = ssh_sftp:open(Sftp, FileName, [read]),
+
+ {ok, 3} = ssh_sftp:position(Sftp, Handle, {bof, 3}),
+ {ok, "4"} = ssh_sftp:read(Sftp, Handle, 1),
+
+ {ok, 10} = ssh_sftp:position(Sftp, Handle, eof),
+ eof = ssh_sftp:read(Sftp, Handle, 1),
+
+ {ok, 6} = ssh_sftp:position(Sftp, Handle, {bof, 6}),
+ {ok, "7"} = ssh_sftp:read(Sftp, Handle, 1),
+
+ {ok, 9} = ssh_sftp:position(Sftp, Handle, {cur, 2}),
+ {ok, "0"} = ssh_sftp:read(Sftp, Handle, 1),
+
+ {ok, 0} = ssh_sftp:position(Sftp, Handle, bof),
+ {ok, "1"} = ssh_sftp:read(Sftp, Handle, 1),
+
+ {ok, 1} = ssh_sftp:position(Sftp, Handle, cur),
+ {ok, "2"} = ssh_sftp:read(Sftp, Handle, 1),
+
+ ok.
+
+%%--------------------------------------------------------------------
+pos_read(doc) ->
+ ["Test API functions pread/3 and apread/3"];
+pos_read(suite) ->
+ [];
+pos_read(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ {Sftp, _} = ?config(sftp, Config),
+ Data = list_to_binary("Hej hopp!"),
+ ssh_sftp:write_file(Sftp, FileName, [Data]),
+
+ {ok, Handle} = ssh_sftp:open(Sftp, FileName, [read]),
+
+ {async, Ref} = ssh_sftp:apread(Sftp, Handle, {bof, 5}, 4),
+
+ NewData = "opp!",
+
+ receive
+ {async_reply, Ref, {ok, NewData}} ->
+ ok;
+ Msg ->
+ test_server:fail(Msg)
+ end,
+
+ NewData1 = "hopp",
+
+ {ok, NewData1} = ssh_sftp:pread(Sftp, Handle, {bof, 4}, 4),
+
+ ok.
+%%--------------------------------------------------------------------
+pos_write(doc) ->
+ ["Test API functions pwrite/4 and apwrite/4"];
+pos_write(suite) ->
+ [];
+pos_write(Config) when is_list(Config) ->
+
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok, Handle} = ssh_sftp:open(Sftp, FileName, [write]),
+
+ Data = list_to_binary("Bye,"),
+ ssh_sftp:write_file(Sftp, FileName, [Data]),
+
+ NewData = list_to_binary(" see you tomorrow"),
+ {async, Ref} = ssh_sftp:apwrite(Sftp, Handle, {bof, 4}, NewData),
+ receive
+ {async_reply, Ref, ok} ->
+ ok;
+ Msg ->
+ test_server:fail(Msg)
+ end,
+
+ ok = ssh_sftp:pwrite(Sftp, Handle, eof, list_to_binary("!")),
+
+ NewData1 = list_to_binary("Bye, see you tomorrow!"),
+ {ok, NewData1} = ssh_sftp:read_file(Sftp, FileName),
+
+ ok.
+
+%% Internal functions
+%%--------------------------------------------------------------------
+prep(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ TestFile = filename:join(PrivDir, "sftp.txt"),
+ TestFile1 = filename:join(PrivDir, "test.txt"),
+ TestLink = filename:join(PrivDir, "link_test.txt"),
+
+ file:delete(TestFile),
+ file:delete(TestFile1),
+ file:delete(TestLink),
+
+ %% Initial config
+ DataDir = ?config(data_dir, Config),
+ FileName = filename:join(DataDir, "sftp.txt"),
+ file:copy(FileName, TestFile),
+ Mode = 8#00400 bor 8#00200 bor 8#00040, % read & write owner, read group
+ {ok, FileInfo} = file:read_file_info(TestFile),
+ ok = file:write_file_info(TestFile,
+ FileInfo#file_info{mode = Mode}).
diff --git a/lib/ssh/test/ssh_sftp_SUITE_data/id_rsa b/lib/ssh/test/ssh_sftp_SUITE_data/id_rsa
new file mode 100644
index 0000000000..7e3f885f5d
--- /dev/null
+++ b/lib/ssh/test/ssh_sftp_SUITE_data/id_rsa
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICWwIBAAKBgQDLKYTdRnGzphcN+pF8UuI3sYB7rxZUHbOT87K3vh8XOLkDOsS3
+8VREtNS8Wb3uYXsRtyDoUvrLIDnyllOfJSDupWLr4ibckUZd/nhFAaC6WryVmH6k
+GlQLLp9KU+vcn2DwYeo14gbwHYDB3pmv4CWAlnO1m/BkX4aLz1zC314OkQIBIwKB
+gD/Z2UzboBPjvhpWEHeHw3CW3zzQoJ4X9pw2peH57IOkHOPCA0/A3/hWFvleCH4e
+owWRU3w3ViKVGYbBh/7RJ5rllN+ENUmVn536srJTxLKUtvb5jRGj3W6EWgAGHSUB
+hm83Kt9Lb5hprL7dPrNGvSseBm/LQSfBQ4vUUyiVRKGPAkEA/rPxWoLdBBP+FZtE
+fGzz9izPM6Fe6o8ZGNZIlRBProOhgEvvIqdgzQWObgLVVrw+M/YApPpiYS3PEmWj
+b2b+jwJBAMwyYeL6coKTl8swDu8HvLnshgUFJFTtHhOTXsKtXQNI1b24xhUrB3Sb
+X8fmoByyRNRpOfvg4Jdqi3Z6KfIcsN8CQQDEfC83McBw3DkJWoVKCugVrYnmACSm
+USH9N5cT6AL0VupNB2C0VTwL37cEaJXyc/V4ipLIaWHV8CNl9qKmZWVJAkEAurG4
+lQI8zyfbPW3EgsU+1d+QeZ5NGnJkpC73jWtNudwxIn0M4CdXRgpmMxwAGjyWs5No
+Nr75OfsDKn5SPHIAywJAKrtONlOizgDiG3EvAXZlwFtOb+HkQ7lrFwczrQu9m7yi
+brSAcnTrLKI6CrR33b/QJLvb9C/HTEZojFABGq8M7A==
+-----END RSA PRIVATE KEY-----
diff --git a/lib/ssh/test/ssh_sftp_SUITE_data/id_rsa.pub b/lib/ssh/test/ssh_sftp_SUITE_data/id_rsa.pub
new file mode 100644
index 0000000000..77f57de4af
--- /dev/null
+++ b/lib/ssh/test/ssh_sftp_SUITE_data/id_rsa.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAyymE3UZxs6YXDfqRfFLiN7GAe68WVB2zk/Oyt74fFzi5AzrEt/FURLTUvFm97mF7Ebcg6FL6yyA58pZTnyUg7qVi6+Im3JFGXf54RQGgulq8lZh+pBpUCy6fSlPr3J9g8GHqNeIG8B2Awd6Zr+AlgJZztZvwZF+Gi89cwt9eDpE= jakob@balin
diff --git a/lib/ssh/test/ssh_sftp_SUITE_data/sftp.txt b/lib/ssh/test/ssh_sftp_SUITE_data/sftp.txt
new file mode 100644
index 0000000000..2a878ae255
--- /dev/null
+++ b/lib/ssh/test/ssh_sftp_SUITE_data/sftp.txt
@@ -0,0 +1,252 @@
+There are 5 KeySyms per KeyCode; KeyCodes range from 8 to 254.
+
+ KeyCode Keysym (Keysym) ...
+ Value Value (Name) ...
+
+ 8
+ 9
+ 10
+ 11 0x0041 (A)
+ 12 0x0042 (B)
+ 13 0x0043 (C)
+ 14 0x0044 (D)
+ 15 0x0065 (e) 0x0045 (E) 0x20ac (EuroSign)
+ 16 0x0046 (F)
+ 17 0x0047 (G)
+ 18 0x0048 (H)
+ 19 0x0049 (I)
+ 20 0x004a (J)
+ 21 0x004b (K)
+ 22 0x004c (L)
+ 23 0x004d (M)
+ 24 0x004e (N)
+ 25 0x004f (O)
+ 26 0x0050 (P)
+ 27 0x0051 (Q)
+ 28 0x0052 (R)
+ 29 0x0053 (S)
+ 30 0x0054 (T)
+ 31 0x0055 (U)
+ 32 0x0056 (V)
+ 33 0x0057 (W)
+ 34 0x0058 (X)
+ 35 0x0059 (Y)
+ 36 0x005a (Z)
+ 37 0x0031 (1) 0x0021 (exclam)
+ 38 0x0032 (2) 0x0022 (quotedbl) 0x0040 (at)
+ 39 0x0033 (3) 0x0023 (numbersign) 0x00a3 (sterling)
+ 40 0x0034 (4) 0x00a4 (currency) 0x0024 (dollar)
+ 41 0x0035 (5) 0x0025 (percent)
+ 42 0x0036 (6) 0x0026 (ampersand)
+ 43 0x0037 (7) 0x002f (slash) 0x007b (braceleft)
+ 44 0x0038 (8) 0x0028 (parenleft) 0x005b (bracketleft)
+ 45 0x0039 (9) 0x0029 (parenright) 0x005d (bracketright)
+ 46 0x0030 (0) 0x003d (equal) 0x007d (braceright)
+ 47 0xff0d (Return)
+ 48 0xff1b (Escape)
+ 49 0xff08 (BackSpace)
+ 50 0xff09 (Tab)
+ 51 0x0020 (space)
+ 52 0x002b (plus) 0x003f (question) 0x005c (backslash)
+ 53 0x1005ff03 (SunFA_Acute) 0x1005ff00 (SunFA_Grave)
+ 54 0x00c5 (Aring)
+ 55 0x1005ff04 (SunFA_Diaeresis) 0x005e (asciicircum) 0x007e (asciitilde)
+ 56
+ 57 0x0027 (apostrophe) 0x002a (asterisk) 0x0060 (grave)
+ 58 0x00d6 (Odiaeresis)
+ 59 0x00c4 (Adiaeresis)
+ 60 0x00a7 (section) 0x00bd (onehalf)
+ 61 0x002c (comma) 0x003b (semicolon)
+ 62 0x002e (period) 0x003a (colon)
+ 63 0x002d (minus) 0x005f (underscore)
+ 64 0xffe5 (Caps_Lock)
+ 65 0xffbe (F1)
+ 66 0xffbf (F2)
+ 67 0xffc0 (F3)
+ 68 0xffc1 (F4)
+ 69 0xffc2 (F5)
+ 70 0xffc3 (F6)
+ 71 0xffc4 (F7)
+ 72 0xffc5 (F8)
+ 73 0xffc6 (F9)
+ 74 0xffc7 (F10)
+ 75 0x1005ff10 (SunF36)
+ 76 0x1005ff11 (SunF37)
+ 77 0xffd3 (F22) 0xffd3 (F22) 0xff61 (Print) 0x1005ff60 (SunSys_Req)
+ 78 0xffd4 (F23) 0xffd4 (F23) 0xff14 (Scroll_Lock)
+ 79 0xffd2 (F21) 0xffd2 (F21) 0xff13 (Pause) 0xff6b (Break)
+ 80 0xff63 (Insert)
+ 81 0xff50 (Home)
+ 82 0xff55 (Prior)
+ 83 0xffff (Delete)
+ 84 0xff57 (End)
+ 85 0xff56 (Next)
+ 86 0xff53 (Right)
+ 87 0xff51 (Left)
+ 88 0xff54 (Down)
+ 89 0xff52 (Up)
+ 90 0xff7f (Num_Lock)
+ 91 0xffd6 (F25) 0xffd6 (F25) 0xffaf (KP_Divide)
+ 92 0xffd7 (F26) 0xffd7 (F26) 0xffaa (KP_Multiply)
+ 93 0xffd5 (F24) 0xffd5 (F24) 0xffad (KP_Subtract)
+ 94 0xffab (KP_Add)
+ 95 0xff8d (KP_Enter)
+ 96 0xffde (F33) 0xffde (F33) 0xffb1 (KP_1) 0xff57 (End)
+ 97 0xff54 (Down) 0xffdf (F34) 0xffb2 (KP_2)
+ 98 0xffe0 (F35) 0xffe0 (F35) 0xffb3 (KP_3) 0xff56 (Next)
+ 99 0xff51 (Left) 0xffdb (F30) 0xffb4 (KP_4)
+ 100 0xffdc (F31) 0xffdc (F31) 0xffb5 (KP_5)
+ 101 0xff53 (Right) 0xffdd (F32) 0xffb6 (KP_6)
+ 102 0xffd8 (F27) 0xffd8 (F27) 0xffb7 (KP_7) 0xff50 (Home)
+ 103 0xff52 (Up) 0xffd9 (F28) 0xffb8 (KP_8)
+ 104 0xffda (F29) 0xffda (F29) 0xffb9 (KP_9) 0xff55 (Prior)
+ 105 0xff9e (KP_Insert) 0xff9e (KP_Insert) 0xffb0 (KP_0)
+ 106 0xffff (Delete) 0xffff (Delete) 0xffac (KP_Separator)
+ 107 0x003c (less) 0x003e (greater) 0x007c (bar)
+ 108 0xff20 (Multi_key)
+ 109 0x1005ff76 (SunPowerSwitch) 0x1005ff7d (SunPowerSwitchShift)
+ 110
+ 111
+ 112
+ 113
+ 114
+ 115
+ 116
+ 117
+ 118
+ 119
+ 120
+ 121
+ 122
+ 123 0xffce (F17) 0xffce (F17) 0x1005ff73 (SunOpen)
+ 124 0xff6a (Help)
+ 125 0xffca (F13) 0xffca (F13) 0x1005ff70 (SunProps)
+ 126 0xffcc (F15) 0xffcc (F15) 0x1005ff71 (SunFront)
+ 127 0xffc8 (F11) 0xffc8 (F11) 0xff69 (Cancel)
+ 128 0xffc9 (F12) 0xffc9 (F12) 0xff66 (Redo)
+ 129 0xffcb (F14) 0xffcb (F14) 0xff65 (Undo)
+ 130 0xffd1 (F20) 0xffd1 (F20) 0x1005ff75 (SunCut)
+ 131 0xffcd (F16) 0xffcd (F16) 0x1005ff72 (SunCopy)
+ 132 0xffcf (F18) 0xffcf (F18) 0x1005ff74 (SunPaste)
+ 133 0xffd0 (F19) 0xffd0 (F19) 0xff68 (Find)
+ 134 0x1005ff78 (SunAudioMute) 0x1005ff7a (SunVideoDegauss)
+ 135 0x1005ff79 (SunAudioRaiseVolume) 0x1005ff7c (SunVideoRaiseBrightness)
+ 136 0x1005ff77 (SunAudioLowerVolume) 0x1005ff7b (SunVideoLowerBrightness)
+ 137
+ 138
+ 139
+ 140
+ 141
+ 142
+ 143
+ 144
+ 145
+ 146
+ 147
+ 148
+ 149
+ 150
+ 151
+ 152
+ 153
+ 154
+ 155
+ 156
+ 157
+ 158
+ 159
+ 160
+ 161
+ 162
+ 163
+ 164
+ 165
+ 166
+ 167
+ 168
+ 169
+ 170
+ 171
+ 172
+ 173
+ 174
+ 175
+ 176
+ 177
+ 178
+ 179
+ 180
+ 181
+ 182
+ 183
+ 184
+ 185
+ 186
+ 187
+ 188
+ 189
+ 190
+ 191
+ 192
+ 193
+ 194
+ 195
+ 196
+ 197
+ 198
+ 199
+ 200
+ 201
+ 202
+ 203
+ 204
+ 205
+ 206
+ 207
+ 208
+ 209
+ 210
+ 211
+ 212
+ 213
+ 214
+ 215
+ 216
+ 217
+ 218
+ 219
+ 220
+ 221
+ 222
+ 223
+ 224
+ 225
+ 226
+ 227
+ 228
+ 229
+ 230
+ 231 0xffe3 (Control_L)
+ 232 0xffe1 (Shift_L)
+ 233 0xffe9 (Alt_L)
+ 234 0xffe7 (Meta_L)
+ 235
+ 236 0xffe2 (Shift_R)
+ 237 0xff7e (Mode_switch)
+ 238 0xffe8 (Meta_R)
+ 239
+ 240
+ 241
+ 242
+ 243
+ 244
+ 245
+ 246
+ 247
+ 248
+ 249
+ 250
+ 251
+ 252
+ 253
+ 254
diff --git a/lib/ssh/test/ssh_sftpd_SUITE.erl b/lib/ssh/test/ssh_sftpd_SUITE.erl
new file mode 100644
index 0000000000..bfe54a3e75
--- /dev/null
+++ b/lib/ssh/test/ssh_sftpd_SUITE.erl
@@ -0,0 +1,934 @@
+%%
+%% %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%
+%%
+
+%%
+-module(ssh_sftpd_SUITE).
+
+%% Note: This directive should only be used in test suites.
+-compile(export_all).
+
+-include_lib("common_test/include/ct.hrl").
+-include("test_server_line.hrl").
+-include("ssh_xfer.hrl").
+-include("ssh.hrl").
+
+-include_lib("kernel/include/file.hrl").
+
+-define(SFPD_PORT, 9999).
+-define(USER, "Alladin").
+-define(PASSWD, "Sesame").
+-define(XFER_PACKET_SIZE, 32768).
+-define(XFER_WINDOW_SIZE, 4*?XFER_PACKET_SIZE).
+-define(TIMEOUT, 10000).
+-define(REG_ATTERS, <<0,0,0,0,1>>).
+-define(UNIX_EPOCH, 62167219200).
+
+-define(is_set(F, Bits),
+ ((F) band (Bits)) == (F)).
+
+%% Test server callback functions
+%%--------------------------------------------------------------------
+%% Function: init_per_suite(Config) -> Config
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Initiation before the whole suite
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%%--------------------------------------------------------------------
+init_per_suite(Config) ->
+ case {catch ssh:stop(),catch crypto:start()} of
+ {ok,ok} ->
+ ssh_test_lib:make_dsa_files(Config),
+ Config;
+ {ok,_} ->
+ {skip,"Could not start ssh!"};
+ {_,ok} ->
+ {skip,"Could not start crypto!"};
+ {_,_} ->
+ {skip,"Could not start crypto and ssh!"}
+ end.
+
+%%--------------------------------------------------------------------
+%% Function: end_per_suite(Config) -> _
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after the whole suite
+%%--------------------------------------------------------------------
+end_per_suite(_Config) ->
+ crypto:stop(),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: init_per_testcase(TestCase, Config) -> Config
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%%
+%% Description: Initiation before each test case
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%% Description: Initiation before each test case
+%%--------------------------------------------------------------------
+init_per_testcase(TestCase, Config) ->
+ ssh:start(),
+ prep(Config),
+ SysDir = ?config(data_dir, Config),
+ {ok, Sftpd} =
+ ssh_sftpd:listen(?SFPD_PORT, [{system_dir, SysDir},
+ {user_passwords,[{?USER, ?PASSWD}]},
+ {pwdfun, fun(_,_) -> true end}]),
+
+ Cm = ssh_test_lib:connect(?SFPD_PORT,
+ [{system_dir, SysDir},
+ {user_dir, SysDir},
+ {user, ?USER}, {password, ?PASSWD},
+ {user_interaction, false},
+ {silently_accept_hosts, true},
+ {pwdfun, fun(_,_) -> true end}]),
+ {ok, Channel} =
+ ssh_connection:session_channel(Cm, ?XFER_WINDOW_SIZE,
+ ?XFER_PACKET_SIZE, ?TIMEOUT),
+
+ success = ssh_connection:subsystem(Cm, Channel, "sftp", ?TIMEOUT),
+
+ ProtocolVer = case atom_to_list(TestCase) of
+ "ver3_" ++ _ ->
+ 3;
+ _ ->
+ ?SSH_SFTP_PROTOCOL_VERSION
+ end,
+
+ Data = <<?UINT32(ProtocolVer)>> ,
+
+ Size = 1 + size(Data),
+
+ ssh_connection:send(Cm, Channel, << ?UINT32(Size),
+ ?SSH_FXP_INIT, Data/binary >>),
+
+ {ok, <<?SSH_FXP_VERSION, ?UINT32(Version), _Ext/binary>>, _}
+ = reply(Cm, Channel),
+
+ test_server:format("Client: ~p Server ~p~n", [ProtocolVer, Version]),
+
+ [{sftp, {Cm, Channel}}, {sftpd, Sftpd }| Config].
+
+%%--------------------------------------------------------------------
+%% Function: end_per_testcase(TestCase, Config) -> _
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after each test case
+%%--------------------------------------------------------------------
+end_per_testcase(_TestCase, Config) ->
+ ssh_sftpd:stop(?config(sftpd, Config)),
+ {Cm, Channel} = ?config(sftp, Config),
+ ssh_connection:close(Cm, Channel),
+ ssh:close(Cm),
+ ssh:stop(),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: all(Clause) -> TestCases
+%% Clause - atom() - suite | doc
+%% TestCases - [Case]
+%% Case - atom()
+%% Name of a test case.
+%% Description: Returns a list of all test cases in this test suite
+%%--------------------------------------------------------------------
+all() ->
+ [open_close_file, open_close_dir, read_file, read_dir,
+ write_file, rename_file, mk_rm_dir, remove_file,
+ real_path, retrieve_attributes, set_attributes, links,
+ ver3_rename_OTP_6352, seq10670, sshd_read_file].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+
+%% Test cases starts here.
+%%--------------------------------------------------------------------
+open_close_file(doc) ->
+ ["Test SSH_FXP_OPEN and SSH_FXP_CLOSE commands"];
+open_close_file(suite) ->
+ [];
+open_close_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ {Cm, Channel} = ?config(sftp, Config),
+ ReqId = 0,
+
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(ReqId), Handle/binary>>, _} =
+ open_file(FileName, Cm, Channel, ReqId,
+ ?ACE4_READ_DATA bor ?ACE4_READ_ATTRIBUTES,
+ ?SSH_FXF_OPEN_EXISTING),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} = close(Handle, ReqId,
+ Cm, Channel),
+ NewReqId = ReqId + 1,
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_INVALID_HANDLE), _/binary>>, _} =
+ close(Handle, ReqId, Cm, Channel),
+
+ NewReqId1 = NewReqId + 1,
+ %% {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId), % Ver 6 we have 5
+ %% ?UINT32(?SSH_FX_FILE_IS_A_DIRECTORY), _/binary>>, _} =
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId1),
+ ?UINT32(?SSH_FX_FAILURE), _/binary>>, _} =
+ open_file(PrivDir, Cm, Channel, NewReqId1,
+ ?ACE4_READ_DATA bor ?ACE4_READ_ATTRIBUTES,
+ ?SSH_FXF_OPEN_EXISTING),
+
+ ok.
+
+%%--------------------------------------------------------------------
+open_close_dir(doc) ->
+ ["Test SSH_FXP_OPENDIR and SSH_FXP_CLOSE commands"];
+open_close_dir(suite) ->
+ [];
+open_close_dir(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ {Cm, Channel} = ?config(sftp, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ ReqId = 0,
+
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(ReqId), Handle/binary>>, _} =
+ open_dir(PrivDir, Cm, Channel, ReqId),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} = close(Handle, ReqId,
+ Cm, Channel),
+
+ NewReqId = 1,
+ case open_dir(FileName, Cm, Channel, NewReqId) of
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId),
+ ?UINT32(?SSH_FX_NOT_A_DIRECTORY), _/binary>>, _} ->
+ %% Only if server is using vsn > 5.
+ ok;
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId),
+ ?UINT32(?SSH_FX_FAILURE), _/binary>>, _} ->
+ ok
+ end.
+
+%%--------------------------------------------------------------------
+read_file(doc) ->
+ ["Test SSH_FXP_READ command"];
+read_file(suite) ->
+ [];
+read_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(ReqId), Handle/binary>>, _} =
+ open_file(FileName, Cm, Channel, ReqId,
+ ?ACE4_READ_DATA bor ?ACE4_READ_ATTRIBUTES,
+ ?SSH_FXF_OPEN_EXISTING),
+
+ NewReqId = 1,
+
+ {ok, <<?SSH_FXP_DATA, ?UINT32(NewReqId), ?UINT32(_Length),
+ Data/binary>>, _} =
+ read_file(Handle, 100, 0, Cm, Channel, NewReqId),
+
+ {ok, Data} = file:read_file(FileName),
+
+ ok.
+%%--------------------------------------------------------------------
+read_dir(doc) ->
+ ["Test SSH_FXP_READDIR command"];
+read_dir(suite) ->
+ [];
+read_dir(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ {Cm, Channel} = ?config(sftp, Config),
+ ReqId = 0,
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(ReqId), Handle/binary>>, _} =
+ open_dir(PrivDir, Cm, Channel, ReqId),
+ ok = read_dir(Handle, Cm, Channel, ReqId),
+ ok.
+
+%%--------------------------------------------------------------------
+write_file(doc) ->
+ ["Test SSH_FXP_WRITE command"];
+write_file(suite) ->
+ [];
+write_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(ReqId), Handle/binary>>, _} =
+ open_file(FileName, Cm, Channel, ReqId,
+ ?ACE4_WRITE_DATA bor ?ACE4_WRITE_ATTRIBUTES,
+ ?SSH_FXF_OPEN_EXISTING),
+
+ NewReqId = 1,
+ Data = list_to_binary("Write file test"),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId), ?UINT32(?SSH_FX_OK),
+ _/binary>>, _}
+ = write_file(Handle, Data, 0, Cm, Channel, NewReqId),
+
+ {ok, Data} = file:read_file(FileName),
+
+ ok.
+
+%%--------------------------------------------------------------------
+remove_file(doc) ->
+ ["Test SSH_FXP_REMOVE command"];
+remove_file(suite) ->
+ [];
+remove_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} =
+ remove(FileName, Cm, Channel, ReqId),
+
+ NewReqId = 1,
+ %% {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId), % ver 6 we have 5
+ %% ?UINT32(?SSH_FX_FILE_IS_A_DIRECTORY ), _/binary>>, _} =
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId),
+ ?UINT32(?SSH_FX_FAILURE), _/binary>>, _} =
+ remove(PrivDir, Cm, Channel, NewReqId),
+
+ ok.
+
+%%--------------------------------------------------------------------
+rename_file(doc) ->
+ ["Test SSH_FXP_RENAME command"];
+rename_file(suite) ->
+ [];
+rename_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ NewFileName = filename:join(PrivDir, "test1.txt"),
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} =
+ rename(FileName, NewFileName, Cm, Channel, ReqId, 6, 0),
+
+ NewReqId = ReqId + 1,
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} =
+ rename(NewFileName, FileName, Cm, Channel, NewReqId, 6,
+ ?SSH_FXP_RENAME_OVERWRITE),
+
+ NewReqId1 = NewReqId + 1,
+ file:copy(FileName, NewFileName),
+
+ %% No owerwrite
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId1),
+ ?UINT32(?SSH_FX_FILE_ALREADY_EXISTS), _/binary>>, _} =
+ rename(FileName, NewFileName, Cm, Channel, NewReqId1, 6,
+ ?SSH_FXP_RENAME_NATIVE),
+
+ NewReqId2 = NewReqId1 + 1,
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId2),
+ ?UINT32(?SSH_FX_OP_UNSUPPORTED), _/binary>>, _} =
+ rename(FileName, NewFileName, Cm, Channel, NewReqId2, 6,
+ ?SSH_FXP_RENAME_ATOMIC),
+
+ ok.
+
+%%--------------------------------------------------------------------
+mk_rm_dir(doc) ->
+ ["Test SSH_FXP_MKDIR and SSH_FXP_RMDIR command"];
+mk_rm_dir(suite) ->
+ [];
+mk_rm_dir(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ {Cm, Channel} = ?config(sftp, Config),
+ DirName = filename:join(PrivDir, "test"),
+ ReqId = 0,
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId), ?UINT32(?SSH_FX_OK),
+ _/binary>>, _} = mkdir(DirName, Cm, Channel, ReqId),
+
+ NewReqId = 1,
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId), ?UINT32(?SSH_FX_FAILURE),
+ _/binary>>, _} = mkdir(DirName, Cm, Channel, NewReqId),
+
+ NewReqId1 = 2,
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId1), ?UINT32(?SSH_FX_OK),
+ _/binary>>, _} = rmdir(DirName, Cm, Channel, NewReqId1),
+
+ NewReqId2 = 3,
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId2), ?UINT32(?SSH_FX_NO_SUCH_FILE),
+ _/binary>>, _} = rmdir(DirName, Cm, Channel, NewReqId2),
+
+ ok.
+%%--------------------------------------------------------------------
+real_path(doc) ->
+ ["Test SSH_FXP_REALPATH command"];
+real_path(suite) ->
+ [];
+real_path(Config) when is_list(Config) ->
+ case test_server:os_type() of
+ {win32, _} ->
+ {skip, "Not a relevant test on windows"};
+ _ ->
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+ PrivDir = ?config(priv_dir, Config),
+ TestDir = filename:join(PrivDir, "ssh_test"),
+ ok = file:make_dir(TestDir),
+
+ OrigPath = filename:join(TestDir, ".."),
+
+ {ok, <<?SSH_FXP_NAME, ?UINT32(ReqId), ?UINT32(_), ?UINT32(Len),
+ Path:Len/binary, _/binary>>, _}
+ = real_path(OrigPath, Cm, Channel, ReqId),
+
+ RealPath = filename:absname(binary_to_list(Path)),
+ AbsPrivDir = filename:absname(PrivDir),
+
+ test_server:format("Path: ~p PrivDir: ~p~n", [RealPath, AbsPrivDir]),
+
+ true = RealPath == AbsPrivDir,
+
+ ok
+ end.
+
+%%--------------------------------------------------------------------
+links(doc) ->
+ [];
+links(suite) ->
+ [];
+links(Config) when is_list(Config) ->
+ case test_server:os_type() of
+ {win32, _} ->
+ {skip, "Links are not fully supported by windows"};
+ _ ->
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ LinkFileName = filename:join(PrivDir, "link_test.txt"),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} =
+ create_link(LinkFileName, FileName, Cm, Channel, ReqId),
+
+ NewReqId = 1,
+ {ok, <<?SSH_FXP_NAME, ?UINT32(NewReqId), ?UINT32(_), ?UINT32(Len),
+ Path:Len/binary, _/binary>>, _}
+ = read_link(LinkFileName, Cm, Channel, NewReqId),
+
+
+ true = binary_to_list(Path) == FileName,
+
+ test_server:format("Path: ~p~n", [binary_to_list(Path)]),
+ ok
+ end.
+
+%%--------------------------------------------------------------------
+retrieve_attributes(doc) ->
+ ["Test SSH_FXP_STAT, SSH_FXP_LSTAT AND SSH_FXP_FSTAT commands"];
+retrieve_attributes(suite) ->
+ [];
+retrieve_attributes(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, FileInfo} = file:read_file_info(FileName),
+
+ AttrValues =
+ retrive_attributes(FileName, Cm, Channel, ReqId),
+
+ Type = encode_file_type(FileInfo#file_info.type),
+ Size = FileInfo#file_info.size,
+ Owner = FileInfo#file_info.uid,
+ Group = FileInfo#file_info.gid,
+ Permissions = FileInfo#file_info.mode,
+ Atime = calendar:datetime_to_gregorian_seconds(
+ erlang:localtime_to_universaltime(FileInfo#file_info.atime))
+ - ?UNIX_EPOCH,
+ Mtime = calendar:datetime_to_gregorian_seconds(
+ erlang:localtime_to_universaltime(FileInfo#file_info.mtime))
+ - ?UNIX_EPOCH,
+ Ctime = calendar:datetime_to_gregorian_seconds(
+ erlang:localtime_to_universaltime(FileInfo#file_info.ctime))
+ - ?UNIX_EPOCH,
+
+ lists:foreach(fun(Value) ->
+ <<?UINT32(Flags), _/binary>> = Value,
+ true = ?is_set(?SSH_FILEXFER_ATTR_SIZE,
+ Flags),
+ true = ?is_set(?SSH_FILEXFER_ATTR_PERMISSIONS,
+ Flags),
+ true = ?is_set(?SSH_FILEXFER_ATTR_ACCESSTIME,
+ Flags),
+ true = ?is_set(?SSH_FILEXFER_ATTR_CREATETIME,
+ Flags),
+ true = ?is_set(?SSH_FILEXFER_ATTR_MODIFYTIME,
+ Flags),
+ true = ?is_set(?SSH_FILEXFER_ATTR_OWNERGROUP,
+ Flags),
+ false = ?is_set(?SSH_FILEXFER_ATTR_ACL,
+ Flags),
+ false = ?is_set(?SSH_FILEXFER_ATTR_SUBSECOND_TIMES,
+ Flags),
+ false = ?is_set(?SSH_FILEXFER_ATTR_BITS,
+ Flags),
+ false = ?is_set(?SSH_FILEXFER_ATTR_EXTENDED,
+ Flags),
+
+ <<?UINT32(_Flags), ?BYTE(Type),
+ ?UINT64(Size),
+ ?UINT32(OwnerLen), BinOwner:OwnerLen/binary,
+ ?UINT32(GroupLen), BinGroup:GroupLen/binary,
+ ?UINT32(Permissions),
+ ?UINT64(Atime),
+ ?UINT64(Ctime),
+ ?UINT64(Mtime)>> = Value,
+
+ Owner = list_to_integer(binary_to_list(BinOwner)),
+ Group = list_to_integer(binary_to_list(BinGroup))
+ end, AttrValues),
+
+ ok.
+%%--------------------------------------------------------------------
+set_attributes(doc) ->
+ ["Test SSH_FXP_SETSTAT AND SSH_FXP_FSETSTAT commands"];
+set_attributes(suite) ->
+ [];
+set_attributes(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, FileInfo} = file:read_file_info(FileName),
+
+ OrigPermissions = FileInfo#file_info.mode,
+ Permissions = 8#400, %% User read-only
+
+ Flags = ?SSH_FILEXFER_ATTR_PERMISSIONS,
+
+ Atters = [?uint32(Flags), ?byte(?SSH_FILEXFER_TYPE_REGULAR),
+ ?uint32(Permissions)],
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} =
+ set_attributes_file(FileName, Atters, Cm, Channel, ReqId),
+
+ {ok, NewFileInfo} = file:read_file_info(FileName),
+ NewPermissions = NewFileInfo#file_info.mode,
+
+ %% Can not test that NewPermissions = Permissions as
+ %% on Unix platforms, other bits than those listed in the
+ %% API may be set.
+ test_server:format("Org: ~p New: ~p~n", [OrigPermissions, NewPermissions]),
+ true = OrigPermissions =/= NewPermissions,
+
+ test_server:format("Try to open the file"),
+ NewReqId = 2,
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(NewReqId), Handle/binary>>, _} =
+ open_file(FileName, Cm, Channel, NewReqId,
+ ?ACE4_READ_DATA bor ?ACE4_WRITE_ATTRIBUTES,
+ ?SSH_FXF_OPEN_EXISTING),
+
+ NewAtters = [?uint32(Flags), ?byte(?SSH_FILEXFER_TYPE_REGULAR),
+ ?uint32(OrigPermissions)],
+
+ NewReqId1 = 3,
+
+ test_server:format("Set original permissions on the now open file"),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(NewReqId1),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} =
+ set_attributes_open_file(Handle, NewAtters, Cm, Channel, NewReqId1),
+
+ {ok, NewFileInfo1} = file:read_file_info(FileName),
+ OrigPermissions = NewFileInfo1#file_info.mode,
+
+ ok.
+
+%%--------------------------------------------------------------------
+ver3_rename_OTP_6352(doc) ->
+ ["Test that ver3 rename message is handled"];
+
+ver3_rename_OTP_6352(suite) ->
+ [];
+
+ver3_rename_OTP_6352(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+ NewFileName = filename:join(PrivDir, "test1.txt"),
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_OK), _/binary>>, _} =
+ rename(FileName, NewFileName, Cm, Channel, ReqId, 3, 0),
+
+ ok.
+
+%%--------------------------------------------------------------------
+seq10670(doc) ->
+ ["Check that realpath works ok"];
+
+seq10670(suite) ->
+ [];
+
+seq10670(Config) when is_list(Config) ->
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ case test_server:os_type() of
+ {win32, _} ->
+ {skip, "Not a relevant test on windows"};
+ _ ->
+ {ok, <<?SSH_FXP_NAME, ?UINT32(ReqId), ?UINT32(_), ?UINT32(Len),
+ Root:Len/binary, _/binary>>, _}
+ = real_path("/..", Cm, Channel, ReqId),
+
+ <<"/">> = Root,
+
+ {ok, <<?SSH_FXP_NAME, ?UINT32(ReqId), ?UINT32(_), ?UINT32(Len),
+ Path:Len/binary, _/binary>>, _}
+ = real_path("/usr/bin/../..", Cm, Channel, ReqId),
+
+ Root = Path
+ end.
+
+%% Internal functions
+%%--------------------------------------------------------------------
+prep(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ TestFile = filename:join(PrivDir, "test.txt"),
+ TestFile1 = filename:join(PrivDir, "test1.txt"),
+
+ file:delete(TestFile),
+ file:delete(TestFile1),
+
+ %% Initial config
+ DataDir = ?config(data_dir, Config),
+ FileName = filename:join(DataDir, "test.txt"),
+ file:copy(FileName, TestFile),
+ Mode = 8#00400 bor 8#00200 bor 8#00040, % read & write owner, read group
+ {ok, FileInfo} = file:read_file_info(TestFile),
+ ok = file:write_file_info(TestFile,
+ FileInfo#file_info{mode = Mode}).
+
+reply(Cm, Channel) ->
+ reply(Cm, Channel,<<>>).
+
+reply(Cm, Channel, RBuf) ->
+ receive
+ {ssh_cm, Cm, {data, Channel, 0, Data}} ->
+ case <<RBuf/binary, Data/binary>> of
+ <<?UINT32(Len),Reply:Len/binary,Rest/binary>> ->
+ {ok, Reply, Rest};
+ RBuf2 ->
+ reply(Cm, Channel, RBuf2)
+ end;
+ {ssh_cm, Cm, {eof, Channel}} ->
+ eof;
+ {ssh_cm, Cm, {closed, Channel}} ->
+ closed;
+ {ssh_cm, Cm, Msg} ->
+ test_server:fail(Msg)
+ end.
+
+
+open_file(File, Cm, Channel, ReqId, Access, Flags) ->
+
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(File)),
+ ?uint32(Access),
+ ?uint32(Flags),
+ ?REG_ATTERS]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_OPEN, Data/binary>>),
+ reply(Cm, Channel).
+
+
+
+close(Handle, ReqId, Cm , Channel) ->
+ Data = list_to_binary([?uint32(ReqId), Handle]),
+
+ Size = 1 + size(Data),
+
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size), ?SSH_FXP_CLOSE,
+ Data/binary>>),
+
+ reply(Cm, Channel).
+
+
+
+open_dir(Dir, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(Dir))]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_OPENDIR, Data/binary>>),
+ reply(Cm, Channel).
+
+
+rename(OldName, NewName, Cm, Channel, ReqId, Version, Flags) ->
+ Data =
+ case Version of
+ 3 ->
+ list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(OldName)),
+ ?binary(list_to_binary(NewName))]);
+ _ ->
+ list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(OldName)),
+ ?binary(list_to_binary(NewName)),
+ ?uint32(Flags)])
+ end,
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_RENAME, Data/binary>>),
+ reply(Cm, Channel).
+
+
+mkdir(Dir, Cm, Channel, ReqId)->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(Dir)),
+ ?REG_ATTERS]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_MKDIR, Data/binary>>),
+ reply(Cm, Channel).
+
+
+rmdir(Dir, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(Dir))]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_RMDIR, Data/binary>>),
+ reply(Cm, Channel).
+
+remove(File, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(File))]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_REMOVE, Data/binary>>),
+ reply(Cm, Channel).
+
+
+read_dir(Handle, Cm, Channel, ReqId) ->
+
+ Data = list_to_binary([?uint32(ReqId), Handle]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_READDIR, Data/binary>>),
+ case reply(Cm, Channel) of
+ {ok, <<?SSH_FXP_NAME, ?UINT32(ReqId), ?UINT32(Count),
+ ?UINT32(Len), Listing:Len/binary, _/binary>>, _} ->
+ test_server:format("Count: ~p Listing: ~p~n",
+ [Count, binary_to_list(Listing)]),
+ read_dir(Handle, Cm, Channel, ReqId);
+ {ok, <<?SSH_FXP_STATUS, ?UINT32(ReqId),
+ ?UINT32(?SSH_FX_EOF), _/binary>>, _} ->
+ ok
+ end.
+
+read_file(Handle, MaxLength, OffSet, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId), Handle,
+ ?uint64(OffSet),
+ ?uint32(MaxLength)]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_READ, Data/binary>>),
+ reply(Cm, Channel).
+
+
+write_file(Handle, FileData, OffSet, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId), Handle,
+ ?uint64(OffSet),
+ ?binary(FileData)]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_WRITE, Data/binary>>),
+ reply(Cm, Channel).
+
+
+real_path(OrigPath, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(OrigPath))]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_REALPATH, Data/binary>>),
+ reply(Cm, Channel).
+
+create_link(LinkPath, Path, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(LinkPath)),
+ ?binary(list_to_binary(Path))]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_SYMLINK, Data/binary>>),
+ reply(Cm, Channel).
+
+
+read_link(Link, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(Link))]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_READLINK, Data/binary>>),
+ reply(Cm, Channel).
+
+retrive_attributes_file(FilePath, Flags, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(FilePath)),
+ ?uint32(Flags)]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_STAT, Data/binary>>),
+ reply(Cm, Channel).
+
+retrive_attributes_file_or_link(FilePath, Flags, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(FilePath)),
+ ?uint32(Flags)]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_LSTAT, Data/binary>>),
+ reply(Cm, Channel).
+
+retrive_attributes_open_file(Handle, Flags, Cm, Channel, ReqId) ->
+
+ Data = list_to_binary([?uint32(ReqId),
+ Handle,
+ ?uint32(Flags)]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_FSTAT, Data/binary>>),
+ reply(Cm, Channel).
+
+retrive_attributes(FileName, Cm, Channel, ReqId) ->
+
+ Attr = ?SSH_FILEXFER_ATTR_SIZE,
+
+ {ok, <<?SSH_FXP_ATTRS, ?UINT32(ReqId), Value/binary>>, _}
+ = retrive_attributes_file(FileName, Attr,
+ Cm, Channel, ReqId),
+
+ NewReqId = ReqId + 1,
+ {ok, <<?SSH_FXP_ATTRS, ?UINT32(NewReqId), Value1/binary>>, _}
+ = retrive_attributes_file_or_link(FileName,
+ Attr, Cm, Channel, NewReqId),
+
+ NewReqId1 = NewReqId + 1,
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(NewReqId1), Handle/binary>>, _} =
+ open_file(FileName, Cm, Channel, NewReqId1,
+ ?ACE4_READ_DATA bor ?ACE4_READ_ATTRIBUTES,
+ ?SSH_FXF_OPEN_EXISTING),
+
+ NewReqId2 = NewReqId1 + 1,
+ {ok, <<?SSH_FXP_ATTRS, ?UINT32(NewReqId2), Value2/binary>>, _}
+ = retrive_attributes_open_file(Handle, Attr, Cm, Channel, NewReqId2),
+
+ [Value, Value1, Value2].
+
+set_attributes_file(FilePath, Atters, Cm, Channel, ReqId) ->
+ Data = list_to_binary([?uint32(ReqId),
+ ?binary(list_to_binary(FilePath)),
+ Atters]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_SETSTAT, Data/binary>>),
+ reply(Cm, Channel).
+
+
+set_attributes_open_file(Handle, Atters, Cm, Channel, ReqId) ->
+
+ Data = list_to_binary([?uint32(ReqId),
+ Handle,
+ Atters]),
+ Size = 1 + size(Data),
+ ssh_connection:send(Cm, Channel, <<?UINT32(Size),
+ ?SSH_FXP_FSETSTAT, Data/binary>>),
+ reply(Cm, Channel).
+
+
+encode_file_type(Type) ->
+ case Type of
+ regular -> ?SSH_FILEXFER_TYPE_REGULAR;
+ directory -> ?SSH_FILEXFER_TYPE_DIRECTORY;
+ symlink -> ?SSH_FILEXFER_TYPE_SYMLINK;
+ special -> ?SSH_FILEXFER_TYPE_SPECIAL;
+ unknown -> ?SSH_FILEXFER_TYPE_UNKNOWN;
+ other -> ?SSH_FILEXFER_TYPE_UNKNOWN;
+ socket -> ?SSH_FILEXFER_TYPE_SOCKET;
+ char_device -> ?SSH_FILEXFER_TYPE_CHAR_DEVICE;
+ block_device -> ?SSH_FILEXFER_TYPE_BLOCK_DEVICE;
+ fifo -> ?SSH_FILEXFER_TYPE_FIFO;
+ undefined -> ?SSH_FILEXFER_TYPE_UNKNOWN
+ end.
+
+%%--------------------------------------------------------------------
+sshd_read_file(doc) ->
+ ["Test SSH_FXP_READ command, using sshd-server"];
+sshd_read_file(suite) ->
+ [];
+sshd_read_file(Config) when is_list(Config) ->
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(PrivDir, "test.txt"),
+
+ ReqId = 0,
+ {Cm, Channel} = ?config(sftp, Config),
+
+ {ok, <<?SSH_FXP_HANDLE, ?UINT32(ReqId), Handle/binary>>, _} =
+ open_file(FileName, Cm, Channel, ReqId,
+ ?ACE4_READ_DATA bor ?ACE4_READ_ATTRIBUTES,
+ ?SSH_FXF_OPEN_EXISTING),
+
+ NewReqId = 1,
+
+ {ok, <<?SSH_FXP_DATA, ?UINT32(NewReqId), ?UINT32(_Length),
+ Data/binary>>, _} =
+ read_file(Handle, 100, 0, Cm, Channel, NewReqId),
+
+ {ok, Data} = file:read_file(FileName),
+
+ ok.
diff --git a/lib/ssh/test/ssh_sftpd_SUITE_data/test.txt b/lib/ssh/test/ssh_sftpd_SUITE_data/test.txt
new file mode 100644
index 0000000000..681bff80a0
--- /dev/null
+++ b/lib/ssh/test/ssh_sftpd_SUITE_data/test.txt
@@ -0,0 +1 @@
+Sftp test file. \ No newline at end of file
diff --git a/lib/ssh/test/ssh_sftpd_erlclient_SUITE.erl b/lib/ssh/test/ssh_sftpd_erlclient_SUITE.erl
new file mode 100644
index 0000000000..2209af05d5
--- /dev/null
+++ b/lib/ssh/test/ssh_sftpd_erlclient_SUITE.erl
@@ -0,0 +1,328 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2007-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(ssh_sftpd_erlclient_SUITE).
+
+%% Note: This directive should only be used in test suites.
+-compile(export_all).
+
+-include_lib("common_test/include/ct.hrl").
+-include("test_server_line.hrl").
+
+-include_lib("kernel/include/file.hrl").
+
+-define(SSHD_PORT, 9999).
+-define(USER, "Alladin").
+-define(PASSWD, "Sesame").
+-define(SSH_MAX_PACKET_SIZE, 32768).
+
+%% Test server callback functions
+%%--------------------------------------------------------------------
+%% Function: init_per_suite(Config) -> Config
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Initiation before the whole suite
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%%--------------------------------------------------------------------
+init_per_suite(Config) ->
+ catch ssh:stop(),
+ case catch crypto:start() of
+ ok ->
+ DataDir = ?config(data_dir, Config),
+ FileAlt = filename:join(DataDir, "ssh_sftpd_file_alt.erl"),
+ c:c(FileAlt),
+ FileName = filename:join(DataDir, "test.txt"),
+ {ok, FileInfo} = file:read_file_info(FileName),
+ ok = file:write_file_info(FileName,
+ FileInfo#file_info{mode = 8#400}),
+ ssh_test_lib:make_dsa_files(Config),
+ Config;
+ _Else ->
+ {skip,"Could not start ssh!"}
+ end.
+
+%%--------------------------------------------------------------------
+%% Function: end_per_suite(Config) -> _
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after the whole suite
+%%--------------------------------------------------------------------
+end_per_suite(_Config) ->
+ crypto:stop(),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: init_per_testcase(TestCase, Config) -> Config
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%%
+%% Description: Initiation before each test case
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%% Description: Initiation before each test case
+%%--------------------------------------------------------------------
+init_per_testcase(TestCase, Config) ->
+ ssh:start(),
+ DataDir = ?config(data_dir, Config),
+
+ Options =
+ case atom_to_list(TestCase) of
+ "file_cb" ++ _ ->
+ Spec =
+ ssh_sftpd:subsystem_spec([{file_handler,
+ ssh_sftpd_file_alt}]),
+ [{user_passwords,[{?USER, ?PASSWD}]},
+ {pwdfun, fun(_,_) -> true end},
+ {system_dir, DataDir},
+ {user_dir, DataDir},
+ {subsystems, [Spec]}];
+ "root_dir" ->
+ Privdir = ?config(priv_dir, Config),
+ Root = filename:join(Privdir, root),
+ file:make_dir(Root),
+ Spec = ssh_sftpd:subsystem_spec([{root,Root}]),
+ [{user_passwords,[{?USER, ?PASSWD}]},
+ {pwdfun, fun(_,_) -> true end},
+ {system_dir, DataDir},
+ {user_dir, DataDir},
+ {subsystems, [Spec]}];
+ "list_dir_limited" ->
+ Spec =
+ ssh_sftpd:subsystem_spec([{max_files,1}]),
+ [{user_passwords,[{?USER, ?PASSWD}]},
+ {pwdfun, fun(_,_) -> true end},
+ {system_dir, DataDir},
+ {user_dir, DataDir},
+ {subsystems, [Spec]}];
+
+ _ ->
+ [{user_passwords,[{?USER, ?PASSWD}]},
+ {pwdfun, fun(_,_) -> true end},
+ {user_dir, DataDir},
+ {system_dir, DataDir}]
+ end,
+
+ {Sftpd, Host, _Port} = ssh_test_lib:daemon(any, ?SSHD_PORT, Options),
+
+ {ok, ChannelPid, Connection} =
+ ssh_sftp:start_channel(Host, ?SSHD_PORT,
+ [{silently_accept_hosts, true},
+ {user, ?USER}, {password, ?PASSWD},
+ {pwdfun, fun(_,_) -> true end},
+ {system_dir, DataDir},
+ {user_dir, DataDir},
+ {timeout, 30000}]),
+ TmpConfig = lists:keydelete(sftp, 1, Config),
+ NewConfig = lists:keydelete(sftpd, 1, TmpConfig),
+ [{sftp, {ChannelPid, Connection}}, {sftpd, Sftpd} | NewConfig].
+
+%%--------------------------------------------------------------------
+%% Function: end_per_testcase(TestCase, Config) -> _
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after each test case
+%%--------------------------------------------------------------------
+end_per_testcase(_TestCase, Config) ->
+ catch ssh_sftpd:stop(?config(sftpd, Config)),
+ {Sftp, Connection} = ?config(sftp, Config),
+ catch ssh_sftp:stop_channel(Sftp),
+ catch ssh:close(Connection),
+ ssh:stop(),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: all(Clause) -> TestCases
+%% Clause - atom() - suite | doc
+%% TestCases - [Case]
+%% Case - atom()
+%% Name of a test case.
+%% Description: Returns a list of all test cases in this test suite
+%%--------------------------------------------------------------------
+all() ->
+ [close_file_OTP_6350, quit_OTP_6349, file_cb_OTP_6356,
+ root_dir, list_dir_limited].
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+%% Test cases starts here.
+%%--------------------------------------------------------------------
+close_file_OTP_6350(doc) ->
+ ["Test that sftpd closes its fildescriptors after compleating the "
+ "transfer"];
+
+close_file_OTP_6350(suite) ->
+ [];
+
+close_file_OTP_6350(Config) when is_list(Config) ->
+ DataDir = ?config(data_dir, Config),
+ FileName = filename:join(DataDir, "test.txt"),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ NumOfPorts = length(erlang:ports()),
+
+ test_server:format("Number of open ports: ~p~n", [NumOfPorts]),
+
+ {ok, <<_/binary>>} = ssh_sftp:read_file(Sftp, FileName),
+
+ NumOfPorts = length(erlang:ports()),
+
+ test_server:format("Number of open ports: ~p~n",
+ [length(erlang:ports())]),
+
+ ok.
+
+%%--------------------------------------------------------------------
+
+quit_OTP_6349(doc) ->
+ [" When the sftp client ends the session the "
+ "server will now behave correctly and not leave the "
+ "client hanging."];
+
+quit_OTP_6349(suite) ->
+ [];
+
+quit_OTP_6349(Config) when is_list(Config) ->
+ DataDir = ?config(data_dir, Config),
+ FileName = filename:join(DataDir, "test.txt"),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok, <<_/binary>>} = ssh_sftp:read_file(Sftp, FileName),
+
+ ok = ssh_sftp:stop_channel(Sftp),
+
+ Host = ssh_test_lib:hostname(),
+
+ timer:sleep(5000),
+ {ok, NewSftp, _Conn} = ssh_sftp:start_channel(Host, ?SSHD_PORT,
+ [{silently_accept_hosts, true},
+ {pwdfun, fun(_,_) -> true end},
+ {system_dir, DataDir},
+ {user_dir, DataDir},
+ {user, ?USER}, {password, ?PASSWD}]),
+
+ {ok, <<_/binary>>} = ssh_sftp:read_file(NewSftp, FileName),
+
+ ok = ssh_sftp:stop_channel(NewSftp),
+ ok.
+
+%%--------------------------------------------------------------------
+
+file_cb_OTP_6356(doc) ->
+ ["Test that it is possible to change the callback module for"
+ " the sftpds filehandling."];
+
+file_cb_OTP_6356(suite) ->
+ [];
+
+file_cb_OTP_6356(Config) when is_list(Config) ->
+ DataDir = ?config(data_dir, Config),
+ PrivDir = ?config(priv_dir, Config),
+ FileName = filename:join(DataDir, "test.txt"),
+
+ register(sftpd_file_alt_tester, self()),
+
+ {Sftp, _} = ?config(sftp, Config),
+
+ {ok, Bin} = ssh_sftp:read_file(Sftp, FileName),
+ alt_file_handler_check(alt_open),
+ alt_file_handler_check(alt_read_file_info),
+ alt_file_handler_check(alt_position),
+ alt_file_handler_check(alt_read),
+ alt_file_handler_check(alt_position),
+ alt_file_handler_check(alt_read),
+ alt_file_handler_check(alt_close),
+
+
+ NewFileName = filename:join(PrivDir, "test.txt"),
+ ok = ssh_sftp:write_file(Sftp, NewFileName, Bin),
+ alt_file_handler_check(alt_open),
+ alt_file_handler_check(alt_read_file_info),
+ alt_file_handler_check(alt_position),
+ alt_file_handler_check(alt_write),
+ alt_file_handler_check(alt_close),
+
+ ReFileName = filename:join(PrivDir, "test1.txt"),
+ ok = ssh_sftp:rename(Sftp, NewFileName, ReFileName),
+ alt_file_handler_check(alt_rename),
+
+ ok = ssh_sftp:delete(Sftp, ReFileName),
+ alt_file_handler_check(alt_delete),
+
+ NewDir = filename:join(PrivDir, "testdir"),
+ ok = ssh_sftp:make_dir(Sftp, NewDir),
+ alt_file_handler_check(alt_make_dir),
+
+ ok = ssh_sftp:del_dir(Sftp, NewDir),
+ alt_file_handler_check(alt_read_link_info),
+ alt_file_handler_check(alt_write_file_info),
+ alt_file_handler_check(alt_del_dir),
+ ok.
+
+root_dir(doc) ->
+ [""];
+root_dir(suite) ->
+ [];
+root_dir(Config) when is_list(Config) ->
+ {Sftp, _} = ?config(sftp, Config),
+ FileName = "test.txt",
+ Bin = <<"Test file for root dir option">>,
+ ok = ssh_sftp:write_file(Sftp, FileName, Bin),
+ {ok, Bin} = ssh_sftp:read_file(Sftp, FileName),
+ {ok, Listing} =
+ ssh_sftp:list_dir(Sftp, "."),
+ test_server:format("Listing: ~p~n", [Listing]),
+ ok.
+
+list_dir_limited(doc) ->
+ [""];
+list_dir_limited(suite) ->
+ [];
+list_dir_limited(Config) when is_list(Config) ->
+ {Sftp, _} = ?config(sftp, Config),
+ {ok, Listing} =
+ ssh_sftp:list_dir(Sftp, "."),
+ test_server:format("Listing: ~p~n", [Listing]),
+ ok.
+
+alt_file_handler_check(Msg) ->
+ receive
+ Msg ->
+ ok;
+ Other ->
+ test_server:fail({Msg, Other})
+ after 10000 ->
+ test_server:fail("Not alt file handler")
+ end.
diff --git a/lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/ssh_sftpd_file_alt.erl b/lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/ssh_sftpd_file_alt.erl
new file mode 100644
index 0000000000..9e119c4929
--- /dev/null
+++ b/lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/ssh_sftpd_file_alt.erl
@@ -0,0 +1,100 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2007-2010. 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%
+%%
+
+%%
+
+%%% Description: Dummy Callback module for ssh_sftpd to test
+%%% the possibility to switch file handling implementation.
+
+-module(ssh_sftpd_file_alt).
+
+-behaviour(ssh_sftpd_file_api).
+
+%% API
+-export([close/2, delete/2, del_dir/2, get_cwd/1, is_dir/2, list_dir/2,
+ make_dir/2, make_symlink/3, open/3, position/3, read/3,
+ read_file_info/2, read_link/2, read_link_info/2, rename/3,
+ write/3, write_file_info/3]).
+
+close(IoDevice, State) ->
+ sftpd_file_alt_tester ! alt_close,
+ {file:close(IoDevice), State}.
+
+delete(Path, State) ->
+ sftpd_file_alt_tester ! alt_delete,
+ {file:delete(Path), State}.
+
+del_dir(Path, State) ->
+ sftpd_file_alt_tester ! alt_del_dir,
+ {file:del_dir(Path), State}.
+
+get_cwd(State) ->
+ {file:get_cwd(), State}.
+
+is_dir(AbsPath, State) ->
+ sftpd_file_alt_tester ! alt_is_dir,
+ {filelib:is_dir(AbsPath), State}.
+
+list_dir(AbsPath, State) ->
+ sftpd_file_alt_tester ! alt_list_dir,
+ {file:list_dir(AbsPath), State}.
+
+make_dir(Dir, State) ->
+ sftpd_file_alt_tester ! alt_make_dir,
+ {file:make_dir(Dir), State}.
+
+make_symlink(Path2, Path, State) ->
+ sftpd_file_alt_tester ! alt_make_symlink,
+ {file:make_symlink(Path2, Path), State}.
+
+open(Path, Flags, State) ->
+ sftpd_file_alt_tester ! alt_open,
+ {file:open(Path, Flags), State}.
+
+position(IoDevice, Offs, State) ->
+ sftpd_file_alt_tester ! alt_position,
+ {file:position(IoDevice, Offs), State}.
+
+read(IoDevice, Len, State) ->
+ sftpd_file_alt_tester ! alt_read,
+ {file:read(IoDevice, Len), State}.
+
+read_link(Path, State) ->
+ sftpd_file_alt_tester ! alt_read_link,
+ {file:read_link(Path), State}.
+
+read_link_info(Path, State) ->
+ sftpd_file_alt_tester ! alt_read_link_info,
+ {file:read_link_info(Path), State}.
+
+read_file_info(Path, State) ->
+ sftpd_file_alt_tester ! alt_read_file_info,
+ {file:read_file_info(Path), State}.
+
+rename(Path, Path2, State) ->
+ sftpd_file_alt_tester ! alt_rename,
+ {file:rename(Path, Path2), State}.
+
+write(IoDevice, Data, State) ->
+ sftpd_file_alt_tester ! alt_write,
+ {file:write(IoDevice, Data), State}.
+
+write_file_info(Path,Info, State) ->
+ sftpd_file_alt_tester ! alt_write_file_info,
+ {file:write_file_info(Path, Info), State}.
diff --git a/lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/test.txt b/lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/test.txt
new file mode 100644
index 0000000000..681bff80a0
--- /dev/null
+++ b/lib/ssh/test/ssh_sftpd_erlclient_SUITE_data/test.txt
@@ -0,0 +1 @@
+Sftp test file. \ No newline at end of file
diff --git a/lib/ssh/test/ssh_test_lib.erl b/lib/ssh/test/ssh_test_lib.erl
new file mode 100644
index 0000000000..425fae22c1
--- /dev/null
+++ b/lib/ssh/test/ssh_test_lib.erl
@@ -0,0 +1,684 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2004-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(ssh_test_lib).
+
+%% Note: This directive should only be used in test suites.
+-compile(export_all).
+
+-include_lib("public_key/include/public_key.hrl").
+-include("test_server.hrl").
+-include("test_server_line.hrl").
+
+-define(TIMEOUT, 50000).
+
+connect(Options) ->
+ connect(hostname(), inet_port(), Options).
+
+connect(Port, Options) when is_integer(Port) ->
+ connect(hostname(), Port, Options);
+connect(any, Options) ->
+ connect(hostname(), inet_port(), Options);
+connect(Host, Options) ->
+ connect(Host, inet_port(), Options).
+
+connect(any, Port, Options) ->
+ connect(hostname(), Port, Options);
+connect(Host, Port, Options) ->
+ case ssh:connect(Host, Port, Options) of
+ {ok, ConnectionRef} ->
+ ConnectionRef;
+ Error ->
+ Error
+ end.
+
+daemon(Options) ->
+ daemon(any, inet_port(), Options).
+
+daemon(Port, Options) when is_integer(Port) ->
+ daemon(any, Port, Options);
+daemon(Host, Options) ->
+ daemon(Host, inet_port(), Options).
+
+daemon(Host, Port, Options) ->
+ case ssh:daemon(Host, Port, Options) of
+ {ok, Pid} when Host == any ->
+ {Pid, hostname(), Port};
+ {ok, Pid} ->
+ {Pid, Host, Port};
+ Error ->
+ Error
+ end.
+
+
+
+
+start_shell(Port, IOServer) ->
+ spawn_link(?MODULE, init_shell, [Port, IOServer]).
+
+init_shell(Port, IOServer) ->
+ Host = hostname(),
+ UserDir = get_user_dir(),
+ Options = [{user_interaction, false}, {silently_accept_hosts,
+ true}] ++ UserDir,
+ group_leader(IOServer, self()),
+ loop_shell(Host, Port, Options).
+
+loop_shell(Host, Port, Options) ->
+ ssh:shell(Host, Port, Options).
+
+start_io_server() ->
+ spawn_link(?MODULE, init_io_server, [self()]).
+
+init_io_server(TestCase) ->
+ process_flag(trap_exit, true),
+ loop_io_server(TestCase, []).
+
+loop_io_server(TestCase, Buff0) ->
+ receive
+ {input, TestCase, Line} ->
+ %io:format("~p~n",[{input, TestCase, Line}]),
+ loop_io_server(TestCase, Buff0 ++ [Line]);
+ {io_request, From, ReplyAs, Request} ->
+ %io:format("request -> ~p~n",[Request]),
+ {ok, Reply, Buff} = io_request(Request, TestCase, From,
+ ReplyAs, Buff0),
+ %io:format("reply -> ~p~n",[Reply]),
+ io_reply(From, ReplyAs, Reply),
+ loop_io_server(TestCase, Buff);
+ {'EXIT',_, _} ->
+ erlang:display('EXIT'),
+ ok
+ end.
+
+io_request({put_chars, Chars}, TestCase, _, _, Buff) ->
+ reply(TestCase, Chars),
+ {ok, ok, Buff};
+io_request({put_chars, Enc, Chars}, TestCase, _, _, Buff) ->
+ reply(TestCase, unicode:characters_to_binary(Chars,Enc,latin1)),
+ {ok, ok, Buff};
+
+io_request({get_line, _} = Request, _, From, ReplyAs, [] = Buff) ->
+ erlang:send_after(1000, self(), {io_request, From, ReplyAs, Request}),
+ {ok, [], Buff};
+io_request({get_line, _Enc, _Prompt} = Request, _, From, ReplyAs, [] = Buff) ->
+ erlang:send_after(1000, self(), {io_request, From, ReplyAs, Request}),
+ {ok, [], Buff};
+
+io_request({get_line, _Enc,_}, _, _, _, [Line | Buff]) ->
+ {ok, Line, Buff}.
+
+io_reply(_, _, []) ->
+ ok;
+io_reply(From, ReplyAs, Reply) ->
+ From ! {io_reply, ReplyAs, Reply}.
+
+reply(_, []) ->
+ ok;
+reply(TestCase, Result) ->
+ TestCase ! Result.
+
+receive_exec_result(Msg) ->
+ test_server:format("Expect data! ~p", [Msg]),
+ receive
+ Msg ->
+ test_server:format("1: Collected data ~p", [Msg]),
+ expected;
+ Other ->
+ {unexpected_msg, Other}
+ end.
+receive_exec_end(ConnectionRef, ChannelId) ->
+ Eof = {ssh_cm, ConnectionRef, {eof, ChannelId}},
+ ExitStatus = {ssh_cm, ConnectionRef, {exit_status, ChannelId, 0}},
+ Closed = {ssh_cm, ConnectionRef,{closed, ChannelId}},
+ case receive_exec_result(ExitStatus) of
+ {unexpected_msg, Eof} -> %% Open ssh seems to not allways send these messages
+ %% in the same order!
+ test_server:format("2: Collected data ~p", [Eof]),
+ case receive_exec_result(ExitStatus) of
+ expected ->
+ expected = receive_exec_result(Closed);
+ {unexpected_msg, Closed} ->
+ test_server:format("3: Collected data ~p", [Closed])
+ end;
+ expected ->
+ test_server:format("4: Collected data ~p", [ExitStatus]),
+ expected = receive_exec_result(Eof),
+ expected = receive_exec_result(Closed);
+ Other ->
+ test_server:fail({unexpected_msg, Other})
+ end.
+
+receive_exec_result(Data, ConnectionRef, ChannelId) ->
+ Eof = {ssh_cm, ConnectionRef, {eof, ChannelId}},
+ Closed = {ssh_cm, ConnectionRef,{closed, ChannelId}},
+ expected = receive_exec_result(Data),
+ expected = receive_exec_result(Eof),
+ expected = receive_exec_result(Closed).
+
+
+inet_port()->
+ {ok, Socket} = gen_tcp:listen(0, [{reuseaddr, true}]),
+ {ok, Port} = inet:port(Socket),
+ gen_tcp:close(Socket),
+ Port.
+
+
+%% copy private keys to given dir from ~/.ssh
+get_id_keys(DstDir) ->
+ SrcDir = filename:join(os:getenv("HOME"), ".ssh"),
+ RsaOk = copyfile(SrcDir, DstDir, "id_rsa"),
+ DsaOk = copyfile(SrcDir, DstDir, "id_dsa"),
+ case {RsaOk, DsaOk} of
+ {{ok, _}, {ok, _}} -> {ok, both};
+ {{ok, _}, _} -> {ok, rsa};
+ {_, {ok, _}} -> {ok, dsa};
+ {Error, _} -> Error
+ end.
+
+remove_id_keys(Dir) ->
+ file:delete(filename:join(Dir, "id_rsa")),
+ file:delete(filename:join(Dir, "id_dsa")).
+
+copyfile(SrcDir, DstDir, Fn) ->
+ file:copy(filename:join(SrcDir, Fn),
+ filename:join(DstDir, Fn)).
+
+failfun(_User, {authmethod,none}) ->
+ ok;
+failfun(User, Reason) ->
+ error_logger:format("~p failed XXX to login: ~p~n", [User, Reason]).
+
+hostname() ->
+ {ok,Host} = inet:gethostname(),
+ Host.
+
+known_hosts(BR) ->
+ KnownHosts = ssh_file:file_name(user, "known_hosts", []),
+ B = KnownHosts ++ "xxx",
+ case BR of
+ backup ->
+ file:rename(KnownHosts, B);
+ restore ->
+ file:delete(KnownHosts),
+ file:rename(B, KnownHosts)
+ end.
+
+
+get_user_dir() ->
+ case os:type() of
+ {win32, _} ->
+ [{user_dir, filename:join([os:getenv("HOME"), ".ssh"])}];
+ _ ->
+ []
+ end.
+
+
+make_dsa_cert_files(Config) ->
+ make_dsa_cert_files("", Config).
+
+make_dsa_cert_files(RoleStr, Config) ->
+
+ CaInfo = {CaCert, _} = make_cert([{key, dsa}]),
+ {Cert, CertKey} = make_cert([{key, dsa}, {issuer, CaInfo}]),
+ CaCertFile = filename:join([?config(data_dir, Config),
+ RoleStr, "dsa_cacerts.pem"]),
+ CertFile = filename:join([?config(data_dir, Config),
+ RoleStr, "dsa_cert.pem"]),
+ KeyFile = filename:join([?config(data_dir, Config),
+ RoleStr, "dsa_key.pem"]),
+
+ der_to_pem(CaCertFile, [{'Certificate', CaCert, not_encrypted}]),
+ der_to_pem(CertFile, [{'Certificate', Cert, not_encrypted}]),
+ der_to_pem(KeyFile, [CertKey]),
+ {CaCertFile, CertFile, KeyFile}.
+
+make_dsa_files(Config) ->
+ make_dsa_files(Config, rfc4716_public_key).
+make_dsa_files(Config, Type) ->
+ {DSA, EncodedKey} = ssh_test_lib:gen_dsa(128, 20),
+ PKey = DSA#'DSAPrivateKey'.y,
+ P = DSA#'DSAPrivateKey'.p,
+ Q = DSA#'DSAPrivateKey'.q,
+ G = DSA#'DSAPrivateKey'.g,
+ Dss = #'Dss-Parms'{p=P, q=Q, g=G},
+ {ok, Hostname} = inet:gethostname(),
+ {ok, {A, B, C, D}} = inet:getaddr(Hostname, inet),
+ IP = lists:concat([A, ".", B, ".", C, ".", D]),
+ Attributes = [], % Could be [{comment,"user@" ++ Hostname}],
+ HostNames = [{hostnames,[IP, IP]}],
+ PublicKey = [{{PKey, Dss}, Attributes}],
+ KnownHosts = [{{PKey, Dss}, HostNames}],
+
+ KnownHostsEnc = public_key:ssh_encode(KnownHosts, known_hosts),
+ KnownHosts = public_key:ssh_decode(KnownHostsEnc, known_hosts),
+
+ PublicKeyEnc = public_key:ssh_encode(PublicKey, Type),
+% PublicKey = public_key:ssh_decode(PublicKeyEnc, Type),
+
+ SystemTmpDir = ?config(data_dir, Config),
+ filelib:ensure_dir(SystemTmpDir),
+ file:make_dir(SystemTmpDir),
+
+ DSAFile = filename:join(SystemTmpDir, "ssh_host_dsa_key.pub"),
+ file:delete(DSAFile),
+
+ DSAPrivateFile = filename:join(SystemTmpDir, "ssh_host_dsa_key"),
+ file:delete(DSAPrivateFile),
+
+ KHFile = filename:join(SystemTmpDir, "known_hosts"),
+ file:delete(KHFile),
+
+ PemBin = public_key:pem_encode([EncodedKey]),
+
+ file:write_file(DSAFile, PublicKeyEnc),
+ file:write_file(KHFile, KnownHostsEnc),
+ file:write_file(DSAPrivateFile, PemBin),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Create and return a der encoded certificate
+%% Option Default
+%% -------------------------------------------------------
+%% digest sha1
+%% validity {date(), date() + week()}
+%% version 3
+%% subject [] list of the following content
+%% {name, Name}
+%% {email, Email}
+%% {city, City}
+%% {state, State}
+%% {org, Org}
+%% {org_unit, OrgUnit}
+%% {country, Country}
+%% {serial, Serial}
+%% {title, Title}
+%% {dnQualifer, DnQ}
+%% issuer = {Issuer, IssuerKey} true (i.e. a ca cert is created)
+%% (obs IssuerKey migth be {Key, Password}
+%% key = KeyFile|KeyBin|rsa|dsa Subject PublicKey rsa or dsa generates key
+%%
+%%
+%% (OBS: The generated keys are for testing only)
+%% make_cert([{::atom(), ::term()}]) -> {Cert::binary(), Key::binary()}
+%%--------------------------------------------------------------------
+make_cert(Opts) ->
+ SubjectPrivateKey = get_key(Opts),
+ {TBSCert, IssuerKey} = make_tbs(SubjectPrivateKey, Opts),
+ Cert = public_key:pkix_sign(TBSCert, IssuerKey),
+ true = verify_signature(Cert, IssuerKey, undef), %% verify that the keys where ok
+ {Cert, encode_key(SubjectPrivateKey)}.
+
+%%--------------------------------------------------------------------
+%% Writes cert files in Dir with FileName and FileName ++ Suffix
+%% write_cert(::string(), ::string(), {Cert,Key}) -> ok
+%%--------------------------------------------------------------------
+write_cert(Dir, FileName, Suffix, {Cert, Key = {_,_,not_encrypted}}) when is_binary(Cert) ->
+ ok = der_to_pem(filename:join(Dir, FileName),
+ [{'Certificate', Cert, not_encrypted}]),
+ ok = der_to_pem(filename:join(Dir, FileName ++ Suffix), [Key]).
+
+%%--------------------------------------------------------------------
+%% Creates a rsa key (OBS: for testing only)
+%% the size are in bytes
+%% gen_rsa(::integer()) -> {::atom(), ::binary(), ::opaque()}
+%%--------------------------------------------------------------------
+gen_rsa(Size) when is_integer(Size) ->
+ Key = gen_rsa2(Size),
+ {Key, encode_key(Key)}.
+
+%%--------------------------------------------------------------------
+%% Creates a dsa key (OBS: for testing only)
+%% the sizes are in bytes
+%% gen_dsa(::integer()) -> {::atom(), ::binary(), ::opaque()}
+%%--------------------------------------------------------------------
+gen_dsa(LSize,NSize) when is_integer(LSize), is_integer(NSize) ->
+ Key = gen_dsa2(LSize, NSize),
+ {Key, encode_key(Key)}.
+
+%%--------------------------------------------------------------------
+%% Verifies cert signatures
+%% verify_signature(::binary(), ::tuple()) -> ::boolean()
+%%--------------------------------------------------------------------
+verify_signature(DerEncodedCert, DerKey, _KeyParams) ->
+ Key = decode_key(DerKey),
+ case Key of
+ #'RSAPrivateKey'{modulus=Mod, publicExponent=Exp} ->
+ public_key:pkix_verify(DerEncodedCert,
+ #'RSAPublicKey'{modulus=Mod, publicExponent=Exp});
+ #'DSAPrivateKey'{p=P, q=Q, g=G, y=Y} ->
+ public_key:pkix_verify(DerEncodedCert, {Y, #'Dss-Parms'{p=P, q=Q, g=G}})
+ end.
+
+%%%%%%%%%%%%%%%%%%%%%%%%% Implementation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+get_key(Opts) ->
+ case proplists:get_value(key, Opts) of
+ undefined -> make_key(rsa, Opts);
+ rsa -> make_key(rsa, Opts);
+ dsa -> make_key(dsa, Opts);
+ Key ->
+ Password = proplists:get_value(password, Opts, no_passwd),
+ decode_key(Key, Password)
+ end.
+
+decode_key({Key, Pw}) ->
+ decode_key(Key, Pw);
+decode_key(Key) ->
+ decode_key(Key, no_passwd).
+
+
+decode_key(#'RSAPublicKey'{} = Key,_) ->
+ Key;
+decode_key(#'RSAPrivateKey'{} = Key,_) ->
+ Key;
+decode_key(#'DSAPrivateKey'{} = Key,_) ->
+ Key;
+decode_key(PemEntry = {_,_,_}, Pw) ->
+ public_key:pem_entry_decode(PemEntry, Pw);
+decode_key(PemBin, Pw) ->
+ [KeyInfo] = public_key:pem_decode(PemBin),
+ decode_key(KeyInfo, Pw).
+
+encode_key(Key = #'RSAPrivateKey'{}) ->
+ {ok, Der} = 'OTP-PUB-KEY':encode('RSAPrivateKey', Key),
+ {'RSAPrivateKey', list_to_binary(Der), not_encrypted};
+encode_key(Key = #'DSAPrivateKey'{}) ->
+ {ok, Der} = 'OTP-PUB-KEY':encode('DSAPrivateKey', Key),
+ {'DSAPrivateKey', list_to_binary(Der), not_encrypted}.
+
+make_tbs(SubjectKey, Opts) ->
+ Version = list_to_atom("v"++integer_to_list(proplists:get_value(version, Opts, 3))),
+
+ IssuerProp = proplists:get_value(issuer, Opts, true),
+ {Issuer, IssuerKey} = issuer(IssuerProp, Opts, SubjectKey),
+
+ {Algo, Parameters} = sign_algorithm(IssuerKey, Opts),
+
+ SignAlgo = #'SignatureAlgorithm'{algorithm = Algo,
+ parameters = Parameters},
+ Subject = case IssuerProp of
+ true -> %% Is a Root Ca
+ Issuer;
+ _ ->
+ subject(proplists:get_value(subject, Opts),false)
+ end,
+
+ {#'OTPTBSCertificate'{serialNumber = trunc(random:uniform()*100000000)*10000 + 1,
+ signature = SignAlgo,
+ issuer = Issuer,
+ validity = validity(Opts),
+ subject = Subject,
+ subjectPublicKeyInfo = publickey(SubjectKey),
+ version = Version,
+ extensions = extensions(Opts)
+ }, IssuerKey}.
+
+issuer(true, Opts, SubjectKey) ->
+ %% Self signed
+ {subject(proplists:get_value(subject, Opts), true), SubjectKey};
+issuer({Issuer, IssuerKey}, _Opts, _SubjectKey) when is_binary(Issuer) ->
+ {issuer_der(Issuer), decode_key(IssuerKey)};
+issuer({File, IssuerKey}, _Opts, _SubjectKey) when is_list(File) ->
+ {ok, [{cert, Cert, _}|_]} = pem_to_der(File),
+ {issuer_der(Cert), decode_key(IssuerKey)}.
+
+issuer_der(Issuer) ->
+ Decoded = public_key:pkix_decode_cert(Issuer, otp),
+ #'OTPCertificate'{tbsCertificate=Tbs} = Decoded,
+ #'OTPTBSCertificate'{subject=Subject} = Tbs,
+ Subject.
+
+subject(undefined, IsRootCA) ->
+ User = if IsRootCA -> "RootCA"; true -> os:getenv("USER") end,
+ Opts = [{email, User ++ "@erlang.org"},
+ {name, User},
+ {city, "Stockholm"},
+ {country, "SE"},
+ {org, "erlang"},
+ {org_unit, "testing dep"}],
+ subject(Opts);
+subject(Opts, _) ->
+ subject(Opts).
+
+subject(SubjectOpts) when is_list(SubjectOpts) ->
+ Encode = fun(Opt) ->
+ {Type,Value} = subject_enc(Opt),
+ [#'AttributeTypeAndValue'{type=Type, value=Value}]
+ end,
+ {rdnSequence, [Encode(Opt) || Opt <- SubjectOpts]}.
+
+%% Fill in the blanks
+subject_enc({name, Name}) -> {?'id-at-commonName', {printableString, Name}};
+subject_enc({email, Email}) -> {?'id-emailAddress', Email};
+subject_enc({city, City}) -> {?'id-at-localityName', {printableString, City}};
+subject_enc({state, State}) -> {?'id-at-stateOrProvinceName', {printableString, State}};
+subject_enc({org, Org}) -> {?'id-at-organizationName', {printableString, Org}};
+subject_enc({org_unit, OrgUnit}) -> {?'id-at-organizationalUnitName', {printableString, OrgUnit}};
+subject_enc({country, Country}) -> {?'id-at-countryName', Country};
+subject_enc({serial, Serial}) -> {?'id-at-serialNumber', Serial};
+subject_enc({title, Title}) -> {?'id-at-title', {printableString, Title}};
+subject_enc({dnQualifer, DnQ}) -> {?'id-at-dnQualifier', DnQ};
+subject_enc(Other) -> Other.
+
+
+extensions(Opts) ->
+ case proplists:get_value(extensions, Opts, []) of
+ false ->
+ asn1_NOVALUE;
+ Exts ->
+ lists:flatten([extension(Ext) || Ext <- default_extensions(Exts)])
+ end.
+
+default_extensions(Exts) ->
+ Def = [{key_usage,undefined},
+ {subject_altname, undefined},
+ {issuer_altname, undefined},
+ {basic_constraints, default},
+ {name_constraints, undefined},
+ {policy_constraints, undefined},
+ {ext_key_usage, undefined},
+ {inhibit_any, undefined},
+ {auth_key_id, undefined},
+ {subject_key_id, undefined},
+ {policy_mapping, undefined}],
+ Filter = fun({Key, _}, D) -> lists:keydelete(Key, 1, D) end,
+ Exts ++ lists:foldl(Filter, Def, Exts).
+
+extension({_, undefined}) -> [];
+extension({basic_constraints, Data}) ->
+ case Data of
+ default ->
+ #'Extension'{extnID = ?'id-ce-basicConstraints',
+ extnValue = #'BasicConstraints'{cA=true},
+ critical=true};
+ false ->
+ [];
+ Len when is_integer(Len) ->
+ #'Extension'{extnID = ?'id-ce-basicConstraints',
+ extnValue = #'BasicConstraints'{cA=true, pathLenConstraint=Len},
+ critical=true};
+ _ ->
+ #'Extension'{extnID = ?'id-ce-basicConstraints',
+ extnValue = Data}
+ end;
+extension({Id, Data, Critical}) ->
+ #'Extension'{extnID = Id, extnValue = Data, critical = Critical}.
+
+
+publickey(#'RSAPrivateKey'{modulus=N, publicExponent=E}) ->
+ Public = #'RSAPublicKey'{modulus=N, publicExponent=E},
+ Algo = #'PublicKeyAlgorithm'{algorithm= ?rsaEncryption, parameters='NULL'},
+ #'OTPSubjectPublicKeyInfo'{algorithm = Algo,
+ subjectPublicKey = Public};
+publickey(#'DSAPrivateKey'{p=P, q=Q, g=G, y=Y}) ->
+ Algo = #'PublicKeyAlgorithm'{algorithm= ?'id-dsa',
+ parameters={params, #'Dss-Parms'{p=P, q=Q, g=G}}},
+ #'OTPSubjectPublicKeyInfo'{algorithm = Algo, subjectPublicKey = Y}.
+
+validity(Opts) ->
+ DefFrom0 = calendar:gregorian_days_to_date(calendar:date_to_gregorian_days(date())-1),
+ DefTo0 = calendar:gregorian_days_to_date(calendar:date_to_gregorian_days(date())+7),
+ {DefFrom, DefTo} = proplists:get_value(validity, Opts, {DefFrom0, DefTo0}),
+ Format = fun({Y,M,D}) -> lists:flatten(io_lib:format("~w~2..0w~2..0w000000Z",[Y,M,D])) end,
+ #'Validity'{notBefore={generalTime, Format(DefFrom)},
+ notAfter ={generalTime, Format(DefTo)}}.
+
+sign_algorithm(#'RSAPrivateKey'{}, Opts) ->
+ Type = case proplists:get_value(digest, Opts, sha1) of
+ sha1 -> ?'sha1WithRSAEncryption';
+ sha512 -> ?'sha512WithRSAEncryption';
+ sha384 -> ?'sha384WithRSAEncryption';
+ sha256 -> ?'sha256WithRSAEncryption';
+ md5 -> ?'md5WithRSAEncryption';
+ md2 -> ?'md2WithRSAEncryption'
+ end,
+ {Type, 'NULL'};
+sign_algorithm(#'DSAPrivateKey'{p=P, q=Q, g=G}, _Opts) ->
+ {?'id-dsa-with-sha1', {params,#'Dss-Parms'{p=P, q=Q, g=G}}}.
+
+make_key(rsa, _Opts) ->
+ %% (OBS: for testing only)
+ gen_rsa2(64);
+make_key(dsa, _Opts) ->
+ gen_dsa2(128, 20). %% Bytes i.e. {1024, 160}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% RSA key generation (OBS: for testing only)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+-define(SMALL_PRIMES, [65537,97,89,83,79,73,71,67,61,59,53,
+ 47,43,41,37,31,29,23,19,17,13,11,7,5,3]).
+
+gen_rsa2(Size) ->
+ P = prime(Size),
+ Q = prime(Size),
+ N = P*Q,
+ Tot = (P - 1) * (Q - 1),
+ [E|_] = lists:dropwhile(fun(Candidate) -> (Tot rem Candidate) == 0 end, ?SMALL_PRIMES),
+ {D1,D2} = extended_gcd(E, Tot),
+ D = erlang:max(D1,D2),
+ case D < E of
+ true ->
+ gen_rsa2(Size);
+ false ->
+ {Co1,Co2} = extended_gcd(Q, P),
+ Co = erlang:max(Co1,Co2),
+ #'RSAPrivateKey'{version = 'two-prime',
+ modulus = N,
+ publicExponent = E,
+ privateExponent = D,
+ prime1 = P,
+ prime2 = Q,
+ exponent1 = D rem (P-1),
+ exponent2 = D rem (Q-1),
+ coefficient = Co
+ }
+ end.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% DSA key generation (OBS: for testing only)
+%% See http://en.wikipedia.org/wiki/Digital_Signature_Algorithm
+%% and the fips_186-3.pdf
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+gen_dsa2(LSize, NSize) ->
+ Q = prime(NSize), %% Choose N-bit prime Q
+ X0 = prime(LSize),
+ P0 = prime((LSize div 2) +1),
+
+ %% Choose L-bit prime modulus P such that p-1 is a multiple of q.
+ case dsa_search(X0 div (2*Q*P0), P0, Q, 1000) of
+ error ->
+ gen_dsa2(LSize, NSize);
+ P ->
+ G = crypto:mod_exp(2, (P-1) div Q, P), % Choose G a number whose multiplicative order modulo p is q.
+ %% such that This may be done by setting g = h^(p-1)/q mod p, commonly h=2 is used.
+
+ X = prime(20), %% Choose x by some random method, where 0 < x < q.
+ Y = crypto:mod_exp(G, X, P), %% Calculate y = g^x mod p.
+
+ #'DSAPrivateKey'{version=0, p=P, q=Q, g=G, y=Y, x=X}
+ end.
+
+%% See fips_186-3.pdf
+dsa_search(T, P0, Q, Iter) when Iter > 0 ->
+ P = 2*T*Q*P0 + 1,
+ case is_prime(crypto:mpint(P), 50) of
+ true -> P;
+ false -> dsa_search(T+1, P0, Q, Iter-1)
+ end;
+dsa_search(_,_,_,_) ->
+ error.
+
+
+%%%%%%% Crypto Math %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+prime(ByteSize) ->
+ Rand = odd_rand(ByteSize),
+ crypto:erlint(prime_odd(Rand, 0)).
+
+prime_odd(Rand, N) ->
+ case is_prime(Rand, 50) of
+ true ->
+ Rand;
+ false ->
+ NotPrime = crypto:erlint(Rand),
+ prime_odd(crypto:mpint(NotPrime+2), N+1)
+ end.
+
+%% see http://en.wikipedia.org/wiki/Fermat_primality_test
+is_prime(_, 0) -> true;
+is_prime(Candidate, Test) ->
+ CoPrime = odd_rand(<<0,0,0,4, 10000:32>>, Candidate),
+ case crypto:mod_exp(CoPrime, Candidate, Candidate) of
+ CoPrime -> is_prime(Candidate, Test-1);
+ _ -> false
+ end.
+
+odd_rand(Size) ->
+ Min = 1 bsl (Size*8-1),
+ Max = (1 bsl (Size*8))-1,
+ odd_rand(crypto:mpint(Min), crypto:mpint(Max)).
+
+odd_rand(Min,Max) ->
+ Rand = <<Sz:32, _/binary>> = crypto:rand_uniform(Min,Max),
+ BitSkip = (Sz+4)*8-1,
+ case Rand of
+ Odd = <<_:BitSkip, 1:1>> -> Odd;
+ Even = <<_:BitSkip, 0:1>> ->
+ crypto:mpint(crypto:erlint(Even)+1)
+ end.
+
+extended_gcd(A, B) ->
+ case A rem B of
+ 0 ->
+ {0, 1};
+ N ->
+ {X, Y} = extended_gcd(B, N),
+ {Y, X-Y*(A div B)}
+ end.
+
+pem_to_der(File) ->
+ {ok, PemBin} = file:read_file(File),
+ public_key:pem_decode(PemBin).
+
+der_to_pem(File, Entries) ->
+ PemBin = public_key:pem_encode(Entries),
+ file:write_file(File, PemBin).
diff --git a/lib/ssh/test/ssh_to_openssh_SUITE.erl b/lib/ssh/test/ssh_to_openssh_SUITE.erl
new file mode 100644
index 0000000000..f959d50484
--- /dev/null
+++ b/lib/ssh/test/ssh_to_openssh_SUITE.erl
@@ -0,0 +1,458 @@
+%%
+%% %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%
+%%
+
+%%
+-module(ssh_to_openssh_SUITE).
+
+-include_lib("common_test/include/ct.hrl").
+-include("test_server_line.hrl").
+
+%% Note: This directive should only be used in test suites.
+-compile(export_all).
+
+-define(TIMEOUT, 50000).
+-define(SSH_DEFAULT_PORT, 22).
+
+%% Test server callback functions
+%%--------------------------------------------------------------------
+%% Function: init_per_suite(Config) -> Config
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Initialization before the whole suite
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%%--------------------------------------------------------------------
+init_per_suite(Config) ->
+ case catch crypto:start() of
+ ok ->
+ ssh_test_lib:make_dsa_files(Config),
+ Config;
+ _Else ->
+ {skip,"Could not start crypto!"}
+ end.
+
+%%--------------------------------------------------------------------
+%% Function: end_per_suite(Config) -> _
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after the whole suite
+%%--------------------------------------------------------------------
+end_per_suite(_Config) ->
+ crypto:stop(),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: init_per_testcase(TestCase, Config) -> Config
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%%
+%% Description: Initialization before each test case
+%%
+%% Note: This function is free to add any key/value pairs to the Config
+%% variable, but should NOT alter/remove any existing entries.
+%% Description: Initialization before each test case
+%%--------------------------------------------------------------------
+init_per_testcase(_TestCase, Config) ->
+ ssh:start(),
+ Config.
+
+%%--------------------------------------------------------------------
+%% Function: end_per_testcase(TestCase, Config) -> _
+%% Case - atom()
+%% Name of the test case that is about to be run.
+%% Config - [tuple()]
+%% A list of key/value pairs, holding the test case configuration.
+%% Description: Cleanup after each test case
+%%--------------------------------------------------------------------
+end_per_testcase(_TestCase, _Config) ->
+ ssh:stop(),
+ ok.
+
+%%--------------------------------------------------------------------
+%% Function: all(Clause) -> TestCases
+%% Clause - atom() - suite | doc
+%% TestCases - [Case]
+%% Case - atom()
+%% Name of a test case.
+%% Description: Returns a list of all test cases in this test suite
+%%--------------------------------------------------------------------
+all() ->
+ case os:find_executable("ssh") of
+ false ->
+ {skip, "openSSH not installed on host"};
+ _ ->
+ [erlang_shell_client_openssh_server,
+ erlang_client_openssh_server_exec,
+ erlang_client_openssh_server_exec_compressed,
+ erlang_server_openssh_client_exec,
+ erlang_server_openssh_client_exec_compressed,
+ erlang_client_openssh_server_setenv,
+ erlang_client_openssh_server_publickey_rsa,
+ erlang_client_openssh_server_publickey_dsa,
+ erlang_server_openssh_client_pulic_key_dsa,
+ erlang_client_openssh_server_password]
+ end.
+
+groups() ->
+ [].
+
+init_per_group(_GroupName, Config) ->
+ Config.
+
+end_per_group(_GroupName, Config) ->
+ Config.
+
+%% TEST cases starts here.
+%%--------------------------------------------------------------------
+erlang_shell_client_openssh_server(doc) ->
+ ["Test that ssh:shell/2 works"];
+
+erlang_shell_client_openssh_server(suite) ->
+ [];
+
+erlang_shell_client_openssh_server(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ IO = ssh_test_lib:start_io_server(),
+ Shell = ssh_test_lib:start_shell(?SSH_DEFAULT_PORT, IO),
+ IO ! {input, self(), "echo Hej\n"},
+ receive_hej(),
+ IO ! {input, self(), "exit\n"},
+ receive
+ <<"logout">> ->
+ receive
+ <<"Connection closed">> ->
+ ok
+ end;
+ Other0 ->
+ test_server:fail({unexpected_msg, Other0})
+ end,
+ receive
+ {'EXIT', Shell, normal} ->
+ ok;
+ Other1 ->
+ test_server:fail({unexpected_msg, Other1})
+ end.
+
+%--------------------------------------------------------------------
+erlang_client_openssh_server_exec(doc) ->
+ ["Test api function ssh_connection:exec"];
+
+erlang_client_openssh_server_exec(suite) ->
+ [];
+
+erlang_client_openssh_server_exec(Config) when is_list(Config) ->
+ ConnectionRef = ssh_test_lib:connect(?SSH_DEFAULT_PORT, [{silently_accept_hosts, true},
+ {user_interaction, false}]),
+ {ok, ChannelId0} = ssh_connection:session_channel(ConnectionRef, infinity),
+ success = ssh_connection:exec(ConnectionRef, ChannelId0,
+ "echo testing", infinity),
+ Data0 = {ssh_cm, ConnectionRef, {data, ChannelId0, 0, <<"testing\n">>}},
+ case ssh_test_lib:receive_exec_result(Data0) of
+ expected ->
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId0);
+ {unexpected_msg,{ssh_cm, ConnectionRef, {exit_status, ChannelId0, 0}}
+ = ExitStatus0} ->
+ test_server:format("0: Collected data ~p", [ExitStatus0]),
+ ssh_test_lib:receive_exec_result(Data0,
+ ConnectionRef, ChannelId0);
+ Other0 ->
+ test_server:fail(Other0)
+ end,
+
+ {ok, ChannelId1} = ssh_connection:session_channel(ConnectionRef, infinity),
+ success = ssh_connection:exec(ConnectionRef, ChannelId1,
+ "echo testing1", infinity),
+ Data1 = {ssh_cm, ConnectionRef, {data, ChannelId1, 0, <<"testing1\n">>}},
+ case ssh_test_lib:receive_exec_result(Data1) of
+ expected ->
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId1);
+ {unexpected_msg,{ssh_cm, ConnectionRef, {exit_status, ChannelId1, 0}}
+ = ExitStatus1} ->
+ test_server:format("0: Collected data ~p", [ExitStatus1]),
+ ssh_test_lib:receive_exec_result(Data1,
+ ConnectionRef, ChannelId1);
+ Other1 ->
+ test_server:fail(Other1)
+ end.
+
+%%--------------------------------------------------------------------
+erlang_client_openssh_server_exec_compressed(doc) ->
+ ["Test that compression option works"];
+
+erlang_client_openssh_server_exec_compressed(suite) ->
+ [];
+
+erlang_client_openssh_server_exec_compressed(Config) when is_list(Config) ->
+ ConnectionRef = ssh_test_lib:connect(?SSH_DEFAULT_PORT, [{silently_accept_hosts, true},
+ {user_interaction, false},
+ {compression, zlib}]),
+ {ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity),
+ success = ssh_connection:exec(ConnectionRef, ChannelId,
+ "echo testing", infinity),
+ Data = {ssh_cm, ConnectionRef, {data, ChannelId, 0, <<"testing\n">>}},
+ case ssh_test_lib:receive_exec_result(Data) of
+ expected ->
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId);
+ {unexpected_msg,{ssh_cm, ConnectionRef,
+ {exit_status, ChannelId, 0}} = ExitStatus} ->
+ test_server:format("0: Collected data ~p", [ExitStatus]),
+ ssh_test_lib:receive_exec_result(Data, ConnectionRef, ChannelId);
+ Other ->
+ test_server:fail(Other)
+ end.
+
+%%--------------------------------------------------------------------
+erlang_server_openssh_client_exec(doc) ->
+ ["Test that exec command works."];
+
+erlang_server_openssh_client_exec(suite) ->
+ [];
+
+erlang_server_openssh_client_exec(Config) when is_list(Config) ->
+ SystemDir = ?config(data_dir, Config),
+
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+
+
+ test_server:sleep(500),
+
+ Cmd = "ssh -p " ++ integer_to_list(Port) ++
+ " -o StrictHostKeyChecking=no "++ Host ++ " 1+1.",
+ SshPort = open_port({spawn, Cmd}, [binary]),
+
+ receive
+ {SshPort,{data, <<"2\n">>}} ->
+ ok
+ after ?TIMEOUT ->
+ test_server:fail("Did not receive answer")
+
+ end,
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+erlang_server_openssh_client_exec_compressed(doc) ->
+ ["Test that exec command works."];
+
+erlang_server_openssh_client_exec_compressed(suite) ->
+ [];
+
+erlang_server_openssh_client_exec_compressed(Config) when is_list(Config) ->
+ SystemDir = ?config(data_dir, Config),
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {compression, zlib},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+
+ test_server:sleep(500),
+
+ Cmd = "ssh -p " ++ integer_to_list(Port) ++
+ " -o StrictHostKeyChecking=no -C "++ Host ++ " 1+1.",
+ SshPort = open_port({spawn, Cmd}, [binary]),
+
+ receive
+ {SshPort,{data, <<"2\n">>}} ->
+ ok
+ after ?TIMEOUT ->
+ test_server:fail("Did not receive answer")
+
+ end,
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+erlang_client_openssh_server_setenv(doc) ->
+ ["Test api function ssh_connection:setenv"];
+
+erlang_client_openssh_server_setenv(suite) ->
+ [];
+
+erlang_client_openssh_server_setenv(Config) when is_list(Config) ->
+ ConnectionRef =
+ ssh_test_lib:connect(?SSH_DEFAULT_PORT, [{silently_accept_hosts, true},
+ {user_interaction, false}]),
+ {ok, ChannelId} =
+ ssh_connection:session_channel(ConnectionRef, infinity),
+ Env = case ssh_connection:setenv(ConnectionRef, ChannelId,
+ "ENV_TEST", "testing_setenv",
+ infinity) of
+ success ->
+ <<"tesing_setenv\n">>;
+ failure ->
+ <<"\n">>
+ end,
+ success = ssh_connection:exec(ConnectionRef, ChannelId,
+ "echo $ENV_TEST", infinity),
+ Data = {ssh_cm, ConnectionRef, {data, ChannelId, 0, Env}},
+ case ssh_test_lib:receive_exec_result(Data) of
+ expected ->
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId);
+ {unexpected_msg,{ssh_cm, ConnectionRef,
+ {data,0,1, UnxpectedData}}} ->
+ %% Some os may return things as
+ %% ENV_TEST: Undefined variable.\n"
+ test_server:format("UnxpectedData: ~p", [UnxpectedData]),
+ ssh_test_lib:receive_exec_end(ConnectionRef, ChannelId);
+ {unexpected_msg,{ssh_cm, ConnectionRef, {exit_status, ChannelId, 0}}
+ = ExitStatus} ->
+ test_server:format("0: Collected data ~p", [ExitStatus]),
+ ssh_test_lib:receive_exec_result(Data,
+ ConnectionRef, ChannelId);
+ Other ->
+ test_server:fail(Other)
+ end.
+
+%%--------------------------------------------------------------------
+
+%% setenv not meaningfull on erlang ssh daemon!
+
+%%--------------------------------------------------------------------
+erlang_client_openssh_server_publickey_rsa(doc) ->
+ ["Validate using rsa publickey."];
+erlang_client_openssh_server_publickey_rsa(suite) ->
+ [];
+erlang_client_openssh_server_publickey_rsa(Config) when is_list(Config) ->
+ {ok,[[Home]]} = init:get_argument(home),
+ SrcDir = filename:join(Home, ".ssh"),
+ UserDir = ?config(priv_dir, Config),
+ case ssh_test_lib:copyfile(SrcDir, UserDir, "id_rsa") of
+ {ok, _} ->
+ ConnectionRef =
+ ssh_test_lib:connect(?SSH_DEFAULT_PORT,
+ [{user_dir, UserDir},
+ {public_key_alg, ssh_rsa},
+ {user_interaction, false},
+ silently_accept_hosts]),
+ {ok, Channel} =
+ ssh_connection:session_channel(ConnectionRef, infinity),
+ ok = ssh_connection:close(ConnectionRef, Channel),
+ ok = ssh:close(ConnectionRef),
+ ok = file:delete(filename:join(UserDir, "id_rsa"));
+ {error, enoent} ->
+ {skip, "no ~/.ssh/id_rsa"}
+ end.
+
+%%--------------------------------------------------------------------
+erlang_client_openssh_server_publickey_dsa(doc) ->
+ ["Validate using dsa publickey."];
+erlang_client_openssh_server_publickey_dsa(suite) ->
+ [];
+erlang_client_openssh_server_publickey_dsa(Config) when is_list(Config) ->
+ {ok,[[Home]]} = init:get_argument(home),
+ SrcDir = filename:join(Home, ".ssh"),
+ UserDir = ?config(priv_dir, Config),
+ case ssh_test_lib:copyfile(SrcDir, UserDir, "id_dsa") of
+ {ok, _} ->
+ ConnectionRef =
+ ssh_test_lib:connect(?SSH_DEFAULT_PORT,
+ [{user_dir, UserDir},
+ {public_key_alg, ssh_dsa},
+ {user_interaction, false},
+ silently_accept_hosts]),
+ {ok, Channel} =
+ ssh_connection:session_channel(ConnectionRef, infinity),
+ ok = ssh_connection:close(ConnectionRef, Channel),
+ ok = ssh:close(ConnectionRef),
+ ok = file:delete(filename:join(UserDir, "id_dsa"));
+ {error, enoent} ->
+ {skip, "no ~/.ssh/id_dsa"}
+ end.
+
+%%--------------------------------------------------------------------
+erlang_server_openssh_client_pulic_key_dsa(doc) ->
+ ["Validate using dsa publickey."];
+
+erlang_server_openssh_client_pulic_key_dsa(suite) ->
+ [];
+
+erlang_server_openssh_client_pulic_key_dsa(Config) when is_list(Config) ->
+ SystemDir = ?config(data_dir, Config),
+ {Pid, Host, Port} = ssh_test_lib:daemon([{system_dir, SystemDir},
+ {public_key_alg, ssh_dsa},
+ {failfun, fun ssh_test_lib:failfun/2}]),
+
+ test_server:sleep(500),
+
+ Cmd = "ssh -p " ++ integer_to_list(Port) ++
+ " -o StrictHostKeyChecking=no "++ Host ++ " 1+1.",
+ SshPort = open_port({spawn, Cmd}, [binary]),
+
+ receive
+ {SshPort,{data, <<"2\n">>}} ->
+ ok
+ after ?TIMEOUT ->
+ test_server:fail("Did not receive answer")
+
+ end,
+ ssh:stop_daemon(Pid).
+
+%%--------------------------------------------------------------------
+erlang_client_openssh_server_password(doc) ->
+ ["Test client password option"];
+
+erlang_client_openssh_server_password(suite) ->
+ [];
+
+erlang_client_openssh_server_password(Config) when is_list(Config) ->
+ %% to make sure we don't public-key-auth
+ UserDir = ?config(data_dir, Config),
+ {error, Reason0} =
+ ssh_test_lib:connect(?SSH_DEFAULT_PORT, [{silently_accept_hosts, true},
+ {user, "foo"},
+ {password, "morot"},
+ {user_interaction, false},
+ {user_dir, UserDir}]),
+
+ test_server:format("Test of user foo that does not exist. "
+ "Error msg: ~p~n", [Reason0]),
+
+ User = string:strip(os:cmd("whoami"), right, $\n),
+
+ case length(string:tokens(User, " ")) of
+ 1 ->
+ {error, Reason1} =
+ ssh_test_lib:connect(?SSH_DEFAULT_PORT,
+ [{silently_accept_hosts, true},
+ {user, User},
+ {password, "foo"},
+ {user_interaction, false},
+ {user_dir, UserDir}]),
+ test_server:format("Test of wrong Pasword. "
+ "Error msg: ~p~n", [Reason1]);
+ _ ->
+ test_server:format("Whoami failed reason: ~n", [])
+ end.
+
+%%--------------------------------------------------------------------
+%
+%% Not possible to send password with openssh without user interaction
+%%
+%%--------------------------------------------------------------------
+%%--------------------------------------------------------------------
+%%% Internal functions
+%%--------------------------------------------------------------------
+receive_hej() ->
+ receive
+ <<"Hej\n">> = Hej->
+ test_server:format("Expected result: ~p~n", [Hej]);
+ Info ->
+ test_server:format("Extra info: ~p~n", [Info]),
+ receive_hej()
+ end.
diff --git a/lib/ssh/vsn.mk b/lib/ssh/vsn.mk
index d0861b3ddc..d79038df29 100644
--- a/lib/ssh/vsn.mk
+++ b/lib/ssh/vsn.mk
@@ -1,5 +1,5 @@
#-*-makefile-*- ; force emacs to enter makefile-mode
-SSH_VSN = 2.0.6
+SSH_VSN = 2.0.7
APP_VSN = "ssh-$(SSH_VSN)"
diff --git a/lib/ssl/c_src/Makefile.in b/lib/ssl/c_src/Makefile.in
index 49a209f2eb..da716f7c40 100644
--- a/lib/ssl/c_src/Makefile.in
+++ b/lib/ssl/c_src/Makefile.in
@@ -28,6 +28,8 @@ include $(ERL_TOP)/make/$(TARGET)/otp.mk
# ----------------------------------------------------
SSL_LIBDIR = @SSL_LIBDIR@
SSL_INCLUDE = @SSL_INCLUDE@
+SSL_CRYPTO_LIBNAME = @SSL_CRYPTO_LIBNAME@
+SSL_SSL_LIBNAME = @SSL_SSL_LIBNAME@
# ----------------------------------------------------
# Application version
@@ -134,7 +136,7 @@ ifeq ($(findstring @,$(SSL_CC_RUNTIME_LIBRARY_PATH)),@)
SSL_CC_RUNTIME_LIBRARY_PATH = $(CC_R_OPT)
endif
-SSL_LINK_LIB=-L$(SSL_LIBDIR) -lssl -lcrypto
+SSL_LINK_LIB=-L$(SSL_LIBDIR) -l$(SSL_SSL_LIBNAME) -l$(SSL_CRYPTO_LIBNAME)
else
# not dynamic crypto lib (default from R11B-5)
NEED_KERBEROS=@SSL_LINK_WITH_KERBEROS@
@@ -142,7 +144,7 @@ NEED_ZLIB=@SSL_LINK_WITH_ZLIB@
SSL_MAKEFILE =
CC_R_OPT =
SSL_CC_RUNTIME_LIBRARY_PATH=
-SSL_LINK_LIB = $(SSL_LIBDIR)/libssl.a $(SSL_LIBDIR)/libcrypto.a
+SSL_LINK_LIB = $(SSL_LIBDIR)/lib$(SSL_SSL_LIBNAME).a $(SSL_LIBDIR)/lib$(SSL_CRYPTO_LIBNAME).a
ifeq ($(NEED_KERBEROS),yes)
SSL_LINK_LIB += @STATIC_KERBEROS_LIBS@
endif
@@ -175,7 +177,7 @@ $(BINDIR)/ssl_esock: $(OBJS)
# Win32/Cygwin
$(BINDIR)/ssl_esock.exe: $(OBJS)
- $(LD) $(SSL_CC_RUNTIME_LIBRARY_PATH) -L$(SSL_LIBDIR) -o $@ $^ -lwsock32 -llibeay32 -lssleay32
+ $(LD) $(SSL_CC_RUNTIME_LIBRARY_PATH) -L$(SSL_LIBDIR) -o $@ $^ -lwsock32 -l$(SSL_CRYPTO_LIBNAME) -l$(SSL_SSL_LIBNAME)
# Unix only, and only when linking statically
$(SSL_MAKEFILE):
diff --git a/lib/ssl/doc/src/notes.xml b/lib/ssl/doc/src/notes.xml
index 52ee9c086a..b2d17925fd 100644
--- a/lib/ssl/doc/src/notes.xml
+++ b/lib/ssl/doc/src/notes.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
@@ -28,59 +28,47 @@
<rev>G</rev>
<file>notes.xml</file>
</header>
- <p>This document describes the changes made to the SSL application.
- </p>
-
- <section><title>SSL 4.1.4</title>
-
+ <p>This document describes the changes made to the SSL application.</p>
+
+ <section>
+ <title>SSL 4.1.5</title>
+
<section><title>Improvements and New Features</title>
- <list>
- <item>
- <p>
- Reduced memory footprint of an ssl connection.</p>
- <p>
- Handshake hashes, premaster secret and "public_key_info"
- does not need to be saved when the connection has been
- established. The own certificate is no longer duplicated
- in the state.</p>
- <p>
- Own Id: OTP-9021</p>
- </item>
- <item>
- <p>
- Add the option {hibernate_after, int()} to ssl:connect
- and ssl:listen</p>
- <p>
- Own Id: OTP-9106</p>
- </item>
- </list>
+ <list>
+ <item>
+ <p>Calling gen_tcp:connect with option {ip, {127,0,0,1}} results in
+ an exit with reason badarg. Neither SSL nor INETS This was not
+ catched, resulting in crashes with incomprehensible reasons.</p>
+ <p>Own Id: OTP-9289 Aux Id: seq11845</p>
+ </item>
+ </list>
</section>
-
-</section>
-
-<section><title>SSL 4.1.3</title>
-
+
+ </section>
+
+ <section>
+ <title>SSL 4.1.3</title>
+
<section><title>Fixed Bugs and Malfunctions</title>
- <list>
- <item>
- <p>
- Fixed error in cache-handling fix from ssl-4.1.2</p>
- <p>
- Own Id: OTP-9018 Aux Id: seq11739 </p>
- </item>
- <item>
- <p>
- Verification of a critical extended_key_usage-extension
- corrected</p>
- <p>
- Own Id: OTP-9029 Aux Id: seq11541 </p>
- </item>
- </list>
+ <list>
+ <item>
+ <p>
+ Fixed error in cache-handling fix from ssl-4.1.2</p>
+ <p>
+ Own Id: OTP-9018 Aux Id: seq11739 </p>
+ </item>
+ <item>
+ <p>Verification of a critical extended_key_usage-extension
+ corrected</p>
+ <p>Own Id: OTP-9029 Aux Id: seq11541 </p>
+ </item>
+ </list>
</section>
-</section>
+ </section>
-<section><title>SSL 4.1.2</title>
+ <section>
+ <title>SSL 4.1.2</title>
<section><title>Fixed Bugs and Malfunctions</title>
<list>
diff --git a/lib/ssl/src/ssl.appup.src b/lib/ssl/src/ssl.appup.src
index a0ecb4ac6f..cf8867245b 100644
--- a/lib/ssl/src/ssl.appup.src
+++ b/lib/ssl/src/ssl.appup.src
@@ -5,7 +5,7 @@
{"4.1.3", [{restart_application, ssl}]},
{"4.1.2", [{restart_application, ssl}]},
{"4.1.1", [{restart_application, ssl}]},
- {"4.1", [{restart_application, ssl}]},
+ {"4.1", [{restart_application, ssl}]},
{"4.0.1", [{restart_application, ssl}]}
],
[
@@ -13,7 +13,7 @@
{"4.1.3", [{restart_application, ssl}]},
{"4.1.2", [{restart_application, ssl}]},
{"4.1.1", [{restart_application, ssl}]},
- {"4.1", [{restart_application, ssl}]},
+ {"4.1", [{restart_application, ssl}]},
{"4.0.1", [{restart_application, ssl}]}
]}.
diff --git a/lib/ssl/src/ssl.erl b/lib/ssl/src/ssl.erl
index 380c59b058..0ced6707eb 100644
--- a/lib/ssl/src/ssl.erl
+++ b/lib/ssl/src/ssl.erl
@@ -611,8 +611,10 @@ do_new_connect(Address, Port,
catch
exit:{function_clause, _} ->
{error, {eoptions, {cb_info, CbInfo}}};
+ exit:badarg ->
+ {error, {eoptions, {inet_options, UserOpts}}};
exit:{badarg, _} ->
- {error,{eoptions, {inet_options, UserOpts}}}
+ {error, {eoptions, {inet_options, UserOpts}}}
end.
old_connect(Address, Port, Options, Timeout) ->
diff --git a/lib/ssl/src/ssl_connection.erl b/lib/ssl/src/ssl_connection.erl
index 0a86e9bd29..2c452837f8 100644
--- a/lib/ssl/src/ssl_connection.erl
+++ b/lib/ssl/src/ssl_connection.erl
@@ -941,17 +941,23 @@ handle_info({Protocol, _, Data}, StateName,
handle_info({CloseTag, Socket}, _StateName,
#state{socket = Socket, close_tag = CloseTag,
- negotiated_version = Version, host = Host,
- port = Port, socket_options = Opts,
+ negotiated_version = Version,
+ socket_options = Opts,
user_application = {_Mon,Pid}, from = From,
- role = Role, session = Session} = State) ->
- %% Debug option maybe, the user do NOT want to see these in their logs
- %% error_logger:info_report("SSL: Peer did not send close notify alert."),
+ role = Role} = State) ->
+ %% Note that as of TLS 1.1,
+ %% failure to properly close a connection no longer requires that a
+ %% session not be resumed. This is a change from TLS 1.0 to conform
+ %% with widespread implementation practice.
case Version of
{1, N} when N >= 1 ->
ok;
_ ->
- invalidate_session(Role, Host, Port, Session)
+ %% As invalidate_sessions here causes performance issues,
+ %% we will conform to the widespread implementation
+ %% practice and go aginst the spec
+ %%invalidate_session(Role, Host, Port, Session)
+ ok
end,
alert_user(Opts#socket_options.active, Pid, From,
?ALERT_REC(?WARNING, ?CLOSE_NOTIFY), Role),
diff --git a/lib/ssl/src/ssl_manager.erl b/lib/ssl/src/ssl_manager.erl
index f845b1ecc0..5a2d0c9496 100644
--- a/lib/ssl/src/ssl_manager.erl
+++ b/lib/ssl/src/ssl_manager.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2007-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2007-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
@@ -57,6 +57,7 @@
-define('24H_in_sec', 8640).
-define(SESSION_VALIDATION_INTERVAL, 60000).
-define(CERTIFICATE_CACHE_CLEANUP, 30000).
+-define(CLEAN_SESSION_DB, 60000).
%%====================================================================
%% API
@@ -70,7 +71,8 @@ start_link(Opts) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [Opts], []).
%%--------------------------------------------------------------------
--spec connection_init(string()| {der, list()}, client | server) -> {ok, reference(), cache_ref()}.
+-spec connection_init(string()| {der, list()}, client | server) ->
+ {ok, reference(), cache_ref()}.
%%
%% Description: Do necessary initializations for a new connection.
%%--------------------------------------------------------------------
@@ -101,7 +103,9 @@ lookup_trusted_cert(Ref, SerialNumber, Issuer) ->
ssl_certificate_db:lookup_trusted_cert(Ref, SerialNumber, Issuer).
%%--------------------------------------------------------------------
-spec issuer_candidate(cert_key() | no_candidate) ->
- {cert_key(), {der_cert(), #'OTPCertificate'{}}} | no_more_candidates.
+ {cert_key(),
+ {der_cert(),
+ #'OTPCertificate'{}}} | no_more_candidates.
%%
%% Description: Return next issuer candidate.
%%--------------------------------------------------------------------
@@ -117,7 +121,8 @@ client_session_id(Host, Port, SslOpts, OwnCert) ->
call({client_session_id, Host, Port, SslOpts, OwnCert}).
%%--------------------------------------------------------------------
--spec server_session_id(host(), port_num(), #ssl_options{}, der_cert()) -> session_id().
+-spec server_session_id(host(), port_num(), #ssl_options{},
+ der_cert()) -> session_id().
%%
%% Description: Select a session id for the server.
%%--------------------------------------------------------------------
@@ -139,7 +144,9 @@ register_session(Port, Session) ->
-spec invalidate_session(port_num(), #session{}) -> ok.
-spec invalidate_session(host(), port_num(), #session{}) -> ok.
%%
-%% Description: Make the session unavilable for reuse.
+%% Description: Make the session unavailable for reuse. After
+%% a the session has been marked "is_resumable = false" for some while
+%% it will be safe to remove the data from the session database.
%%--------------------------------------------------------------------
invalidate_session(Host, Port, Session) ->
cast({invalidate_session, Host, Port, Session}).
@@ -259,23 +266,26 @@ handle_cast({register_session, Port, Session},
{noreply, State};
handle_cast({invalidate_session, Host, Port,
- #session{session_id = ID}},
+ #session{session_id = ID} = Session},
#state{session_cache = Cache,
session_cache_cb = CacheCb} = State) ->
- CacheCb:delete(Cache, {{Host, Port}, ID}),
+ CacheCb:update(Cache, {{Host, Port}, ID}, Session#session{is_resumable = false}),
+ timer:apply_after(?CLEAN_SESSION_DB, CacheCb, delete, {{Host, Port}, ID}),
{noreply, State};
-handle_cast({invalidate_session, Port, #session{session_id = ID}},
+handle_cast({invalidate_session, Port, #session{session_id = ID} = Session},
#state{session_cache = Cache,
session_cache_cb = CacheCb} = State) ->
- CacheCb:delete(Cache, {Port, ID}),
+ CacheCb:update(Cache, {Port, ID}, Session#session{is_resumable = false}),
+ timer:apply_after(?CLEAN_SESSION_DB, CacheCb, delete, {Port, ID}),
{noreply, State};
handle_cast({recache_pem, File, LastWrite, Pid, From},
#state{certificate_db = [_, FileToRefDb, _]} = State0) ->
case ssl_certificate_db:lookup(File, FileToRefDb) of
undefined ->
- {reply, Msg, State} = handle_call({{cache_pem, File, LastWrite}, Pid}, From, State0),
+ {reply, Msg, State} =
+ handle_call({{cache_pem, File, LastWrite}, Pid}, From, State0),
gen_server:reply(From, Msg),
{noreply, State};
_ -> %% Send message to self letting cleanup messages be handled
diff --git a/lib/stdlib/doc/specs/.gitignore b/lib/stdlib/doc/specs/.gitignore
new file mode 100644
index 0000000000..322eebcb06
--- /dev/null
+++ b/lib/stdlib/doc/specs/.gitignore
@@ -0,0 +1 @@
+specs_*.xml
diff --git a/lib/stdlib/doc/src/Makefile b/lib/stdlib/doc/src/Makefile
index b558697d63..16e0a86e3b 100644
--- a/lib/stdlib/doc/src/Makefile
+++ b/lib/stdlib/doc/src/Makefile
@@ -1,7 +1,7 @@
#
# %CopyrightBegin%
#
-# Copyright Ericsson AB 1997-2010. All Rights Reserved.
+# 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
@@ -125,18 +125,24 @@ HTML_REF_MAN_FILE = $(HTMLDIR)/index.html
TOP_PDF_FILE = $(PDFDIR)/$(APPLICATION)-$(VSN).pdf
+SPECS_FILES = $(XML_REF3_FILES:%.xml=$(SPECDIR)/specs_%.xml)
+
+TOP_SPECS_FILE = specs.xml
+
# ----------------------------------------------------
# FLAGS
# ----------------------------------------------------
XML_FLAGS +=
+SPECS_FLAGS = -I../../include -I../../../kernel/include
+
# ----------------------------------------------------
# Targets
# ----------------------------------------------------
$(HTMLDIR)/%.gif: %.gif
$(INSTALL_DATA) $< $@
-docs: pdf html man
+docs: man pdf html
$(TOP_PDF_FILE): $(XML_FILES)
@@ -155,8 +161,13 @@ clean clean_docs:
rm -f $(MAN3DIR)/*
rm -f $(MAN6DIR)/*
rm -f $(TOP_PDF_FILE) $(TOP_PDF_FILE:%.pdf=%.fo)
+ rm -f $(SPECDIR)/*
rm -f errs core *~
+$(SPECDIR)/specs_erl_id_trans.xml:
+ escript $(SPECS_EXTRACTOR) $(SPECS_FLAGS) \
+ -o$(dir $@) -module erl_id_trans
+
# ----------------------------------------------------
# Release Target
# ----------------------------------------------------
diff --git a/lib/stdlib/doc/src/array.xml b/lib/stdlib/doc/src/array.xml
index 5c3ac6a2a9..a79fcd487e 100644
--- a/lib/stdlib/doc/src/array.xml
+++ b/lib/stdlib/doc/src/array.xml
@@ -3,7 +3,7 @@
<erlref>
<header>
<copyright>
- <year>2007</year><year>2009</year>
+ <year>2007</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -82,19 +82,35 @@ the default value cannot be confused with the values of set entries.</p>
%% allow accesses beyond the last set entry
{'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
{'EXIT',{badarg,_}} = (catch array:get(18, A3)).</pre></description>
-<section><title>DATA TYPES</title><marker id="types"/>
-
-<taglist>
-<tag><c>array()</c></tag>
-<item><marker id="type-array"/>
-<p>A functional, extendible array. The representation is
- not documented and is subject to change without notice. Note that
- arrays cannot be directly compared for equality.</p>
-</item>
-</taglist></section>
+<datatypes>
+ <datatype>
+ <name><marker id="type-array">array()</marker></name>
+ <desc>
+ <p>A functional, extendible array. The representation is
+ not documented and is subject to change without notice. Note that
+ arrays cannot be directly compared for equality.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="array_indx"/>
+ </datatype>
+ <datatype>
+ <name name="array_opts"/>
+ </datatype>
+ <datatype>
+ <name name="array_opt"/>
+ </datatype>
+ <datatype>
+ <name name="indx_pairs"/>
+ </datatype>
+ <datatype>
+ <name name="indx_pair"/>
+ </datatype>
+</datatypes>
+
<funcs>
<func>
-<name>default(Array::array()) -&gt; term()</name>
+<name name="default" arity="1"/>
<fsummary>Get the value used for uninitialized entries.</fsummary>
<desc><marker id="default-1"/>
@@ -104,7 +120,7 @@ the default value cannot be confused with the values of set entries.</p>
<p><em>See also:</em> <seealso marker="#new-2">new/2</seealso>.</p>
</desc></func>
<func>
-<name>fix(Array::array()) -&gt; array()</name>
+<name name="fix" arity="1"/>
<fsummary>Fix the size of the array.</fsummary>
<desc><marker id="fix-1"/>
@@ -114,105 +130,100 @@ the default value cannot be confused with the values of set entries.</p>
<p><em>See also:</em> <seealso marker="#relax-1">relax/1</seealso>.</p>
</desc></func>
<func>
-<name>foldl(Function, InitialAcc::term(), Array::array()) -&gt; term()</name>
+<name name="foldl" arity="3"/>
<fsummary>Fold the elements of the array using the given function and
initial accumulator value.</fsummary>
-<type>
-<v>Function = (Index::integer(), Value::term(), Acc::term()) -&gt; term()</v></type>
<desc><marker id="foldl-3"/>
-
<p>Fold the elements of the array using the given function and
initial accumulator value. The elements are visited in order from the
- lowest index to the highest. If <c>Function</c> is not a function, the
+ lowest index to the highest. If <c><anno>Function</anno></c> is not a function, the
call fails with reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#foldr-3">foldr/3</seealso>, <seealso marker="#map-2">map/2</seealso>, <seealso marker="#sparse_foldl-3">sparse_foldl/3</seealso>.</p>
</desc></func>
<func>
-<name>foldr(Function, InitialAcc::term(), Array::array()) -&gt; term()</name>
+<name name="foldr" arity="3"/>
<fsummary>Fold the elements of the array right-to-left using the given
function and initial accumulator value.</fsummary>
-<type>
-<v>Function = (Index::integer(), Value::term(), Acc::term()) -&gt; term()</v></type>
<desc><marker id="foldr-3"/>
<p>Fold the elements of the array right-to-left using the given
function and initial accumulator value. The elements are visited in
- order from the highest index to the lowest. If <c>Function</c> is not a
+ order from the highest index to the lowest. If <c><anno>Function</anno></c> is not a
function, the call fails with reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#foldl-3">foldl/3</seealso>, <seealso marker="#map-2">map/2</seealso>.</p>
</desc></func>
<func>
-<name>from_list(List::list()) -&gt; array()</name>
+<name name="from_list" arity="1"/>
<fsummary>Equivalent to from_list(List, undefined).
</fsummary>
<desc><marker id="from_list-1"/>
-<p>Equivalent to <seealso marker="#from_list-2">from_list(List, undefined)</seealso>.</p>
+<p>Equivalent to <seealso marker="#from_list-2">from_list(<anno>List</anno>, undefined)</seealso>.</p>
</desc></func>
<func>
-<name>from_list(List::list(), Default::term()) -&gt; array()</name>
+<name name="from_list" arity="2"/>
<fsummary>Convert a list to an extendible array.</fsummary>
<desc><marker id="from_list-2"/>
-<p>Convert a list to an extendible array. <c>Default</c> is used as the value
- for uninitialized entries of the array. If <c>List</c> is not a proper list,
+<p>Convert a list to an extendible array. <c><anno>Default</anno></c> is used as the value
+ for uninitialized entries of the array. If <c><anno>List</anno></c> is not a proper list,
the call fails with reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#new-2">new/2</seealso>, <seealso marker="#to_list-1">to_list/1</seealso>.</p>
</desc></func>
<func>
-<name>from_orddict(Orddict::list()) -&gt; array()</name>
+<name name="from_orddict" arity="1"/>
<fsummary>Equivalent to from_orddict(Orddict, undefined).
</fsummary>
<desc><marker id="from_orddict-1"/>
-<p>Equivalent to <seealso marker="#from_orddict-2">from_orddict(Orddict, undefined)</seealso>.</p>
+<p>Equivalent to <seealso marker="#from_orddict-2">from_orddict(<anno>Orddict</anno>, undefined)</seealso>.</p>
</desc></func>
<func>
-<name>from_orddict(List::list(), Default::term()) -&gt; array()</name>
+<name name="from_orddict" arity="2"/>
<fsummary>Convert an ordered list of pairs {Index, Value} to a
corresponding extendible array.</fsummary>
<desc><marker id="from_orddict-2"/>
<p>Convert an ordered list of pairs <c>{Index, Value}</c> to a
- corresponding extendible array. <c>Default</c> is used as the value for
- uninitialized entries of the array. If <c>List</c> is not a proper,
+ corresponding extendible array. <c><anno>Default</anno></c> is used as the value for
+ uninitialized entries of the array. If <c><anno>Orddict</anno></c> is not a proper,
ordered list of pairs whose first elements are nonnegative
integers, the call fails with reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#new-2">new/2</seealso>, <seealso marker="#to_orddict-1">to_orddict/1</seealso>.</p>
</desc></func>
<func>
-<name>get(I::integer(), Array::array()) -&gt; term()</name>
+<name name="get" arity="2"/>
<fsummary>Get the value of entry I.</fsummary>
<desc><marker id="get-2"/>
-<p>Get the value of entry <c>I</c>. If <c>I</c> is not a nonnegative
- integer, or if the array has fixed size and <c>I</c> is larger than the
+<p>Get the value of entry <c><anno>I</anno></c>. If <c><anno>I</anno></c> is not a nonnegative
+ integer, or if the array has fixed size and <c><anno>I</anno></c> is larger than the
maximum index, the call fails with reason <c>badarg</c>.</p>
<p>If the array does not have fixed size, this function will return the
- default value for any index <c>I</c> greater than <c>size(Array)-1</c>.</p>
+ default value for any index <c><anno>I</anno></c> greater than <c>size(<anno>Array</anno>)-1</c>.</p>
<p><em>See also:</em> <seealso marker="#set-3">set/3</seealso>.</p>
</desc></func>
<func>
-<name>is_array(X::term()) -&gt; bool()</name>
+<name name="is_array" arity="1"/>
<fsummary>Returns true if X appears to be an array, otherwise false.</fsummary>
<desc><marker id="is_array-1"/>
-<p>Returns <c>true</c> if <c>X</c> appears to be an array, otherwise <c>false</c>.
- Note that the check is only shallow; there is no guarantee that <c>X</c>
+<p>Returns <c>true</c> if <c><anno>X</anno></c> appears to be an array, otherwise <c>false</c>.
+ Note that the check is only shallow; there is no guarantee that <c><anno>X</anno></c>
is a well-formed array representation even if this function returns
<c>true</c>.</p>
</desc></func>
<func>
-<name>is_fix(Array::array()) -&gt; bool()</name>
+<name name="is_fix" arity="1"/>
<fsummary>Check if the array has fixed size.</fsummary>
<desc><marker id="is_fix-1"/>
@@ -222,20 +233,18 @@ the default value cannot be confused with the values of set entries.</p>
<p><em>See also:</em> <seealso marker="#fix-1">fix/1</seealso>.</p>
</desc></func>
<func>
-<name>map(Function, Array::array()) -&gt; array()</name>
+<name name="map" arity="2"/>
<fsummary>Map the given function onto each element of the array.</fsummary>
-<type>
-<v>Function = (Index::integer(), Value::term()) -&gt; term()</v></type>
<desc><marker id="map-2"/>
<p>Map the given function onto each element of the array. The
elements are visited in order from the lowest index to the highest.
- If <c>Function</c> is not a function, the call fails with reason <c>badarg</c>.
+ If <c><anno>Function</anno></c> is not a function, the call fails with reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#foldl-3">foldl/3</seealso>, <seealso marker="#foldr-3">foldr/3</seealso>, <seealso marker="#sparse_map-2">sparse_map/2</seealso>.</p>
</desc></func>
<func>
-<name>new() -&gt; array()</name>
+<name name="new" arity="0"/>
<fsummary>Create a new, extendible array with initial size zero.</fsummary>
<desc><marker id="new-0"/>
@@ -244,7 +253,7 @@ the default value cannot be confused with the values of set entries.</p>
<p><em>See also:</em> <seealso marker="#new-1">new/1</seealso>, <seealso marker="#new-2">new/2</seealso>.</p>
</desc></func>
<func>
-<name>new(Options::term()) -&gt; array()</name>
+<name name="new" arity="1"/>
<fsummary>Create a new array according to the given options.</fsummary>
<desc><marker id="new-1"/>
@@ -253,10 +262,10 @@ the default value cannot be confused with the values of set entries.</p>
the array is extendible and has initial size zero. Array indices
start at 0.</p>
- <p><c>Options</c> is a single term or a list of terms, selected from the
+ <p><c><anno>Options</anno></c> is a single term or a list of terms, selected from the
following:
</p><taglist>
- <tag><c>N::integer()</c> or <c>{size, N::integer()}</c></tag>
+ <tag><c>N::integer() >= 0</c> or <c>{size, N::integer() >= 0}</c></tag>
<item><p>Specifies the initial size of the array; this also implies
<c>{fixed, true}</c>. If <c>N</c> is not a nonnegative integer, the call
fails with reason <c>badarg</c>.</p></item>
@@ -283,19 +292,19 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#fix-1">fix/1</seealso>, <seealso marker="#from_list-2">from_list/2</seealso>, <seealso marker="#get-2">get/2</seealso>, <seealso marker="#new-0">new/0</seealso>, <seealso marker="#new-2">new/2</seealso>, <seealso marker="#set-3">set/3</seealso>.</p>
</desc></func>
<func>
-<name>new(Size::integer(), Options::term()) -&gt; array()</name>
+<name name="new" arity="2"/>
<fsummary>Create a new array according to the given size and options.</fsummary>
<desc><marker id="new-2"/>
<p>Create a new array according to the given size and options. If
- <c>Size</c> is not a nonnegative integer, the call fails with reason
+ <c><anno>Size</anno></c> is not a nonnegative integer, the call fails with reason
<c>badarg</c>. By default, the array has fixed size. Note that any size
- specifications in <c>Options</c> will override the <c>Size</c> parameter.</p>
+ specifications in <c><anno>Options</anno></c> will override the <c><anno>Size</anno></c> parameter.</p>
- <p>If <c>Options</c> is a list, this is simply equivalent to <c>new([{size,
- Size} | Options]</c>, otherwise it is equivalent to <c>new([{size, Size} |
- [Options]]</c>. However, using this function directly is more efficient.</p>
+ <p>If <c><anno>Options</anno></c> is a list, this is simply equivalent to <c>new([{size,
+ <anno>Size</anno>} | <anno>Options</anno>]</c>, otherwise it is equivalent to <c>new([{size, <anno>Size</anno>} |
+ [<anno>Options</anno>]]</c>. However, using this function directly is more efficient.</p>
<p>Example:
</p><pre> array:new(100, {default,0})</pre><p> creates a fixed-size array of size
@@ -304,7 +313,7 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#new-1">new/1</seealso>.</p>
</desc></func>
<func>
-<name>relax(Array::array()) -&gt; array()</name>
+<name name="relax" arity="1"/>
<fsummary>Make the array resizable.</fsummary>
<desc><marker id="relax-1"/>
@@ -313,24 +322,24 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#fix-1">fix/1</seealso>.</p>
</desc></func>
<func>
-<name>reset(I::integer(), Array::array()) -&gt; array()</name>
+<name name="reset" arity="2"/>
<fsummary>Reset entry I to the default value for the array.</fsummary>
<desc><marker id="reset-2"/>
-<p>Reset entry <c>I</c> to the default value for the array.
- If the value of entry <c>I</c> is the default value the array will be
+<p>Reset entry <c><anno>I</anno></c> to the default value for the array.
+ If the value of entry <c><anno>I</anno></c> is the default value the array will be
returned unchanged. Reset will never change size of the array.
Shrinking can be done explicitly by calling <seealso marker="#resize-2">resize/2</seealso>.</p>
- <p>If <c>I</c> is not a nonnegative integer, or if the array has fixed size
- and <c>I</c> is larger than the maximum index, the call fails with reason
+ <p>If <c><anno>I</anno></c> is not a nonnegative integer, or if the array has fixed size
+ and <c><anno>I</anno></c> is larger than the maximum index, the call fails with reason
<c>badarg</c>; cf. <seealso marker="#set-3">set/3</seealso>
</p>
<p><em>See also:</em> <seealso marker="#new-2">new/2</seealso>, <seealso marker="#set-3">set/3</seealso>.</p>
</desc></func>
<func>
-<name>resize(Array::array()) -&gt; array()</name>
+<name name="resize" arity="1"/>
<fsummary>Change the size of the array to that reported by sparse_size/1.</fsummary>
<desc><marker id="resize-1"/>
@@ -340,90 +349,84 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#resize-2">resize/2</seealso>, <seealso marker="#sparse_size-1">sparse_size/1</seealso>.</p>
</desc></func>
<func>
-<name>resize(Size::integer(), Array::array()) -&gt; array()</name>
+<name name="resize" arity="2"/>
<fsummary>Change the size of the array.</fsummary>
<desc><marker id="resize-2"/>
-<p>Change the size of the array. If <c>Size</c> is not a nonnegative
+<p>Change the size of the array. If <c><anno>Size</anno></c> is not a nonnegative
integer, the call fails with reason <c>badarg</c>. If the given array has
fixed size, the resulting array will also have fixed size.</p>
</desc></func>
<func>
-<name>set(I::integer(), Value::term(), Array::array()) -&gt; array()</name>
+<name name="set" arity="3"/>
<fsummary>Set entry I of the array to Value.</fsummary>
<desc><marker id="set-3"/>
-<p>Set entry <c>I</c> of the array to <c>Value</c>. If <c>I</c> is not a
- nonnegative integer, or if the array has fixed size and <c>I</c> is larger
+<p>Set entry <c><anno>I</anno></c> of the array to <c><anno>Value</anno></c>. If <c><anno>I</anno></c> is not a
+ nonnegative integer, or if the array has fixed size and <c><anno>I</anno></c> is larger
than the maximum index, the call fails with reason <c>badarg</c>.</p>
- <p>If the array does not have fixed size, and <c>I</c> is greater than
- <c>size(Array)-1</c>, the array will grow to size <c>I+1</c>.
+ <p>If the array does not have fixed size, and <c><anno>I</anno></c> is greater than
+ <c>size(<anno>Array</anno>)-1</c>, the array will grow to size <c><anno>I</anno>+1</c>.
</p>
<p><em>See also:</em> <seealso marker="#get-2">get/2</seealso>, <seealso marker="#reset-2">reset/2</seealso>.</p>
</desc></func>
<func>
-<name>size(Array::array()) -&gt; integer()</name>
+<name name="size" arity="1"/>
<fsummary>Get the number of entries in the array.</fsummary>
<desc><marker id="size-1"/>
<p>Get the number of entries in the array. Entries are numbered
- from 0 to <c>size(Array)-1</c>; hence, this is also the index of the first
+ from 0 to <c>size(<anno>Array</anno>)-1</c>; hence, this is also the index of the first
entry that is guaranteed to not have been previously set.</p>
<p><em>See also:</em> <seealso marker="#set-3">set/3</seealso>, <seealso marker="#sparse_size-1">sparse_size/1</seealso>.</p>
</desc></func>
<func>
-<name>sparse_foldl(Function, InitialAcc::term(), Array::array()) -&gt; term()</name>
+<name name="sparse_foldl" arity="3"/>
<fsummary>Fold the elements of the array using the given function and
initial accumulator value, skipping default-valued entries.</fsummary>
-<type>
-<v>Function = (Index::integer(), Value::term(), Acc::term()) -&gt; term()</v></type>
<desc><marker id="sparse_foldl-3"/>
<p>Fold the elements of the array using the given function and
initial accumulator value, skipping default-valued entries. The
elements are visited in order from the lowest index to the highest.
- If <c>Function</c> is not a function, the call fails with reason <c>badarg</c>.
+ If <c><anno>Function</anno></c> is not a function, the call fails with reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#foldl-3">foldl/3</seealso>, <seealso marker="#sparse_foldr-3">sparse_foldr/3</seealso>.</p>
</desc></func>
<func>
-<name>sparse_foldr(Function, InitialAcc::term(), Array::array()) -&gt; term()</name>
+<name name="sparse_foldr" arity="3"/>
<fsummary>Fold the elements of the array right-to-left using the given
function and initial accumulator value, skipping default-valued
entries.</fsummary>
-<type>
-<v>Function = (Index::integer(), Value::term(), Acc::term()) -&gt; term()</v></type>
<desc><marker id="sparse_foldr-3"/>
<p>Fold the elements of the array right-to-left using the given
function and initial accumulator value, skipping default-valued
entries. The elements are visited in order from the highest index to
- the lowest. If <c>Function</c> is not a function, the call fails with
+ the lowest. If <c><anno>Function</anno></c> is not a function, the call fails with
reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#foldr-3">foldr/3</seealso>, <seealso marker="#sparse_foldl-3">sparse_foldl/3</seealso>.</p>
</desc></func>
<func>
-<name>sparse_map(Function, Array::array()) -&gt; array()</name>
+<name name="sparse_map" arity="2"/>
<fsummary>Map the given function onto each element of the array, skipping
default-valued entries.</fsummary>
-<type>
-<v>Function = (Index::integer(), Value::term()) -&gt; term()</v></type>
<desc><marker id="sparse_map-2"/>
<p>Map the given function onto each element of the array, skipping
default-valued entries. The elements are visited in order from the
- lowest index to the highest. If <c>Function</c> is not a function, the
+ lowest index to the highest. If <c><anno>Function</anno></c> is not a function, the
call fails with reason <c>badarg</c>.
</p>
<p><em>See also:</em> <seealso marker="#map-2">map/2</seealso>.</p>
</desc></func>
<func>
-<name>sparse_size(A::array()) -&gt; integer()</name>
+<name name="sparse_size" arity="1"/>
<fsummary>Get the number of entries in the array up until the last
non-default valued entry.</fsummary>
@@ -436,7 +439,7 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#resize-1">resize/1</seealso>, <seealso marker="#size-1">size/1</seealso>.</p>
</desc></func>
<func>
-<name>sparse_to_list(Array::array()) -&gt; list()</name>
+<name name="sparse_to_list" arity="1"/>
<fsummary>Converts the array to a list, skipping default-valued entries.</fsummary>
<desc><marker id="sparse_to_list-1"/>
@@ -446,7 +449,7 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#to_list-1">to_list/1</seealso>.</p>
</desc></func>
<func>
-<name>sparse_to_orddict(Array::array()) -&gt; [{Index::integer(), Value::term()}]</name>
+<name name="sparse_to_orddict" arity="1"/>
<fsummary>Convert the array to an ordered list of pairs {Index, Value},
skipping default-valued entries.</fsummary>
@@ -458,7 +461,7 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#to_orddict-1">to_orddict/1</seealso>.</p>
</desc></func>
<func>
-<name>to_list(Array::array()) -&gt; list()</name>
+<name name="to_list" arity="1"/>
<fsummary>Converts the array to a list.</fsummary>
<desc><marker id="to_list-1"/>
@@ -468,7 +471,7 @@ cannot be changed once the array has been created.</p>
<p><em>See also:</em> <seealso marker="#from_list-2">from_list/2</seealso>, <seealso marker="#sparse_to_list-1">sparse_to_list/1</seealso>.</p>
</desc></func>
<func>
-<name>to_orddict(Array::array()) -&gt; [{Index::integer(), Value::term()}]</name>
+<name name="to_orddict" arity="1"/>
<fsummary>Convert the array to an ordered list of pairs {Index, Value}.</fsummary>
<desc><marker id="to_orddict-1"/>
diff --git a/lib/stdlib/doc/src/base64.xml b/lib/stdlib/doc/src/base64.xml
index d3fd7a843b..bfe8494a73 100644
--- a/lib/stdlib/doc/src/base64.xml
+++ b/lib/stdlib/doc/src/base64.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2007</year><year>2009</year>
+ <year>2007</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -33,32 +33,33 @@
<description>
<p>Implements base 64 encode and decode, see RFC2045. </p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="ascii_string"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>encode(Data) -> Base64 </name>
- <name>encode_to_string(Data) -> Base64String</name>
+ <name name="encode" arity="1"/>
+ <name name="encode_to_string" arity="1"/>
<fsummary>Encodes data into base64. </fsummary>
- <type>
- <v>Data = string() | binary()</v>
- <v>Base64 = binary()</v>
- <v>Base64String = string()</v>
- </type>
+ <type variable="Data"/>
+ <type variable="Base64" name_i="1"/>
+ <type variable="Base64String"/>
<desc>
<p>Encodes a plain ASCII string into base64. The result will
be 33% larger than the data.</p>
</desc>
</func>
<func>
- <name>decode(Base64) -> Data</name>
- <name>decode_to_string(Base64) -> DataString</name>
- <name>mime_decode(Base64) -> Data</name>
- <name>mime_decode_to_string(Base64) -> DataString</name>
+ <name name="decode" arity="1"/>
+ <name name="decode_to_string" arity="1"/>
+ <name name="mime_decode" arity="1"/>
+ <name name="mime_decode_to_string" arity="1"/>
<fsummary>Decodes a base64 encoded string to data. </fsummary>
- <type>
- <v>Base64 = string() | binary()</v>
- <v>Data = binary()</v>
- <v>DataString = string()</v>
- </type>
+ <type variable="Base64" name_i="1"/>
+ <type variable="Data" name_i="1"/>
+ <type variable="DataString" name_i="2"/>
<desc>
<p>Decodes a base64 encoded string to plain ASCII. See RFC4648.
<c>mime_decode/1</c> and <c>mime_decode_to_string/1</c>
diff --git a/lib/stdlib/doc/src/beam_lib.xml b/lib/stdlib/doc/src/beam_lib.xml
index adc411e272..013e94c393 100644
--- a/lib/stdlib/doc/src/beam_lib.xml
+++ b/lib/stdlib/doc/src/beam_lib.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2000</year><year>2010</year>
+ <year>2000</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -154,70 +154,78 @@
</section>
</section>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-beam() -> Module | Filename | binary()
- Module = atom()
- Filename = string() | atom()</code>
- <p>Each of the functions described below accept either the module
- name, the filename, or a binary containing the beam module.</p>
- <code type="none">
-chunkdata() = {ChunkId, DataB} | {ChunkName, DataT}
- ChunkId = chunkid()
- DataB = binary()
- {ChunkName, DataT} =
- {abstract_code, AbstractCode}
- | {attributes, [{Attribute, [AttributeValue]}]}
- | {compile_info, [{InfoKey, [InfoValue]}]}
- | {exports, [{Function, Arity}]}
- | {labeled_exports, [{Function, Arity, Label}]}
- | {imports, [{Module, Function, Arity}]}
- | {indexed_imports, [{Index, Module, Function, Arity}]}
- | {locals, [{Function, Arity}]}]}
- | {labeled_locals, [{Function, Arity, Label}]}]}
- | {atoms, [{integer(), atom()}]}
- AbstractCode = {AbstVersion, Forms} | no_abstract_code
- AbstVersion = atom()
- Attribute = atom()
- AttributeValue = term()
- Module = Function = atom()
- Arity = int()
- Label = int()</code>
- <p>It is not checked that the forms conform to the abstract format
- indicated by <c>AbstVersion</c>. <c>no_abstract_code</c> means
- that the <c>"Abst"</c> chunk is present, but empty.</p>
- <p>The list of attributes is sorted on <c>Attribute</c>, and each
- attribute name occurs once in the list. The attribute values
- occur in the same order as in the file. The lists of functions
- are also sorted.</p>
- <code type="none">
-chunkid() = "Abst" | "Attr" | "CInf"
- | "ExpT" | "ImpT" | "LocT"
- | "Atom"
+ <datatypes>
+ <datatype>
+ <name name="beam"/>
+ <desc>
+ <p>Each of the functions described below accept either the
+ module name, the filename, or a binary containing the beam
+ module.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="chunkdata"/>
+ <desc>
+ <p>The list of attributes is sorted on <c>Attribute</c>
+ (in attrib_entry()), and each
+ attribute name occurs once in the list. The attribute values
+ occur in the same order as in the file. The lists of functions
+ are also sorted.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="chunkid"/>
+ <desc>
+ <p>"Abst" | "Attr" | "CInf" | "ExpT" | "ImpT" | "LocT" | "Atom"</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="dataB"/>
+ </datatype>
+ <datatype>
+ <name name="abst_code"/>
+ <desc>
+ <p>It is not checked that the forms conform to the abstract format
+ indicated by <c><anno>AbstVersion</anno></c>. <c>no_abstract_code</c> means
+ that the <c>"Abst"</c> chunk is present, but empty.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="forms"/>
+ </datatype>
+ <datatype>
+ <name name="compinfo_entry"/>
+ </datatype>
+ <datatype>
+ <name name="attrib_entry"/>
+ </datatype>
+ <datatype>
+ <name name="labeled_entry"/>
+ </datatype>
+ <datatype>
+ <name name="index"/>
+ </datatype>
+ <datatype>
+ <name name="label"/>
+ </datatype>
+ <datatype>
+ <name name="chunkref"/>
+ </datatype>
+ <datatype>
+ <name name="chunkname"/>
+ </datatype>
+ <datatype>
+ <name name="chnk_rsn"/>
+ </datatype>
+ <datatype>
+ <name name="info_rsn"/>
+ </datatype>
+ </datatypes>
-chunkname() = abstract_code | attributes | compile_info
- | exports | labeled_exports
- | imports | indexed_imports
- | locals | labeled_locals
- | atoms
-
-chunkref() = chunkname() | chunkid()</code>
- </section>
<funcs>
<func>
- <name>chunks(Beam, [ChunkRef]) -> {ok, {Module, [ChunkData]}} | {error, beam_lib, Reason}</name>
+ <name name="chunks" arity="2"/>
<fsummary>Read selected chunks from a BEAM file or binary</fsummary>
- <type>
- <v>Beam = beam()</v>
- <v>ChunkRef = chunkref()</v>
- <v>Module = atom()</v>
- <v>ChunkData = chunkdata()</v>
- <v>Reason = {unknown_chunk, Filename, atom()}</v>
- <v>&nbsp;&nbsp;| {key_missing_or_invalid, Filename, abstract_code}</v>
- <v>&nbsp;&nbsp;| Reason1 -- see info/1</v>
- <v>&nbsp;Filename = string()</v>
- </type>
<desc>
<p>Reads chunk data for selected chunks refs. The order of
the returned list of chunk data is determined by the order
@@ -225,43 +233,26 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>chunks(Beam, [ChunkRef], [Option]) -> {ok, {Module, [ChunkResult]}} | {error, beam_lib, Reason}</name>
+ <name name="chunks" arity="3"/>
<fsummary>Read selected chunks from a BEAM file or binary</fsummary>
- <type>
- <v>Beam = beam()</v>
- <v>ChunkRef = chunkref()</v>
- <v>Module = atom()</v>
- <v>Option = allow_missing_chunks</v>
- <v>ChunkResult = {chunkref(), ChunkContents} | {chunkref(), missing_chunk}</v>
- <v>Reason = {missing_chunk, Filename, atom()}</v>
- <v>&nbsp;&nbsp;| {key_missing_or_invalid, Filename, abstract_code}</v>
- <v>&nbsp;&nbsp;| Reason1 -- see info/1</v>
- <v>&nbsp;Filename = string()</v>
- </type>
<desc>
<p>Reads chunk data for selected chunks refs. The order of
the returned list of chunk data is determined by the order
of the list of chunks references.</p>
- <p>By default, if any requested chunk is missing in <c>Beam</c>,
+ <p>By default, if any requested chunk is missing in <c><anno>Beam</anno></c>,
an <c>error</c> tuple is returned.
However, if the option <c>allow_missing_chunks</c> has been given,
a result will be returned even if chunks are missing.
In the result list, any missing chunks will be represented as
- <c>{ChunkRef,missing_chunk}</c>.
+ <c>{<anno>ChunkRef</anno>,missing_chunk}</c>.
Note, however, that if the <c>"Atom"</c> chunk if missing, that is
considered a fatal error and the return value will be an <c>error</c>
tuple.</p>
</desc>
</func>
<func>
- <name>version(Beam) -> {ok, {Module, [Version]}} | {error, beam_lib, Reason}</name>
+ <name name="version" arity="1"/>
<fsummary>Read the BEAM file's module version</fsummary>
- <type>
- <v>Beam = beam()</v>
- <v>Module = atom()</v>
- <v>Version = term()</v>
- <v>Reason -- see chunks/2</v>
- </type>
<desc>
<p>Returns the module version(s). A version is defined by
the module attribute <c>-vsn(Vsn)</c>. If this attribute is
@@ -282,51 +273,30 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>md5(Beam) -> {ok, {Module, MD5}} | {error, beam_lib, Reason}</name>
+ <name name="md5" arity="1"/>
<fsummary>Read the BEAM file's module version</fsummary>
- <type>
- <v>Beam = beam()</v>
- <v>Module = atom()</v>
- <v>MD5 = binary()</v>
- <v>Reason -- see chunks/2</v>
- </type>
<desc>
<p>Calculates an MD5 redundancy check for the code of the module
(compilation date and other attributes are not included).</p>
</desc>
</func>
<func>
- <name>info(Beam) -> [{Item, Info}] | {error, beam_lib, Reason1}</name>
+ <name name="info" arity="1"/>
<fsummary>Information about a BEAM file</fsummary>
- <type>
- <v>Beam = beam()</v>
- <v>Item, Info -- see below</v>
- <v>Reason1 = {chunk_too_big, Filename, ChunkId, ChunkSize, FileSize}</v>
- <v>&nbsp;&nbsp;| {invalid_beam_file, Filename, Pos}</v>
- <v>&nbsp;&nbsp;| {invalid_chunk, Filename, ChunkId}</v>
- <v>&nbsp;&nbsp;| {missing_chunk, Filename, ChunkId}</v>
- <v>&nbsp;&nbsp;| {not_a_beam_file, Filename}</v>
- <v>&nbsp;&nbsp;| {file_error, Filename, Posix}</v>
- <v>&nbsp;Filename = string()</v>
- <v>&nbsp;ChunkId = chunkid()</v>
- <v>&nbsp;ChunkSize = FileSize = int()</v>
- <v>&nbsp;Pos = int()</v>
- <v>&nbsp;Posix = posix() -- see file(3)</v>
- </type>
<desc>
<p>Returns a list containing some information about a BEAM file
as tuples <c>{Item, Info}</c>:</p>
<taglist>
- <tag><c>{file, Filename} | {binary, Binary}</c></tag>
+ <tag><c>{file, <anno>Filename</anno>} | {binary, <anno>Binary</anno>}</c></tag>
<item>
<p>The name (string) of the BEAM file, or the binary from
which the information was extracted.</p>
</item>
- <tag><c>{module, Module}</c></tag>
+ <tag><c>{module, <anno>Module</anno>}</c></tag>
<item>
<p>The name (atom) of the module.</p>
</item>
- <tag><c>{chunks, [{ChunkId, Pos, Size}]}</c></tag>
+ <tag><c>{chunks, [{<anno>ChunkId</anno>, <anno>Pos</anno>, <anno>Size</anno>}]}</c></tag>
<item>
<p>For each chunk, the identifier (string) and the position
and size of the chunk data, in bytes.</p>
@@ -335,17 +305,9 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>cmp(Beam1, Beam2) -> ok | {error, beam_lib, Reason}</name>
+ <name name="cmp" arity="2"/>
<fsummary>Compare two BEAM files</fsummary>
- <type>
- <v>Beam1 = Beam2 = beam()</v>
- <v>Reason = {modules_different, Module1, Module2}</v>
- <v>&nbsp;&nbsp;| {chunks_different, ChunkId}</v>
- <v>&nbsp;&nbsp;| different_chunks</v>
- <v>&nbsp;&nbsp;| Reason1 -- see info/1</v>
- <v>&nbsp;Module1 = Module2 = atom()</v>
- <v>&nbsp;ChunkId = chunkid()</v>
- </type>
+ <type name="cmp_rsn"/>
<desc>
<p>Compares the contents of two BEAM files. If the module names
are the same, and all chunks except for the <c>"CInf"</c> chunk
@@ -356,34 +318,23 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>cmp_dirs(Dir1, Dir2) -> {Only1, Only2, Different} | {error, beam_lib, Reason1}</name>
+ <name name="cmp_dirs" arity="2"/>
<fsummary>Compare the BEAM files in two directories</fsummary>
- <type>
- <v>Dir1 = Dir2 = string() | atom()</v>
- <v>Different = [{Filename1, Filename2}]</v>
- <v>Only1 = Only2 = [Filename]</v>
- <v>Filename = Filename1 = Filename2 = string()</v>
- <v>Reason1 = {not_a_directory, term()} | -- see info/1</v>
- </type>
<desc>
<p>The <c>cmp_dirs/2</c> function compares the BEAM files in
two directories. Only files with extension <c>".beam"</c> are
- compared. BEAM files that exist in directory <c>Dir1</c>
- (<c>Dir2</c>) only are returned in <c>Only1</c>
- (<c>Only2</c>). BEAM files that exist on both directories but
+ compared. BEAM files that exist in directory <c><anno>Dir1</anno></c>
+ (<c><anno>Dir2</anno></c>) only are returned in <c><anno>Only1</anno></c>
+ (<c><anno>Only2</anno></c>). BEAM files that exist on both directories but
are considered different by <c>cmp/2</c> are returned as
- pairs {<c>Filename1</c>, <c>Filename2</c>} where
- <c>Filename1</c> (<c>Filename2</c>) exists in directory
- <c>Dir1</c> (<c>Dir2</c>).</p>
+ pairs {<c><anno>Filename1</anno></c>, <c><anno>Filename2</anno></c>} where
+ <c><anno>Filename1</anno></c> (<c><anno>Filename2</anno></c>) exists in directory
+ <c><anno>Dir1</anno></c> (<c><anno>Dir2</anno></c>).</p>
</desc>
</func>
<func>
- <name>diff_dirs(Dir1, Dir2) -> ok | {error, beam_lib, Reason1}</name>
+ <name name="diff_dirs" arity="2"/>
<fsummary>Compare the BEAM files in two directories</fsummary>
- <type>
- <v>Dir1 = Dir2 = string() | atom()</v>
- <v>Reason1 = {not_a_directory, term()} | -- see info/1</v>
- </type>
<desc>
<p>The <c>diff_dirs/2</c> function compares the BEAM files in
two directories the way <c>cmp_dirs/2</c> does, but names of
@@ -392,13 +343,8 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>strip(Beam1) -> {ok, {Module, Beam2}} | {error, beam_lib, Reason1}</name>
+ <name name="strip" arity="1"/>
<fsummary>Removes chunks not needed by the loader from a BEAM file</fsummary>
- <type>
- <v>Beam1 = Beam2 = beam()</v>
- <v>Module = atom()</v>
- <v>Reason1 -- see info/1</v>
- </type>
<desc>
<p>The <c>strip/1</c> function removes all chunks from a BEAM
file except those needed by the loader. In particular,
@@ -406,15 +352,8 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>strip_files(Files) -> {ok, [{Module, Beam2}]} | {error, beam_lib, Reason1}</name>
+ <name name="strip_files" arity="1"/>
<fsummary>Removes chunks not needed by the loader from BEAM files</fsummary>
- <type>
- <v>Files = [Beam1]</v>
- <v>&nbsp;Beam1 = beam()</v>
- <v>Module = atom()</v>
- <v>Beam2 = beam()</v>
- <v>Reason1 -- see info/1</v>
- </type>
<desc>
<p>The <c>strip_files/1</c> function removes all chunks except
those needed by the loader from BEAM files. In particular,
@@ -424,30 +363,20 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>strip_release(Dir) -> {ok, [{Module, Filename]}} | {error, beam_lib, Reason1}</name>
+ <name name="strip_release" arity="1"/>
<fsummary>Removes chunks not needed by the loader from all BEAM files of a release</fsummary>
- <type>
- <v>Dir = string() | atom()</v>
- <v>Module = atom()</v>
- <v>Filename = string()</v>
- <v>Reason1 = {not_a_directory, term()} | -- see info/1</v>
- </type>
<desc>
<p>The <c>strip_release/1</c> function removes all chunks
except those needed by the loader from the BEAM files of a
- release. <c>Dir</c> should be the installation root
+ release. <c><anno>Dir</anno></c> should be the installation root
directory. For example, the current OTP release can be
stripped with the call
<c>beam_lib:strip_release(code:root_dir())</c>.</p>
</desc>
</func>
<func>
- <name>format_error(Reason) -> Chars</name>
+ <name name="format_error" arity="1"/>
<fsummary>Return an English description of a BEAM read error reply</fsummary>
- <type>
- <v>Reason -- see other functions</v>
- <v>Chars = [char() | Chars]</v>
- </type>
<desc>
<p>Given the error returned by any function in this module,
the function <c>format_error</c> returns a descriptive string
@@ -456,12 +385,11 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>crypto_key_fun(CryptoKeyFun) -> ok | {error, Reason}</name>
+ <name name="crypto_key_fun" arity="1"/>
<fsummary>Register a fun that provides a crypto key</fsummary>
- <type>
- <v>CryptoKeyFun = fun() -- see below</v>
- <v>Reason = badfun | exists | term()</v>
- </type>
+ <type name="crypto_fun"/>
+ <type name="crypto_fun_arg"/>
+ <type name="mode"/>
<desc>
<p>The <c>crypto_key_fun/1</c> function registers a unary fun
that will be called if <c>beam_lib</c> needs to read an
@@ -495,11 +423,8 @@ chunkref() = chunkname() | chunkid()</code>
</desc>
</func>
<func>
- <name>clear_crypto_key_fun() -> {ok, Result}</name>
+ <name name="clear_crypto_key_fun" arity="0"/>
<fsummary>Unregister the current crypto key fun</fsummary>
- <type>
- <v>Result = undefined | term()</v>
- </type>
<desc>
<p>Unregisters the crypto key fun and terminates the process
holding it, started by <c>crypto_key_fun/1</c>.</p>
diff --git a/lib/stdlib/doc/src/binary.xml b/lib/stdlib/doc/src/binary.xml
index c81023862e..88ce77e0d0 100644
--- a/lib/stdlib/doc/src/binary.xml
+++ b/lib/stdlib/doc/src/binary.xml
@@ -5,7 +5,7 @@
<header>
<copyright>
<year>2009</year>
- <year>2010</year>
+ <year>2011</year>
<holder>Ericsson AB, All Rights Reserved</holder>
</copyright>
<legalnotice>
@@ -53,37 +53,35 @@
module.
</p>
</note>
-
-
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
- cp()
- - Opaque data-type representing a compiled search-pattern. Guaranteed to be a tuple()
- to allow programs to distinguish it from non precompiled search patterns.
- </code>
- <code type="none">
- part() = {Start,Length}
- Start = int()
- Length = int()
- - A representaion of a part (or range) in a binary. Start is a
+ <datatypes>
+ <datatype>
+ <name name="cp"/>
+ <desc><p>Opaque data-type representing a compiled
+ search-pattern. Guaranteed to be a tuple() to allow programs to
+ distinguish it from non precompiled search patterns.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="part"/>
+ <desc><p>A representaion of a part (or range) in a binary. Start is a
zero-based offset into a binary() and Length is the length of
that part. As input to functions in this module, a reverse
part specification is allowed, constructed with a negative
Length, so that the part of the binary begins at Start +
Length and is -Length long. This is useful for referencing the
last N bytes of a binary as {size(Binary), -N}. The functions
- in this module always return part()'s with positive Length.
- </code>
- </section>
+ in this module always return part()'s with positive Length.</p>
+ </desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>at(Subject, Pos) -> int()</name>
+ <name>at(Subject, Pos) -> byte()</name>
<fsummary>Returns the byte at a specific position in a binary</fsummary>
<type>
<v>Subject = binary()</v>
- <v>Pos = int() >= 0</v>
+ <v>Pos = integer() >= 0</v>
</type>
<desc>
@@ -95,7 +93,7 @@
</desc>
</func>
<func>
- <name>bin_to_list(Subject) -> list()</name>
+ <name>bin_to_list(Subject) -> [byte()]</name>
<fsummary>Convert a binary to a list of integers</fsummary>
<type>
<v>Subject = binary()</v>
@@ -105,7 +103,7 @@
</desc>
</func>
<func>
- <name>bin_to_list(Subject, PosLen) -> list()</name>
+ <name>bin_to_list(Subject, PosLen) -> [byte()]</name>
<fsummary>Convert a binary to a list of integers</fsummary>
<type>
<v>Subject = binary()</v>
@@ -113,7 +111,7 @@
</type>
<desc>
- <p>Converts <c>Subject</c> to a list of <c>int()</c>s, each representing
+ <p>Converts <c>Subject</c> to a list of <c>byte()</c>s, each representing
the value of one byte. The <c>part()</c> denotes which part of the
<c>binary()</c> to convert. Example:</p>
@@ -126,12 +124,12 @@
</desc>
</func>
<func>
- <name>bin_to_list(Subject, Pos, Len) -> list()</name>
+ <name>bin_to_list(Subject, Pos, Len) -> [byte()]</name>
<fsummary>Convert a binary to a list of integers</fsummary>
<type>
<v>Subject = binary()</v>
- <v>Pos = int()</v>
- <v>Len = int()</v>
+ <v>Pos = integer() >= 0</v>
+ <v>Len = integer() >= 0</v>
</type>
<desc>
<p>The same as<c> bin_to_list(Subject,{Pos,Len})</c>.</p>
@@ -185,7 +183,7 @@
<fsummary>Duplicates a binary N times and creates a new</fsummary>
<type>
<v>Subject = binary()</v>
- <v>N = int() >= 0</v>
+ <v>N = integer() >= 0</v>
</type>
<desc>
<p>Creates a binary with the content of <c>Subject</c> duplicated <c>N</c> times.</p>
@@ -211,7 +209,7 @@
<fsummary>Decode a whole binary into an integer of arbitrary size</fsummary>
<type>
<v>Subject = binary()</v>
- <v>Unsigned = int() >= 0</v>
+ <v>Unsigned = integer() >= 0</v>
</type>
<desc>
<p>The same as <c>decode_unsigned(Subject,big)</c>.</p>
@@ -223,12 +221,12 @@
<type>
<v>Subject = binary()</v>
<v>Endianess = big | little</v>
- <v>Unsigned = int() >= 0</v>
+ <v>Unsigned = integer() >= 0</v>
</type>
<desc>
<p>Converts the binary digit representation, in big or little
- endian, of a positive integer in <c>Subject</c> to an Erlang <c>int()</c>.</p>
+ endian, of a positive integer in <c>Subject</c> to an Erlang <c>integer()</c>.</p>
<p>Example:</p>
@@ -242,7 +240,7 @@
<name>encode_unsigned(Unsigned) -> binary()</name>
<fsummary>Encodes an unsigned integer into the minimal binary</fsummary>
<type>
- <v>Unsigned = int() >= 0</v>
+ <v>Unsigned = integer() >= 0</v>
</type>
<desc>
<p>The same as <c>encode_unsigned(Unsigned,big)</c>.</p>
@@ -252,7 +250,7 @@
<name>encode_unsigned(Unsigned,Endianess) -> binary()</name>
<fsummary>Encodes an unsigned integer into the minimal binary</fsummary>
<type>
- <v>Unsigned = int() >= 0</v>
+ <v>Unsigned = integer() >= 0</v>
<v>Endianess = big | little</v>
</type>
<desc>
@@ -270,7 +268,7 @@
</desc>
</func>
<func>
- <name>first(Subject) -> int()</name>
+ <name>first(Subject) -> byte()</name>
<fsummary>Returns the first byte of a binary</fsummary>
<type>
<v>Subject = binary()</v>
@@ -283,7 +281,7 @@
</desc>
</func>
<func>
- <name>last(Subject) -> int()</name>
+ <name>last(Subject) -> byte()</name>
<fsummary>Returns the last byte of a binary</fsummary>
<type>
<v>Subject = binary()</v>
@@ -306,7 +304,7 @@
</desc>
</func>
<func>
- <name>longest_common_prefix(Binaries) -> int()</name>
+ <name>longest_common_prefix(Binaries) -> integer() >= 0</name>
<fsummary>Returns length of longest common prefix for a set of binaries</fsummary>
<type>
<v>Binaries = [ binary() ]</v>
@@ -327,7 +325,7 @@
</desc>
</func>
<func>
- <name>longest_common_suffix(Binaries) -> int()</name>
+ <name>longest_common_suffix(Binaries) -> integer() >= 0</name>
<fsummary>Returns length of longest common suffix for a set of binaries</fsummary>
<type>
<v>Binaries = [ binary() ]</v>
@@ -450,7 +448,7 @@
[{1,4}]
</code>
- <p>The result shows that &lt;&lt;bcde"&gt;&gt; is selected instead of the
+ <p>The result shows that &lt;&lt;"bcde"&gt;&gt; is selected instead of the
shorter match &lt;&lt;"bc"&gt;&gt; (which would have given raise to one
more match,&lt;&lt;"de"&gt;&gt;). This corresponds to the behavior of posix
regular expressions (and programs like awk), but is not
@@ -506,15 +504,15 @@
<fsummary>Extracts a part of a binary</fsummary>
<type>
<v>Subject = binary()</v>
- <v>Pos = int()</v>
- <v>Len = int()</v>
+ <v>Pos = integer() >= 0</v>
+ <v>Len = integer() >= 0</v>
</type>
<desc>
<p>The same as <c>part(Subject, {Pos, Len})</c>.</p>
</desc>
</func>
<func>
- <name>referenced_byte_size(binary()) -> int()</name>
+ <name>referenced_byte_size(binary()) -> integer() >= 0</name>
<fsummary>Determines the size of the actual binary pointed out by a sub-binary</fsummary>
<desc>
@@ -581,42 +579,28 @@ store(Binary, GBSet) ->
</desc>
</func>
<func>
- <name>replace(Subject,Pattern,Replacement) -> Result</name>
+ <name name="replace" arity="3"/>
<fsummary>Replaces bytes in a binary according to a pattern</fsummary>
- <type>
- <v>Subject = binary()</v>
- <v>Pattern = binary() | [ binary() ] | cp()</v>
- <v>Replacement = binary()</v>
- <v>Result = binary()</v>
- </type>
<desc>
- <p>The same as <c>replace(Subject,Pattern,Replacement,[])</c>.</p>
+ <p>The same as <c>replace(<anno>Subject</anno>,<anno>Pattern</anno>,<anno>Replacement</anno>,[])</c>.</p>
</desc>
</func>
<func>
- <name>replace(Subject,Pattern,Replacement,Options) -> Result</name>
+ <name name="replace" arity="4"/>
<fsummary>Replaces bytes in a binary according to a pattern</fsummary>
- <type>
- <v>Subject = binary()</v>
- <v>Pattern = binary() | [ binary() ] | cp()</v>
- <v>Replacement = binary()</v>
- <v>Result = binary()</v>
- <v>Options = [ Option ]</v>
- <v>Option = global | {scope, part()} | {insert_replaced, InsPos}</v>
- <v>InsPos = OnePos | [ OnePos ]</v>
- <v>OnePos = int() =&lt; byte_size(Replacement)</v>
- </type>
+ <type_desc variable="OnePos">An integer() =&lt; byte_size(<anno>Replacement</anno>)
+ </type_desc>
<desc>
<p>Constructs a new binary by replacing the parts in
- <c>Subject</c> matching <c>Pattern</c> with the content of
- <c>Replacement</c>.</p>
+ <c><anno>Subject</anno></c> matching <c><anno>Pattern</anno></c> with the content of
+ <c><anno>Replacement</anno></c>.</p>
- <p>If the matching sub-part of <c>Subject</c> giving raise to the
+ <p>If the matching sub-part of <c><anno>Subject</anno></c> giving raise to the
replacement is to be inserted in the result, the option
- <c>{insert_replaced, InsPos}</c> will insert the matching part into
- <c>Replacement</c> at the given position (or positions) before actually
- inserting <c>Replacement</c> into the <c>Subject</c>. Example:</p>
+ <c>{insert_replaced, <anno>InsPos</anno>}</c> will insert the matching part into
+ <c><anno>Replacement</anno></c> at the given position (or positions) before actually
+ inserting <c><anno>Replacement</anno></c> into the <c><anno>Subject</anno></c>. Example:</p>
<code>
1> binary:replace(&lt;&lt;"abcde"&gt;&gt;,&lt;&lt;"b"&gt;&gt;,&lt;&lt;"[]"&gt;&gt;,[{insert_replaced,1}]).
@@ -632,42 +616,30 @@ store(Binary, GBSet) ->
&lt;&lt;"a[b-b]c[d-d]e"&gt;&gt;
</code>
- <p>If any position given in <c>InsPos</c> is greater than the size of the replacement binary, a <c>badarg</c> exception is raised.</p>
+ <p>If any position given in <c><anno>InsPos</anno></c> is greater than the size of the replacement binary, a <c>badarg</c> exception is raised.</p>
<p>The options <c>global</c> and <c>{scope, part()}</c> work as for <seealso marker="#split-3">split/3</seealso>. The return type is always a <c>binary()</c>.</p>
- <p>For a description of <c>Pattern</c>, see <seealso marker="#compile_pattern-1">compile_pattern/1</seealso>.</p>
+ <p>For a description of <c><anno>Pattern</anno></c>, see <seealso marker="#compile_pattern-1">compile_pattern/1</seealso>.</p>
</desc>
</func>
<func>
- <name>split(Subject,Pattern) -> Parts</name>
+ <name name="split" arity="2"/>
<fsummary>Splits a binary according to a pattern</fsummary>
- <type>
- <v>Subject = binary()</v>
- <v>Pattern = binary() | [ binary() ] | cp()</v>
- <v>Parts = [ binary() ]</v>
- </type>
<desc>
- <p>The same as <c>split(Subject, Pattern, [])</c>.</p>
+ <p>The same as <c>split(<anno>Subject</anno>, <anno>Pattern</anno>, [])</c>.</p>
</desc>
</func>
<func>
- <name>split(Subject,Pattern,Options) -> Parts</name>
+ <name name="split" arity="3"/>
<fsummary>Splits a binary according to a pattern</fsummary>
- <type>
- <v>Subject = binary()</v>
- <v>Pattern = binary() | [ binary() ] | cp()</v>
- <v>Parts = [ binary() ]</v>
- <v>Options = [ Option ]</v>
- <v>Option = {scope, part()} | trim | global</v>
- </type>
<desc>
- <p>Splits Binary into a list of binaries based on Pattern. If
+ <p>Splits <c><anno>Subject</anno></c> into a list of binaries based on <c><anno>Pattern</anno></c>. If
the option global is not given, only the first occurrence of
- Pattern in Subject will give rise to a split.</p>
+ <c><anno>Pattern</anno></c> in <c><anno>Subject</anno></c> will give rise to a split.</p>
- <p>The parts of Pattern actually found in Subject are not included in the result.</p>
+ <p>The parts of <c><anno>Pattern</anno></c> actually found in <c><anno>Subject</anno></c> are not included in the result.</p>
<p>Example:</p>
@@ -696,7 +668,7 @@ store(Binary, GBSet) ->
<tag>global</tag>
- <item><p>Repeats the split until the <c>Subject</c> is
+ <item><p>Repeats the split until the <c><anno>Subject</anno></c> is
exhausted. Conceptually the global option makes split work on
the positions returned by <seealso marker="#matches-3">matches/3</seealso>,
while it normally
@@ -716,12 +688,12 @@ store(Binary, GBSet) ->
</code>
<p>The return type is always a list of binaries that are all
- referencing <c>Subject</c>. This means that the data in <c>Subject</c> is not
- actually copied to new binaries and that <c>Subject</c> cannot be
+ referencing <c><anno>Subject</anno></c>. This means that the data in <c><anno>Subject</anno></c> is not
+ actually copied to new binaries and that <c><anno>Subject</anno></c> cannot be
garbage collected until the results of the split are no longer
referenced.</p>
- <p>For a description of <c>Pattern</c>, see <seealso marker="#compile_pattern-1">compile_pattern/1</seealso>.</p>
+ <p>For a description of <c><anno>Pattern</anno></c>, see <seealso marker="#compile_pattern-1">compile_pattern/1</seealso>.</p>
</desc>
</func>
diff --git a/lib/stdlib/doc/src/c.xml b/lib/stdlib/doc/src/c.xml
index 19e3ac1f08..ddae388a1b 100644
--- a/lib/stdlib/doc/src/c.xml
+++ b/lib/stdlib/doc/src/c.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -39,43 +39,33 @@
</description>
<funcs>
<func>
- <name>bt(Pid) -> void()</name>
+ <name name="bt" arity="1"/>
<fsummary>Stack backtrace for a process</fsummary>
- <type>
- <v>Pid = pid()</v>
- </type>
<desc>
<p>Stack backtrace for a process. Equivalent to
- <c>erlang:process_display(Pid, backtrace)</c>.</p>
+ <c>erlang:process_display(<anno>Pid</anno>, backtrace)</c>.</p>
</desc>
</func>
<func>
- <name>c(File) -> {ok, Module} | error</name>
- <name>c(File, Options) -> {ok, Module} | error</name>
+ <name name="c" arity="1"/>
+ <name name="c" arity="2"/>
<fsummary>Compile and load code in a file</fsummary>
- <type>
- <v>File = name() -- see filename(3)</v>
- <v>Options = [Opt] -- see compile:file/2</v>
- </type>
<desc>
<p><c>c/1,2</c> compiles and then purges and loads the code for
- a file. <c>Options</c> defaults to []. Compilation is
+ a file. <c><anno>Options</anno></c> defaults to []. Compilation is
equivalent to:</p>
<code type="none">
-compile:file(File, Options ++ [report_errors, report_warnings])</code>
+compile:file(<anno>File</anno>, <anno>Options</anno> ++ [report_errors, report_warnings])</code>
<p>Note that purging the code means that any processes
lingering in old code for the module are killed without
warning. See <c>code/3</c> for more information.</p>
</desc>
</func>
<func>
- <name>cd(Dir) -> void()</name>
+ <name name="cd" arity="1"/>
<fsummary>Change working directory</fsummary>
- <type>
- <v>Dir = name() -- see filename(3)</v>
- </type>
<desc>
- <p>Changes working directory to <c>Dir</c>, which may be a
+ <p>Changes working directory to <c><anno>Dir</anno></c>, which may be a
relative name, and then prints the name of the new working
directory.</p>
<pre>
@@ -84,14 +74,14 @@ compile:file(File, Options ++ [report_errors, report_warnings])</code>
</desc>
</func>
<func>
- <name>flush() -> void()</name>
+ <name name="flush" arity="0"/>
<fsummary>Flush any messages sent to the shell</fsummary>
<desc>
<p>Flushes any messages sent to the shell.</p>
</desc>
</func>
<func>
- <name>help() -> void()</name>
+ <name name="help" arity="0"/>
<fsummary>Help information</fsummary>
<desc>
<p>Displays help information: all valid shell internal commands,
@@ -99,8 +89,8 @@ compile:file(File, Options ++ [report_errors, report_warnings])</code>
</desc>
</func>
<func>
- <name>i() -> void()</name>
- <name>ni() -> void()</name>
+ <name name="i" arity="0"/>
+ <name name="ni" arity="0"/>
<fsummary>Information about the system</fsummary>
<desc>
<p><c>i/0</c> displays information about the system, listing
@@ -109,26 +99,20 @@ compile:file(File, Options ++ [report_errors, report_warnings])</code>
</desc>
</func>
<func>
- <name>i(X, Y, Z) -> void()</name>
+ <name name="i" arity="3"/>
<fsummary>Information about pid &lt;X.Y.Z&gt;</fsummary>
- <type>
- <v>X = Y = Z = int()</v>
- </type>
<desc>
<p>Displays information about a process, Equivalent to
- <c>process_info(pid(X, Y, Z))</c>, but location transparent.</p>
+ <c>process_info(pid(<anno>X</anno>, <anno>Y</anno>, <anno>Z</anno>))</c>, but location transparent.</p>
</desc>
</func>
<func>
- <name>l(Module) -> void()</name>
+ <name name="l" arity="1"/>
<fsummary>Load or reload module</fsummary>
- <type>
- <v>Module = atom()</v>
- </type>
<desc>
<p>Purges and loads, or reloads, a module by calling
- <c>code:purge(Module)</c> followed by
- <c>code:load_file(Module)</c>.</p>
+ <c>code:purge(<anno>Module</anno>)</c> followed by
+ <c>code:load_file(<anno>Module</anno>)</c>.</p>
<p>Note that purging the code means that any processes
lingering in old code for the module are killed without
warning. See <c>code/3</c> for more information.</p>
@@ -136,35 +120,33 @@ compile:file(File, Options ++ [report_errors, report_warnings])</code>
</func>
<func>
<name>lc(Files) -> ok</name>
- <fsummary>Compile a list of files</fsummary>
<type>
<v>Files = [File]</v>
- <v>&nbsp;File = name() -- see filename(3)</v>
+ <v>File = <seealso marker="file#type-filename">file:filename()
+ </seealso></v>
</type>
+ <fsummary>Compile a list of files</fsummary>
<desc>
<p>Compiles a list of files by calling <c>compile:file(File, [report_errors, report_warnings])</c> for each <c>File</c>
in <c>Files</c>.</p>
</desc>
</func>
<func>
- <name>ls() -> void()</name>
+ <name name="ls" arity="0"/>
<fsummary>List files in the current directory</fsummary>
<desc>
<p>Lists files in the current directory.</p>
</desc>
</func>
<func>
- <name>ls(Dir) -> void()</name>
+ <name name="ls" arity="1"/>
<fsummary>List files in a directory</fsummary>
- <type>
- <v>Dir = name() -- see filename(3)</v>
- </type>
<desc>
- <p>Lists files in directory <c>Dir</c>.</p>
+ <p>Lists files in directory <c><anno>Dir</anno></c>.</p>
</desc>
</func>
<func>
- <name>m() -> void()</name>
+ <name name="m" arity="0"/>
<fsummary>Which modules are loaded</fsummary>
<desc>
<p>Displays information about the loaded modules, including
@@ -172,84 +154,67 @@ compile:file(File, Options ++ [report_errors, report_warnings])</code>
</desc>
</func>
<func>
- <name>m(Module) -> void()</name>
+ <name name="m" arity="1"/>
<fsummary>Information about a module</fsummary>
- <type>
- <v>Module = atom()</v>
- </type>
<desc>
- <p>Displays information about <c>Module</c>.</p>
+ <p>Displays information about <c><anno>Module</anno></c>.</p>
</desc>
</func>
<func>
- <name>memory() -> [{Type, Size}]</name>
+ <name name="memory" arity="0"/>
<fsummary>Memory allocation information</fsummary>
- <type>
- <v>Type, Size -- see erlang:memory/0</v>
- </type>
<desc>
<p>Memory allocation information. Equivalent to
- <c>erlang:memory/0</c>.</p>
+ <seealso marker="erts:erlang#memory/0"><c>erlang:memory/0</c>
+ </seealso>.</p>
</desc>
</func>
<func>
- <name>memory(Type) -> Size</name>
- <name>memory([Type]) -> [{Type, Size}]</name>
+ <name name="memory" arity="1" clause_i="1"/>
+ <name name="memory" arity="1" clause_i="2"/>
<fsummary>Memory allocation information</fsummary>
- <type>
- <v>Type, Size -- see erlang:memory/0</v>
- </type>
<desc>
<p>Memory allocation information. Equivalent to
- <c>erlang:memory/1</c>.</p>
+ <seealso marker="erts:erlang#memory/1"><c>erlang:memory/1</c>
+ </seealso>.</p>
</desc>
</func>
<func>
- <name>nc(File) -> {ok, Module} | error</name>
- <name>nc(File, Options) -> {ok, Module} | error</name>
+ <name name="nc" arity="1"/>
+ <name name="nc" arity="2"/>
<fsummary>Compile and load code in a file on all nodes</fsummary>
- <type>
- <v>File = name() -- see filename(3)</v>
- <v>Options = [Opt] -- see compile:file/2</v>
- </type>
<desc>
<p>Compiles and then loads the code for a file on all nodes.
- <c>Options</c> defaults to []. Compilation is equivalent to:</p>
+ <c><anno>Options</anno></c> defaults to []. Compilation is equivalent to:</p>
<code type="none">
-compile:file(File, Opts ++ [report_errors, report_warnings])</code>
+compile:file(<anno>File</anno>, <anno>Options</anno> ++ [report_errors, report_warnings])</code>
</desc>
</func>
<func>
- <name>nl(Module) -> void()</name>
+ <name name="nl" arity="1"/>
<fsummary>Load module on all nodes</fsummary>
- <type>
- <v>Module = atom()</v>
- </type>
<desc>
- <p>Loads <c>Module</c> on all nodes.</p>
+ <p>Loads <c><anno>Module</anno></c> on all nodes.</p>
</desc>
</func>
<func>
- <name>pid(X, Y, Z) -> pid()</name>
+ <name name="pid" arity="3"/>
<fsummary>Convert X,Y,Z to a pid</fsummary>
- <type>
- <v>X = Y = Z = int()</v>
- </type>
<desc>
- <p>Converts <c>X</c>, <c>Y</c>, <c>Z</c> to the pid
+ <p>Converts <c><anno>X</anno></c>, <c><anno>Y</anno></c>, <c><anno>Z</anno></c> to the pid
<c><![CDATA[<X.Y.Z>]]></c>. This function should only be used when
debugging.</p>
</desc>
</func>
<func>
- <name>pwd() -> void()</name>
+ <name name="pwd" arity="0"/>
<fsummary>Print working directory</fsummary>
<desc>
<p>Prints the name of the working directory.</p>
</desc>
</func>
<func>
- <name>q() -> void()</name>
+ <name name="q" arity="0"/>
<fsummary>Quit - shorthand for <c>init:stop()</c></fsummary>
<desc>
<p>This function is shorthand for <c>init:stop()</c>, that is,
@@ -257,8 +222,8 @@ compile:file(File, Opts ++ [report_errors, report_warnings])</code>
</desc>
</func>
<func>
- <name>regs() -> void()</name>
- <name>nregs() -> void()</name>
+ <name name="regs" arity="0"/>
+ <name name="nregs" arity="0"/>
<fsummary>Information about registered processes</fsummary>
<desc>
<p><c>regs/0</c> displays information about all registered
diff --git a/lib/stdlib/doc/src/calendar.xml b/lib/stdlib/doc/src/calendar.xml
index 075c7f9c78..4876b37127 100644
--- a/lib/stdlib/doc/src/calendar.xml
+++ b/lib/stdlib/doc/src/calendar.xml
@@ -73,100 +73,125 @@
week number.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-date() = {Year, Month, Day}
- Year = int()
- Month = 1..12
- Day = 1..31
-Year cannot be abbreviated. Example: 93 denotes year 93, not 1993.
-Valid range depends on the underlying OS.
-The date tuple must denote a valid date.
+ <datatypes>
+ <datatype>
+ <name name="t_datetime"/>
+ </datatype>
+ <datatype>
+ <name name="t_datetime1970"/>
+ </datatype>
+ <datatype>
+ <name name="t_date"/>
+ </datatype>
+ <datatype>
+ <name name="year"/>
+ <desc><p>Year cannot be abbreviated. Example: 93 denotes year
+ 93, not 1993. Valid range depends on the underlying OS. The
+ date tuple must denote a valid date.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="year1970"/>
+ </datatype>
+ <datatype>
+ <name name="month"/>
+ </datatype>
+ <datatype>
+ <name name="day"/>
+ </datatype>
+ <datatype>
+ <name name="t_time"/>
+ </datatype>
+ <datatype>
+ <name name="hour"/>
+ </datatype>
+ <datatype>
+ <name name="minute"/>
+ </datatype>
+ <datatype>
+ <name name="second"/>
+ </datatype>
+ <datatype>
+ <name name="daynum"/>
+ </datatype>
+ <datatype>
+ <name name="ldom"/>
+ </datatype>
+ <datatype>
+ <name name="t_now"/>
+ <desc><p>See <seealso marker="erts:erlang#now/0">erlang:now/0</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="t_yearweeknum"/>
+ </datatype>
+ <datatype>
+ <name name="weeknum"/>
+ </datatype>
+ </datatypes>
-time() = {Hour, Minute, Second}
- Hour = 0..23
- Minute = Second = 0..59</code>
- </section>
<funcs>
<func>
- <name>date_to_gregorian_days(Date) -> Days</name>
- <name>date_to_gregorian_days(Year, Month, Day) -> Days</name>
+ <name name="date_to_gregorian_days" arity="1"/>
+ <name name="date_to_gregorian_days" arity="3"/>
+ <type variable="Date" name_i="1"/>
+ <type variable="Year"/>
+ <type variable="Month"/>
+ <type variable="Day"/>
<fsummary>Compute the number of days from year 0 up to the given date</fsummary>
- <type>
- <v>Date = date()</v>
- <v>Days = int()</v>
- </type>
<desc>
<p>This function computes the number of gregorian days starting
with year 0 and ending at the given date.</p>
</desc>
</func>
<func>
- <name>datetime_to_gregorian_seconds({Date, Time}) -> Seconds</name>
+ <name name="datetime_to_gregorian_seconds" arity="1"/>
<fsummary>Compute the number of seconds from year 0 up to the given date and time</fsummary>
- <type>
- <v>Date = date()</v>
- <v>Time = time()</v>
- <v>Seconds = int()</v>
- </type>
<desc>
<p>This function computes the number of gregorian seconds
starting with year 0 and ending at the given date and time.</p>
</desc>
</func>
<func>
- <name>day_of_the_week(Date) -> DayNumber</name>
- <name>day_of_the_week(Year, Month, Day) -> DayNumber</name>
+ <name name="day_of_the_week" arity="1"/>
+ <name name="day_of_the_week" arity="3"/>
<fsummary>Compute the day of the week</fsummary>
- <type>
- <v>Date = date()</v>
- <v>DayNumber = 1..7</v>
- </type>
+ <type variable="Date" name_i="1"/>
+ <type variable="Year"/>
+ <type variable="Month"/>
+ <type variable="Day"/>
<desc>
- <p>This function computes the day of the week given <c>Year</c>,
- <c>Month</c> and <c>Day</c>. The return value denotes the day
+ <p>This function computes the day of the week given <c><anno>Year</anno></c>,
+ <c><anno>Month</anno></c> and <c><anno>Day</anno></c>. The return value denotes the day
of the week as <c>1</c>: Monday, <c>2</c>: Tuesday, and so on.</p>
</desc>
</func>
<func>
- <name>gregorian_days_to_date(Days) -> Date</name>
+ <name name="gregorian_days_to_date" arity="1"/>
<fsummary>Compute the date given the number of gregorian days</fsummary>
- <type>
- <v>Days = int()</v>
- <v>Date = date()</v>
- </type>
<desc>
<p>This function computes the date given the number of
gregorian days.</p>
</desc>
</func>
<func>
- <name>gregorian_seconds_to_datetime(Seconds) -> {Date, Time}</name>
+ <name name="gregorian_seconds_to_datetime" arity="1"/>
<fsummary>Compute the date given the number of gregorian days</fsummary>
- <type>
- <v>Seconds = int()</v>
- <v>Date = date()</v>
- <v>Time = time()</v>
- </type>
<desc>
<p>This function computes the date and time from the given
number of gregorian seconds.</p>
</desc>
</func>
<func>
- <name>is_leap_year(Year) -> bool()</name>
+ <name name="is_leap_year" arity="1"/>
<fsummary>Check if a year is a leap year</fsummary>
<desc>
<p>This function checks if a year is a leap year.</p>
</desc>
</func>
<func>
- <name>iso_week_number() -> IsoWeekNumber</name>
+ <name name="iso_week_number" arity="0"/>
<fsummary>Compute the iso week number for the actual date</fsummary>
- <type>
- <v>IsoWeekNumber = {int(), int()}</v>
- </type>
<desc>
<p>This function returns the tuple {Year, WeekNum} representing
the iso week number for the actual date. For determining the
@@ -174,42 +199,34 @@ time() = {Hour, Minute, Second}
</desc>
</func>
<func>
- <name>iso_week_number(Date) -> IsoWeekNumber</name>
+ <name name="iso_week_number" arity="1"/>
<fsummary>Compute the iso week number for the given date</fsummary>
- <type>
- <v>Date = date()</v>
- <v>IsoWeekNumber = {int(), int()}</v>
- </type>
<desc>
<p>This function returns the tuple {Year, WeekNum} representing
the iso week number for the given date.</p>
</desc>
</func>
<func>
- <name>last_day_of_the_month(Year, Month) -> int()</name>
+ <name name="last_day_of_the_month" arity="2"/>
<fsummary>Compute the number of days in a month</fsummary>
<desc>
<p>This function computes the number of days in a month.</p>
</desc>
</func>
<func>
- <name>local_time() -> {Date, Time}</name>
+ <name name="local_time" arity="0"/>
<fsummary>Compute local time</fsummary>
- <type>
- <v>Date = date()</v>
- <v>Time = time()</v>
- </type>
<desc>
<p>This function returns the local time reported by
the underlying operating system.</p>
</desc>
</func>
<func>
- <name>local_time_to_universal_time({Date1, Time1}) -> {Date2, Time2}</name>
+ <name name="local_time_to_universal_time" arity="1"/>
<fsummary>Convert from local time to universal time (deprecated)</fsummary>
<desc>
<p>This function converts from local time to Universal
- Coordinated Time (UTC). <c>Date1</c> must refer to a local
+ Coordinated Time (UTC). <c><anno>DateTime1</anno></c> must refer to a local
date after Jan 1, 1970.</p>
<warning>
<p>This function is deprecated. Use
@@ -222,15 +239,11 @@ time() = {Hour, Minute, Second}
</desc>
</func>
<func>
- <name>local_time_to_universal_time_dst({Date1, Time1}) -> [{Date, Time}]</name>
+ <name name="local_time_to_universal_time_dst" arity="1"/>
<fsummary>Convert from local time to universal time(s)</fsummary>
- <type>
- <v>Date1 = Date = date()</v>
- <v>Time1 = Time = time()</v>
- </type>
<desc>
<p>This function converts from local time to Universal
- Coordinated Time (UTC). <c>Date1</c> must refer to a local
+ Coordinated Time (UTC). <c><anno>DateTime1</anno></c> must refer to a local
date after Jan 1, 1970.</p>
<p>The return value is a list of 0, 1 or 2 possible UTC times:</p>
<taglist>
@@ -258,65 +271,48 @@ time() = {Hour, Minute, Second}
</desc>
</func>
<func>
- <name>now_to_local_time(Now) -> {Date, Time}</name>
+ <name name="now_to_local_time" arity="1"/>
<fsummary>Convert now to local date and time</fsummary>
- <type>
- <v>Now -- see erlang:now/0</v>
- <v>Date = date()</v>
- <v>Time = time()</v>
- </type>
<desc>
<p>This function returns local date and time converted from
the return value from <c>erlang:now()</c>.</p>
</desc>
</func>
<func>
- <name>now_to_universal_time(Now) -> {Date, Time}</name>
- <name>now_to_datetime(Now) -> {Date, Time}</name>
+ <name name="now_to_universal_time" arity="1"/>
+ <name name="now_to_datetime" arity="1"/>
<fsummary>Convert now to date and time</fsummary>
- <type>
- <v>Now -- see erlang:now/0</v>
- <v>Date = date()</v>
- <v>Time = time()</v>
- </type>
<desc>
<p>This function returns Universal Coordinated Time (UTC)
converted from the return value from <c>erlang:now()</c>.</p>
</desc>
</func>
<func>
- <name>seconds_to_daystime(Seconds) -> {Days, Time}</name>
+ <name name="seconds_to_daystime" arity="1"/>
<fsummary>Compute days and time from seconds</fsummary>
- <type>
- <v>Seconds = Days = int()</v>
- <v>Time = time()</v>
- </type>
<desc>
<p>This function transforms a given number of seconds into days,
- hours, minutes, and seconds. The <c>Time</c> part is always
- non-negative, but <c>Days</c> is negative if the argument
- <c>Seconds</c> is.</p>
+ hours, minutes, and seconds. The <c><anno>Time</anno></c> part is always
+ non-negative, but <c><anno>Days</anno></c> is negative if the argument
+ <c><anno>Seconds</anno></c> is.</p>
</desc>
</func>
<func>
- <name>seconds_to_time(Seconds) -> Time</name>
+ <name name="seconds_to_time" arity="1"/>
<fsummary>Compute time from seconds</fsummary>
- <type>
- <v>Seconds = int() &lt; 86400</v>
- <v>Time = time()</v>
- </type>
+ <type name="secs_per_day"/>
<desc>
<p>This function computes the time from the given number of
- seconds. <c>Seconds</c> must be less than the number of
+ seconds. <c><anno>Seconds</anno></c> must be less than the number of
seconds per day (86400).</p>
</desc>
</func>
<func>
- <name>time_difference(T1, T2) -> {Days, Time}</name>
+ <name name="time_difference" arity="2"/>
<fsummary>Compute the difference between two times (deprecated)</fsummary>
<desc>
- <p>This function returns the difference between two <c>{Date, Time}</c> tuples. <c>T2</c> should refer to an epoch later
- than <c>T1</c>.</p>
+ <p>This function returns the difference between two <c>{Date, Time}</c> tuples. <c><anno>T2</anno></c> should refer to an epoch later
+ than <c><anno>T1</anno></c>.</p>
<warning>
<p>This function is obsolete. Use the conversion functions for
gregorian days and seconds instead.</p>
@@ -324,24 +320,17 @@ time() = {Hour, Minute, Second}
</desc>
</func>
<func>
- <name>time_to_seconds(Time) -> Seconds</name>
+ <name name="time_to_seconds" arity="1"/>
<fsummary>Compute the number of seconds since midnight up to the given time</fsummary>
- <type>
- <v>Time = time()</v>
- <v>Seconds = int()</v>
- </type>
+ <type name="secs_per_day"/>
<desc>
<p>This function computes the number of seconds since midnight
up to the specified time.</p>
</desc>
</func>
<func>
- <name>universal_time() -> {Date, Time}</name>
+ <name name="universal_time" arity="0"/>
<fsummary>Compute universal time</fsummary>
- <type>
- <v>Date = date()</v>
- <v>Time = time()</v>
- </type>
<desc>
<p>This function returns the Universal Coordinated Time (UTC)
reported by the underlying operating system. Local time is
@@ -349,25 +338,22 @@ time() = {Hour, Minute, Second}
</desc>
</func>
<func>
- <name>universal_time_to_local_time({Date1, Time1}) -> {Date2, Time2}</name>
+ <name name="universal_time_to_local_time" arity="1"/>
<fsummary>Convert from universal time to local time</fsummary>
- <type>
- <v>Date1 = Date2 = date()</v>
- <v>Time1 = Time2 = time()</v>
- </type>
<desc>
<p>This function converts from Universal Coordinated Time (UTC)
- to local time. <c>Date1</c> must refer to a date after Jan 1,
+ to local time. <c><anno>DateTime</anno></c> must refer to a date after Jan 1,
1970.</p>
</desc>
</func>
<func>
- <name>valid_date(Date) -> bool()</name>
- <name>valid_date(Year, Month, Day) -> bool()</name>
+ <name name="valid_date" arity="1"/>
+ <name name="valid_date" arity="3"/>
+ <type variable="Date" name_i="1"/>
+ <type variable="Year"/>
+ <type variable="Month"/>
+ <type variable="Day"/>
<fsummary>Check if a date is valid</fsummary>
- <type>
- <v>Date = date()</v>
- </type>
<desc>
<p>This function checks if a date is a valid.</p>
</desc>
diff --git a/lib/stdlib/doc/src/dets.xml b/lib/stdlib/doc/src/dets.xml
index b002af6616..2512c84e18 100644
--- a/lib/stdlib/doc/src/dets.xml
+++ b/lib/stdlib/doc/src/dets.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -100,50 +100,99 @@
the process with the error tuple). If given badly formed
arguments, all functions exit the process with a <c>badarg</c>
message.</p>
- <p><em>Types</em></p>
- <pre>
-access() = read | read_write
-auto_save() = infinity | int()
-bindings_cont() = tuple()
-bool() = true | false
-file() = string()
-int() = integer() >= 0
-keypos() = integer() >= 1
-name() = atom() | reference()
-no_slots() = integer() >= 0 | default
-object() = tuple()
-object_cont() = tuple()
-select_cont() = tuple()
-type() = bag | duplicate_bag | set
-version() = 8 | 9 | default </pre>
</description>
+ <datatypes>
+ <datatype>
+ <name name="access"/>
+ </datatype>
+ <datatype>
+ <name name="auto_save"/>
+ </datatype>
+ <datatype>
+ <name name="bindings_cont"/>
+ <desc>
+ <p>Opaque continuation used by <seealso marker="#match/1">
+ <c>match/1</c></seealso> and <seealso marker="#match/3">
+ <c>match/3</c></seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="cont"/>
+ <desc>
+ <p>Opaque continuation used by <seealso marker="#bchunk/2">
+ <c>bchunk/2</c></seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="keypos"/>
+ </datatype>
+ <datatype>
+ <name name="match_spec"/>
+ <desc>
+ <p>Match&nbsp;specifications, see the <seealso
+ marker="erts:match_spec">match specification</seealso>
+ documentation in the ERTS User's Guide and <seealso
+ marker="ms_transform">ms_transform(3).</seealso></p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="no_slots"/>
+ </datatype>
+ <datatype>
+ <name name="object"/>
+ </datatype>
+ <datatype>
+ <name name="object_cont"/>
+ <desc>
+ <p>Opaque continuation used by <seealso marker="#match_object/1">
+ <c>match_object/1</c></seealso> and <seealso marker="#match_object/3">
+ <c>match_object/3</c></seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="pattern"/>
+ <desc>
+ <p>See <seealso marker="ets#match/2">ets:match/2</seealso> for a
+ description of patterns.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="select_cont"/>
+ <desc>
+ <p>Opaque continuation used by <seealso marker="#select/1">
+ <c>select/1</c></seealso> and <seealso marker="#select/3">
+ <c>select/3</c></seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="tab_name"/>
+ </datatype>
+ <datatype>
+ <name name="type"/>
+ </datatype>
+ <datatype>
+ <name name="version"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>all() -> [Name]</name>
+ <name name="all" arity="0"/>
<fsummary>Return a list of the names of all open Dets tables on this node.</fsummary>
- <type>
- <v>Name = name()</v>
- </type>
<desc>
<p>Returns a list of the names of all open tables on this
node.</p>
</desc>
</func>
<func>
- <name>bchunk(Name, Continuation) -> {Continuation2, Data} | '$end_of_table' | {error, Reason}</name>
+ <name name="bchunk" arity="2"/>
<fsummary>Return a chunk of objects stored in a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Continuation = start | cont()</v>
- <v>Continuation2 = cont()</v>
- <v>Data = binary() | tuple()</v>
- </type>
<desc>
<p>Returns a list of objects stored in a table. The exact
representation of the returned objects is not public. The
lists of data can be used for initializing a table by giving
the value <c>bchunk</c> to the <c>format</c> option of the
- <c>init_table/3</c> function. The Mnesia application uses this
+ <seealso marker="#init_table/3"><c>init_table/3</c></seealso>
+ function. The Mnesia application uses this
function for copying open tables.</p>
<p>Unless the table is protected using <c>safe_fixtable/2</c>,
calls to <c>bchunk/2</c> may not work as expected if
@@ -151,24 +200,23 @@ version() = 8 | 9 | default </pre>
<p>The first time <c>bchunk/2</c> is called, an initial
continuation, the atom <c>start</c>, must be provided.</p>
<p>The <c>bchunk/2</c> function returns a tuple
- <c>{Continuation2, Data}</c>, where <c>Data</c> is a list of
- objects. <c>Continuation2</c> is another continuation which is
+ <c>{<anno>Continuation2</anno>, <anno>Data</anno>}</c>,
+ where <c><anno>Data</anno></c> is a list of
+ objects. <c><anno>Continuation2</anno></c> is another continuation
+ which is
to be passed on to a subsequent call to <c>bchunk/2</c>. With
a series of calls to <c>bchunk/2</c> it is possible to extract
all objects of the table.
</p>
<p><c>bchunk/2</c> returns <c>'$end_of_table'</c> when all
- objects have been returned, or <c>{error, Reason}</c> if an
- error occurs.
+ objects have been returned, or <c>{error, <anno>Reason</anno>}</c>
+ if an error occurs.
</p>
</desc>
</func>
<func>
- <name>close(Name) -> ok | {error, Reason} </name>
+ <name name="close" arity="1"/>
<fsummary>Close a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- </type>
<desc>
<p>Closes a table. Only processes that have opened a table are
allowed to close it.
@@ -180,22 +228,16 @@ version() = 8 | 9 | default </pre>
</desc>
</func>
<func>
- <name>delete(Name, Key) -> ok | {error, Reason}</name>
+ <name name="delete" arity="2"/>
<fsummary>Delete all objects with a given key from a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- </type>
<desc>
- <p>Deletes all objects with the key <c>Key</c> from the table
- <c>Name</c>.</p>
+ <p>Deletes all objects with the key <c><anno>Key</anno></c> from
+ the table <c><anno>Name</anno></c>.</p>
</desc>
</func>
<func>
- <name>delete_all_objects(Name) -> ok | {error, Reason}</name>
+ <name name="delete_all_objects" arity="1"/>
<fsummary>Delete all objects from a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- </type>
<desc>
<p>Deletes all objects from a table in almost constant time.
However, if the table if fixed, <c>delete_all_objects(T)</c>
@@ -203,12 +245,8 @@ version() = 8 | 9 | default </pre>
</desc>
</func>
<func>
- <name>delete_object(Name, Object) -> ok | {error, Reason}</name>
+ <name name="delete_object" arity="2"/>
<fsummary>Delete a given object from a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Object = object()</v>
- </type>
<desc>
<p>Deletes all instances of a given object from a table. If a
table is of type <c>bag</c> or <c>duplicate_bag</c>, the
@@ -218,18 +256,15 @@ version() = 8 | 9 | default </pre>
</desc>
</func>
<func>
- <name>first(Name) -> Key | '$end_of_table'</name>
+ <name name="first" arity="1"/>
<fsummary>Return the first key stored in a Dets table.</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Name = name()</v>
- </type>
<desc>
- <p>Returns the first key stored in the table <c>Name</c>
+ <p>Returns the first key stored in the table <c><anno>Name</anno></c>
according to the table's internal order, or
<c>'$end_of_table'</c> if the table is empty.</p>
<p>Unless the table is protected using <c>safe_fixtable/2</c>,
- subsequent calls to <c>next/2</c> may not work as expected if
+ subsequent calls to <seealso marker="#next/2"><c>next/2</c></seealso>
+ may not work as expected if
concurrent updates are made to the table.</p>
<p>Should an error occur, the process is exited with an error
tuple <c>{error, Reason}</c>. The reason for not returning the
@@ -243,107 +278,78 @@ version() = 8 | 9 | default </pre>
</desc>
</func>
<func>
- <name>foldl(Function, Acc0, Name) -> Acc1 | {error, Reason}</name>
- <fsummary>Fold a function over a Dets table.</fsummary>
- <type>
- <v>Function = fun(Object, AccIn) -> AccOut</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Name = name()</v>
- <v>Object = object()</v>
- </type>
- <desc>
- <p>Calls <c>Function</c> on successive elements of the table
- <c>Name</c> together with an extra argument <c>AccIn</c>. The
- order in which the elements of the table are traversed is
- unspecified. <c>Function</c> must return a new accumulator
- which is passed to the next call. <c>Acc0</c> is returned if
- the table is empty.</p>
- </desc>
- </func>
- <func>
- <name>foldr(Function, Acc0, Name) -> Acc1 | {error, Reason}</name>
+ <name name="foldl" arity="3"/>
+ <name name="foldr" arity="3"/>
<fsummary>Fold a function over a Dets table.</fsummary>
- <type>
- <v>Function = fun(Object, AccIn) -> AccOut</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Name = name()</v>
- <v>Object = object()</v>
- </type>
<desc>
- <p>Calls <c>Function</c> on successive elements of the table
- <c>Name</c> together with an extra argument <c>AccIn</c>. The
+ <p>Calls <c><anno>Function</anno></c> on successive elements of
+ the table <c><anno>Name</anno></c> together with an extra argument
+ <c>AccIn</c>. The
order in which the elements of the table are traversed is
- unspecified. <c>Function</c> must return a new accumulator
- which is passed to the next call. <c>Acc0</c> is returned if
+ unspecified. <c><anno>Function</anno></c> must return a new
+ accumulator which is passed to the next call.
+ <c><anno>Acc0</anno></c> is returned if
the table is empty.</p>
</desc>
</func>
<func>
- <name>from_ets(Name, EtsTab) -> ok | {error, Reason}</name>
+ <name name="from_ets" arity="2"/>
<fsummary>Replace the objects of a Dets table with the objects of an Ets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>EtsTab = -&nbsp;see ets(3)&nbsp;-</v>
- </type>
<desc>
- <p>Deletes all objects of the table <c>Name</c> and then
- inserts all the objects of the Ets table <c>EtsTab</c>. The
- order in which the objects are inserted is not specified.
+ <p>Deletes all objects of the table <c><anno>Name</anno></c> and then
+ inserts all the objects of the Ets table <c><anno>EtsTab</anno></c>.
+ The order in which the objects are inserted is not specified.
Since <c>ets:safe_fixtable/2</c> is called the Ets table must
be public or owned by the calling process.</p>
</desc>
</func>
<func>
- <name>info(Name) -> InfoList | undefined</name>
+ <name name="info" arity="1"/>
<fsummary>Return information about a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>InfoList = [{Item, Value}]</v>
- </type>
<desc>
- <p>Returns information about the table <c>Name</c> as a list of
- <c>{Item, Value}</c> tuples:</p>
+ <p>Returns information about the table <c><anno>Name</anno></c>
+ as a list of tuples:</p>
<list type="bulleted">
<item>
- <p><c>{file_size, int()}</c>, the size of the file in
+ <p><c>{file_size, integer() >= 0}</c>, the size of the file in
bytes.</p>
</item>
<item>
- <p><c>{filename, file()}</c>, the name of the file
- where objects are stored.</p>
+ <p><c>{filename, <seealso marker="file#type-name">file:name()</seealso>}</c>,
+ the name of the file where objects are stored.</p>
</item>
<item>
- <p><c>{keypos, keypos()}</c>, the position of the
- key.</p>
+ <p><c>{keypos, <seealso marker="#type-keypos">keypos()</seealso>}
+ </c>, the position of the key.</p>
</item>
<item>
- <p><c>{size, int()}</c>, the number of objects stored
+ <p><c>{size, integer() >= 0}</c>, the number of objects stored
in the table.</p>
</item>
<item>
- <p><c>{type, type()}</c>, the type of the table.</p>
+ <p><c>{type, <seealso marker="#type-type">type()</seealso>}</c>,
+ the type of the table.</p>
</item>
</list>
</desc>
</func>
<func>
- <name>info(Name, Item) -> Value | undefined</name>
+ <name name="info" arity="2"/>
<fsummary>Return the information associated with a given item for a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- </type>
<desc>
- <p>Returns the information associated with <c>Item</c> for the
- table <c>Name</c>. In addition to the <c>{Item, Value}</c>
+ <p>Returns the information associated with <c><anno>Item</anno></c>
+ for the table <c><anno>Name</anno></c>.
+ In addition to the <c>{<anno>Item</anno>, <anno>Value</anno>}</c>
pairs defined for <c>info/1</c>, the following items are
allowed:</p>
<list type="bulleted">
<item>
- <p><c>{access, access()}</c>, the access mode.</p>
+ <p><c>{access, <seealso marker="#type-access">access()</seealso>}
+ </c>, the access mode.</p>
</item>
<item>
- <p><c>{auto_save, auto_save()}</c>, the auto save
- interval.</p>
+ <p><c>{auto_save, <seealso marker="#type-auto_save">
+ auto_save()</seealso>}</c>, the auto save interval.</p>
</item>
<item>
<p><c>{bchunk_format, binary()}</c>, an opaque binary
@@ -362,21 +368,22 @@ version() = 8 | 9 | default </pre>
<c>erlang:phash2/1</c> BIF is used.</p>
</item>
<item>
- <p><c>{memory, int()}</c>, the size of the file in
+ <p><c>{memory, integer() >= 0}</c>, the size of the file in
bytes. The same value is associated with the item
<c>file_size</c>.</p>
</item>
<item>
- <p><c>{no_keys, int()}</c>, the number of different
+ <p><c>{no_keys, integer >= 0()}</c>, the number of different
keys stored in the table. Only available for version 9
tables.</p>
</item>
<item>
- <p><c>{no_objects, int()}</c>, the number of objects
+ <p><c>{no_objects, integer >= 0()}</c>, the number of objects
stored in the table.</p>
</item>
<item>
- <p><c>{no_slots, {Min, Used, Max}}</c>, the number of
+ <p><c>{no_slots, {</c>Min<c>, </c>Used<c>, </c>Max<c>}}</c>,
+ the number of
slots of the table. <c>Min</c> is the minimum number of
slots, <c>Used</c> is the number of currently used slots,
and <c>Max</c> is the maximum number of slots. Only
@@ -387,7 +394,7 @@ version() = 8 | 9 | default </pre>
handles requests to the Dets table.</p>
</item>
<item>
- <p><c>{ram_file, bool()}</c>, whether the table is
+ <p><c>{ram_file, boolean()}</c>, whether the table is
kept in RAM.</p>
</item>
<item>
@@ -399,32 +406,28 @@ version() = 8 | 9 | default </pre>
table is not fixed, SafeFixed is the atom <c>false</c>.</p>
</item>
<item>
- <p><c>{version, int()}</c>, the version of the format
- of the table.</p>
+ <p><c>{version, integer()</c>, the version of the format of
+ the table.</p>
</item>
</list>
</desc>
</func>
<func>
- <name>init_table(Name, InitFun [, Options]) -> ok | {error, Reason}</name>
+ <name name="init_table" arity="2"/>
+ <name name="init_table" arity="3"/>
<fsummary>Replace all objects of a Dets table.</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>InitFun = fun(Arg) -> Res</v>
- <v>Arg = read | close</v>
- <v>Res = end_of_input | {[object()], InitFun} | {Data, InitFun} | term()</v>
- <v>Data = binary() | tuple()</v>
- </type>
<desc>
- <p>Replaces the existing objects of the table <c>Name</c> with
- objects created by calling the input function <c>InitFun</c>,
+ <p>Replaces the existing objects of the table <c><anno>Name</anno></c>
+ with objects created by calling the input function
+ <c><anno>InitFun</anno></c>,
see below. The reason for using this function rather than
calling <c>insert/2</c> is that of efficiency. It should be
noted that the input functions are called by the process that
handles requests to the Dets table, not by the calling
process.</p>
<p>When called with the argument <c>read</c> the function
- <c>InitFun</c> is assumed to return <c>end_of_input</c> when
+ <c><anno>InitFun</anno></c> is assumed to return
+ <c>end_of_input</c> when
there is no more input, or <c>{Objects, Fun}</c>, where
<c>Objects</c> is a list of objects and <c>Fun</c> is a new
input function. Any other value Value is returned as an error
@@ -448,7 +451,8 @@ version() = 8 | 9 | default </pre>
item <c>no_slots</c>. See also the <c>min_no_slots</c> option
below.
</p>
- <p>The <c>Options</c> argument is a list of <c>{Key, Val}</c>
+ <p>The <c><anno>Options</anno></c> argument is a list of
+ <c>{Key, Val}</c>
tuples where the following values are allowed:</p>
<list type="bulleted">
<item>
@@ -461,87 +465,68 @@ version() = 8 | 9 | default </pre>
</item>
<item>
<p><c>{format, Format}</c>. Specifies the format of the
- objects returned by the function <c>InitFun</c>. If
+ objects returned by the function <c><anno>InitFun</anno></c>. If
<c>Format</c> is <c>term</c> (the default),
- <c>InitFun</c> is assumed to return a list of tuples. If
- <c>Format</c> is <c>bchunk</c>, <c>InitFun</c> is
- assumed to return <c>Data</c> as returned by
- <c>bchunk/2</c>. This option overrides the
+ <c><anno>InitFun</anno></c> is assumed to return a list of tuples. If
+ <c>Format</c> is <c>bchunk</c>, <c><anno>InitFun</anno></c> is
+ assumed to return <c><anno>Data</anno></c> as returned by
+ <seealso marker="#bchunk/2"><c>bchunk/2</c></seealso>.
+ This option overrides the
<c>min_no_slots</c> option.</p>
</item>
</list>
</desc>
</func>
<func>
- <name>insert(Name, Objects) -> ok | {error, Reason}</name>
+ <name name="insert" arity="2"/>
<fsummary>Insert one or more objects into a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Objects = object() | [object()]</v>
- </type>
<desc>
- <p>Inserts one or more objects into the table <c>Name</c>. If
- there already exists an object with a key matching the key of
+ <p>Inserts one or more objects into the table <c><anno>Name</anno></c>.
+ If there already exists an object with a key matching the key of
some of the given objects and the table type is <c>set</c>,
the old object will be replaced.</p>
</desc>
</func>
<func>
- <name>insert_new(Name, Objects) -> Bool</name>
+ <name name="insert_new" arity="2"/>
<fsummary>Insert one or more objects into a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Objects = object() | [object()]</v>
- <v>Bool = bool()</v>
- </type>
<desc>
- <p>Inserts one or more objects into the table <c>Name</c>. If
- there already exists some object with a key matching the key
+ <p>Inserts one or more objects into the table <c><anno>Name</anno></c>.
+ If there already exists some object with a key matching the key
of any of the given objects the table is not updated and
<c>false</c> is returned, otherwise the objects are inserted
and <c>true</c> returned.</p>
</desc>
</func>
<func>
- <name>is_compatible_bchunk_format(Name, BchunkFormat) -> Bool</name>
+ <name name="is_compatible_bchunk_format" arity="2"/>
<fsummary>Test compatibility of a table's chunk data.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>BchunkFormat = binary()</v>
- <v>Bool = bool()</v>
- </type>
<desc>
<p>Returns <c>true</c> if it would be possible to initialize
- the table <c>Name</c>, using <c>init_table/3</c> with the
+ the table <c><anno>Name</anno></c>, using
+ <seealso marker="#init_table/3"><c>init_table/3</c></seealso>
+ with the
option <c>{format,&nbsp;bchunk}</c>, with objects read with
- <c>bchunk/2</c> from some table <c>T</c> such that calling
+ <seealso marker="#bchunk/2"><c>bchunk/2</c></seealso> from some
+ table <c>T</c> such that calling
<c>info(T,&nbsp;bchunk_format)</c> returns
<c>BchunkFormat</c>.</p>
</desc>
</func>
<func>
- <name>is_dets_file(FileName) -> Bool | {error, Reason}</name>
+ <name name="is_dets_file" arity="1"/>
<fsummary>Test for a Dets table.</fsummary>
- <type>
- <v>FileName = file()</v>
- <v>Bool = bool()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if the file <c>FileName</c> is a Dets
- table, <c>false</c> otherwise.</p>
+ <p>Returns <c>true</c> if the file <c><anno>Filename</anno></c>
+ is a Dets table, <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>lookup(Name, Key) -> [Object] | {error, Reason}</name>
+ <name name="lookup" arity="2"/>
<fsummary>Return all objects with a given key stored in a Dets table.</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Name = name()</v>
- <v>Object = object()</v>
- </type>
<desc>
- <p>Returns a list of all objects with the key <c>Key</c>
- stored in the table <c>Name</c>. For example:</p>
+ <p>Returns a list of all objects with the key <c><anno>Key</anno></c>
+ stored in the table <c><anno>Name</anno></c>. For example:</p>
<pre>
2> <input>dets:open_file(abc, [{type, bag}]).</input>
{ok,abc}
@@ -562,71 +547,57 @@ ok
</desc>
</func>
<func>
- <name>match(Continuation) -> {[Match], Continuation2} | '$end_of_table' | {error, Reason}</name>
+ <name name="match" arity="1"/>
<fsummary>Match a chunk of objects stored in a Dets table and return a list of variable bindings.</fsummary>
- <type>
- <v>Continuation = Continuation2 = bindings_cont()</v>
- <v>Match = [term()]</v>
- </type>
<desc>
<p>Matches some objects stored in a table and returns a
non-empty list of the bindings that match a given pattern in
some unspecified order. The table, the pattern, and the number
of objects that are matched are all defined by
- <c>Continuation</c>, which has been returned by a prior call
- to <c>match/1</c> or <c>match/3</c>.</p>
+ <c><anno>Continuation</anno></c>, which has been returned by a prior
+ call to <c>match/1</c> or <c>match/3</c>.</p>
<p>When all objects of the table have been matched,
<c>'$end_of_table'</c> is returned.</p>
</desc>
</func>
<func>
- <name>match(Name, Pattern) -> [Match] | {error, Reason}</name>
+ <name name="match" arity="2"/>
<fsummary>Match the objects stored in a Dets table and return a list of variable bindings.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Pattern = tuple()</v>
- <v>Match = [term()]</v>
- </type>
<desc>
- <p>Returns for each object of the table <c>Name</c> that
- matches <c>Pattern</c> a list of bindings in some unspecified
- order. See <seealso marker="ets">ets(3)</seealso> for a
+ <p>Returns for each object of the table <c><anno>Name</anno></c> that
+ matches <c><anno>Pattern</anno></c> a list of bindings in some unspecified
+ order. See <seealso marker="ets#match/2">ets:match/2</seealso> for a
description of patterns. If the keypos'th element of
- <c>Pattern</c> is unbound, all objects of the table are
+ <c><anno>Pattern</anno></c> is unbound, all objects of the table are
matched. If the keypos'th element is bound, only the
objects with the right key are matched.</p>
</desc>
</func>
<func>
- <name>match(Name, Pattern, N) -> {[Match], Continuation} | '$end_of_table' | {error, Reason}</name>
+ <name name="match" arity="3"/>
<fsummary>Match the first chunk of objects stored in a Dets table and return a list of variable bindings.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Pattern = tuple()</v>
- <v>N = default | int()</v>
- <v>Match = [term()]</v>
- <v>Continuation = bindings_cont()</v>
- </type>
<desc>
- <p>Matches some or all objects of the table <c>Name</c> and
+ <p>Matches some or all objects of the table <c><anno>Name</anno></c> and
returns a non-empty list of the bindings that match
- <c>Pattern</c> in some unspecified order. See <seealso marker="ets">ets(3)</seealso> for a description of
- patterns.</p>
+ <c><anno>Pattern</anno></c> in some unspecified order.
+ See <seealso marker="ets#match/2">ets:match/2</seealso> for a
+ description of patterns.</p>
<p>A tuple of the bindings and a continuation is returned,
unless the table is empty, in which case
<c>'$end_of_table'</c> is returned. The continuation is to be
used when matching further objects by calling
- <c>match/1</c>.</p>
- <p>If the keypos'th element of <c>Pattern</c> is bound, all
- objects of the table are matched. If the keypos'th element is
- unbound, all objects of the table are matched, <c>N</c>
+ <seealso marker="#match/1"><c>match/1</c></seealso>.</p>
+ <p>If the keypos'th element of <c><anno>Pattern</anno></c> is bound,
+ all objects of the table are matched. If the keypos'th element is
+ unbound, all objects of the table are matched, <c><anno>N</anno></c>
objects at a time, until at least one object matches or the
end of the table has been reached. The default, indicated by
- giving <c>N</c> the value <c>default</c>, is to let the number
+ giving <c><anno>N</anno></c> the value <c>default</c>,
+ is to let the number
of objects vary depending on the sizes of the objects. If
- <c>Name</c> is a version 9 table, all objects with the same
+ <c><anno>Name</anno></c> is a version 9 table, all objects with the same
key are always matched at the same time which implies that
- more than N objects may sometimes be matched.
+ more than <anno>N</anno> objects may sometimes be matched.
</p>
<p>The table should always be protected using
<c>safe_fixtable/2</c> before calling <c>match/3</c>, or
@@ -634,15 +605,11 @@ ok
</desc>
</func>
<func>
- <name>match_delete(Name, Pattern) -> ok | {error, Reason}</name>
+ <name name="match_delete" arity="2"/>
<fsummary>Delete all objects that match a given pattern from a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Pattern = tuple()</v>
- </type>
<desc>
- <p>Deletes all objects that match <c>Pattern</c> from the
- table <c>Name</c>.
+ <p>Deletes all objects that match <c><anno>Pattern</anno></c> from the
+ table <c><anno>Name</anno></c>.
See <seealso marker="ets#match/2">ets:match/2</seealso> for a
description of patterns.</p>
<p>If the keypos'th element of <c>Pattern</c> is bound,
@@ -650,17 +617,13 @@ ok
</desc>
</func>
<func>
- <name>match_object(Continuation) -> {[Object], Continuation2} | '$end_of_table' | {error, Reason}</name>
+ <name name="match_object" arity="1"/>
<fsummary>Match a chunk of objects stored in a Dets table and return a list of objects.</fsummary>
- <type>
- <v>Continuation = Continuation2 = object_cont()</v>
- <v>Object = object()</v>
- </type>
<desc>
<p>Returns a non-empty list of some objects stored in a table
that match a given pattern in some unspecified order. The
table, the pattern, and the number of objects that are matched
- are all defined by <c>Continuation</c>, which has been
+ are all defined by <c><anno>Continuation</anno></c>, which has been
returned by a prior call to <c>match_object/1</c> or
<c>match_object/3</c>.</p>
<p>When all objects of the table have been matched,
@@ -668,20 +631,17 @@ ok
</desc>
</func>
<func>
- <name>match_object(Name, Pattern) -> [Object] | {error, Reason}</name>
+ <name name="match_object" arity="2"/>
<fsummary>Match the objects stored in a Dets table and return a list of objects.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Pattern = tuple()</v>
- <v>Object = object()</v>
- </type>
<desc>
- <p>Returns a list of all objects of the table <c>Name</c> that
- match <c>Pattern</c> in some unspecified order. See <seealso marker="ets">ets(3)</seealso> for a description of patterns.
+ <p>Returns a list of all objects of the table <c><anno>Name</anno></c> that
+ match <c><anno>Pattern</anno></c> in some unspecified order.
+ See <seealso marker="ets#match/2">ets:match/2</seealso> for a
+ description of patterns.
</p>
- <p>If the keypos'th element of <c>Pattern</c> is
+ <p>If the keypos'th element of <c><anno>Pattern</anno></c> is
unbound, all objects of the table are matched. If the
- keypos'th element of <c>Pattern</c> is bound, only the
+ keypos'th element of <c><anno>Pattern</anno></c> is bound, only the
objects with the right key are matched.</p>
<p>Using the <c>match_object</c> functions for traversing all
objects of a table is more efficient than calling
@@ -689,34 +649,28 @@ ok
</desc>
</func>
<func>
- <name>match_object(Name, Pattern, N) -> {[Object], Continuation} | '$end_of_table' | {error, Reason}</name>
+ <name name="match_object" arity="3"/>
<fsummary>Match the first chunk of objects stored in a Dets table and return a list of objects.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Pattern = tuple()</v>
- <v>N = default | int()</v>
- <v>Object = object()</v>
- <v>Continuation = object_cont()</v>
- </type>
<desc>
- <p>Matches some or all objects stored in the table <c>Name</c>
+ <p>Matches some or all objects stored in the table <c><anno>Name</anno></c>
and returns a non-empty list of the objects that match
- <c>Pattern</c> in some unspecified order. See <seealso marker="ets">ets(3)</seealso> for a description of
- patterns.</p>
+ <c><anno>Pattern</anno></c> in some unspecified order.
+ See <seealso marker="ets#match/2">ets:match/2</seealso> for a
+ description of patterns.</p>
<p>A list of objects and a continuation is returned, unless
the table is empty, in which case <c>'$end_of_table'</c>
is returned. The continuation is to be used when matching
further objects by calling <c>match_object/1</c>.</p>
- <p>If the keypos'th element of <c>Pattern</c> is bound, all
+ <p>If the keypos'th element of <c><anno>Pattern</anno></c> is bound, all
objects of the table are matched. If the keypos'th element is
- unbound, all objects of the table are matched, <c>N</c>
+ unbound, all objects of the table are matched, <c><anno>N</anno></c>
objects at a time, until at least one object matches or the
end of the table has been reached. The default, indicated by
- giving <c>N</c> the value <c>default</c>, is to let the number
+ giving <c><anno>N</anno></c> the value <c>default</c>, is to let the number
of objects vary depending on the sizes of the objects. If
- <c>Name</c> is a version 9 table, all matching objects with
+ <c><anno>Name</anno></c> is a version 9 table, all matching objects with
the same key are always returned in the same reply which
- implies that more than N objects may sometimes be returned.
+ implies that more than <anno>N</anno> objects may sometimes be returned.
</p>
<p>The table should always be protected using
<c>safe_fixtable/2</c> before calling <c>match_object/3</c>,
@@ -724,43 +678,31 @@ ok
</desc>
</func>
<func>
- <name>member(Name, Key) -> Bool | {error, Reason}</name>
+ <name name="member" arity="2"/>
<fsummary>Test for occurrence of a key in a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Key = term()</v>
- <v>Bool = bool()</v>
- </type>
<desc>
<p>Works like <c>lookup/2</c>, but does not return the
objects. The function returns <c>true</c> if one or more
- elements of the table has the key <c>Key</c>, <c>false</c>
+ elements of the table has the key <c><anno>Key</anno></c>, <c>false</c>
otherwise.</p>
</desc>
</func>
<func>
- <name>next(Name, Key1) -> Key2 | '$end_of_table'</name>
+ <name name="next" arity="2"/>
<fsummary>Return the next key in a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Key1 = Key2 = term()</v>
- </type>
<desc>
- <p>Returns the key following <c>Key1</c> in the table
- <c>Name</c> according to the table's internal order, or
+ <p>Returns the key following <c><anno>Key1</anno></c> in the table
+ <c><anno>Name</anno></c> according to the table's internal order, or
<c>'$end_of_table'</c> if there is no next key.</p>
<p>Should an error occur, the process is exited with an error
tuple <c>{error, Reason}</c>.</p>
- <p>Use <c>first/1</c> to find the first key in the table.</p>
+ <p>Use <seealso marker="#first/1"><c>first/1</c></seealso> to find
+ the first key in the table.</p>
</desc>
</func>
<func>
- <name>open_file(Filename) -> {ok, Reference} | {error, Reason}</name>
+ <name name="open_file" arity="1"/>
<fsummary>Open an existing Dets table.</fsummary>
- <type>
- <v>FileName = file()</v>
- <v>Reference = reference()</v>
- </type>
<desc>
<p>Opens an existing table. If the table has not been properly
closed, it will be repaired. The returned reference is to be
@@ -769,15 +711,12 @@ ok
</desc>
</func>
<func>
- <name>open_file(Name, Args) -> {ok, Name} | {error, Reason}</name>
+ <name name="open_file" arity="2"/>
<fsummary>Open a Dets table.</fsummary>
- <type>
- <v>Name = atom()</v>
- </type>
<desc>
<p>Opens a table. An empty Dets table is created if no file
exists.</p>
- <p>The atom <c>Name</c> is the name of the table. The table
+ <p>The atom <c><anno>Name</anno></c> is the name of the table. The table
name must be provided in all subsequent operations on the
table. The name can be used by other processes as well, and
several process can share one table.
@@ -786,18 +725,20 @@ ok
name and arguments, then the table will have two users. If one
user closes the table, it still remains open until the second
user closes the table.</p>
- <p>The <c>Args</c> argument is a list of <c>{Key, Val}</c>
+ <p>The <c><anno>Args</anno></c> argument is a list of <c>{Key, Val}</c>
tuples where the following values are allowed:</p>
<list type="bulleted">
<item>
- <p><c>{access, access()}</c>. It is possible to open
+ <p><c>{access, <seealso marker="#type-access">
+ access()</seealso>}</c>. It is possible to open
existing tables in read-only mode. A table which is opened
in read-only mode is not subjected to the automatic file
reparation algorithm if it is later opened after a crash.
The default value is <c>read_write</c>.</p>
</item>
<item>
- <p><c>{auto_save, auto_save()}</c>, the auto save
+ <p><c>{auto_save, <seealso marker="#type-auto_save">
+ auto_save()</seealso>}</c>, the auto save
interval. If the interval is an integer <c>Time</c>, the
table is flushed to disk whenever it is not accessed for
<c>Time</c> milliseconds. A table that has been flushed
@@ -807,15 +748,18 @@ ok
is 180000 (3 minutes).</p>
</item>
<item>
- <p><c>{estimated_no_objects, int()}</c>. Equivalent to the
+ <p><c>{estimated_no_objects, <seealso marker="#type-no_slots">
+ no_slots()</seealso>}</c>. Equivalent to the
<c>min_no_slots</c> option.</p>
</item>
<item>
- <p><c>{file, file()}</c>, the name of the file to be
+ <p><c>{file, <seealso marker="file#type-name">
+ file:name()</seealso>}</c>, the name of the file to be
opened. The default value is the name of the table.</p>
</item>
<item>
- <p><c>{max_no_slots, no_slots()}</c>, the maximum number
+ <p><c>{max_no_slots, <seealso marker="#type-no_slots">
+ no_slots()</seealso>}</c>, the maximum number
of slots that will be used. The default value as well as
the maximal value is 32 M. Note that a higher value may
increase the fragmentation of the table, and conversely,
@@ -824,14 +768,16 @@ ok
9 tables.</p>
</item>
<item>
- <p><c>{min_no_slots, no_slots()}</c>. Application
+ <p><c>{min_no_slots, <seealso marker="#type-no_slots">
+ no_slots()</seealso>}</c>. Application
performance can be enhanced with this flag by specifying,
when the table is created, the estimated number of
different keys that will be stored in the table. The
default value as well as the minimum value is 256.</p>
</item>
<item>
- <p><c>{keypos, keypos()}</c>, the position of the
+ <p><c>{keypos, <seealso marker="#type-keypos">
+ keypos()</seealso>}</c>, the position of the
element of each object to be used as key. The default
value is 1. The ability to explicitly state the key
position is most convenient when we want to store Erlang
@@ -839,7 +785,7 @@ ok
name of the record type.</p>
</item>
<item>
- <p><c>{ram_file, bool()}</c>, whether the table is to
+ <p><c>{ram_file, boolean()}</c>, whether the table is to
be kept in RAM. Keeping the table in RAM may sound like an
anomaly, but can enhance the performance of applications
which open a table, insert a set of objects, and then
@@ -849,7 +795,7 @@ ok
</item>
<item>
<p><c>{repair, Value}</c>. <c>Value</c> can be either
- a <c>bool()</c> or the atom <c>force</c>. The flag
+ a <c>boolean()</c> or the atom <c>force</c>. The flag
specifies whether the Dets server should invoke the
automatic file reparation algorithm. The default is
<c>true</c>. If <c>false</c> is specified, there is no
@@ -868,11 +814,12 @@ ok
already open.</p>
</item>
<item>
- <p><c>{type, type()}</c>, the type of the table. The
- default value is <c>set</c>.</p>
+ <p><c>{type, <seealso marker="#type-type">type()</seealso>}</c>,
+ the type of the table. The default value is <c>set</c>.</p>
</item>
<item>
- <p><c>{version, version()}</c>, the version of the format
+ <p><c>{version, <seealso marker="#type-version">
+ version()</seealso>}</c>, the version of the format
used for the table. The default value is <c>9</c>. Tables
on the format used before OTP R8 can be created by giving
the value <c>8</c>. A version 8 table can be converted to
@@ -883,12 +830,8 @@ ok
</desc>
</func>
<func>
- <name>pid2name(Pid) -> {ok, Name} | undefined</name>
+ <name name="pid2name" arity="1"/>
<fsummary>Return the name of the Dets table handled by a pid.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Pid = pid()</v>
- </type>
<desc>
<p>Returns the name of the table given the pid of a process
that handles requests to a table, or <c>undefined</c> if
@@ -897,12 +840,8 @@ ok
</desc>
</func>
<func>
- <name>repair_continuation(Continuation, MatchSpec) -> Continuation2</name>
+ <name name="repair_continuation" arity="2"/>
<fsummary>Repair a continuation from select/1 or select/3.</fsummary>
- <type>
- <v>Continuation = Continuation2 = select_cont()</v>
- <v>MatchSpec = match_spec()</v>
- </type>
<desc>
<p>This function can be used to restore an opaque continuation
returned by <c>select/3</c> or <c>select/1</c> if the
@@ -932,14 +871,11 @@ ok
</desc>
</func>
<func>
- <name>safe_fixtable(Name, Fix)</name>
+ <name name="safe_fixtable" arity="2"/>
<fsummary>Fix a Dets table for safe traversal.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Fix = bool()</v>
- </type>
<desc>
- <p>If <c>Fix</c> is <c>true</c>, the table <c>Name</c> is
+ <p>If <c><anno>Fix</anno></c> is <c>true</c>, the table
+ <c><anno>Name</anno></c> is
fixed (once more) by the calling process, otherwise the table
is released. The table is also released when a fixing process
terminates.
@@ -961,17 +897,13 @@ ok
</desc>
</func>
<func>
- <name>select(Continuation) -> {Selection, Continuation2} | '$end_of_table' | {error, Reason}</name>
+ <name name="select" arity="1"/>
<fsummary>Apply a match specification to some objects stored in a Dets table.</fsummary>
- <type>
- <v>Continuation = Continuation2 = select_cont()</v>
- <v>Selection = [term()]</v>
- </type>
<desc>
<p>Applies a match specification to some objects stored in a
table and returns a non-empty list of the results. The
table, the match specification, and the number of objects
- that are matched are all defined by <c>Continuation</c>,
+ that are matched are all defined by <c><anno>Continuation</anno></c>,
which has been returned by a prior call to <c>select/1</c>
or <c>select/3</c>.</p>
<p>When all objects of the table have been matched,
@@ -979,20 +911,15 @@ ok
</desc>
</func>
<func>
- <name>select(Name, MatchSpec) -> Selection | {error, Reason}</name>
+ <name name="select" arity="2"/>
<fsummary>Apply a match specification to all objects stored in a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>MatchSpec = match_spec()</v>
- <v>Selection = [term()]</v>
- </type>
<desc>
<p>Returns the results of applying the match specification
- <c>MatchSpec</c> to all or some objects stored in the table
- <c>Name</c>. The order of the objects is not specified. See
+ <c><anno>MatchSpec</anno></c> to all or some objects stored in the table
+ <c><anno>Name</anno></c>. The order of the objects is not specified. See
the ERTS User's Guide for a description of match
specifications.</p>
- <p>If the keypos'th element of <c>MatchSpec</c> is
+ <p>If the keypos'th element of <c><anno>MatchSpec</anno></c> is
unbound, the match specification is applied to all objects of
the table. If the keypos'th element is bound, the match
specification is applied to the objects with the right key(s)
@@ -1004,19 +931,12 @@ ok
</desc>
</func>
<func>
- <name>select(Name, MatchSpec, N) -> {Selection, Continuation} | '$end_of_table' | {error, Reason}</name>
+ <name name="select" arity="3"/>
<fsummary>Apply a match specification to the first chunk of objects stored in a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>MatchSpec = match_spec()</v>
- <v>N = default | int()</v>
- <v>Selection = [term()]</v>
- <v>Continuation = select_cont()</v>
- </type>
<desc>
<p>Returns the results of applying the match specification
- <c>MatchSpec</c> to some or all objects stored in the table
- <c>Name</c>. The order of the objects is not specified. See
+ <c><anno>MatchSpec</anno></c> to some or all objects stored in the table
+ <c><anno>Name</anno></c>. The order of the objects is not specified. See
the ERTS User's Guide for a description of match
specifications.</p>
<p>A tuple of the results of applying the match specification
@@ -1024,18 +944,18 @@ ok
in which case <c>'$end_of_table'</c> is returned. The
continuation is to be used when matching further objects by
calling <c>select/1</c>.</p>
- <p>If the keypos'th element of <c>MatchSpec</c> is bound, the
+ <p>If the keypos'th element of <c><anno>MatchSpec</anno></c> is bound, the
match specification is applied to all objects of the table
with the right key(s). If the keypos'th element of
- <c>MatchSpec</c> is unbound, the match specification is
- applied to all objects of the table, <c>N</c> objects at a
+ <c><anno>MatchSpec</anno></c> is unbound, the match specification is
+ applied to all objects of the table, <c><anno>N</anno></c> objects at a
time, until at least one object matches or the end of the
table has been reached. The default, indicated by giving
- <c>N</c> the value <c>default</c>, is to let the number of
+ <c><anno>N</anno></c> the value <c>default</c>, is to let the number of
objects vary depending on the sizes of the objects. If
- <c>Name</c> is a version 9 table, all objects with the same
+ <c><anno>Name</anno></c> is a version 9 table, all objects with the same
key are always handled at the same time which implies that the
- match specification may be applied to more than N objects.
+ match specification may be applied to more than <anno>N</anno> objects.
</p>
<p>The table should always be protected using
<c>safe_fixtable/2</c> before calling <c>select/3</c>, or
@@ -1043,48 +963,35 @@ ok
</desc>
</func>
<func>
- <name>select_delete(Name, MatchSpec) -> N | {error, Reason}</name>
+ <name name="select_delete" arity="2"/>
<fsummary>Delete all objects that match a given pattern from a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>MatchSpec = match_spec()</v>
- <v>N = int()</v>
- </type>
<desc>
- <p>Deletes each object from the table <c>Name</c> such that
- applying the match specification <c>MatchSpec</c> to the
+ <p>Deletes each object from the table <c><anno>Name</anno></c> such that
+ applying the match specification <c><anno>MatchSpec</anno></c> to the
object returns the value <c>true</c>. See the ERTS
User's Guide for a description of match
specifications. Returns the number of deleted objects.</p>
- <p>If the keypos'th element of <c>MatchSpec</c> is
+ <p>If the keypos'th element of <c><anno>MatchSpec</anno></c> is
bound, the match specification is applied to the objects
with the right key(s) only.</p>
</desc>
</func>
<func>
- <name>slot(Name, I) -> '$end_of_table' | [Object] | {error, Reason}</name>
+ <name name="slot" arity="2"/>
<fsummary>Return the list of objects associated with a slot of a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>I = int()</v>
- <v>Object = object()</v>
- </type>
<desc>
<p>The objects of a table are distributed among slots,
starting with slot <c>0</c> and ending with slot n. This
function returns the list of objects associated with slot
- <c>I</c>. If <c>I</c> is greater than n <c>'$end_of_table'</c>
- is returned.</p>
+ <c><anno>I</anno></c>. If <c><anno>I</anno></c> is greater than n
+ <c>'$end_of_table'</c> is returned.</p>
</desc>
</func>
<func>
- <name>sync(Name) -> ok | {error, Reason}</name>
+ <name name="sync" arity="1"/>
<fsummary>Ensure that all updates made to a Dets table are written to disk.</fsummary>
- <type>
- <v>Name = name()</v>
- </type>
<desc>
- <p>Ensures that all updates made to the table <c>Name</c> are
+ <p>Ensures that all updates made to the table <c><anno>Name</anno></c> are
written to disk. This also applies to tables which have been
opened with the <c>ram_file</c> flag set to <c>true</c>. In
this case, the contents of the RAM file are flushed to
@@ -1095,25 +1002,17 @@ ok
</desc>
</func>
<func>
- <name>table(Name [, Options]) -> QueryHandle</name>
+ <name name="table" arity="1"/>
+ <name name="table" arity="2"/>
<fsummary>Return a QLC query handle.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>QueryHandle = -&nbsp;a query handle, see qlc(3)&nbsp;-</v>
- <v>Options = [Option] | Option</v>
- <v>Option = {n_objects, Limit} | {traverse, TraverseMethod}</v>
- <v>Limit = default | integer() >= 1</v>
- <v>TraverseMethod = first_next | select | {select, MatchSpec}</v>
- <v>MatchSpec = match_spec()</v>
- </type>
<desc>
- <p> <marker id="qlc_table"></marker>
-Returns a QLC (Query List
+ <p><marker id="qlc_table"></marker>
+ Returns a QLC (Query List
Comprehension) query handle. The module <c>qlc</c>
implements a query language aimed mainly at Mnesia but Ets
tables, Dets tables, and lists are also recognized by <c>qlc</c>
as sources of data. Calling <c>dets:table/1,2</c> is the
- means to make the Dets table <c>Name</c> usable to <c>qlc</c>.</p>
+ means to make the Dets table <c><anno>Name</anno></c> usable to <c>qlc</c>.</p>
<p>When there are only simple restrictions on the key position
<c>qlc</c> uses <c>dets:lookup/2</c> to look up the keys, but when
that is not possible the whole table is traversed. The
@@ -1137,7 +1036,8 @@ Returns a QLC (Query List
specification that matches all objects.</p>
</item>
<item>
- <p><c>{select, MatchSpec}</c>. As for <c>select</c>
+ <p><c>{select, <seealso marker="#type-match_spec">
+ match_spec()}</seealso></c>. As for <c>select</c>
the table is traversed by calling <c>dets:select/3</c>
and <c>dets:select/1</c>. The difference is that the
match specification is explicitly given. This is how to
@@ -1166,35 +1066,23 @@ true </pre>
</desc>
</func>
<func>
- <name>to_ets(Name, EtsTab) -> EtsTab | {error, Reason}</name>
+ <name name="to_ets" arity="2"/>
<fsummary>Insert all objects of a Dets table into an Ets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>EtsTab = -&nbsp;see ets(3)&nbsp;-</v>
- </type>
<desc>
- <p>Inserts the objects of the Dets table <c>Name</c> into the
- Ets table <c>EtsTab</c>. The order in which the objects are
+ <p>Inserts the objects of the Dets table <c><anno>Name</anno></c> into the
+ Ets table <c><anno>EtsTab</anno></c>. The order in which the objects are
inserted is not specified. The existing objects of the Ets
table are kept unless overwritten.</p>
</desc>
</func>
<func>
- <name>traverse(Name, Fun) -> Return | {error, Reason}</name>
+ <name name="traverse" arity="2"/>
<fsummary>Apply a function to all or some objects stored in a Dets table.</fsummary>
- <type>
- <v>Fun = fun(Object) -> FunReturn</v>
- <v>FunReturn = continue | {continue, Val} | {done, Value}</v>
- <v>Val = Value = term()</v>
- <v>Name = name()</v>
- <v>Object = object()</v>
- <v>Return = [term()]</v>
- </type>
<desc>
- <p>Applies <c>Fun</c> to each object stored in the table
- <c>Name</c> in some unspecified order. Different actions are
- taken depending on the return value of <c>Fun</c>. The
- following <c>Fun</c> return values are allowed:</p>
+ <p>Applies <c><anno>Fun</anno></c> to each object stored in the table
+ <c><anno>Name</anno></c> in some unspecified order. Different actions are
+ taken depending on the return value of <c><anno>Fun</anno></c>. The
+ following <c><anno>Fun</anno></c> return values are allowed:</p>
<taglist>
<tag><c>continue</c></tag>
<item>
@@ -1206,35 +1094,31 @@ fun(X) -> io:format("~p~n", [X]), continue end. </pre>
</item>
<tag><c>{continue, Val}</c></tag>
<item>
- <p>Continue the traversal and accumulate <c>Val</c>. The
+ <p>Continue the traversal and accumulate <c><anno>Val</anno></c>. The
following function is supplied in order to collect all
objects of a table in a list: </p>
<pre>
fun(X) -> {continue, X} end. </pre>
</item>
- <tag><c>{done, Value}</c></tag>
+ <tag><c>{done, <anno>Value</anno>}</c></tag>
<item>
- <p>Terminate the traversal and return <c>[Value | Acc]</c>.</p>
+ <p>Terminate the traversal and return <c>[<anno>Value</anno> | Acc]</c>.</p>
</item>
</taglist>
- <p>Any other value returned by <c>Fun</c> terminates the
+ <p>Any other value returned by <c><anno>Fun</anno></c> terminates the
traversal and is immediately returned.
</p>
</desc>
</func>
<func>
- <name>update_counter(Name, Key, Increment) -> Result</name>
+ <name name="update_counter" arity="3"/>
<fsummary>Update a counter object stored in a Dets table.</fsummary>
- <type>
- <v>Name = name()</v>
- <v>Key = term()</v>
- <v>Increment = {Pos, Incr} | Incr</v>
- <v>Pos = Incr = Result = integer()</v>
- </type>
<desc>
- <p>Updates the object with key <c>Key</c> stored in the table
- <c>Name</c> of type <c>set</c> by adding <c>Incr</c> to the
- element at the <c>Pos</c>:th position. The new counter value
+ <p>Updates the object with key <c><anno>Key</anno></c> stored in the
+ table <c><anno>Name</anno></c> of type <c>set</c> by adding
+ <c><anno>Incr</anno></c> to the
+ element at the <c><anno>Pos</anno></c>:th position.
+ The new counter value
is returned. If no position is specified, the element directly
following the key is updated.</p>
<p>This functions provides a way of updating a counter,
@@ -1252,4 +1136,3 @@ fun(X) -> {continue, X} end. </pre>
<seealso marker="qlc">qlc(3)</seealso></p>
</section>
</erlref>
-
diff --git a/lib/stdlib/doc/src/dict.xml b/lib/stdlib/doc/src/dict.xml
index 0cc76e0c78..b01acd02bf 100644
--- a/lib/stdlib/doc/src/dict.xml
+++ b/lib/stdlib/doc/src/dict.xml
@@ -39,174 +39,120 @@
they do not compare equal (<c>==</c>).</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-dictionary()
- as returned by new/0</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name><marker id="type-dict">dict()</marker></name>
+ <desc><p>Dictionary as returned by <c>new/0</c>.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>append(Key, Value, Dict1) -> Dict2</name>
+ <name name="append" arity="3"/>
<fsummary>Append a value to keys in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p>This function appends a new <c>Value</c> to the current list
- of values associated with <c>Key</c>.</p>
- </desc>
+ <p>This function appends a new <c><anno>Value</anno></c> to the current list
+ of values associated with <c><anno>Key</anno></c>.</p>
+ </desc>
</func>
<func>
- <name>append_list(Key, ValList, Dict1) -> Dict2</name>
+ <name name="append_list" arity="3"/>
<fsummary>Append new values to keys in a dictionary</fsummary>
- <type>
- <v>ValList = [Value]</v>
- <v>Key = Value = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p>This function appends a list of values <c>ValList</c> to
- the current list of values associated with <c>Key</c>. An
+ <p>This function appends a list of values <c><anno>ValList</anno></c> to
+ the current list of values associated with <c><anno>Key</anno></c>. An
exception is generated if the initial value associated with
- <c>Key</c> is not a list of values.</p>
+ <c><anno>Key</anno></c> is not a list of values.</p>
</desc>
</func>
<func>
- <name>erase(Key, Dict1) -> Dict2</name>
+ <name name="erase" arity="2"/>
<fsummary>Erase a key from a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
<p>This function erases all items with a given key from a
dictionary.</p>
</desc>
</func>
<func>
- <name>fetch(Key, Dict) -> Value</name>
+ <name name="fetch" arity="2"/>
<fsummary>Look-up values in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Dict = dictionary()</v>
- </type>
<desc>
- <p>This function returns the value associated with <c>Key</c>
- in the dictionary <c>Dict</c>. <c>fetch</c> assumes that
- the <c>Key</c> is present in the dictionary and an exception
- is generated if <c>Key</c> is not in the dictionary.</p>
+ <p>This function returns the value associated with <c><anno>Key</anno></c>
+ in the dictionary <c><anno>Dict</anno></c>. <c>fetch</c> assumes that
+ the <c><anno>Key</anno></c> is present in the dictionary and an exception
+ is generated if <c><anno>Key</anno></c> is not in the dictionary.</p>
</desc>
</func>
<func>
- <name>fetch_keys(Dict) -> Keys</name>
+ <name name="fetch_keys" arity="1"/>
<fsummary>Return all keys in a dictionary</fsummary>
- <type>
- <v>Dict = dictionary()</v>
- <v>Keys = [term()]</v>
- </type>
<desc>
<p>This function returns a list of all keys in the dictionary.</p>
</desc>
</func>
<func>
- <name>filter(Pred, Dict1) -> Dict2</name>
+ <name name="filter" arity="2"/>
<fsummary>Choose elements which satisfy a predicate</fsummary>
- <type>
- <v>Pred = fun(Key, Value) -> bool()</v>
- <v>&nbsp;Key = Value = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p><c>Dict2</c> is a dictionary of all keys and values in
- <c>Dict1</c> for which <c>Pred(Key, Value)</c> is <c>true</c>.</p>
+ <p><c><anno>Dict2</anno></c> is a dictionary of all keys and values in
+ <c><anno>Dict1</anno></c> for which <c><anno>Pred</anno>(<anno>Key</anno>, <anno>Value</anno>)</c> is <c>true</c>.</p>
</desc>
</func>
<func>
- <name>find(Key, Dict) -> {ok, Value} | error</name>
+ <name name="find" arity="2"/>
<fsummary>Search for a key in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Dict = dictionary()</v>
- </type>
<desc>
<p>This function searches for a key in a dictionary. Returns
- <c>{ok, Value}</c> where <c>Value</c> is the value associated
- with <c>Key</c>, or <c>error</c> if the key is not present in
+ <c>{ok, <anno>Value</anno>}</c> where <c><anno>Value</anno></c> is the value associated
+ with <c><anno>Key</anno></c>, or <c>error</c> if the key is not present in
the dictionary.</p>
</desc>
</func>
<func>
- <name>fold(Fun, Acc0, Dict) -> Acc1</name>
+ <name name="fold" arity="3"/>
<fsummary>Fold a function over a dictionary</fsummary>
- <type>
- <v>Fun = fun(Key, Value, AccIn) -> AccOut</v>
- <v>Key = Value = term()</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Dict = dictionary()</v>
- </type>
<desc>
- <p>Calls <c>Fun</c> on successive keys and values of
- <c>Dict</c> together with an extra argument <c>Acc</c>
- (short for accumulator). <c>Fun</c> must return a new
- accumulator which is passed to the next call. <c>Acc0</c> is
+ <p>Calls <c><anno>Fun</anno></c> on successive keys and values of
+ <c><anno>Dict</anno></c> together with an extra argument <c>Acc</c>
+ (short for accumulator). <c><anno>Fun</anno></c> must return a new
+ accumulator which is passed to the next call. <c><anno>Acc0</anno></c> is
returned if the list is empty. The evaluation order is
undefined.</p>
</desc>
</func>
<func>
- <name>from_list(List) -> Dict</name>
+ <name name="from_list" arity="1"/>
<fsummary>Convert a list of pairs to a dictionary</fsummary>
- <type>
- <v>List = [{Key, Value}]</v>
- <v>Dict = dictionary()</v>
- </type>
<desc>
- <p>This function converts the <c>Key</c> - <c>Value</c> list
- <c>List</c> to a dictionary.</p>
+ <p>This function converts the <c><anno>Key</anno></c> - <c><anno>Value</anno></c> list
+ <c><anno>List</anno></c> to a dictionary.</p>
</desc>
</func>
<func>
- <name>is_key(Key, Dict) -> bool()</name>
+ <name name="is_key" arity="2"/>
<fsummary>Test if a key is in a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Dict = dictionary()</v>
- </type>
<desc>
- <p>This function tests if <c>Key</c> is contained in
- the dictionary <c>Dict</c>.</p>
+ <p>This function tests if <c><anno>Key</anno></c> is contained in
+ the dictionary <c><anno>Dict</anno></c>.</p>
</desc>
</func>
<func>
- <name>map(Fun, Dict1) -> Dict2</name>
+ <name name="map" arity="2"/>
<fsummary>Map a function over a dictionary</fsummary>
- <type>
- <v>Fun = fun(Key, Value1) -> Value2</v>
- <v>&nbsp;Key = Value1 = Value2 = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p><c>map</c> calls <c>Func</c> on successive keys and values
- of <c>Dict</c> to return a new value for each key.
+ <p><c>map</c> calls <c><anno>Fun</anno></c> on successive keys and values
+ of <c><anno>Dict1</anno></c> to return a new value for each key.
The evaluation order is undefined.</p>
</desc>
</func>
<func>
- <name>merge(Fun, Dict1, Dict2) -> Dict3</name>
+ <name name="merge" arity="3"/>
<fsummary>Merge two dictionaries</fsummary>
- <type>
- <v>Fun = fun(Key, Value1, Value2) -> Value</v>
- <v>&nbsp;Key = Value1 = Value2 = Value3 = term()</v>
- <v>Dict1 = Dict2 = Dict3 = dictionary()</v>
- </type>
<desc>
- <p><c>merge</c> merges two dictionaries, <c>Dict1</c> and
- <c>Dict2</c>, to create a new dictionary. All the <c>Key</c>
- - <c>Value</c> pairs from both dictionaries are included in
+ <p><c>merge</c> merges two dictionaries, <c><anno>Dict1</anno></c> and
+ <c><anno>Dict2</anno></c>, to create a new dictionary. All the <c><anno>Key</anno></c>
+ - <c><anno>Value</anno></c> pairs from both dictionaries are included in
the new dictionary. If a key occurs in both dictionaries then
- <c>Fun</c> is called with the key and both values to return a
+ <c><anno>Fun</anno></c> is called with the key and both values to return a
new value. <c>merge</c> could be defined as:</p>
<code type="none">
merge(Fun, D1, D2) ->
@@ -217,75 +163,52 @@ merge(Fun, D1, D2) ->
</desc>
</func>
<func>
- <name>new() -> dictionary()</name>
+ <name name="new" arity="0"/>
<fsummary>Create a dictionary</fsummary>
<desc>
<p>This function creates a new dictionary.</p>
</desc>
</func>
<func>
- <name>size(Dict) -> int()</name>
+ <name name="size" arity="1"/>
<fsummary>Return the number of elements in a dictionary</fsummary>
- <type>
- <v>Dict = dictionary()</v>
- </type>
<desc>
- <p>Returns the number of elements in a <c>Dict</c>.</p>
+ <p>Returns the number of elements in a <c><anno>Dict</anno></c>.</p>
</desc>
</func>
<func>
- <name>store(Key, Value, Dict1) -> Dict2</name>
+ <name name="store" arity="3"/>
<fsummary>Store a value in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p>This function stores a <c>Key</c> - <c>Value</c> pair in a
- dictionary. If the <c>Key</c> already exists in <c>Dict1</c>,
- the associated value is replaced by <c>Value</c>.</p>
+ <p>This function stores a <c><anno>Key</anno></c> - <c><anno>Value</anno></c> pair in a
+ dictionary. If the <c><anno>Key</anno></c> already exists in <c><anno>Dict1</anno></c>,
+ the associated value is replaced by <c><anno>Value</anno></c>.</p>
</desc>
</func>
<func>
- <name>to_list(Dict) -> List</name>
+ <name name="to_list" arity="1"/>
<fsummary>Convert a dictionary to a list of pairs</fsummary>
- <type>
- <v>Dict = dictionary()</v>
- <v>List = [{Key, Value}]</v>
- </type>
<desc>
<p>This function converts the dictionary to a list
representation.</p>
</desc>
</func>
<func>
- <name>update(Key, Fun, Dict1) -> Dict2</name>
+ <name name="update" arity="3"/>
<fsummary>Update a value in a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Fun = fun(Value1) -> Value2</v>
- <v>&nbsp;Value1 = Value2 = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p>Update a value in a dictionary by calling <c>Fun</c> on
+ <p>Update a value in a dictionary by calling <c><anno>Fun</anno></c> on
the value to get a new value. An exception is generated if
- <c>Key</c> is not present in the dictionary.</p>
+ <c><anno>Key</anno></c> is not present in the dictionary.</p>
</desc>
</func>
<func>
- <name>update(Key, Fun, Initial, Dict1) -> Dict2</name>
+ <name name="update" arity="4"/>
<fsummary>Update a value in a dictionary</fsummary>
- <type>
- <v>Key = Initial = term()</v>
- <v>Fun = fun(Value1) -> Value2</v>
- <v>&nbsp;Value1 = Value2 = term()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p>Update a value in a dictionary by calling <c>Fun</c> on
- the value to get a new value. If <c>Key</c> is not present
- in the dictionary then <c>Initial</c> will be stored as
+ <p>Update a value in a dictionary by calling <c><anno>Fun</anno></c> on
+ the value to get a new value. If <c><anno>Key</anno></c> is not present
+ in the dictionary then <c><anno>Initial</anno></c> will be stored as
the first value. For example <c>append/3</c> could be defined
as:</p>
<code type="none">
@@ -294,17 +217,12 @@ append(Key, Val, D) ->
</desc>
</func>
<func>
- <name>update_counter(Key, Increment, Dict1) -> Dict2</name>
+ <name name="update_counter" arity="3"/>
<fsummary>Increment a value in a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Increment = number()</v>
- <v>Dict1 = Dict2 = dictionary()</v>
- </type>
<desc>
- <p>Add <c>Increment</c> to the value associated with <c>Key</c>
- and store this value. If <c>Key</c> is not present in
- the dictionary then <c>Increment</c> will be stored as
+ <p>Add <c><anno>Increment</anno></c> to the value associated with <c><anno>Key</anno></c>
+ and store this value. If <c><anno>Key</anno></c> is not present in
+ the dictionary then <c><anno>Increment</anno></c> will be stored as
the first value.</p>
<p>This could be defined as:</p>
<code type="none">
diff --git a/lib/stdlib/doc/src/digraph.xml b/lib/stdlib/doc/src/digraph.xml
index ad256e671f..0afc70ebe0 100644
--- a/lib/stdlib/doc/src/digraph.xml
+++ b/lib/stdlib/doc/src/digraph.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -87,67 +87,79 @@
is a digraph that has no cycles.
</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="d_type"/>
+ </datatype>
+ <datatype>
+ <name name="d_cyclicity"/>
+ </datatype>
+ <datatype>
+ <name name="d_protection"/>
+ </datatype>
+ <datatype>
+ <name><marker id="type-digraph">digraph()</marker></name>
+ <desc><p>A digraph as returned by <c>new/0,1</c>.</p></desc>
+ </datatype>
+ <datatype>
+ <name><marker id="type-edge">edge()</marker></name>
+ </datatype>
+ <datatype>
+ <name name="label"/>
+ </datatype>
+ <datatype>
+ <name><marker id="type-vertex">vertex()</marker></name>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>add_edge(G, E, V1, V2, Label) -> edge() | {error, Reason}</name>
- <name>add_edge(G, V1, V2, Label) -> edge() | {error, Reason}</name>
- <name>add_edge(G, V1, V2) -> edge() | {error, Reason}</name>
+ <name name="add_edge" arity="3"/>
+ <name name="add_edge" arity="4"/>
+ <name name="add_edge" arity="5"/>
<fsummary>Add an edge to a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>E = edge()</v>
- <v>V1 = V2 = vertex()</v>
- <v>Label = label()</v>
- <v>Reason = {bad_edge, Path} | {bad_vertex, V}</v>
- <v>Path = [vertex()]</v>
- </type>
+ <type name="add_edge_err_rsn"/>
<desc>
- <p><c>add_edge/5</c> creates (or modifies) the edge <c>E</c>
- of the digraph <c>G</c>, using <c>Label</c> as the (new)
+ <p><c>add_edge/5</c> creates (or modifies) the edge <c><anno>E</anno></c>
+ of the digraph <c><anno>G</anno></c>, using <c><anno>Label</anno></c> as the (new)
<seealso marker="#label">label</seealso> of the edge. The
edge is <seealso marker="#emanate">emanating</seealso> from
- <c>V1</c> and <seealso marker="#incident">incident</seealso>
- on <c>V2</c>. Returns <c>E</c>.
+ <c><anno>V1</anno></c> and <seealso marker="#incident">incident</seealso>
+ on <c><anno>V2</anno></c>. Returns <c><anno>E</anno></c>.
</p>
- <p><c>add_edge(G,&nbsp;V1,&nbsp;V2,&nbsp;Label)</c> is
+ <p><c>add_edge(<anno>G</anno>,&nbsp;<anno>V1</anno>,&nbsp;<anno>V2</anno>,&nbsp;<anno>Label</anno>)</c> is
equivalent to
- <c>add_edge(G,&nbsp;E,&nbsp;V1,&nbsp;V2,&nbsp;Label)</c>,
- where <c>E</c> is a created edge. The created edge is
+ <c>add_edge(<anno>G</anno>,&nbsp;<anno>E</anno>,&nbsp;<anno>V1</anno>,&nbsp;<anno>V2</anno>,&nbsp;<anno>Label</anno>)</c>,
+ where <c><anno>E</anno></c> is a created edge. The created edge is
represented by the term <c>['$e'&nbsp;|&nbsp;N]</c>, where N
is an integer&nbsp;&gt;=&nbsp;0.
</p>
- <p><c>add_edge(G,&nbsp;V1,&nbsp;V2)</c> is equivalent to
- <c>add_edge(G,&nbsp;V1,&nbsp;V2,&nbsp;[])</c>.
+ <p><c>add_edge(<anno>G</anno>,&nbsp;<anno>V1</anno>,&nbsp;<anno>V2</anno>)</c> is equivalent to
+ <c>add_edge(<anno>G</anno>,&nbsp;<anno>V1</anno>,&nbsp;<anno>V2</anno>,&nbsp;[])</c>.
</p>
<p>If the edge would create a cycle in
an <seealso marker="#acyclic_digraph">acyclic digraph</seealso>,
- then <c>{error,&nbsp;{bad_edge,&nbsp;Path}}</c> is returned. If
- either of <c>V1</c> or <c>V2</c> is not a vertex of the
- digraph <c>G</c>, then
- <c>{error,&nbsp;{bad_vertex,&nbsp;</c>V<c>}}</c> is
- returned, V&nbsp;=&nbsp;<c>V1</c> or
- V&nbsp;=&nbsp;<c>V2</c>.
+ then <c>{error,&nbsp;{bad_edge,&nbsp;<anno>Path</anno>}}</c> is returned. If
+ either of <c><anno>V1</anno></c> or <c><anno>V2</anno></c> is not a vertex of the
+ digraph <c><anno>G</anno></c>, then
+ <c>{error,&nbsp;{bad_vertex,&nbsp;</c><anno>V</anno><c>}}</c> is
+ returned, <anno>V</anno>&nbsp;=&nbsp;<c><anno>V1</anno></c> or
+ <anno>V</anno>&nbsp;=&nbsp;<c><anno>V2</anno></c>.
</p>
</desc>
</func>
<func>
- <name>add_vertex(G, V, Label) -> vertex()</name>
- <name>add_vertex(G, V) -> vertex()</name>
- <name>add_vertex(G) -> vertex()</name>
+ <name name="add_vertex" arity="1"/>
+ <name name="add_vertex" arity="2"/>
+ <name name="add_vertex" arity="3"/>
<fsummary>Add or modify a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- <v>Label = label()</v>
- </type>
<desc>
- <p><c>add_vertex/3</c> creates (or modifies) the vertex <c>V</c>
- of the digraph <c>G</c>, using <c>Label</c> as the (new)
+ <p><c>add_vertex/3</c> creates (or modifies) the vertex <c><anno>V</anno></c>
+ of the digraph <c><anno>G</anno></c>, using <c><anno>Label</anno></c> as the (new)
<seealso marker="#label">label</seealso> of the
- vertex. Returns <c>V</c>.
+ vertex. Returns <c><anno>V</anno></c>.
</p>
- <p><c>add_vertex(G,&nbsp;V)</c> is equivalent to
- <c>add_vertex(G,&nbsp;V,&nbsp;[])</c>.
+ <p><c>add_vertex(<anno>G</anno>,&nbsp;<anno>V</anno>)</c> is equivalent to
+ <c>add_vertex(<anno>G</anno>,&nbsp;<anno>V</anno>,&nbsp;[])</c>.
</p>
<p><c>add_vertex/1</c> creates a vertex using the empty list
as label, and returns the created vertex. The created vertex
@@ -157,304 +169,227 @@
</desc>
</func>
<func>
- <name>del_edge(G, E) -> true</name>
+ <name name="del_edge" arity="2"/>
<fsummary>Delete an edge from a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>E = edge()</v>
- </type>
<desc>
- <p>Deletes the edge <c>E</c> from the digraph <c>G</c>.
+ <p>Deletes the edge <c><anno>E</anno></c> from the digraph <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>del_edges(G, Edges) -> true</name>
+ <name name="del_edges" arity="2"/>
<fsummary>Delete edges from a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>Edges = [edge()]</v>
- </type>
<desc>
- <p>Deletes the edges in the list <c>Edges</c> from the digraph
- <c>G</c>.
+ <p>Deletes the edges in the list <c><anno>Edges</anno></c> from the digraph
+ <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>del_path(G, V1, V2) -> true</name>
+ <name name="del_path" arity="3"/>
<fsummary>Delete paths from a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V1 = V2 = vertex()</v>
- </type>
<desc>
- <p>Deletes edges from the digraph <c>G</c> until there are no
+ <p>Deletes edges from the digraph <c><anno>G</anno></c> until there are no
<seealso marker="#path">paths</seealso> from the vertex
- <c>V1</c> to the vertex <c>V2</c>.
+ <c><anno>V1</anno></c> to the vertex <c><anno>V2</anno></c>.
</p>
<p>A sketch of the procedure employed: Find an arbitrary
<seealso marker="#simple_path">simple path</seealso>
- v[1],&nbsp;v[2],&nbsp;...,&nbsp;v[k] from <c>V1</c> to
- <c>V2</c> in <c>G</c>. Remove all edges of
- <c>G</c> <seealso marker="#emanate">emanating</seealso> from v[i]
+ v[1],&nbsp;v[2],&nbsp;...,&nbsp;v[k] from <c><anno>V1</anno></c> to
+ <c><anno>V2</anno></c> in <c><anno>G</anno></c>. Remove all edges of
+ <c><anno>G</anno></c> <seealso marker="#emanate">emanating</seealso> from v[i]
and <seealso marker="#incident">incident</seealso> to v[i+1] for
1&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;k (including multiple
- edges). Repeat until there is no path between <c>V1</c> and
- <c>V2</c>.
+ edges). Repeat until there is no path between <c><anno>V1</anno></c> and
+ <c><anno>V2</anno></c>.
</p>
</desc>
</func>
<func>
- <name>del_vertex(G, V) -> true</name>
+ <name name="del_vertex" arity="2"/>
<fsummary>Delete a vertex from a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- </type>
<desc>
- <p>Deletes the vertex <c>V</c> from the digraph <c>G</c>. Any
+ <p>Deletes the vertex <c><anno>V</anno></c> from the digraph <c><anno>G</anno></c>. Any
edges <seealso marker="#emanate">emanating</seealso> from
- <c>V</c> or <seealso marker="#incident">incident</seealso>
- on <c>V</c> are also deleted.
+ <c><anno>V</anno></c> or <seealso marker="#incident">incident</seealso>
+ on <c><anno>V</anno></c> are also deleted.
</p>
</desc>
</func>
<func>
- <name>del_vertices(G, Vertices) -> true</name>
+ <name name="del_vertices" arity="2"/>
<fsummary>Delete vertices from a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
- <p>Deletes the vertices in the list <c>Vertices</c> from the
- digraph <c>G</c>.
+ <p>Deletes the vertices in the list <c><anno>Vertices</anno></c> from the
+ digraph <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>delete(G) -> true</name>
+ <name name="delete" arity="1"/>
<fsummary>Delete a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- </type>
<desc>
- <p>Deletes the digraph <c>G</c>. This call is important
- because digraphs are implemented with <c>Ets</c>. There is
- no garbage collection of <c>Ets</c> tables. The digraph
+ <p>Deletes the digraph <c><anno>G</anno></c>. This call is important
+ because digraphs are implemented with <c>ETS</c>. There is
+ no garbage collection of <c>ETS</c> tables. The digraph
will, however, be deleted if the process that created the
digraph terminates.
</p>
</desc>
</func>
<func>
- <name>edge(G, E) -> {E, V1, V2, Label} | false</name>
+ <name name="edge" arity="2"/>
<fsummary>Return the vertices and the label of an edge of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>E = edge()</v>
- <v>V1 = V2 = vertex()</v>
- <v>Label = label()</v>
- </type>
<desc>
- <p>Returns <c>{E,&nbsp;V1,&nbsp;V2,&nbsp;Label}</c> where
- <c>Label</c> is the <seealso marker="#label">label</seealso>
+ <p>Returns <c>{<anno>E</anno>,&nbsp;<anno>V1</anno>,&nbsp;<anno>V2</anno>,&nbsp;<anno>Label</anno>}</c> where
+ <c><anno>Label</anno></c> is the <seealso marker="#label">label</seealso>
of the edge
- <c>E</c> <seealso marker="#emanate">emanating</seealso> from
- <c>V1</c> and <seealso marker="#incident">incident</seealso> on
- <c>V2</c> of the digraph <c>G</c>.
- If there is no edge <c>E</c> of the
- digraph <c>G</c>, then <c>false</c> is returned.
+ <c><anno>E</anno></c> <seealso marker="#emanate">emanating</seealso> from
+ <c><anno>V1</anno></c> and <seealso marker="#incident">incident</seealso> on
+ <c><anno>V2</anno></c> of the digraph <c><anno>G</anno></c>.
+ If there is no edge <c><anno>E</anno></c> of the
+ digraph <c><anno>G</anno></c>, then <c>false</c> is returned.
</p>
</desc>
</func>
<func>
- <name>edges(G) -> Edges</name>
+ <name name="edges" arity="1"/>
<fsummary>Return all edges of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>Edges = [edge()]</v>
- </type>
<desc>
- <p>Returns a list of all edges of the digraph <c>G</c>, in
+ <p>Returns a list of all edges of the digraph <c><anno>G</anno></c>, in
some unspecified order.
</p>
</desc>
</func>
<func>
- <name>edges(G, V) -> Edges</name>
+ <name name="edges" arity="2"/>
<fsummary>Return the edges emanating from or incident on a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- <v>Edges = [edge()]</v>
- </type>
<desc>
<p>Returns a list of all
edges <seealso marker="#emanate">emanating</seealso> from
- or <seealso marker="#incident">incident</seealso> on <c>V</c>
- of the digraph <c>G</c>, in some unspecified order.</p>
+ or <seealso marker="#incident">incident</seealso> on <c><anno>V</anno></c>
+ of the digraph <c><anno>G</anno></c>, in some unspecified order.</p>
</desc>
</func>
<func>
- <name>get_cycle(G, V) -> Vertices | false</name>
+ <name name="get_cycle" arity="2"/>
<fsummary>Find one cycle in a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V1 = V2 = vertex()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>If there is
a <seealso marker="#simple_cycle">simple cycle</seealso> of
length two or more through the vertex
- <c>V</c>, then the cycle is returned as a list
- <c>[V,&nbsp;...,&nbsp;V]</c> of vertices, otherwise if there
+ <c><anno>V</anno></c>, then the cycle is returned as a list
+ <c>[<anno>V</anno>,&nbsp;...,&nbsp;<anno>V</anno>]</c> of vertices, otherwise if there
is a <seealso marker="#loop">loop</seealso> through
- <c>V</c>, then the loop is returned as a list <c>[V]</c>. If
- there are no cycles through <c>V</c>, then <c>false</c> is
+ <c><anno>V</anno></c>, then the loop is returned as a list <c>[<anno>V</anno>]</c>. If
+ there are no cycles through <c><anno>V</anno></c>, then <c>false</c> is
returned.
</p>
<p><c>get_path/3</c> is used for finding a simple cycle
- through <c>V</c>.
+ through <c><anno>V</anno></c>.
</p>
</desc>
</func>
<func>
- <name>get_path(G, V1, V2) -> Vertices | false</name>
+ <name name="get_path" arity="3"/>
<fsummary>Find one path in a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V1 = V2 = vertex()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Tries to find
a <seealso marker="#simple_path">simple path</seealso> from
- the vertex <c>V1</c> to the vertex
- <c>V2</c> of the digraph <c>G</c>. Returns the path as a
- list <c>[V1,&nbsp;...,&nbsp;V2]</c> of vertices, or
- <c>false</c> if no simple path from <c>V1</c> to <c>V2</c>
+ the vertex <c><anno>V1</anno></c> to the vertex
+ <c><anno>V2</anno></c> of the digraph <c><anno>G</anno></c>. Returns the path as a
+ list <c>[<anno>V1</anno>,&nbsp;...,&nbsp;<anno>V2</anno>]</c> of vertices, or
+ <c>false</c> if no simple path from <c><anno>V1</anno></c> to <c><anno>V2</anno></c>
of length one or more exists.
</p>
- <p>The digraph <c>G</c> is traversed in a depth-first manner,
+ <p>The digraph <c><anno>G</anno></c> is traversed in a depth-first manner,
and the first path found is returned.
</p>
</desc>
</func>
<func>
- <name>get_short_cycle(G, V) -> Vertices | false</name>
+ <name name="get_short_cycle" arity="2"/>
<fsummary>Find one short cycle in a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V1 = V2 = vertex()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Tries to find an as short as
possible <seealso marker="#simple_cycle">simple cycle</seealso> through
- the vertex <c>V</c> of the digraph <c>G</c>. Returns the cycle
- as a list <c>[V,&nbsp;...,&nbsp;V]</c> of vertices, or
- <c>false</c> if no simple cycle through <c>V</c> exists.
+ the vertex <c><anno>V</anno></c> of the digraph <c>G</c>. Returns the cycle
+ as a list <c>[<anno>V</anno>,&nbsp;...,&nbsp;<anno>V</anno>]</c> of vertices, or
+ <c>false</c> if no simple cycle through <c><anno>V</anno></c> exists.
Note that a <seealso marker="#loop">loop</seealso> through
- <c>V</c> is returned as the list <c>[V,&nbsp;V]</c>.
+ <c><anno>V</anno></c> is returned as the list <c>[<anno>V</anno>,&nbsp;<anno>V</anno>]</c>.
</p>
<p><c>get_short_path/3</c> is used for finding a simple cycle
- through <c>V</c>.
+ through <c><anno>V</anno></c>.
</p>
</desc>
</func>
<func>
- <name>get_short_path(G, V1, V2) -> Vertices | false</name>
+ <name name="get_short_path" arity="3"/>
<fsummary>Find one short path in a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V1 = V2 = vertex()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Tries to find an as short as
possible <seealso marker="#simple_path">simple path</seealso> from
- the vertex <c>V1</c> to the vertex <c>V2</c> of the digraph <c>G</c>.
- Returns the path as a list <c>[V1,&nbsp;...,&nbsp;V2]</c> of
- vertices, or <c>false</c> if no simple path from <c>V1</c>
- to <c>V2</c> of length one or more exists.
+ the vertex <c><anno>V1</anno></c> to the vertex <c><anno>V2</anno></c> of the digraph <c><anno>G</anno></c>.
+ Returns the path as a list <c>[<anno>V1</anno>,&nbsp;...,&nbsp;<anno>V2</anno>]</c> of
+ vertices, or <c>false</c> if no simple path from <c><anno>V1</anno></c>
+ to <c><anno>V2</anno></c> of length one or more exists.
</p>
- <p>The digraph <c>G</c> is traversed in a breadth-first
+ <p>The digraph <c><anno>G</anno></c> is traversed in a breadth-first
manner, and the first path found is returned.
</p>
</desc>
</func>
<func>
- <name>in_degree(G, V) -> integer()</name>
+ <name name="in_degree" arity="2"/>
<fsummary>Return the in-degree of a vertex of a digraph.</fsummary>
- <type>
- <v>G= digraph()</v>
- <v>V = vertex()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#in_degree">in-degree</seealso> of the vertex
- <c>V</c> of the digraph <c>G</c>.
+ <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>in_edges(G, V) -> Edges</name>
+ <name name="in_edges" arity="2"/>
<fsummary>Return all edges incident on a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- <v>Edges = [edge()]</v>
- </type>
<desc>
<p>Returns a list of all
edges <seealso marker="#incident">incident</seealso> on
- <c>V</c> of the digraph <c>G</c>, in some unspecified order.
+ <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>, in some unspecified order.
</p>
</desc>
</func>
<func>
- <name>in_neighbours(G, V) -> Vertices</name>
+ <name name="in_neighbours" arity="2"/>
<fsummary>Return all in-neighbours of a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Returns a list of
all <seealso marker="#in_neighbour">in-neighbours</seealso> of
- <c>V</c> of the digraph <c>G</c>, in some unspecified order.
+ <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>, in some unspecified order.
</p>
</desc>
</func>
<func>
- <name>info(G) -> InfoList</name>
+ <name name="info" arity="1"/>
<fsummary>Return information about a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>InfoList = [{cyclicity, Cyclicity}, {memory, NoWords}, {protection, Protection}]</v>
- <v>Cyclicity = cyclic | acyclic</v>
- <v>Protection = protected | private</v>
- <v>NoWords = integer() >= 0</v>
- </type>
+ <type name="d_cyclicity"/>
+ <type name="d_protection"/>
<desc>
<p>Returns a list of <c>{Tag, Value}</c> pairs describing the
- digraph <c>G</c>. The following pairs are returned:
+ digraph <c><anno>G</anno></c>. The following pairs are returned:
</p>
<list type="bulleted">
<item>
- <p><c>{cyclicity, Cyclicity}</c>, where <c>Cyclicity</c>
+ <p><c>{cyclicity, <anno>Cyclicity</anno>}</c>, where <c><anno>Cyclicity</anno></c>
is <c>cyclic</c> or <c>acyclic</c>, according to the
options given to <c>new</c>.</p>
</item>
<item>
- <p><c>{memory, NoWords}</c>, where <c>NoWords</c> is
- the number of words allocated to the <c>ets</c> tables.</p>
+ <p><c>{memory, <anno>NoWords</anno>}</c>, where <c><anno>NoWords</anno></c> is
+ the number of words allocated to the <c>ETS</c> tables.</p>
</item>
<item>
- <p><c>{protection, Protection}</c>, where <c>Protection</c>
+ <p><c>{protection, <anno>Protection</anno>}</c>, where <c><anno>Protection</anno></c>
is <c>protected</c> or <c>private</c>, according
to the options given to <c>new</c>.</p>
</item>
@@ -462,7 +397,7 @@
</desc>
</func>
<func>
- <name>new() -> digraph()</name>
+ <name name="new" arity="0"/>
<fsummary>Return a protected empty digraph, where cycles are allowed.</fsummary>
<desc>
<p>Equivalent to <c>new([])</c>.
@@ -470,15 +405,16 @@
</desc>
</func>
<func>
- <name>new(Type) -> digraph()</name>
+ <name name="new" arity="1"/>
<fsummary>Create a new empty digraph.</fsummary>
- <type>
- <v>Type = [cyclic | acyclic | private | protected]</v>
- </type>
+ <type variable="Type"/>
+ <type name="d_type"/>
+ <type name="d_cyclicity"/>
+ <type name="d_protection"/>
<desc>
<p>Returns
an <seealso marker="#empty_digraph">empty digraph</seealso> with
- properties according to the options in <c>Type</c>:</p>
+ properties according to the options in <c><anno>Type</anno></c>:</p>
<taglist>
<tag><c>cyclic</c></tag>
<item>Allow <seealso marker="#cycle">cycles</seealso> in the
@@ -491,101 +427,72 @@
<item>The digraph can be read and modified by the creating
process only.</item>
</taglist>
- <p>If an unrecognized type option <c>T</c> is given or <c>Type</c>
+ <p>If an unrecognized type option <c>T</c> is given or <c><anno>Type</anno></c>
is not a proper list, there will be a <c>badarg</c> exception.
</p>
</desc>
</func>
<func>
- <name>no_edges(G) -> integer() >= 0</name>
+ <name name="no_edges" arity="1"/>
<fsummary>Return the number of edges of the a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- </type>
<desc>
- <p>Returns the number of edges of the digraph <c>G</c>.
+ <p>Returns the number of edges of the digraph <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>no_vertices(G) -> integer() >= 0</name>
+ <name name="no_vertices" arity="1"/>
<fsummary>Return the number of vertices of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- </type>
<desc>
- <p>Returns the number of vertices of the digraph <c>G</c>.
+ <p>Returns the number of vertices of the digraph <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>out_degree(G, V) -> integer()</name>
+ <name name="out_degree" arity="2"/>
<fsummary>Return the out-degree of a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#out_degree">out-degree</seealso> of the vertex
- <c>V</c> of the digraph <c>G</c>.
+ <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>out_edges(G, V) -> Edges</name>
+ <name name="out_edges" arity="2"/>
<fsummary>Return all edges emanating from a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- <v>Edges = [edge()]</v>
- </type>
<desc>
<p>Returns a list of all
edges <seealso marker="#emanate">emanating</seealso> from
- <c>V</c> of the digraph <c>G</c>, in some unspecified order.
+ <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>, in some unspecified order.
</p>
</desc>
</func>
<func>
- <name>out_neighbours(G, V) -> Vertices</name>
+ <name name="out_neighbours" arity="2"/>
<fsummary>Return all out-neighbours of a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Returns a list of
all <seealso marker="#out_neighbour">out-neighbours</seealso> of
- <c>V</c> of the digraph <c>G</c>, in some unspecified order.
+ <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>, in some unspecified order.
</p>
</desc>
</func>
<func>
- <name>vertex(G, V) -> {V, Label} | false</name>
+ <name name="vertex" arity="2"/>
<fsummary>Return the label of a vertex of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>V = vertex()</v>
- <v>Label = label()</v>
- </type>
<desc>
- <p>Returns <c>{V,&nbsp;Label}</c> where <c>Label</c> is the
+ <p>Returns <c>{<anno>V</anno>,&nbsp;<anno>Label</anno>}</c> where <c><anno>Label</anno></c> is the
<seealso marker="#label">label</seealso> of the vertex
- <c>V</c> of the digraph <c>G</c>, or <c>false</c> if there
- is no vertex <c>V</c> of the digraph <c>G</c>.
+ <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>, or <c>false</c> if there
+ is no vertex <c><anno>V</anno></c> of the digraph <c><anno>G</anno></c>.
</p>
</desc>
</func>
<func>
- <name>vertices(G) -> Vertices</name>
+ <name name="vertices" arity="1"/>
<fsummary>Return all vertices of a digraph.</fsummary>
- <type>
- <v>G = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
- <p>Returns a list of all vertices of the digraph <c>G</c>, in
+ <p>Returns a list of all vertices of the digraph <c><anno>G</anno></c>, in
some unspecified order.
</p>
</desc>
diff --git a/lib/stdlib/doc/src/digraph_utils.xml b/lib/stdlib/doc/src/digraph_utils.xml
index 4b137456b3..e44632bfd2 100644
--- a/lib/stdlib/doc/src/digraph_utils.xml
+++ b/lib/stdlib/doc/src/digraph_utils.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2000</year><year>2009</year>
+ <year>2000</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -119,49 +119,43 @@
considering all edges undirected.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name><marker id="type-digraph">digraph()</marker></name>
+ <desc><p>A digraph as returned by <c>digraph:new/0,1</c>.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>arborescence_root(Digraph) -> no | {yes, Root}</name>
+ <name name="arborescence_root" arity="1"/>
<fsummary>Check if a digraph is an arborescence.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Root = vertex()</v>
- </type>
<desc>
-
- <p>Returns <c>{yes, Root}</c> if <c>Root</c> is
+ <p>Returns <c>{yes, <anno>Root</anno>}</c> if <c><anno>Root</anno></c> is
the <seealso marker="#root">root</seealso> of the arborescence
- <c>Digraph</c>, <c>no</c> otherwise.
+ <c><anno>Digraph</anno></c>, <c>no</c> otherwise.
</p>
</desc>
</func>
<func>
- <name>components(Digraph) -> [Component]</name>
+ <name name="components" arity="1"/>
<fsummary>Return the components of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Component = [vertex()]</v>
- </type>
<desc>
<p>Returns a list
of <seealso marker="#components">connected components</seealso>.
Each component is represented by its
vertices. The order of the vertices and the order of the
components are arbitrary. Each vertex of the digraph
- <c>Digraph</c> occurs in exactly one component.
+ <c><anno>Digraph</anno></c> occurs in exactly one component.
</p>
</desc>
</func>
<func>
- <name>condensation(Digraph) -> CondensedDigraph</name>
+ <name name="condensation" arity="1"/>
<fsummary>Return a condensed graph of a digraph.</fsummary>
- <type>
- <v>Digraph = CondensedDigraph = digraph()</v>
- </type>
<desc>
<p>Creates a digraph where the vertices are
the <seealso marker="#strong_components">strongly connected
- components</seealso> of <c>Digraph</c> as returned by
+ components</seealso> of <c><anno>Digraph</anno></c> as returned by
<c>strong_components/1</c>. If X and Y are strongly
connected components, and there exist vertices x and y in X
and Y respectively such that there is an
@@ -169,7 +163,7 @@
and <seealso marker="#incident">incident</seealso> on y, then
an edge emanating from X and incident on Y is created.
</p>
- <p>The created digraph has the same type as <c>Digraph</c>.
+ <p>The created digraph has the same type as <c><anno>Digraph</anno></c>.
All vertices and edges have the
default <seealso marker="#label">label</seealso> <c>[]</c>.
</p>
@@ -181,12 +175,8 @@
</desc>
</func>
<func>
- <name>cyclic_strong_components(Digraph) -> [StrongComponent]</name>
+ <name name="cyclic_strong_components" arity="1"/>
<fsummary>Return the cyclic strong components of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>StrongComponent = [vertex()]</v>
- </type>
<desc>
<p>Returns a list of <seealso marker="#strong_components">strongly
connected components</seealso>.
@@ -194,67 +184,50 @@
by its vertices. The order of the vertices and the order of
the components are arbitrary. Only vertices that are
included in some <seealso marker="#cycle">cycle</seealso> in
- <c>Digraph</c> are returned, otherwise the returned list is
+ <c><anno>Digraph</anno></c> are returned, otherwise the returned list is
equal to that returned by <c>strong_components/1</c>.
</p>
</desc>
</func>
<func>
- <name>is_acyclic(Digraph) -> bool()</name>
+ <name name="is_acyclic" arity="1"/>
<fsummary>Check if a digraph is acyclic.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- </type>
<desc>
<p>Returns <c>true</c> if and only if the digraph
- <c>Digraph</c> is <seealso marker="#acyclic_digraph">acyclic</seealso>.</p>
+ <c><anno>Digraph</anno></c> is <seealso marker="#acyclic_digraph">acyclic</seealso>.</p>
</desc>
</func>
<func>
- <name>is_arborescence(Digraph) -> bool()</name>
+ <name name="is_arborescence" arity="1"/>
<fsummary>Check if a digraph is an arborescence.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- </type>
<desc>
<p>Returns <c>true</c> if and only if the digraph
- <c>Digraph</c> is
+ <c><anno>Digraph</anno></c> is
an <seealso marker="#arborescence">arborescence</seealso>.</p>
</desc>
</func>
<func>
- <name>is_tree(Digraph) -> bool()</name>
+ <name name="is_tree" arity="1"/>
<fsummary>Check if a digraph is a tree.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- </type>
<desc>
<p>Returns <c>true</c> if and only if the digraph
- <c>Digraph</c> is
+ <c><anno>Digraph</anno></c> is
a <seealso marker="#tree">tree</seealso>.</p>
</desc>
</func>
<func>
- <name>loop_vertices(Digraph) -> Vertices</name>
+ <name name="loop_vertices" arity="1"/>
<fsummary>Return the vertices of a digraph included in some loop.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
- <p>Returns a list of all vertices of <c>Digraph</c> that are
+ <p>Returns a list of all vertices of <c><anno>Digraph</anno></c> that are
included in some <seealso marker="#loop">loop</seealso>.</p>
</desc>
</func>
<func>
- <name>postorder(Digraph) -> Vertices</name>
+ <name name="postorder" arity="1"/>
<fsummary>Return the vertices of a digraph in post-order.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
- <p>Returns all vertices of the digraph <c>Digraph</c>. The
+ <p>Returns all vertices of the digraph <c><anno>Digraph</anno></c>. The
order is given by
a <seealso marker="#depth_first_traversal">depth-first
traversal</seealso> of the digraph, collecting visited
@@ -266,14 +239,10 @@
</desc>
</func>
<func>
- <name>preorder(Digraph) -> Vertices</name>
+ <name name="preorder" arity="1"/>
<fsummary>Return the vertices of a digraph in pre-order.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
- <p>Returns all vertices of the digraph <c>Digraph</c>. The
+ <p>Returns all vertices of the digraph <c><anno>Digraph</anno></c>. The
order is given by
a <seealso marker="#depth_first_traversal">depth-first
traversal</seealso> of the digraph, collecting visited
@@ -281,119 +250,94 @@
</desc>
</func>
<func>
- <name>reachable(Vertices, Digraph) -> Vertices</name>
+ <name name="reachable" arity="2"/>
<fsummary>Return the vertices reachable from some vertices of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Returns an unsorted list of digraph vertices such that for
each vertex in the list, there is
- a <seealso marker="#path">path</seealso> in <c>Digraph</c> from some
- vertex of <c>Vertices</c> to the vertex. In particular,
+ a <seealso marker="#path">path</seealso> in <c><anno>Digraph</anno></c> from some
+ vertex of <c><anno>Vertices</anno></c> to the vertex. In particular,
since paths may have length zero, the vertices of
- <c>Vertices</c> are included in the returned list.
+ <c><anno>Vertices</anno></c> are included in the returned list.
</p>
</desc>
</func>
<func>
- <name>reachable_neighbours(Vertices, Digraph) -> Vertices</name>
+ <name name="reachable_neighbours" arity="2"/>
<fsummary>Return the neighbours reachable from some vertices of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Returns an unsorted list of digraph vertices such that for
each vertex in the list, there is
- a <seealso marker="#path">path</seealso> in <c>Digraph</c> of length
- one or more from some vertex of <c>Vertices</c> to the
+ a <seealso marker="#path">path</seealso> in <c><anno>Digraph</anno></c> of length
+ one or more from some vertex of <c><anno>Vertices</anno></c> to the
vertex. As a consequence, only those vertices
- of <c>Vertices</c> that are included in
+ of <c><anno>Vertices</anno></c> that are included in
some <seealso marker="#cycle">cycle</seealso> are returned.
</p>
</desc>
</func>
<func>
- <name>reaching(Vertices, Digraph) -> Vertices</name>
+ <name name="reaching" arity="2"/>
<fsummary>Return the vertices that reach some vertices of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Returns an unsorted list of digraph vertices such that for
each vertex in the list, there is
a <seealso marker="#path">path</seealso> from the vertex to some
- vertex of <c>Vertices</c>. In particular, since paths may have
- length zero, the vertices of <c>Vertices</c> are included in
+ vertex of <c><anno>Vertices</anno></c>. In particular, since paths may have
+ length zero, the vertices of <c><anno>Vertices</anno></c> are included in
the returned list.
</p>
</desc>
</func>
<func>
- <name>reaching_neighbours(Vertices, Digraph) -> Vertices</name>
+ <name name="reaching_neighbours" arity="2"/>
<fsummary>Return the neighbours that reach some vertices of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Returns an unsorted list of digraph vertices such that for
each vertex in the list, there is
a <seealso marker="#path">path</seealso> of length one or more
- from the vertex to some vertex of <c>Vertices</c>. As a consequence,
- only those vertices of <c>Vertices</c> that are included in
+ from the vertex to some vertex of <c><anno>Vertices</anno></c>. As a consequence,
+ only those vertices of <c><anno>Vertices</anno></c> that are included in
some <seealso marker="#cycle">cycle</seealso> are returned.
</p>
</desc>
</func>
<func>
- <name>strong_components(Digraph) -> [StrongComponent]</name>
+ <name name="strong_components" arity="1"/>
<fsummary>Return the strong components of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>StrongComponent = [vertex()]</v>
- </type>
<desc>
<p>Returns a list of <seealso marker="#strong_components">strongly
connected components</seealso>.
Each strongly component is represented
by its vertices. The order of the vertices and the order of
the components are arbitrary. Each vertex of the digraph
- <c>Digraph</c> occurs in exactly one strong component.
+ <c><anno>Digraph</anno></c> occurs in exactly one strong component.
</p>
</desc>
</func>
<func>
- <name>subgraph(Digraph, Vertices [, Options]) -> Subgraph</name>
+ <name name="subgraph" arity="2"/>
+ <name name="subgraph" arity="3"/>
<fsummary>Return a subgraph of a digraph.</fsummary>
- <type>
- <v>Digraph = Subgraph = digraph()</v>
- <v>Options = [{type, SubgraphType}, {keep_labels, bool()}]</v>
- <v>SubgraphType = inherit | type()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Creates a maximal <seealso marker="#subgraph">subgraph</seealso> of <c>Digraph</c> having
- as vertices those vertices of <c>Digraph</c> that are
- mentioned in <c>Vertices</c>.
+ as vertices those vertices of <c><anno>Digraph</anno></c> that are
+ mentioned in <c><anno>Vertices</anno></c>.
</p>
<p>If the value of the option <c>type</c> is <c>inherit</c>,
- which is the default, then the type of <c>Digraph</c> is used
+ which is the default, then the type of <c><anno>Digraph</anno></c> is used
for the subgraph as well. Otherwise the option value of <c>type</c>
is used as argument to <c>digraph:new/1</c>.
</p>
<p>If the value of the option <c>keep_labels</c> is <c>true</c>,
which is the default, then
the <seealso marker="#label">labels</seealso> of vertices and edges
- of <c>Digraph</c> are used for the subgraph as well. If the value
+ of <c><anno>Digraph</anno></c> are used for the subgraph as well. If the value
is <c>false</c>, then the default label, <c>[]</c>, is used
for the subgraph's vertices and edges.
</p>
- <p><c>subgraph(Digraph, Vertices)</c> is equivalent to
- <c>subgraph(Digraph, Vertices, [])</c>.
+ <p><c>subgraph(<anno>Digraph</anno>, <anno>Vertices</anno>)</c> is equivalent to
+ <c>subgraph(<anno>Digraph</anno>, <anno>Vertices</anno>, [])</c>.
</p>
<p>There will be a <c>badarg</c> exception if any of the arguments
are invalid.
@@ -401,16 +345,12 @@
</desc>
</func>
<func>
- <name>topsort(Digraph) -> Vertices | false</name>
+ <name name="topsort" arity="1"/>
<fsummary>Return a topological sorting of the vertices of a digraph.</fsummary>
- <type>
- <v>Digraph = digraph()</v>
- <v>Vertices = [vertex()]</v>
- </type>
<desc>
<p>Returns a <seealso marker="#topsort">topological
ordering</seealso> of the vertices of the digraph
- <c>Digraph</c> if such an ordering exists, <c>false</c>
+ <c><anno>Digraph</anno></c> if such an ordering exists, <c>false</c>
otherwise. For each vertex in the returned list, there are
no <seealso marker="#out_neighbour">out-neighbours</seealso>
that occur earlier in the list.</p>
diff --git a/lib/stdlib/doc/src/epp.xml b/lib/stdlib/doc/src/epp.xml
index e6b48b270a..488499581f 100644
--- a/lib/stdlib/doc/src/epp.xml
+++ b/lib/stdlib/doc/src/epp.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -38,65 +38,61 @@
by <c>compile</c> to preprocess macros and include files before
the actual parsing takes place.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="macros"></name>
+ </datatype>
+ <datatype>
+ <name name="epp_handle"></name>
+ <desc><p>Handle to the epp server.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>open(FileName, IncludePath) -> {ok,Epp} | {error, ErrorDescriptor}</name>
- <name>open(FileName, IncludePath, PredefMacros) -> {ok,Epp} | {error, ErrorDescriptor}</name>
+ <name name="open" arity="2"/>
+ <name name="open" arity="3"/>
<fsummary>Open a file for preprocessing</fsummary>
- <type>
- <v>FileName = atom() | string()</v>
- <v>IncludePath = [DirectoryName]</v>
- <v>DirectoryName = atom() | string()</v>
- <v>PredefMacros = [{atom(),term()}]</v>
- <v>Epp = pid() -- handle to the epp server</v>
- <v>ErrorDescriptor = term()</v>
- </type>
<desc>
<p>Opens a file for preprocessing.</p>
</desc>
</func>
<func>
- <name>close(Epp) -> ok</name>
+ <name name="close" arity="1"/>
<fsummary>Close the preprocessing of the file associated with <c>Epp</c></fsummary>
- <type>
- <v>Epp = pid() -- handle to the epp server</v>
- </type>
<desc>
<p>Closes the preprocessing of a file.</p>
</desc>
</func>
<func>
- <name>parse_erl_form(Epp) -> {ok, AbsForm} | {eof, Line} | {error, ErrorInfo}</name>
+ <name name="parse_erl_form" arity="1"/>
<fsummary>Return the next Erlang form from the opened Erlang source file</fsummary>
- <type>
- <v>Epp = pid()</v>
- <v>AbsForm = term()</v>
- <v>Line = integer()</v>
- <v>ErrorInfo = see separate description below.</v>
- </type>
<desc>
<p>Returns the next Erlang form from the opened Erlang source file.
- The tuple <c>{eof, Line}</c> is returned at end-of-file. The first
+ The tuple <c>{eof, <anno>Line</anno>}</c> is returned at end-of-file. The first
form corresponds to an implicit attribute <c>-file(File,1).</c>, where
<c>File</c> is the name of the file.</p>
</desc>
</func>
<func>
- <name>parse_file(FileName,IncludePath,PredefMacro) -> {ok,[Form]} | {error,OpenError}</name>
- <fsummary>Preprocesse and parse an Erlang source file</fsummary>
- <type>
- <v>FileName = atom() | string()</v>
- <v>IncludePath = [DirectoryName]</v>
- <v>DirectoryName = atom() | string()</v>
- <v>PredefMacros = [{atom(),term()}]</v>
- <v>Form = term() -- same as returned by erl_parse:parse_form</v>
- </type>
+ <name name="parse_file" arity="3"/>
+ <fsummary>Preprocess and parse an Erlang source file</fsummary>
<desc>
<p>Preprocesses and parses an Erlang source file.
- Note that the tuple <c>{eof, Line}</c> returned at end-of-file is
+ Note that the tuple <c>{eof, <anno>Line</anno>}</c> returned at end-of-file is
included as a "form".</p>
</desc>
</func>
+ <func>
+ <name name="format_error" arity="1"/>
+ <fsummary>Format an error descriptor</fsummary>
+ <desc>
+ <p>Takes an <c><anno>ErrorDescriptor</anno></c> and returns
+ a string which
+ describes the error or warning. This function is usually
+ called implicitly when processing an <c>ErrorInfo</c>
+ structure (see below).</p>
+ </desc>
+ </func>
</funcs>
<section>
diff --git a/lib/stdlib/doc/src/erl_eval.xml b/lib/stdlib/doc/src/erl_eval.xml
index 62af23c5eb..d0622594d9 100644
--- a/lib/stdlib/doc/src/erl_eval.xml
+++ b/lib/stdlib/doc/src/erl_eval.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -36,63 +36,108 @@
<description>
<p>This module provides an interpreter for Erlang expressions. The
expressions are in the abstract syntax as returned by
- <c>erl_parse</c>, the Erlang parser, or a call to
- <c>io:parse_erl_exprs/2</c>.</p>
+ <seealso marker="erl_parse"><c>erl_parse</c></seealso>,
+ the Erlang parser, or <seealso marker="io">
+ <c>io</c></seealso>.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="bindings"/>
+ </datatype>
+ <datatype>
+ <name name="binding_struct"/>
+ <desc><p>A binding structure.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="expression"/>
+ </datatype>
+ <datatype>
+ <name name="expressions"/>
+ <desc><p>As returned by <seealso marker="erl_parse#parse_exprs/1">
+ <c>erl_parse:parse_exprs/1</c></seealso> or
+ <seealso marker="io#parse_erl_exprs/2">
+ <c>io:parse_erl_exprs/2</c></seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="expression_list"/>
+ </datatype>
+ <datatype>
+ <name name="func_spec"/>
+ </datatype>
+ <datatype>
+ <name name="lfun_eval_handler"/>
+ </datatype>
+ <datatype>
+ <name name="lfun_value_handler"/>
+ </datatype>
+ <datatype>
+ <name name="local_function_handler"/>
+ <desc><p>Further described
+ <seealso marker="#local_function_handler">below.</seealso></p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="name"/>
+ </datatype>
+ <datatype>
+ <name name="nlfun_handler"/>
+ </datatype>
+ <datatype>
+ <name name="non_local_function_handler"/>
+ <desc><p>Further described
+ <seealso marker="#non_local_function_handler">below.</seealso></p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="value"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>exprs(Expressions, Bindings) -> {value, Value, NewBindings}</name>
- <name>exprs(Expressions, Bindings, LocalFunctionHandler) -> {value, Value, NewBindings}</name>
- <name>exprs(Expressions, Bindings, LocalFunctionHandler, NonlocalFunctionHandler) -> {value, Value, NewBindings}</name>
+ <name name="exprs" arity="2"/>
+ <name name="exprs" arity="3"/>
+ <name name="exprs" arity="4"/>
<fsummary>Evaluate expressions</fsummary>
- <type>
- <v>Expressions = as returned by erl_parse or io:parse_erl_exprs/2</v>
- <v>Bindings = as returned by bindings/1</v>
- <v>LocalFunctionHandler = {value, Func} | {eval, Func} | none</v>
- <v>NonlocalFunctionHandler = {value, Func} | none</v>
- </type>
<desc>
- <p>Evaluates <c>Expressions</c> with the set of bindings
- <c>Bindings</c>, where <c>Expressions</c> is a sequence of
+ <p>Evaluates <c><anno>Expressions</anno></c> with the set of bindings
+ <c><anno>Bindings</anno></c>, where <c><anno>Expressions</anno></c>
+ is a sequence of
expressions (in abstract syntax) of a type which may be
- returned by <c>io:parse_erl_exprs/2</c>. See below for an
+ returned by <seealso marker="io#parse_erl_exprs/2">
+ <c>io:parse_erl_exprs/2</c></seealso>. See below for an
explanation of how and when to use the arguments
- <c>LocalFunctionHandler</c> and <c>NonlocalFunctionHandler</c>.
+ <c><anno>LocalFunctionHandler</anno></c> and
+ <c><anno>NonLocalFunctionHandler</anno></c>.
</p>
- <p>Returns <c>{value, Value, NewBindings}</c></p>
+ <p>Returns <c>{value, <anno>Value</anno>, <anno>NewBindings</anno>}</c>
+ </p>
</desc>
</func>
<func>
- <name>expr(Expression, Bindings) -> { value, Value, NewBindings }</name>
- <name>expr(Expression, Bindings, LocalFunctionHandler) -> { value, Value, NewBindings }</name>
- <name>expr(Expression, Bindings, LocalFunctionHandler, NonlocalFunctionHandler) -> { value, Value, NewBindings }</name>
- <name>expr(Expression, Bindings, LocalFunctionHandler, NonlocalFunctionHandler, ReturnFormat) -> { value, Value, NewBindings } | Value</name>
+ <name name="expr" arity="2"/>
+ <name name="expr" arity="3"/>
+ <name name="expr" arity="4"/>
+ <name name="expr" arity="5"/>
<fsummary>Evaluate expression</fsummary>
- <type>
- <v>Expression = as returned by io:parse_erl_form/2, for example</v>
- <v>Bindings = as returned by bindings/1</v>
- <v>LocalFunctionHandler = {value, Func} | {eval, Func} | none</v>
- <v>NonlocalFunctionHandler = {value, Func} | none</v>
- <v>ReturnFormat = value | none</v>
- </type>
<desc>
- <p>Evaluates <c>Expression</c> with the set of bindings
- <c>Bindings</c>. <c>Expression</c> is an expression (in
- abstract syntax) of a type which may be returned by
- <c>io:parse_erl_form/2</c>. See below for an explanation of
+ <p>Evaluates <c><anno>Expression</anno></c> with the set of bindings
+ <c><anno>Bindings</anno></c>. <c><anno>Expression</anno></c>
+ is an expression in
+ abstract syntax. See below for an explanation of
how and when to use the arguments
- <c>LocalFunctionHandler</c> and
- <c>NonlocalFunctionHandler</c>.
+ <c><anno>LocalFunctionHandler</anno></c> and
+ <c><anno>NonLocalFunctionHandler</anno></c>.
</p>
- <p>Returns <c>{value, Value, NewBindings}</c> by default. But
- if the <c>ReturnFormat</c> is <c>value</c> only the <c>Value</c>
- is returned.</p>
+ <p>Returns <c>{value, <anno>Value</anno>,
+ <anno>NewBindings</anno>}</c> by default. But if the
+ <c><anno>ReturnFormat</anno></c> is <c>value</c> only
+ the <c><anno>Value</anno></c> is returned.</p>
</desc>
</func>
<func>
- <name>expr_list(ExpressionList, Bindings) -> {ValueList, NewBindings}</name>
- <name>expr_list(ExpressionList, Bindings, LocalFunctionHandler) -> {ValueList, NewBindings}</name>
- <name>expr_list(ExpressionList, Bindings, LocalFunctionHandler, NonlocalFunctionHandler) -> {ValueList, NewBindings}</name>
+ <name name="expr_list" arity="2"/>
+ <name name="expr_list" arity="3"/>
+ <name name="expr_list" arity="4"/>
<fsummary>Evaluate a list of expressions</fsummary>
<desc>
<p>Evaluates a list of expressions in parallel, using the same
@@ -100,18 +145,19 @@
merge the bindings returned from each evaluation. This
function is useful in the <c>LocalFunctionHandler</c>. See below.
</p>
- <p>Returns <c>{ValueList, NewBindings}</c>.</p>
+ <p>Returns <c>{<anno>ValueList</anno>, <anno>NewBindings</anno>}</c>.
+ </p>
</desc>
</func>
<func>
- <name>new_bindings() -> BindingStruct</name>
+ <name name="new_bindings" arity="0"/>
<fsummary>Return a bindings structure</fsummary>
<desc>
<p>Returns an empty binding structure.</p>
</desc>
</func>
<func>
- <name>bindings(BindingStruct) -> Bindings</name>
+ <name name="bindings" arity="1"/>
<fsummary>Return bindings</fsummary>
<desc>
<p>Returns the list of bindings contained in the binding
@@ -119,25 +165,28 @@
</desc>
</func>
<func>
- <name>binding(Name, BindingStruct) -> Binding</name>
+ <name name="binding" arity="2"/>
<fsummary>Return bindings</fsummary>
<desc>
- <p>Returns the binding of <c>Name</c> in <c>BindingStruct</c>.</p>
+ <p>Returns the binding of <c><anno>Name</anno></c>
+ in <c><anno>BindingStruct</anno></c>.</p>
</desc>
</func>
<func>
- <name>add_binding(Name, Value, Bindings) -> BindingStruct</name>
+ <name name="add_binding" arity="3"/>
<fsummary>Add a binding</fsummary>
<desc>
- <p>Adds the binding <c>Name = Value</c> to <c>Bindings</c>.
+ <p>Adds the binding <c><anno>Name</anno> = <anno>Value</anno></c>
+ to <c><anno>BindingStruct</anno></c>.
Returns an updated binding structure.</p>
</desc>
</func>
<func>
- <name>del_binding(Name, Bindings) -> BindingStruct</name>
+ <name name="del_binding" arity="2"/>
<fsummary>Delete a binding</fsummary>
<desc>
- <p>Removes the binding of <c>Name</c> in <c>Bindings</c>.
+ <p>Removes the binding of <c><anno>Name</anno></c>
+ in <c><anno>BindingStruct</anno></c>.
Returns an updated binding structure.</p>
</desc>
</func>
@@ -145,7 +194,8 @@
<section>
<title>Local Function Handler</title>
- <p>During evaluation of a function, no calls can be made to local
+ <p><marker id="local_function_handler"></marker>
+ During evaluation of a function, no calls can be made to local
functions. An undefined function error would be
generated. However, the optional argument
<c>LocalFunctionHandler</c> may be used to define a function
@@ -191,7 +241,8 @@ Func(Name, Arguments, Bindings) </code>
<section>
<title>Non-local Function Handler</title>
- <p>The optional argument <c>NonlocalFunctionHandler</c> may be
+ <p><marker id="non_local_function_handler"></marker>
+ The optional argument <c>NonlocalFunctionHandler</c> may be
used to define a function which is called in the following
cases: a functional object (fun) is called; a built-in function
is called; a function is called using the M:F syntax, where M
diff --git a/lib/stdlib/doc/src/erl_expand_records.xml b/lib/stdlib/doc/src/erl_expand_records.xml
index c93248493f..8ead438b31 100644
--- a/lib/stdlib/doc/src/erl_expand_records.xml
+++ b/lib/stdlib/doc/src/erl_expand_records.xml
@@ -39,12 +39,8 @@
</description>
<funcs>
<func>
- <name>module(AbsForms, CompileOptions) -> AbsForms</name>
+ <name name="module" arity="2"/>
<fsummary>Expand all records in a module</fsummary>
- <type>
- <v>AbsForms = [term()]</v>
- <v>CompileOptions = [term()]</v>
- </type>
<desc>
<p>Expands all records in a module. The returned module has no
references to records, neither attributes nor code.</p>
diff --git a/lib/stdlib/doc/src/erl_id_trans.xml b/lib/stdlib/doc/src/erl_id_trans.xml
index cfb18ec131..18cc2460f9 100644
--- a/lib/stdlib/doc/src/erl_id_trans.xml
+++ b/lib/stdlib/doc/src/erl_id_trans.xml
@@ -5,7 +5,7 @@
<header>
<copyright>
<year>1996</year>
- <year>2010</year>
+ <year>2011</year>
<holder>Ericsson AB, All Rights Reserved</holder>
</copyright>
<legalnotice>
@@ -48,8 +48,8 @@
<name>parse_transform(Forms, Options) -> Forms</name>
<fsummary>Transform Erlang forms</fsummary>
<type>
- <v>Forms = [erlang_form()]</v>
- <v>Options = [compiler_options()]</v>
+ <v>Forms = [<seealso marker="erl_parse#type-abstract_form">erl_parse:abstract_form()</seealso>]</v>
+ <v>Options = [<seealso marker="compile#type-option">compile:option()</seealso>]</v>
</type>
<desc>
<p>Performs an identity transformation on Erlang forms, as an example.</p>
diff --git a/lib/stdlib/doc/src/erl_internal.xml b/lib/stdlib/doc/src/erl_internal.xml
index 732d77c3ae..b8d5ad73b3 100644
--- a/lib/stdlib/doc/src/erl_internal.xml
+++ b/lib/stdlib/doc/src/erl_internal.xml
@@ -42,112 +42,75 @@
</description>
<funcs>
<func>
- <name>bif(Name, Arity) -> bool()</name>
+ <name name="bif" arity="2"/>
<fsummary>Test for an Erlang BIF</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Name/Arity</c> is an Erlang BIF
+ <p>Returns <c>true</c> if <c><anno>Name</anno>/<anno>Arity</anno></c> is an Erlang BIF
which is automatically recognized by the compiler, otherwise
<c>false</c>.</p>
</desc>
</func>
<func>
- <name>guard_bif(Name, Arity) -> bool()</name>
+ <name name="guard_bif" arity="2"/>
<fsummary>Test for an Erlang BIF allowed in guards</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Name/Arity</c> is an Erlang BIF
+ <p>Returns <c>true</c> if <c><anno>Name</anno>/<anno>Arity</anno></c> is an Erlang BIF
which is allowed in guards, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>type_test(Name, Arity) -> bool()</name>
+ <name name="type_test" arity="2"/>
<fsummary>Test for a valid type test</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Name/Arity</c> is a valid Erlang
+ <p>Returns <c>true</c> if <c><anno>Name</anno>/<anno>Arity</anno></c> is a valid Erlang
type test, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>arith_op(OpName, Arity) -> bool()</name>
+ <name name="arith_op" arity="2"/>
<fsummary>Test for an arithmetic operator</fsummary>
- <type>
- <v>OpName = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>OpName/Arity</c> is an arithmetic
+ <p>Returns <c>true</c> if <c><anno>OpName</anno>/<anno>Arity</anno></c> is an arithmetic
operator, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>bool_op(OpName, Arity) -> bool()</name>
+ <name name="bool_op" arity="2"/>
<fsummary>Test for a Boolean operator</fsummary>
- <type>
- <v>OpName = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>OpName/Arity</c> is a Boolean
+ <p>Returns <c>true</c> if <c><anno>OpName</anno>/<anno>Arity</anno></c> is a Boolean
operator, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>comp_op(OpName, Arity) -> bool()</name>
+ <name name="comp_op" arity="2"/>
<fsummary>Test for a comparison operator</fsummary>
- <type>
- <v>OpName = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>OpName/Arity</c> is a comparison
+ <p>Returns <c>true</c> if <c><anno>OpName</anno>/<anno>Arity</anno></c> is a comparison
operator, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>list_op(OpName, Arity) -> bool()</name>
+ <name name="list_op" arity="2"/>
<fsummary>Test for a list operator</fsummary>
- <type>
- <v>OpName = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>OpName/Arity</c> is a list
+ <p>Returns <c>true</c> if <c><anno>OpName</anno>/<anno>Arity</anno></c> is a list
operator, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>send_op(OpName, Arity) -> bool()</name>
+ <name name="send_op" arity="2"/>
<fsummary>Test for a send operator</fsummary>
- <type>
- <v>OpName = atom()</v>
- <v>Arity = integer()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>OpName/Arity</c> is a send
+ <p>Returns <c>true</c> if <c><anno>OpName</anno>/<anno>Arity</anno></c> is a send
operator, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>op_type(OpName, Arity) -> Type</name>
+ <name name="op_type" arity="2"/>
<fsummary>Return operator type</fsummary>
- <type>
- <v>OpName = atom()</v>
- <v>Arity = integer()</v>
- <v>Type = arith | bool | comp | list | send</v>
- </type>
<desc>
- <p>Returns the <c>Type</c> of operator that <c>OpName/Arity</c>
+ <p>Returns the <c><anno>Type</anno></c> of operator that <c><anno>OpName</anno>/<anno>Arity</anno></c>
belongs to,
or generates a <c>function_clause</c> error if it is not an
operator at all.</p>
diff --git a/lib/stdlib/doc/src/erl_lint.xml b/lib/stdlib/doc/src/erl_lint.xml
index 8639d678fa..b7fbdd8799 100644
--- a/lib/stdlib/doc/src/erl_lint.xml
+++ b/lib/stdlib/doc/src/erl_lint.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -60,29 +60,30 @@
functions separately unless you have written your own Erlang
compiler.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="error_info"/>
+ </datatype>
+ <datatype>
+ <name name="error_description"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>module(AbsForms) -> {ok,Warnings} | {error,Errors,Warnings}</name>
- <name>module(AbsForms, FileName) -> {ok,Warnings} | {error,Errors,Warnings}</name>
- <name>module(AbsForms, FileName, CompileOptions) -> {ok,Warnings} | {error,Errors,Warnings}</name>
+ <name name="module" arity="1"/>
+ <name name="module" arity="2"/>
+ <name name="module" arity="3"/>
<fsummary>Check a module for errors</fsummary>
- <type>
- <v>AbsForms = [term()]</v>
- <v>FileName = FileName2 = atom() | string()</v>
- <v>Warnings = Errors = [{Filename2,[ErrorInfo]}]</v>
- <v>ErrorInfo = see separate description below.</v>
- <v>CompileOptions = [term()]</v>
- </type>
<desc>
<p>This function checks all the forms in a module for errors.
It returns:
</p>
<taglist>
- <tag><c>{ok,Warnings}</c></tag>
+ <tag><c>{ok,<anno>Warnings</anno>}</c></tag>
<item>
<p>There were no errors in the module.</p>
</item>
- <tag><c>{error,Errors,Warnings}</c></tag>
+ <tag><c>{error,<anno>Errors</anno>,<anno>Warnings</anno>}</c></tag>
<item>
<p>There were errors in the module.</p>
</item>
@@ -93,14 +94,14 @@
elements of <c>Options</c> that control the warnings are
only described in <seealso marker="compiler:compile#erl_lint_options">compile(3)</seealso>.
</p>
- <p>The <c>AbsForms</c> of a module which comes from a file
+ <p>The <c><anno>AbsForms</anno></c> of a module which comes from a file
that is read through <c>epp</c>, the Erlang pre-processor,
can come from many files. This means that any references to
errors must include the file name (see <seealso marker="epp">epp(3)</seealso>, or parser <seealso marker="erl_parse">erl_parse(3)</seealso>).
The warnings and errors returned have the following format:
</p>
<code type="none">
- [{FileName2,[ErrorInfo]}] </code>
+ [{<anno>FileName2</anno>,[<anno>ErrorInfo</anno>]}] </code>
<p>The errors and warnings are listed in the order in which
they are encountered in the forms. This means that the
errors from one file may be split into different entries in
@@ -108,27 +109,20 @@
</desc>
</func>
<func>
- <name>is_guard_test(Expr) -> bool()</name>
+ <name name="is_guard_test" arity="1"/>
<fsummary>Test for a guard test</fsummary>
- <type>
- <v>Expr = term()</v>
- </type>
<desc>
- <p>This function tests if <c>Expr</c> is a legal guard test.
- <c>Expr</c> is an Erlang term representing the abstract form
+ <p>This function tests if <c><anno>Expr</anno></c> is a legal guard test.
+ <c><anno>Expr</anno></c> is an Erlang term representing the abstract form
for the expression. <c>erl_parse:parse_exprs(Tokens)</c> can
- be used to generate a list of <c>Expr</c>.</p>
+ be used to generate a list of <c><anno>Expr</anno></c>.</p>
</desc>
</func>
<func>
- <name>format_error(ErrorDescriptor) -> Chars</name>
+ <name name="format_error" arity="1"/>
<fsummary>Format an error descriptor</fsummary>
- <type>
- <v>ErrorDescriptor = errordesc()</v>
- <v>Chars = [char() | Chars]</v>
- </type>
<desc>
- <p>Takes an <c>ErrorDescriptor</c> and returns a string which
+ <p>Takes an <c><anno>ErrorDescriptor</anno></c> and returns a string which
describes the error or warning. This function is usually
called implicitly when processing an <c>ErrorInfo</c>
structure (see below).</p>
diff --git a/lib/stdlib/doc/src/erl_parse.xml b/lib/stdlib/doc/src/erl_parse.xml
index 18b592deea..bafc2e0746 100644
--- a/lib/stdlib/doc/src/erl_parse.xml
+++ b/lib/stdlib/doc/src/erl_parse.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -36,31 +36,51 @@
<description>
<p>This module is the basic Erlang parser which converts tokens into
the abstract form of either forms (i.e., top-level constructs),
- expressions, or terms. The Abstract Format is described in the ERTS
- User's Guide.
+ expressions, or terms. The Abstract Format is described in the
+ <seealso marker="erts:absform">ERTS User's Guide</seealso>.
Note that a token list must end with the <em>dot</em> token in order
to be acceptable to the parse functions (see <seealso marker="erl_scan">erl_scan(3)</seealso>).</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="abstract_clause"></name>
+ <desc><p>Parse tree for Erlang clause.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="abstract_expr"></name>
+ <desc><p>Parse tree for Erlang expression.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="abstract_form"></name>
+ <desc><p>Parse tree for Erlang form.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="error_description"></name>
+ </datatype>
+ <datatype>
+ <name name="error_info"></name>
+ </datatype>
+ <datatype>
+ <name name="token"></name>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>parse_form(Tokens) -> {ok, AbsForm} | {error, ErrorInfo}</name>
+ <name name="parse_form" arity="1"/>
<fsummary>Parse an Erlang form</fsummary>
- <type>
- <v>Tokens = [Token]</v>
- <v>Token = {Tag,Line} | {Tag,Line,term()}</v>
- <v>Tag = atom()</v>
- <v>AbsForm = term()</v>
- <v>ErrorInfo = see section Error Information below.</v>
- </type>
<desc>
- <p>This function parses <c>Tokens</c> as if it were a form. It returns:</p>
+ <p>This function parses <c><anno>Tokens</anno></c> as if it were
+ a form. It returns:</p>
<taglist>
- <tag><c>{ok, AbsForm}</c></tag>
+ <tag><c>{ok, <anno>AbsForm</anno>}</c></tag>
<item>
- <p>The parsing was successful. <c>AbsForm</c> is the
+ <p>The parsing was successful. <c><anno>AbsForm</anno></c> is the
abstract form of the parsed form.</p>
</item>
- <tag><c>{error, ErrorInfo}</c></tag>
+ <tag><c>{error, <anno>ErrorInfo</anno>}</c></tag>
<item>
<p>An error occurred.</p>
</item>
@@ -68,25 +88,18 @@
</desc>
</func>
<func>
- <name>parse_exprs(Tokens) -> {ok, Expr_list} | {error, ErrorInfo}</name>
+ <name name="parse_exprs" arity="1"/>
<fsummary>Parse Erlang expressions</fsummary>
- <type>
- <v>Tokens = [Token]</v>
- <v>Token = {Tag,Line} | {Tag,Line,term()}</v>
- <v>Tag = atom()</v>
- <v>Expr_list = [AbsExpr]</v>
- <v>AbsExpr = term()</v>
- <v>ErrorInfo = see section Error Information below.</v>
- </type>
<desc>
- <p>This function parses <c>Tokens</c> as if it were a list of expressions. It returns:</p>
+ <p>This function parses <c><anno>Tokens</anno></c> as if it were
+ a list of expressions. It returns:</p>
<taglist>
- <tag><c>{ok, Expr_list}</c></tag>
+ <tag><c>{ok, <anno>ExprList</anno>}</c></tag>
<item>
- <p>The parsing was successful. <c>Expr_list</c> is a
+ <p>The parsing was successful. <c><anno>ExprList</anno></c> is a
list of the abstract forms of the parsed expressions.</p>
</item>
- <tag><c>{error, ErrorInfo}</c></tag>
+ <tag><c>{error, <anno>ErrorInfo</anno>}</c></tag>
<item>
<p>An error occurred.</p>
</item>
@@ -94,21 +107,15 @@
</desc>
</func>
<func>
- <name>parse_term(Tokens) -> {ok, Term} | {error, ErrorInfo}</name>
+ <name name="parse_term" arity="1"/>
<fsummary>Parse an Erlang term</fsummary>
- <type>
- <v>Tokens = [Token]</v>
- <v>Token = {Tag,Line} | {Tag,Line,term()}</v>
- <v>Tag = atom()</v>
- <v>Term = term()</v>
- <v>ErrorInfo = see section Error Information below.</v>
- </type>
<desc>
- <p>This function parses <c>Tokens</c> as if it were a term. It returns:</p>
+ <p>This function parses <c><anno>Tokens</anno></c> as if it were
+ a term. It returns:</p>
<taglist>
- <tag><c>{ok, Term}</c></tag>
+ <tag><c>{ok, <anno>Term</anno>}</c></tag>
<item>
- <p>The parsing was successful. <c>Term</c> is
+ <p>The parsing was successful. <c><anno>Term</anno></c> is
the Erlang term corresponding to the token list.</p>
</item>
<tag><c>{error, ErrorInfo}</c></tag>
@@ -122,7 +129,8 @@
<name>format_error(ErrorDescriptor) -> Chars</name>
<fsummary>Format an error descriptor</fsummary>
<type>
- <v>ErrorDescriptor = errordesc()</v>
+ <v>ErrorDescriptor = <seealso
+ marker="#type-error_info">error_description()</seealso></v>
<v>Chars = [char() | Chars]</v>
</type>
<desc>
@@ -133,44 +141,32 @@
</desc>
</func>
<func>
- <name>tokens(AbsTerm) -> Tokens</name>
- <name>tokens(AbsTerm, MoreTokens) -> Tokens</name>
+ <name name="tokens" arity="1"/>
+ <name name="tokens" arity="2"/>
<fsummary>Generate a list of tokens for an expression</fsummary>
- <type>
- <v>Tokens = MoreTokens = [Token]</v>
- <v>Token = {Tag,Line} | {Tag,Line,term()}</v>
- <v>Tag = atom()</v>
- <v>AbsTerm = term()</v>
- <v>ErrorInfo = see section Error Information below.</v>
- </type>
<desc>
<p>This function generates a list of tokens representing the abstract
- form <c>AbsTerm</c> of an expression. Optionally, it appends
- <c>Moretokens</c>.</p>
+ form <c><anno>AbsTerm</anno></c> of an expression. Optionally, it
+ appends <c><anno>MoreTokens</anno></c>.</p>
</desc>
</func>
<func>
- <name>normalise(AbsTerm) -> Data</name>
+ <name name="normalise" arity="1"/>
<fsummary>Convert abstract form to an Erlang term</fsummary>
- <type>
- <v>AbsTerm = Data = term()</v>
- </type>
<desc>
- <p>Converts the abstract form <c>AbsTerm</c> of a term into a
+ <p>Converts the abstract form <c><anno>AbsTerm</anno></c> of a
+ term into a
conventional Erlang data structure (i.e., the term itself).
This is the inverse of <c>abstract/1</c>.</p>
</desc>
</func>
<func>
- <name>abstract(Data) -> AbsTerm</name>
+ <name name="abstract" arity="1"/>
<fsummary>Convert an Erlang term into an abstract form</fsummary>
- <type>
- <v>Data = AbsTerm = term()</v>
- </type>
<desc>
- <p>Converts the Erlang data structure <c>Data</c> into an
- abstract form of type <c>AbsTerm</c>. This is the inverse of
- <c>normalise/1</c>.</p>
+ <p>Converts the Erlang data structure <c><anno>Data</anno></c> into an
+ abstract form of type <c><anno>AbsTerm</anno></c>.
+ This is the inverse of <c>normalise/1</c>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/erl_pp.xml b/lib/stdlib/doc/src/erl_pp.xml
index 1fdda48893..57b5828bcd 100644
--- a/lib/stdlib/doc/src/erl_pp.xml
+++ b/lib/stdlib/doc/src/erl_pp.xml
@@ -43,93 +43,82 @@
<p>All functions can have an optional argument which specifies a hook
that is called if an attempt is made to print an unknown form.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="hook_function"/>
+ <desc>
+ <p>The optional argument <marker id="hook_function">
+ <c>HookFunction</c></marker>, shown in the functions described below,
+ defines a function which is called when an unknown form occurs where there
+ should be a valid expression.</p>
+
+ <p>If <c>HookFunction</c> is equal to <c>none</c> there is no hook
+ function.</p>
+
+ <p>The called hook function should return a (possibly deep) list
+ of characters. <seealso marker="#expr/4"><c>expr/4</c></seealso>
+ is useful in a hook.
+ </p>
+ <p>If <c><anno>CurrentIndentation</anno></c> is negative, there will be no line
+ breaks and only a space is used as a separator.</p>
+ </desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>form(Form) -> DeepCharList</name>
- <name>form(Form, HookFunction) -> DeepCharList</name>
+ <name name="form" arity="1"/>
+ <name name="form" arity="2"/>
<fsummary>Pretty print a form</fsummary>
- <type>
- <v>Form = term()</v>
- <v>HookFunction = see separate description below.</v>
- <v>DeepCharList = [char()|DeepCharList]</v>
- </type>
<desc>
<p>Pretty prints a
- <c>Form</c> which is an abstract form of a type which is
- returned by <c>erl_parse:parse_form</c>.</p>
+ <c><anno>Form</anno></c> which is an abstract form of a type which is
+ returned by <seealso marker="erl_parse#parse_form/1">
+ <c>erl_parse:parse_form/1</c></seealso>.</p>
</desc>
</func>
<func>
- <name>attribute(Attribute) -> DeepCharList</name>
- <name>attribute(Attribute, HookFunction) -> DeepCharList</name>
+ <name name="attribute" arity="1"/>
+ <name name="attribute" arity="2"/>
<fsummary>Pretty print an attribute</fsummary>
- <type>
- <v>Attribute = term()</v>
- <v>HookFunction = see separate description below.</v>
- <v>DeepCharList = [char()|DeepCharList]</v>
- </type>
<desc>
<p>The same as <c>form</c>, but only for the attribute
- <c>Attribute</c>.</p>
+ <c><anno>Attribute</anno></c>.</p>
</desc>
</func>
<func>
- <name>function(Function) -> DeepCharList</name>
- <name>function(Function, HookFunction) -> DeepCharList</name>
+ <name name="function" arity="1"/>
+ <name name="function" arity="2"/>
<fsummary>Pretty print a function</fsummary>
- <type>
- <v>Function = term()</v>
- <v>HookFunction = see separate description below.</v>
- <v>DeepCharList = [char()|DeepCharList]</v>
- </type>
<desc>
<p>The same as <c>form</c>, but only for the function
- <c>Function</c>.</p>
+ <c><anno>Function</anno></c>.</p>
</desc>
</func>
<func>
- <name>guard(Guard) -> DeepCharList</name>
- <name>guard(Guard, HookFunction) -> DeepCharList</name>
+ <name name="guard" arity="1"/>
+ <name name="guard" arity="2"/>
<fsummary>Pretty print a guard</fsummary>
- <type>
- <v>Form = term()</v>
- <v>HookFunction = see separate description below.</v>
- <v>DeepCharList = [char()|DeepCharList]</v>
- </type>
<desc>
<p>The same as <c>form</c>, but only for the guard test
- <c>Guard</c>.</p>
+ <c><anno>Guard</anno></c>.</p>
</desc>
</func>
<func>
- <name>exprs(Expressions) -> DeepCharList</name>
- <name>exprs(Expressions, HookFunction) -> DeepCharList</name>
- <name>exprs(Expressions, Indent, HookFunction) -> DeepCharList</name>
+ <name name="exprs" arity="1"/>
+ <name name="exprs" arity="2"/>
+ <name name="exprs" arity="3"/>
<fsummary>Pretty print <c>Expressions</c></fsummary>
- <type>
- <v>Expressions = term()</v>
- <v>HookFunction = see separate description below.</v>
- <v>Indent = integer()</v>
- <v>DeepCharList = [char()|DeepCharList]</v>
- </type>
<desc>
<p>The same as <c>form</c>, but only for the sequence of
- expressions in <c>Expressions</c>.</p>
+ expressions in <c><anno>Expressions</anno></c>.</p>
</desc>
</func>
<func>
- <name>expr(Expression) -> DeepCharList</name>
- <name>expr(Expression, HookFunction) -> DeepCharList</name>
- <name>expr(Expression, Indent, HookFunction) -> DeepCharList</name>
- <name>expr(Expression, Indent, Precedence, HookFunction) ->-> DeepCharList</name>
+ <name name="expr" arity="1"/>
+ <name name="expr" arity="2"/>
+ <name name="expr" arity="3"/>
+ <name name="expr" arity="4"/>
<fsummary>Pretty print one <c>Expression</c></fsummary>
- <type>
- <v>Expression = term()</v>
- <v>HookFunction = see separate description below.</v>
- <v>Indent = integer()</v>
- <v>Precedence = </v>
- <v>DeepCharList = [char()|DeepCharList]</v>
- </type>
<desc>
<p>This function prints one expression. It is useful for implementing hooks (see below).</p>
</desc>
@@ -137,32 +126,6 @@
</funcs>
<section>
- <title>Unknown Expression Hooks</title>
- <p>The optional argument <c>HookFunction</c>, shown in the functions described above, defines a function which is called when an unknown form occurs where there
- should be a valid expression. It can have the following formats:</p>
- <taglist>
- <tag><c>Function</c></tag>
- <item>
- <p>The hook function is called by:</p>
- <code type="none">
-Function(Expr,
- CurrentIndentation,
- CurrentPrecedence,
- HookFunction) </code>
- </item>
- <tag><c>none</c></tag>
- <item>
- <p>There is no hook function</p>
- </item>
- </taglist>
- <p>The called hook function should return a (possibly deep) list
- of characters. <c>expr/4</c> is useful in a hook.
- </p>
- <p>If <c>CurrentIndentation</c> is negative, there will be no line
- breaks and only a space is used as a separator.</p>
- </section>
-
- <section>
<title>Bugs</title>
<p>It should be possible to have hook functions for unknown forms
at places other than expressions.</p>
diff --git a/lib/stdlib/doc/src/erl_scan.xml b/lib/stdlib/doc/src/erl_scan.xml
index 1199c34f0f..54240dea19 100644
--- a/lib/stdlib/doc/src/erl_scan.xml
+++ b/lib/stdlib/doc/src/erl_scan.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -37,56 +37,96 @@
<p>This module contains functions for tokenizing characters into
Erlang tokens.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-category() = atom()
-column() = integer() > 0
-line() = integer()
-location() = line() | {line(), column()}
-reserved_word_fun() -> fun(atom()) -> bool()
-set_attribute_fun() -> fun(term()) -> term()
-symbol() = atom() | float() | integer() | string()
-token() = {category(), attributes()} | {category(), attributes(), symbol()}
-attributes() = line() | list() | tuple()</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name name="attribute_info"></name>
+ </datatype>
+ <datatype>
+ <name name="attributes"></name>
+ </datatype>
+ <datatype>
+ <name name="attributes_data"></name>
+ </datatype>
+ <datatype>
+ <name name="category"></name>
+ </datatype>
+ <datatype>
+ <name name="column"></name>
+ </datatype>
+ <datatype>
+ <name name="error_description"></name>
+ </datatype>
+ <datatype>
+ <name name="error_info"></name>
+ </datatype>
+ <datatype>
+ <name name="info_line"></name>
+ </datatype>
+ <datatype>
+ <name name="info_location"></name>
+ </datatype>
+ <datatype>
+ <name name="line"></name>
+ </datatype>
+ <datatype>
+ <name name="location"></name>
+ </datatype>
+ <datatype>
+ <name name="option"></name>
+ </datatype>
+ <datatype>
+ <name name="options"></name>
+ </datatype>
+ <datatype>
+ <name name="symbol"></name>
+ </datatype>
+ <datatype>
+ <name name="resword_fun"></name>
+ </datatype>
+ <datatype>
+ <name name="token"></name>
+ </datatype>
+ <datatype>
+ <name name="token_info"></name>
+ </datatype>
+ <datatype>
+ <name name="tokens"></name>
+ </datatype>
+ <datatype>
+ <name name="tokens_result"></name>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>string(String) -> Return</name>
- <name>string(String, StartLocation) -> Return</name>
- <name>string(String, StartLocation, Options) -> Return</name>
+ <name name="string" arity="1"/>
+ <name name="string" arity="2"/>
+ <name name="string" arity="3"/>
<fsummary>Scan a string and return the Erlang tokens</fsummary>
- <type>
- <v>String = string()</v>
- <v>Return = {ok, Tokens, EndLocation} | Error</v>
- <v>Tokens = [token()]</v>
- <v>Error = {error, ErrorInfo, EndLocation}</v>
- <v>StartLocation = EndLocation = location()</v>
- <v>Options = Option | [Option]</v>
- <v>Option = {reserved_word_fun,reserved_word_fun()}
- | return_comments | return_white_spaces | return
- | text</v>
- </type>
<desc>
- <p>Takes the list of characters <c>String</c> and tries to
- scan (tokenize) them. Returns <c>{ok, Tokens, EndLocation}</c>,
- where <c>Tokens</c> are the Erlang tokens from
- <c>String</c>. <c>EndLocation</c> is the first location
- after the last token.</p>
- <p><c>{error, ErrorInfo, EndLocation}</c> is returned if an
- error occurs. <c>EndLocation</c> is the first location after
+ <p>Takes the list of characters <c><anno>String</anno></c> and tries to
+ scan (tokenize) them. Returns <c>{ok, <anno>Tokens</anno>,
+ <anno>EndLocation</anno>}</c>,
+ where <c><anno>Tokens</anno></c> are the Erlang tokens from
+ <c><anno>String</anno></c>. <c><anno>EndLocation</anno></c>
+ is the first location after the last token.</p>
+ <p><c>{error, <anno>ErrorInfo</anno>, <anno>ErrorLocation</anno>}</c>
+ is returned if an error occurs.
+ <c><anno>ErrorLocation</anno></c> is the first location after
the erroneous token.</p>
- <p><c>string(String)</c> is equivalent to
- <c>string(String, 1)</c>, and <c>string(String,
- StartLocation)</c> is equivalent to <c>string(String,
- StartLocation, [])</c>.</p>
- <p><c>StartLocation</c> indicates the initial location when
- scanning starts. If <c>StartLocation</c> is a line
- <c>attributes()</c> as well as <c>EndLocation</c> and
- <c>ErrorLocation</c> will be lines. If
- <c>StartLocation</c> is a pair of a line and a column
+ <p><c>string(<anno>String</anno>)</c> is equivalent to
+ <c>string(<anno>String</anno>, 1)</c>, and
+ <c>string(<anno>String</anno>,
+ <anno>StartLocation</anno>)</c> is equivalent to
+ <c>string(<anno>String</anno>,
+ <anno>StartLocation</anno>, [])</c>.</p>
+ <p><c><anno>StartLocation</anno></c> indicates the initial location
+ when scanning starts. If <c><anno>StartLocation</anno></c> is a line
+ <c>attributes()</c> as well as <c><anno>EndLocation</anno></c> and
+ <c><anno>ErrorLocation</anno></c> will be lines. If
+ <c><anno>StartLocation</anno></c> is a pair of a line and a column
<c>attributes()</c> takes the form of an opaque compound
- data type, and <c>EndLocation</c> and <c>ErrorLocation</c>
+ data type, and <c><anno>EndLocation</anno></c> and
+ <c><anno>ErrorLocation</anno></c>
will be pairs of a line and a column. The <em>token
attributes</em> contain information about the column and the
line where the token begins, as well as the text of the
@@ -134,148 +174,130 @@ attributes() = line() | list() | tuple()</code>
</desc>
</func>
<func>
- <name>tokens(Continuation, CharSpec, StartLocation) -> Return</name>
- <name>tokens(Continuation, CharSpec, StartLocation, Options) -> Return</name>
+ <name name="tokens" arity="3"/>
+ <name name="tokens" arity="4"/>
+ <type name="char_spec"/>
+ <type name="return_cont"/>
+ <type_desc name="return_cont">An opaque continuation</type_desc>
<fsummary>Re-entrant scanner</fsummary>
- <type>
- <v>Continuation = [] | Continuation1</v>
- <v>Return = {done, Result, LeftOverChars} | {more, Continuation1}</v>
- <v>LeftOverChars = CharSpec</v>
- <v>CharSpec = string() | eof</v>
- <v>Continuation1 = tuple()</v>
- <v>Result = {ok, Tokens, EndLocation} | {eof, EndLocation} | Error</v>
- <v>Tokens = [token()]</v>
- <v>Error = {error, ErrorInfo, EndLocation}</v>
- <v>StartLocation = EndLocation = location()</v>
- <v>Options = Option | [Option]</v>
- <v>Option = {reserved_word_fun,reserved_word_fun()}
- | return_comments | return_white_spaces | return
- | text</v>
- </type>
<desc>
<p>This is the re-entrant scanner which scans characters until
a <em>dot</em> ('.' followed by a white space) or
<c>eof</c> has been reached. It returns:</p>
<taglist>
- <tag><c>{done, Result, LeftOverChars}</c></tag>
+ <tag><c>{done, <anno>Result</anno>, <anno>LeftOverChars</anno>}</c>
+ </tag>
<item>
<p>This return indicates that there is sufficient input
- data to get a result. <c>Result</c> is:</p>
+ data to get a result. <c><anno>Result</anno></c> is:</p>
<taglist>
- <tag><c>{ok, Tokens, EndLocation}</c></tag>
+ <tag><c>{ok, Tokens, EndLocation}</c>
+ </tag>
<item>
- <p>The scanning was successful. <c>Tokens</c> is the
- list of tokens including <em>dot</em>.</p>
+ <p>The scanning was successful. <c>Tokens</c>
+ is the list of tokens including <em>dot</em>.</p>
</item>
<tag><c>{eof, EndLocation}</c></tag>
<item>
<p>End of file was encountered before any more tokens.</p>
</item>
- <tag><c>{error, ErrorInfo, EndLocation}</c></tag>
+ <tag><c>{error, ErrorInfo, EndLocation}</c>
+ </tag>
<item>
- <p>An error occurred. <c>LeftOverChars</c> is the remaining
- characters of the input data,
+ <p>An error occurred. <c><anno>LeftOverChars</anno></c>
+ is the remaining characters of the input data,
starting from <c>EndLocation</c>.</p>
</item>
</taglist>
</item>
- <tag><c>{more, Continuation1}</c></tag>
+ <tag><c>{more, <anno>Continuation1</anno>}</c></tag>
<item>
<p>More data is required for building a term.
- <c>Continuation1</c> must be passed in a new call to
+ <c><anno>Continuation1</anno></c> must be passed in a new call to
<c>tokens/3,4</c> when more data is available.</p>
</item>
</taglist>
- <p>The <c>CharSpec</c> <c>eof</c> signals end of file.
- <c>LeftOverChars</c> will then take the value <c>eof</c> as
- well.</p>
- <p><c>tokens(Continuation, CharSpec, StartLocation)</c> is
- equivalent to <c>tokens(Continuation, CharSpec,
- StartLocation, [])</c>.</p>
+ <p>The <c><anno>CharSpec</anno></c> <c>eof</c> signals end of file.
+ <c><anno>LeftOverChars</anno></c> will then take the value <c>eof</c>
+ as well.</p>
+ <p><c>tokens(<anno>Continuation</anno>, <anno>CharSpec</anno>,
+ <anno>StartLocation</anno>)</c> is equivalent to
+ <c>tokens(<anno>Continuation</anno>, <anno>CharSpec</anno>,
+ <anno>StartLocation</anno>, [])</c>.</p>
<p>See <seealso marker="#string/3">string/3</seealso> for a
description of the various options.</p>
</desc>
</func>
<func>
- <name>reserved_word(Atom) -> bool()</name>
+ <name name="reserved_word" arity="1"/>
<fsummary>Test for a reserved word</fsummary>
- <type>
- <v>Atom = atom()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Atom</c> is an Erlang reserved
- word, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>Atom</anno></c> is an Erlang
+ reserved word, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>token_info(Token) -> TokenInfo</name>
+ <name name="token_info" arity="1"/>
<fsummary>Return information about a token</fsummary>
- <type>
- <v>Token = token()</v>
- <v>TokenInfo = [TokenInfoTuple]</v>
- <v>TokenInfoTuple = {TokenItem, Info}</v>
- <v>TokenItem = atom()</v>
- <v>Info = term()</v>
- </type>
<desc>
<p>Returns a list containing information about the token
- <c>Token</c>. The order of the <c>TokenInfoTuple</c>s is not
- defined. The following <c>TokenItem</c>s are returned:
- <c>category</c>, <c>column</c>, <c>length</c>,
- <c>line</c>, <c>symbol</c>, and <c>text</c>. See <seealso
+ <c><anno>Token</anno></c>. The order of the
+ <c><anno>TokenInfoTuple</anno></c>s is not
+ defined. See <seealso
marker="#token_info/2">token_info/2</seealso> for
information about specific
- <c>TokenInfoTuple</c>s.</p>
+ <c><anno>TokenInfoTuple</anno></c>s.</p>
<p>Note that if <c>token_info(Token, TokenItem)</c> returns
- <c>undefined</c> for some <c>TokenItem</c> in the list above, the
- item is not included in <c>TokenInfo</c>.</p>
+ <c>undefined</c> for some <c>TokenItem</c>, the
+ item is not included in <c><anno>TokenInfo</anno></c>.</p>
</desc>
</func>
<func>
- <name>token_info(Token, TokenItemSpec) -> TokenInfo</name>
+ <name name="token_info" arity="2" clause_i="1"/>
+ <name name="token_info" arity="2" clause_i="2"/>
+ <type name="token_item"/>
+ <type name="attribute_item"/>
<fsummary>Return information about a token</fsummary>
- <type>
- <v>Token = token()</v>
- <v>TokenItemSpec = TokenItem | [TokenItem]</v>
- <v>TokenInfo = TokenInfoTuple | undefined | [TokenInfoTuple]</v>
- <v>TokenInfoTuple = {TokenItem, Info}</v>
- <v>TokenItem = atom()</v>
- <v>Info = term()</v>
- </type>
<desc>
<p>Returns a list containing information about the token
- <c>Token</c>. If <c>TokenItemSpec</c> is a single
- <c>TokenItem</c>, the returned value is the corresponding
+ <c><anno>Token</anno></c>. If one single
+ <c><anno>TokenItem</anno></c> is given the returned value is
+ the corresponding
<c>TokenInfoTuple</c>, or <c>undefined</c> if the
- <c>TokenItem</c> has no value. If <c>TokenItemSpec</c> is a
- list of
- <c>TokenItem</c>, the result is a list of
- <c>TokenInfoTuple</c>. The <c>TokenInfoTuple</c>s will
- appear with the corresponding
- <c>TokenItem</c>s in the same order as the <c>TokenItem</c>s
- appeared in the list of <c>TokenItem</c>s. <c>TokenItem</c>s
- with no value are not included in the list of
- <c>TokenInfoTuple</c>.</p>
- <p>The following <c>TokenInfoTuple</c>s with corresponding
- <c>TokenItem</c>s are valid:</p>
+ <c>TokenItem</c> has no value. If a list of
+ <c><anno>TokenItem</anno></c>s is given the result is a list of
+ <c><anno>TokenInfoTuple</anno></c>. The
+ <c><anno>TokenInfoTuple</anno></c>s will
+ appear with the corresponding <c><anno>TokenItem</anno></c>s in
+ the same order as the <c><anno>TokenItem</anno></c>s
+ appear in the list of <c>TokenItem</c>s.
+ <c><anno>TokenItem</anno></c>s with no value are not included
+ in the list of <c><anno>TokenInfoTuple</anno></c>.</p>
+ <p>The following <c><anno>TokenInfoTuple</anno></c>s with corresponding
+ <c><anno>TokenItem</anno></c>s are valid:</p>
<taglist>
- <tag><c>{category, category()}</c></tag>
+ <tag><c>{category, <seealso marker="#type-category">
+ category()</seealso>}</c></tag>
<item><p>The category of the token.</p>
</item>
- <tag><c>{column, column()}</c></tag>
+ <tag><c>{column, <seealso marker="#type-column">
+ column()</seealso>}</c></tag>
<item><p>The column where the token begins.</p>
</item>
<tag><c>{length, integer() > 0}</c></tag>
<item><p>The length of the token's text.</p>
</item>
- <tag><c>{line, line()}</c></tag>
+ <tag><c>{line, <seealso marker="#type-line">
+ line()</seealso>}</c></tag>
<item><p>The line where the token begins.</p>
</item>
- <tag><c>{location, location()}</c></tag>
+ <tag><c>{location, <seealso marker="#type-location">
+ location()</seealso>}</c></tag>
<item><p>The line and column where the token begins, or
just the line if the column unknown.</p>
</item>
- <tag><c>{symbol, symbol()}</c></tag>
+ <tag><c>{symbol, <seealso marker="#type-symbol">
+ symbol()</seealso>}</c></tag>
<item><p>The token's symbol.</p>
</item>
<tag><c>{text, string()}</c></tag>
@@ -285,70 +307,59 @@ attributes() = line() | list() | tuple()</code>
</desc>
</func>
<func>
- <name>attributes_info(Attributes) -> AttributesInfo</name>
+ <name name="attributes_info" arity="1"/>
<fsummary>Return information about token attributes</fsummary>
- <type>
- <v>Attributes = attributes()</v>
- <v>AttributesInfo = [AttributeInfoTuple]</v>
- <v>AttributeInfoTuple = {AttributeItem, Info}</v>
- <v>AttributeItem = atom()</v>
- <v>Info = term()</v>
- </type>
<desc>
<p>Returns a list containing information about the token
- attributes <c>Attributes</c>. The order of the
- <c>AttributeInfoTuple</c>s is not defined. The following
- <c>AttributeItem</c>s are returned:
- <c>column</c>, <c>length</c>, <c>line</c>, and <c>text</c>.
+ attributes <c><anno>Attributes</anno></c>. The order of the
+ <c><anno>AttributeInfoTuple</anno></c>s is not defined.
See <seealso
marker="#attributes_info/2">attributes_info/2</seealso> for
information about specific
- <c>AttributeInfoTuple</c>s.</p>
+ <c><anno>AttributeInfoTuple</anno></c>s.</p>
<p>Note that if <c>attributes_info(Token, AttributeItem)</c>
returns <c>undefined</c> for some <c>AttributeItem</c> in
the list above, the item is not included in
- <c>AttributesInfo</c>.</p>
+ <c><anno>AttributesInfo</anno></c>.</p>
</desc>
</func>
<func>
- <name>attributes_info(Attributes, AttributeItemSpec) -> AttributesInfo</name>
+ <name name="attributes_info" arity="2" clause_i="1"/>
+ <name name="attributes_info" arity="2" clause_i="2"/>
<fsummary>Return information about a token attributes</fsummary>
- <type>
- <v>Attributes = attributes()</v>
- <v>AttributeItemSpec = AttributeItem | [AttributeItem]</v>
- <v>AttributesInfo = AttributeInfoTuple | undefined
- | [AttributeInfoTuple]</v>
- <v>AttributeInfoTuple = {AttributeItem, Info}</v>
- <v>AttributeItem = atom()</v>
- <v>Info = term()</v>
- </type>
+ <type name="attribute_item"/>
<desc>
<p>Returns a list containing information about the token
- attributes <c>Attributes</c>. If <c>AttributeItemSpec</c> is
- a single <c>AttributeItem</c>, the returned value is the
- corresponding <c>AttributeInfoTuple</c>, or <c>undefined</c>
- if the <c>AttributeItem</c> has no value. If
- <c>AttributeItemSpec</c> is a list of
- <c>AttributeItem</c>, the result is a list of
- <c>AttributeInfoTuple</c>. The <c>AttributeInfoTuple</c>s
- will appear with the corresponding <c>AttributeItem</c>s in
- the same order as the <c>AttributeItem</c>s appeared in the
- list of <c>AttributeItem</c>s. <c>AttributeItem</c>s with no
+ attributes <c><anno>Attributes</anno></c>. If one single
+ <c><anno>AttributeItem</anno></c> is given the returned value is the
+ corresponding <c><anno>AttributeInfoTuple</anno></c>,
+ or <c>undefined</c> if the <c><anno>AttributeItem</anno></c>
+ has no value. If a list of <c><anno>AttributeItem</anno></c>
+ is given the result is a list of
+ <c><anno>AttributeInfoTuple</anno></c>.
+ The <c><anno>AttributeInfoTuple</anno></c>s
+ will appear with the corresponding <c><anno>AttributeItem</anno></c>s
+ in the same order as the <c><anno>AttributeItem</anno></c>s
+ appear in the list of <c><anno>AttributeItem</anno></c>s.
+ <c><anno>AttributeItem</anno></c>s with no
value are not included in the list of
- <c>AttributeInfoTuple</c>.</p>
- <p>The following <c>AttributeInfoTuple</c>s with corresponding
- <c>AttributeItem</c>s are valid:</p>
+ <c><anno>AttributeInfoTuple</anno></c>.</p>
+ <p>The following <c><anno>AttributeInfoTuple</anno></c>s with
+ corresponding <c><anno>AttributeItem</anno></c>s are valid:</p>
<taglist>
- <tag><c>{column, column()}</c></tag>
+ <tag><c>{column, <seealso marker="#type-column">
+ column()</seealso>}</c></tag>
<item><p>The column where the token begins.</p>
</item>
<tag><c>{length, integer() > 0}</c></tag>
<item><p>The length of the token's text.</p>
</item>
- <tag><c>{line, line()}</c></tag>
+ <tag><c>{line, <seealso marker="#type-line">
+ line()</seealso>}</c></tag>
<item><p>The line where the token begins.</p>
</item>
- <tag><c>{location, location()}</c></tag>
+ <tag><c>{location, <seealso marker="#type-location">
+ location()</seealso>}</c></tag>
<item><p>The line and column where the token begins, or
just the line if the column unknown.</p>
</item>
@@ -359,29 +370,22 @@ attributes() = line() | list() | tuple()</code>
</desc>
</func>
<func>
- <name>set_attribute(AttributeItem, Attributes, SetAttributeFun) -> AttributesInfo</name>
+ <name name="set_attribute" arity="3"/>
<fsummary>Set a token attribute value</fsummary>
- <type>
- <v>AttributeItem = line</v>
- <v>Attributes = attributes()</v>
- <v>SetAttributeFun = set_attribute_fun()</v>
- </type>
<desc>
<p>Sets the value of the <c>line</c> attribute of the token
- attributes <c>Attributes</c>.</p>
- <p>The <c>SetAttributeFun</c> is called with the value of
+ attributes <c><anno>Attributes</anno></c>.</p>
+ <p>The <c><anno>SetAttributeFun</anno></c> is called with the value of
the <c>line</c> attribute, and is to return the new value of
the <c>line</c> attribute.</p>
</desc>
</func>
<func>
- <name>format_error(ErrorDescriptor) -> string()</name>
+ <name name="format_error" arity="1"/>
<fsummary>Format an error descriptor</fsummary>
- <type>
- <v>ErrorDescriptor = errordesc()</v>
- </type>
<desc>
- <p>Takes an <c>ErrorDescriptor</c> and returns a string which
+ <p>Takes an <c><anno>ErrorDescriptor</anno></c> and returns
+ a string which
describes the error or warning. This function is usually
called implicitly when processing an <c>ErrorInfo</c>
structure (see below).</p>
diff --git a/lib/stdlib/doc/src/ets.xml b/lib/stdlib/doc/src/ets.xml
index 746f94d3f4..8c952708c5 100644
--- a/lib/stdlib/doc/src/ets.xml
+++ b/lib/stdlib/doc/src/ets.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -126,15 +126,30 @@
<em>ERTS User's Guide</em>.</p>
</section>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-match_spec()
- a match specification, see above
-
-tid()
- a table identifier, as returned by new/2</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name><marker id="type-continuation">continuation()</marker></name>
+ <desc>
+ <p>Opaque continuation used by <seealso marker="#select/1">
+ <c>select/1</c></seealso> and <seealso marker="#select/3">
+ <c>select/3</c></seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="match_spec"/>
+ <desc><p>A match specification, see above.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="match_pattern"/>
+ </datatype>
+ <datatype>
+ <name name="tab"/>
+ </datatype>
+ <datatype>
+ <name name="tid"/>
+ <desc><p>A table identifier, as returned by new/2.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
<name>all() -> [Tab]</name>
@@ -197,37 +212,25 @@ tid()
</desc>
</func>
<func>
- <name>file2tab(Filename) -> {ok,Tab} | {error,Reason}</name>
+ <name name="file2tab" arity="1"/>
<fsummary>Read an ETS table from a file.</fsummary>
- <type>
- <v>Filename = string() | atom()</v>
- <v>Tab = tid() | atom()</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Reads a file produced by <seealso
marker="#tab2file/2">tab2file/2</seealso> or
<seealso marker="#tab2file/3">tab2file/3</seealso> and creates the
- corresponding table <c>Tab</c>.</p>
- <p>Equivalent to <c>file2tab(Filename,[])</c>.</p>
+ corresponding table <c><anno>Tab</anno></c>.</p>
+ <p>Equivalent to <c>file2tab(<anno>Filename</anno>, [])</c>.</p>
</desc>
</func>
<func>
- <name>file2tab(Filename,Options) -> {ok,Tab} | {error,Reason}</name>
+ <name name="file2tab" arity="2"/>
<fsummary>Read an ETS table from a file.</fsummary>
- <type>
- <v>Filename = string() | atom()</v>
- <v>Tab = tid() | atom()</v>
- <v>Options = [Option]</v>
- <v>Option = {verify, bool()}</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Reads a file produced by <seealso
marker="#tab2file/2">tab2file/2</seealso> or
<seealso marker="#tab2file/3">tab2file/3</seealso> and creates the
- corresponding table <c>Tab</c>.</p>
- <p>The currently only supported option is <c>{verify,bool()}</c>. If
+ corresponding table <c><anno>Tab</anno></c>.</p>
+ <p>The currently only supported option is <c>{verify,boolean()}</c>. If
verification is turned on (by means of specifying
<c>{verify,true}</c>), the function utilizes whatever
information is present in the file to assert that the
@@ -271,70 +274,52 @@ tid()
</desc>
</func>
<func>
- <name>foldl(Function, Acc0, Tab) -> Acc1</name>
+ <name name="foldl" arity="3"/>
<fsummary>Fold a function over an ETS table</fsummary>
- <type>
- <v>Function = fun(A, AccIn) -> AccOut</v>
- <v>Tab = tid() | atom()</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- </type>
<desc>
- <p><c>Acc0</c> is returned if the table is empty.
+ <p><c><anno>Acc0</anno></c> is returned if the table is empty.
This function is similar to <c>lists:foldl/3</c>. The order in
which the elements of the table are traversed is unspecified,
except for tables of type <c>ordered_set</c>, for which they
are traversed first to last.</p>
- <p>If <c>Function</c> inserts objects into the table, or another
+ <p>If <c><anno>Function</anno></c> inserts objects into the table, or another
process inserts objects into the table, those objects <em>may</em>
(depending on key ordering) be included in the traversal.</p>
</desc>
</func>
<func>
- <name>foldr(Function, Acc0, Tab) -> Acc1</name>
+ <name name="foldr" arity="3"/>
<fsummary>Fold a function over an ETS table</fsummary>
- <type>
- <v>Function = fun(A, AccIn) -> AccOut</v>
- <v>Tab = tid() | atom()</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- </type>
<desc>
- <p><c>Acc0</c> is returned if the table is empty.
+ <p><c><anno>Acc0</anno></c> is returned if the table is empty.
This function is similar to <c>lists:foldr/3</c>. The order in
which the elements of the table are traversed is unspecified,
except for tables of type <c>ordered_set</c>, for which they
are traversed last to first.</p>
- <p>If <c>Function</c> inserts objects into the table, or another
+ <p>If <c><anno>Function</anno></c> inserts objects into the table, or another
process inserts objects into the table, those objects <em>may</em>
(depending on key ordering) be included in the traversal.</p>
</desc>
</func>
<func>
- <name>from_dets(Tab, DetsTab) -> true</name>
+ <name name="from_dets" arity="2"/>
<fsummary>Fill an ETS table with objects from a Dets table.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- <v>DetsTab = atom()</v>
- </type>
<desc>
<p>Fills an already created ETS table with the objects in the
- already opened Dets table named <c>DetsTab</c>. The existing
+ already opened Dets table named <c><anno>DetsTab</anno></c>. The existing
objects of the ETS table are kept unless overwritten.</p>
<p>Throws a badarg error if any of the tables does not exist or the
dets table is not open.</p>
</desc>
</func>
<func>
- <name>fun2ms(LiteralFun) -> MatchSpec</name>
+ <name name="fun2ms" arity="1"/>
<fsummary>Pseudo function that transforms fun syntax to a match_spec.</fsummary>
- <type>
- <v>LiteralFun -- see below</v>
- <v>MatchSpec = match_spec()</v>
- </type>
<desc>
<p>Pseudo function that by means of a <c>parse_transform</c>
- translates <c>LiteralFun</c> typed as parameter in the
+ translates <c><anno>LiteralFun</anno></c> typed as parameter in the
function call to a
<seealso marker="#match_spec">match_spec</seealso>. With
"literal" is meant that the fun needs to textually be written
@@ -342,7 +327,7 @@ tid()
variable which in turn is passed to the function).</p>
<p>The parse transform is implemented in the module
<c>ms_transform</c> and the source <em>must</em> include the
- file <c>ms_transform.hrl</c> in <c>stdlib</c> for this
+ file <c>ms_transform.hrl</c> in STDLIB for this
pseudo function to work. Failing to include the hrl file in
the source will result in a runtime error, not a compile
time ditto. The include file is easiest included by adding
@@ -422,20 +407,17 @@ Error: fun containing local Erlang function calls
</desc>
</func>
<func>
- <name>i() -> ok</name>
+ <name name="i" arity="0"/>
<fsummary>Display information about all ETS tables on tty.</fsummary>
<desc>
<p>Displays information about all ETS tables on tty.</p>
</desc>
</func>
<func>
- <name>i(Tab) -> ok</name>
+ <name name="i" arity="1"/>
<fsummary>Browse an ETS table on tty.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- </type>
<desc>
- <p>Browses the table <c>Tab</c> on tty.</p>
+ <p>Browses the table <c><anno>Tab</anno></c> on tty.</p>
</desc>
</func>
<func>
@@ -454,7 +436,7 @@ Error: fun containing local Erlang function calls
correct type, this function fails with reason <c>badarg</c>.</p>
<list type="bulleted">
- <item><c>Item=memory, Value=int()</c> <br></br>
+ <item><c>Item=memory, Value=integer()</c> <br></br>
The number of words allocated to the table.</item>
<item><c>Item=owner, Value=pid()</c> <br></br>
@@ -466,7 +448,7 @@ Error: fun containing local Erlang function calls
<item><c>Item=name, Value=atom()</c> <br></br>
The name of the table.</item>
- <item><c>Item=size, Value=int()</c> <br></br>
+ <item><c>Item=size, Value=integer()</c> <br></br>
The number of objects inserted in the table.</item>
<item><c>Item=node, Value=atom()</c> <br></br>
@@ -479,7 +461,7 @@ Error: fun containing local Erlang function calls
<item><c>Item=type, Value=set|ordered_set|bag|duplicate_bag</c> <br></br>
The table type.</item>
- <item><c>Item=keypos, Value=int()</c> <br></br>
+ <item><c>Item=keypos, Value=integer()</c> <br></br>
The key position.</item>
<item><c>Item=protection, Value=public|protected|private</c> <br></br>
@@ -536,25 +518,19 @@ Error: fun containing local Erlang function calls
</desc>
</func>
<func>
- <name>init_table(Name, InitFun) -> true</name>
+ <name name="init_table" arity="2"/>
<fsummary>Replace all objects of an ETS table.</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>InitFun = fun(Arg) -> Res</v>
- <v>Arg = read | close</v>
- <v>Res = end_of_input | {[object()], InitFun} | term()</v>
- </type>
<desc>
- <p>Replaces the existing objects of the table <c>Tab</c> with
- objects created by calling the input function <c>InitFun</c>,
+ <p>Replaces the existing objects of the table <c><anno>Tab</anno></c> with
+ objects created by calling the input function <c><anno>InitFun</anno></c>,
see below. This function is provided for compatibility with
the <c>dets</c> module, it is not more efficient than filling
a table by using <c>ets:insert/2</c>.
</p>
<p>When called with the argument <c>read</c> the function
- <c>InitFun</c> is assumed to return <c>end_of_input</c> when
- there is no more input, or <c>{Objects, Fun}</c>, where
- <c>Objects</c> is a list of objects and <c>Fun</c> is a new
+ <c><anno>InitFun</anno></c> is assumed to return <c>end_of_input</c> when
+ there is no more input, or <c>{<anno>Objects</anno>, Fun}</c>, where
+ <c><anno>Objects</anno></c> is a list of objects and <c>Fun</c> is a new
input function. Any other value Value is returned as an error
<c>{error, {init_fun, Value}}</c>. Each input function will be
called exactly once, and should an error occur, the last
@@ -594,7 +570,7 @@ Error: fun containing local Erlang function calls
</desc>
</func>
<func>
- <name>insert_new(Tab, ObjectOrObjects) -> bool()</name>
+ <name>insert_new(Tab, ObjectOrObjects) -> boolean()</name>
<fsummary>Insert an object into an ETS table if the key is not already present.</fsummary>
<type>
<v>Tab = tid() | atom()</v>
@@ -615,7 +591,7 @@ Error: fun containing local Erlang function calls
</desc>
</func>
<func>
- <name>is_compiled_ms(Term) -> bool()</name>
+ <name>is_compiled_ms(Term) -> boolean()</name>
<fsummary>Checks if an Erlang term is the result of ets:match_spec_compile</fsummary>
<type>
<v>Term = term()</v>
@@ -708,7 +684,7 @@ ets:is_compiled_ms(Broken).</code>
<type>
<v>Tab = tid() | atom()</v>
<v>Key = term()</v>
- <v>Pos = int()</v>
+ <v>Pos = integer()</v>
<v>Elem = term() | [term()]</v>
</type>
<desc>
@@ -802,15 +778,11 @@ ets:is_compiled_ms(Broken).</code>
</desc>
</func>
<func>
- <name>match_delete(Tab, Pattern) -> true</name>
+ <name name="match_delete" arity="2"/>
<fsummary>Delete all objects which match a given pattern from an ETS table.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- <v>Pattern = tuple()</v>
- </type>
<desc>
- <p>Deletes all objects which match the pattern <c>Pattern</c>
- from the table <c>Tab</c>. See <c>match/2</c> for a
+ <p>Deletes all objects which match the pattern <c><anno>Pattern</anno></c>
+ from the table <c><anno>Tab</anno></c>. See <c>match/2</c> for a
description of patterns.</p>
</desc>
</func>
@@ -957,8 +929,8 @@ ets:select(Table,MatchSpec),</code>
<v>&nbsp;Option = Type | Access | named_table | {keypos,Pos} | {heir,pid(),HeirData} | {heir,none} | Tweaks</v>
<v>&nbsp;&nbsp;Type = set | ordered_set | bag | duplicate_bag</v>
<v>&nbsp;&nbsp;Access = public | protected | private</v>
- <v>&nbsp;&nbsp;Tweaks = {write_concurrency,bool()} | {read_concurrency,bool()} | compressed</v>
- <v>&nbsp;&nbsp;Pos = int()</v>
+ <v>&nbsp;&nbsp;Tweaks = {write_concurrency,boolean()} | {read_concurrency,boolean()} | compressed</v>
+ <v>&nbsp;&nbsp;Pos = integer()</v>
<v>&nbsp;&nbsp;HeirData = term()</v>
</type>
<desc>
@@ -1050,7 +1022,7 @@ ets:select(Table,MatchSpec),</code>
</item>
<item>
<marker id="new_2_write_concurrency"></marker>
- <p><c>{write_concurrency,bool()}</c>
+ <p><c>{write_concurrency,boolean()}</c>
Performance tuning. Default is <c>false</c>, in which case an operation that
mutates (writes to) the table will obtain exclusive access,
blocking any concurrent access of the same table until finished.
@@ -1074,7 +1046,7 @@ ets:select(Table,MatchSpec),</code>
</item>
<item>
<marker id="new_2_read_concurrency"></marker>
- <p><c>{read_concurrency,bool()}</c>
+ <p><c>{read_concurrency,boolean()}</c>
Performance tuning. Default is <c>false</c>. When set to
<c>true</c>, the table is optimized for concurrent read
operations. When this option is enabled on a runtime system with
@@ -1160,12 +1132,8 @@ ets:select(Table,MatchSpec),</code>
</desc>
</func>
<func>
- <name>repair_continuation(Continuation, MatchSpec) -> Continuation</name>
+ <name name="repair_continuation" arity="2"/>
<fsummary>Repair a continuation from ets:select/1 or ets:select/3 that has passed through external representation</fsummary>
- <type>
- <v>Continuation = term()</v>
- <v>MatchSpec = match_spec()</v>
- </type>
<desc>
<p>This function can be used to restore an opaque continuation
returned by <c>ets:select/3</c> or <c>ets:select/1</c> if the
@@ -1551,7 +1519,7 @@ is_integer(X), is_integer(Y), X + Y < 4711]]></code>
<fsummary>Return all objects in a given slot of an ETS table.</fsummary>
<type>
<v>Tab = tid() | atom()</v>
- <v>I = int()</v>
+ <v>I = integer()</v>
<v>Object = tuple()</v>
</type>
<desc>
@@ -1572,32 +1540,19 @@ is_integer(X), is_integer(Y), X + Y < 4711]]></code>
</desc>
</func>
<func>
- <name>tab2file(Tab, Filename) -> ok | {error,Reason}</name>
+ <name name="tab2file" arity="2"/>
<fsummary>Dump an ETS table to a file.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- <v>Filename = string() | atom()</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Dumps the table <c>Tab</c> to the file <c>Filename</c>.</p>
- <p>Equivalent to <c>tab2file(Tab, Filename,[])</c></p>
+ <p>Dumps the table <c><anno>Tab</anno></c> to the file <c><anno>Filename</anno></c>.</p>
+ <p>Equivalent to <c>tab2file(<anno>Tab</anno>, <anno>Filename</anno>,[])</c></p>
</desc>
</func>
<func>
- <name>tab2file(Tab, Filename, Options) -> ok | {error,Reason}</name>
+ <name name="tab2file" arity="3"/>
<fsummary>Dump an ETS table to a file.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- <v>Filename = string() | atom()</v>
- <v>Options = [Option]</v>
- <v>Option = {extended_info, [ExtInfo]}</v>
- <v>ExtInfo = object_count | md5sum</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Dumps the table <c>Tab</c> to the file <c>Filename</c>.</p>
+ <p>Dumps the table <c><anno>Tab</anno></c> to the file <c><anno>Filename</anno></c>.</p>
<p>When dumping the table, certain information about the table
is dumped to a header at the beginning of the dump. This
information contains data about the table type,
@@ -1634,26 +1589,15 @@ is_integer(X), is_integer(Y), X + Y < 4711]]></code>
</desc>
</func>
<func>
- <name>tab2list(Tab) -> [Object]</name>
+ <name name="tab2list" arity="1"/>
<fsummary>Return a list of all objects in an ETS table.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- <v>Object = tuple()</v>
- </type>
<desc>
- <p>Returns a list of all objects in the table <c>Tab</c>.</p>
+ <p>Returns a list of all objects in the table <c><anno>Tab</anno></c>.</p>
</desc>
</func>
<func>
- <name>tabfile_info(Filename) -> {ok, TableInfo} | {error, Reason}</name>
+ <name name="tabfile_info" arity="1"/>
<fsummary>Return a list of all objects in an ETS table.</fsummary>
- <type>
- <v>Filename = string() | atom()</v>
- <v>TableInfo = [InfoItem]</v>
- <v>InfoItem = {InfoTag, term()}</v>
- <v>InfoTag = name | type | protection | named_table | keypos | size | extended_info | version</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>Returns information about the table dumped to file by
<seealso marker="#tab2file/2">tab2file/2</seealso> or
@@ -1699,7 +1643,7 @@ is_integer(X), is_integer(Y), X + Y < 4711]]></code>
one or more of the atoms <c>object_count</c> and
<c>md5sum</c>.</item>
<tag>version</tag>
- <item>A tuple <c>{Major,Minor}</c> containing the major and
+ <item>A tuple <c>{<anno>Major</anno>,<anno>Minor</anno>}</c> containing the major and
minor version of the file format for ets table dumps. This
version field was added beginning with stdlib-1.5.1, files
dumped with older versions will return <c>{0,0}</c> in this
@@ -1712,20 +1656,11 @@ is_integer(X), is_integer(Y), X + Y < 4711]]></code>
</desc>
</func>
<func>
- <name>table(Tab [, Options]) -> QueryHandle</name>
+ <name name="table" arity="1"/>
+ <name name="table" arity="2"/>
<fsummary>Return a QLC query handle.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- <v>QueryHandle = -&nbsp;a query handle, see qlc(3)&nbsp;-</v>
- <v>Options = [Option] | Option</v>
- <v>Option = {n_objects, NObjects} | {traverse, TraverseMethod}</v>
- <v>NObjects = default | integer() > 0</v>
- <v>TraverseMethod = first_next | last_prev | select | {select, MatchSpec}</v>
- <v>MatchSpec = match_spec()</v>
- </type>
<desc>
- <p> <marker id="qlc_table"></marker>
-Returns a QLC (Query List
+ <p><marker id="qlc_table"></marker>Returns a QLC (Query List
Comprehension) query handle. The module <c>qlc</c> implements
a query language aimed mainly at Mnesia but ETS tables, Dets
tables, and lists are also recognized by QLC as sources of
@@ -1760,7 +1695,7 @@ Returns a QLC (Query List
that matches all objects.</p>
</item>
<item>
- <p><c>{select, MatchSpec}</c>. As for <c>select</c>
+ <p><c>{select, <anno>MatchSpec</anno>}</c>. As for <c>select</c>
the table is traversed by calling <c>ets:select/3</c> and
<c>ets:select/1</c>. The difference is that the
match_spec is explicitly given. This is how to state
@@ -1788,41 +1723,31 @@ true</pre>
</desc>
</func>
<func>
- <name>test_ms(Tuple, MatchSpec) -> {ok, Result} | {error, Errors}</name>
+ <name name="test_ms" arity="2"/>
<fsummary>Test a match_spec for use in ets:select/2.</fsummary>
- <type>
- <v>Tuple = tuple()</v>
- <v>MatchSpec = match_spec()</v>
- <v>Result = term()</v>
- <v>Errors = [{warning|error, string()}]</v>
- </type>
<desc>
<p>This function is a utility to test a
<seealso marker="#match_spec">match_spec</seealso> used in
calls to <c>ets:select/2</c>. The function both tests
- <c>MatchSpec</c> for "syntactic" correctness and runs the
- match_spec against the object <c>Tuple</c>. If the match_spec
- contains errors, the tuple <c>{error, Errors}</c> is returned
- where <c>Errors</c> is a list of natural language
+ <c><anno>MatchSpec</anno></c> for "syntactic" correctness and runs the
+ match_spec against the object <c><anno>Tuple</anno></c>. If the match_spec
+ contains errors, the tuple <c>{error, <anno>Errors</anno>}</c> is returned
+ where <c><anno>Errors</anno></c> is a list of natural language
descriptions of what was wrong with the match_spec. If the
match_spec is syntactically OK, the function returns
- <c>{ok,Term}</c> where <c>Term</c> is what would have been
+ <c>{ok,<anno>Result</anno>}</c> where <c><anno>Result</anno></c> is what would have been
the result in a real <c>ets:select/2</c> call or <c>false</c>
- if the match_spec does not match the object <c>Tuple</c>.</p>
+ if the match_spec does not match the object <c><anno>Tuple</anno></c>.</p>
<p>This is a useful debugging and test tool, especially when
writing complicated <c>ets:select/2</c> calls.</p>
</desc>
</func>
<func>
- <name>to_dets(Tab, DetsTab) -> DetsTab</name>
+ <name name="to_dets" arity="2"/>
<fsummary>Fill a Dets table with objects from an ETS table.</fsummary>
- <type>
- <v>Tab = tid() | atom()</v>
- <v>DetsTab = atom()</v>
- </type>
<desc>
<p>Fills an already created/opened Dets table with the objects
- in the already opened ETS table named <c>Tab</c>. The Dets
+ in the already opened ETS table named <c><anno>Tab</anno></c>. The Dets
table is emptied before the objects are inserted.</p>
</desc>
</func>
@@ -1835,7 +1760,7 @@ true</pre>
<v>Tab = tid() | atom()</v>
<v>Key = term()</v>
<v>UpdateOp = {Pos,Incr} | {Pos,Incr,Threshold,SetValue}</v>
- <v>Pos = Incr = Threshold = SetValue = Result = int()</v>
+ <v>Pos = Incr = Threshold = SetValue = Result = integer()</v>
</type>
<desc>
<p>This function provides an efficient way to update one or more
@@ -1897,7 +1822,7 @@ true</pre>
<type>
<v>Tab = tid() | atom()</v>
<v>Key = Value = term()</v>
- <v>Pos = int()</v>
+ <v>Pos = integer()</v>
</type>
<desc>
<p>This function provides an efficient way to update one or more
diff --git a/lib/stdlib/doc/src/file_sorter.xml b/lib/stdlib/doc/src/file_sorter.xml
index ccb32659a0..a6b3633066 100644
--- a/lib/stdlib/doc/src/file_sorter.xml
+++ b/lib/stdlib/doc/src/file_sorter.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2001</year><year>2010</year>
+ <year>2001</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -89,7 +89,7 @@
considerably. The <c>keysort</c>, <c>keymerge</c> and
<c>keycheck</c> functions do not accept ordering functions.
</item>
- <item><c>{unique, bool()}</c>. When sorting or merging files,
+ <item><c>{unique, boolean()}</c>. When sorting or merging files,
only the first of a sequence of terms that compare equal (<c>==</c>)
is output if this option is set to <c>true</c>. The default
value is <c>false</c> which implies that all terms that
@@ -112,7 +112,7 @@
overwritten. Temporary files are deleted unless some
uncaught EXIT signal occurs.
</item>
- <item><c>{compressed, bool()}</c>. Temporary files and the
+ <item><c>{compressed, boolean()}</c>. Temporary files and the
output file may be compressed. The default value
<c>false</c> implies that written files are not
compressed. Regardless of the value of the <c>compressed</c>
@@ -128,39 +128,6 @@
merged at a time. This option should rarely be needed.
</item>
</list>
- <p>To summarize, here is the syntax of the options:</p>
- <list type="bulleted">
- <item>
- <p><c>Options = [Option] | Option</c></p>
- </item>
- <item>
- <p><c>Option = {header, HeaderLength} | {format, Format} | {order, Order} | {unique, bool()} | {tmpdir, TempDirectory} | {compressed, bool()} | {size, Size} | {no_files, NoFiles}</c></p>
- </item>
- <item>
- <p><c>HeaderLength = int() > 0</c></p>
- </item>
- <item>
- <p><c>Format = binary_term | term | binary | FormatFun</c></p>
- </item>
- <item>
- <p><c>FormatFun = fun(Binary) -> Term</c></p>
- </item>
- <item>
- <p><c>Order = ascending | descending | OrderFun</c></p>
- </item>
- <item>
- <p><c>OrderFun = fun(Term, Term) -> bool()</c></p>
- </item>
- <item>
- <p><c>TempDirectory = "" | file_name()</c></p>
- </item>
- <item>
- <p><c>Size = int() >= 0</c></p>
- </item>
- <item>
- <p><c>NoFiles = int() > 1</c></p>
- </item>
- </list>
<p>As an alternative to sorting files, a function of one argument
can be given as input. When called with the argument <c>read</c>
the function is assumed to return <c>end_of_input</c> or
@@ -234,8 +201,8 @@ output(L) ->
occurs are:</p>
<list type="bulleted">
<item>
- <p><c>bad_object</c>, <c>{bad_object, FileName}</c>.
- Applying the format function failed for some binary,
+ <p><c>bad_object</c>, <c>{bad_object, FileName}</c>.
+ Applying the format function failed for some binary,
or the key(s) could not be extracted from some term.</p>
</item>
<item>
@@ -243,148 +210,181 @@ output(L) ->
to read some term.</p>
</item>
<item>
- <p><c>{file_error, FileName, Reason2}</c>. See
- <c>file(3)</c> for an explanation of <c>Reason2</c>.</p>
+ <p><c>{file_error, FileName, file:posix()}</c>. See
+ <c>file(3)</c> for an explanation of <c>file:posix()</c>.</p>
</item>
<item>
- <p><c>{premature_eof, FileName}</c>. End-of-file was
+ <p><c>{premature_eof, FileName}</c>. End-of-file was
encountered inside some binary term.</p>
</item>
</list>
- <p><em>Types</em></p>
- <pre>
-Binary = binary()
-FileName = file_name()
-FileNames = [FileName]
-ICommand = read | close
-IReply = end_of_input | {end_of_input, Value} | {[Object], Infun} | InputReply
-Infun = fun(ICommand) -> IReply
-Input = FileNames | Infun
-InputReply = Term
-KeyPos = int() > 0 | [int() > 0]
-OCommand = {value, Value} | [Object] | close
-OReply = Outfun | OutputReply
-Object = Term | Binary
-Outfun = fun(OCommand) -> OReply
-Output = FileName | Outfun
-OutputReply = Term
-Term = term()
-Value = Term</pre>
</description>
+
+ <datatypes>
+ <datatype>
+ <name name="file_name"/><br/>
+ </datatype>
+ <datatype>
+ <name name="file_names"/><br/>
+ </datatype>
+ <datatype>
+ <name name="i_command"/><br/>
+ </datatype>
+ <datatype>
+ <name name="i_reply"/><br/>
+ </datatype>
+ <datatype>
+ <name name="infun"/><br/>
+ </datatype>
+ <datatype>
+ <name name="input"/><br/>
+ </datatype>
+ <datatype>
+ <name name="input_reply"/><br/>
+ </datatype>
+ <datatype>
+ <name name="o_command"/><br/>
+ </datatype>
+ <datatype>
+ <name name="o_reply"/><br/>
+ </datatype>
+ <datatype>
+ <name name="object"/><br/>
+ </datatype>
+ <datatype>
+ <name name="outfun"/><br/>
+ </datatype>
+ <datatype>
+ <name name="output"/><br/>
+ </datatype>
+ <datatype>
+ <name name="output_reply"/><br/>
+ </datatype>
+ <datatype>
+ <name name="value"/><br/>
+ </datatype>
+ <datatype>
+ <name name="options"/><br/>
+ </datatype>
+ <datatype>
+ <name name="option"/><br/>
+ </datatype>
+ <datatype>
+ <name name="format"/><br/>
+ </datatype>
+ <datatype>
+ <name name="format_fun"/><br/>
+ </datatype>
+ <datatype>
+ <name name="header_length"/><br/>
+ </datatype>
+ <datatype>
+ <name name="key_pos"/><br/>
+ </datatype>
+ <datatype>
+ <name name="no_files"/><br/>
+ </datatype>
+ <datatype>
+ <name name="order"/><br/>
+ </datatype>
+ <datatype>
+ <name name="order_fun"/><br/>
+ </datatype>
+ <datatype>
+ <name name="size"/><br/>
+ </datatype>
+ <datatype>
+ <name name="tmp_directory"/><br/>
+ </datatype>
+ <datatype>
+ <name name="reason"/><br/>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
- <name>sort(FileName) -> Reply</name>
- <name>sort(Input, Output) -> Reply</name>
- <name>sort(Input, Output, Options) -> Reply</name>
+ <name name="sort" arity="1"/>
<fsummary>Sort terms on files.</fsummary>
- <type>
- <v>Reply = ok | {error, Reason} | InputReply | OutputReply</v>
- </type>
<desc>
- <p>Sorts terms on files.
- </p>
- <p><c>sort(FileName)</c> is equivalent to
- <c>sort([FileName], FileName)</c>.
- </p>
- <p><c>sort(Input, Output)</c> is equivalent to
- <c>sort(Input, Output, [])</c>.
- </p>
- <p></p>
+ <p>Sorts terms on files. <c>sort(FileName)</c> is equivalent
+ to <c>sort([FileName], FileName)</c>.</p>
+ </desc>
+ </func>
+ <func>
+ <name name="sort" arity="2"/>
+ <name name="sort" arity="3"/>
+ <fsummary>Sort terms on files.</fsummary>
+ <desc>
+ <p>Sorts terms on files. <c>sort(Input, Output)</c> is
+ equivalent to <c>sort(Input, Output, [])</c>.</p>
+ </desc>
+ </func>
+ <func>
+ <name name="keysort" arity="2"/>
+ <fsummary>Sort terms on files by key.</fsummary>
+ <desc>
+ <p>Sorts tuples on files. <c>keysort(N, FileName)</c> is
+ equivalent to <c>keysort(N, [FileName], FileName)</c>.</p>
</desc>
</func>
<func>
- <name>keysort(KeyPos, FileName) -> Reply</name>
- <name>keysort(KeyPos, Input, Output) -> Reply</name>
- <name>keysort(KeyPos, Input, Output, Options) -> Reply</name>
+ <name name="keysort" arity="3"/>
+ <name name="keysort" arity="4"/>
<fsummary>Sort terms on files by key.</fsummary>
- <type>
- <v>Reply = ok | {error, Reason} | InputReply | OutputReply</v>
- </type>
<desc>
<p>Sorts tuples on files. The sort is performed on the
- element(s) mentioned in <c>KeyPos</c>. If two tuples
- compare equal (<c>==</c>) on one element, next element according to
- <c>KeyPos</c> is compared. The sort is stable.
- </p>
- <p><c>keysort(N, FileName)</c> is equivalent to
- <c>keysort(N, [FileName], FileName)</c>.
- </p>
+ element(s) mentioned in <c><anno>KeyPos</anno></c>. If two
+ tuples compare equal (<c>==</c>) on one element, next
+ element according to <c><anno>KeyPos</anno></c>
+ is compared. The sort is stable.</p>
<p><c>keysort(N, Input, Output)</c> is equivalent to
- <c>keysort(N, Input, Output, [])</c>.
- </p>
- <p></p>
+ <c>keysort(N, Input, Output, [])</c>.</p>
</desc>
</func>
<func>
- <name>merge(FileNames, Output) -> Reply</name>
- <name>merge(FileNames, Output, Options) -> Reply</name>
+ <name name="merge" arity="2"/>
+ <name name="merge" arity="3"/>
<fsummary>Merge terms on files.</fsummary>
- <type>
- <v>Reply = ok | {error, Reason} | OutputReply</v>
- </type>
<desc>
<p>Merges terms on files. Each input file is assumed to be
- sorted.
- </p>
+ sorted.</p>
<p><c>merge(FileNames, Output)</c> is equivalent to
- <c>merge(FileNames, Output, [])</c>.
- </p>
+ <c>merge(FileNames, Output, [])</c>.</p>
</desc>
</func>
<func>
- <name>keymerge(KeyPos, FileNames, Output) -> Reply</name>
- <name>keymerge(KeyPos, FileNames, Output, Options) -> Reply</name>
+ <name name="keymerge" arity="3"/>
+ <name name="keymerge" arity="4"/>
<fsummary>Merge terms on files by key.</fsummary>
- <type>
- <v>Reply = ok | {error, Reason} | OutputReply</v>
- </type>
<desc>
<p>Merges tuples on files. Each input file is assumed to be
- sorted on key(s).
- </p>
+ sorted on key(s).</p>
<p><c>keymerge(KeyPos, FileNames, Output)</c> is equivalent
- to <c>keymerge(KeyPos, FileNames, Output, [])</c>.
- </p>
- <p></p>
+ to <c>keymerge(KeyPos, FileNames, Output, [])</c>.</p>
</desc>
</func>
<func>
- <name>check(FileName) -> Reply</name>
- <name>check(FileNames, Options) -> Reply</name>
+ <name name="check" arity="1"/>
+ <name name="check" arity="2"/>
<fsummary>Check whether terms on files are sorted.</fsummary>
- <type>
- <v>Reply = {ok, [Result]} | {error, Reason}</v>
- <v>Result = {FileName, TermPosition, Term}</v>
- <v>TermPosition = int() > 1</v>
- </type>
<desc>
<p>Checks files for sortedness. If a file is not sorted, the
first out-of-order element is returned. The first term on a
- file has position 1.
- </p>
+ file has position 1.</p>
<p><c>check(FileName)</c> is equivalent to
- <c>check([FileName], [])</c>.
- </p>
+ <c>check([FileName], [])</c>.</p>
</desc>
</func>
<func>
- <name>keycheck(KeyPos, FileName) -> CheckReply</name>
- <name>keycheck(KeyPos, FileNames, Options) -> Reply</name>
+ <name name="keycheck" arity="2"/>
+ <name name="keycheck" arity="3"/>
<fsummary>Check whether terms on files are sorted by key.</fsummary>
- <type>
- <v>Reply = {ok, [Result]} | {error, Reason}</v>
- <v>Result = {FileName, TermPosition, Term}</v>
- <v>TermPosition = int() > 1</v>
- </type>
<desc>
<p>Checks files for sortedness. If a file is not sorted, the
first out-of-order element is returned. The first term on a
- file has position 1.
- </p>
+ file has position 1.</p>
<p><c>keycheck(KeyPos, FileName)</c> is equivalent
- to <c>keycheck(KeyPos, [FileName], [])</c>.
- </p>
- <p></p>
+ to <c>keycheck(KeyPos, [FileName], [])</c>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/filelib.xml b/lib/stdlib/doc/src/filelib.xml
index fab68ae77c..f3079c7337 100644
--- a/lib/stdlib/doc/src/filelib.xml
+++ b/lib/stdlib/doc/src/filelib.xml
@@ -41,62 +41,46 @@
<p>For more information about raw file names, see the <seealso marker="kernel:file">file</seealso> module.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-filename() = string() | atom() | DeepList | RawFilename
- DeepList = [char() | atom() | DeepList]
- RawFilename = binary()
- If VM is in unicode filename mode, string() and char() are allowed to be > 255.
- RawFilename is a filename not subject to Unicode translation, meaning that it
- can contain characters not conforming to the Unicode encoding expected from the
- filesystem (i.e. non-UTF-8 characters although the VM is started in Unicode
- filename mode).
-dirname() = filename()</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name name="filename"/>
+ </datatype>
+ <datatype>
+ <name name="dirname"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>ensure_dir(Name) -> ok | {error, Reason}</name>
+ <name name="ensure_dir" arity="1"/>
<fsummary>Ensure that all parent directories for a file or directory exist.</fsummary>
- <type>
- <v>Name = filename() | dirname()</v>
- <v>Reason = posix() -- see file(3)</v>
- </type>
<desc>
<p>The <c>ensure_dir/1</c> function ensures that all parent
- directories for the given file or directory name <c>Name</c>
+ directories for the given file or directory name <c><anno>Name</anno></c>
exist, trying to create them if necessary.</p>
<p>Returns <c>ok</c> if all parent directories already exist
- or could be created, or <c>{error, Reason}</c> if some parent
+ or could be created, or <c>{error, <anno>Reason</anno>}</c> if some parent
directory does not exist and could not be created for some
reason.</p>
</desc>
</func>
<func>
- <name>file_size(Filename) -> integer()</name>
+ <name name="file_size" arity="1"/>
<fsummary>Return the size in bytes of the file.</fsummary>
<desc>
<p>The <c>file_size</c> function returns the size of the given file.</p>
</desc>
</func>
<func>
- <name>fold_files(Dir, RegExp, Recursive, Fun, AccIn) -> AccOut </name>
+ <name name="fold_files" arity="5"/>
<fsummary>Fold over all files matching a regular expression.</fsummary>
- <type>
- <v>Dir = dirname()</v>
- <v>RegExp = regular_expression_string()</v>
- <v>Recursive = true|false</v>
- <v>Fun = fun(F, AccIn) -> AccOut</v>
- <v>AccIn = AccOut = term()</v>
- </type>
<desc>
<p>The <c>fold_files/5</c> function folds the function
- <c>Fun</c> over all (regular) files <c>F</c> in the
- directory <c>Dir</c> that match the regular expression <c>RegExp</c>
+ <c><anno>Fun</anno></c> over all (regular) files <c><anno>F</anno></c> in the
+ directory <c><anno>Dir</anno></c> that match the regular expression <c><anno>RegExp</anno></c>
(see the <seealso marker="re">re</seealso> module for a description
of the allowed regular expressions).
- If <c>Recursive</c> is true all sub-directories to <c>Dir</c>
+ If <c><anno>Recursive</anno></c> is true all sub-directories to <c>Dir</c>
are processed. The regular expression matching is done on just
the filename without the directory part.</p>
@@ -114,44 +98,32 @@ dirname() = filename()</code>
</desc>
</func>
<func>
- <name>is_dir(Name) -> true | false</name>
+ <name name="is_dir" arity="1"/>
<fsummary>Test whether Name refer to a directory or not</fsummary>
- <type>
- <v>Name = filename() | dirname()</v>
- </type>
<desc>
- <p>The <c>is_dir/1</c> function returns <c>true</c> if <c>Name</c>
+ <p>The <c>is_dir/1</c> function returns <c>true</c> if <c><anno>Name</anno></c>
refers to a directory, and <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_file(Name) -> true | false</name>
+ <name name="is_file" arity="1"/>
<fsummary>Test whether Name refer to a file or directory.</fsummary>
- <type>
- <v>Name = filename() | dirname()</v>
- </type>
<desc>
- <p>The <c>is_file/1</c> function returns <c>true</c> if <c>Name</c>
+ <p>The <c>is_file/1</c> function returns <c>true</c> if <c><anno>Name</anno></c>
refers to a file or a directory, and <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_regular(Name) -> true | false</name>
+ <name name="is_regular" arity="1"/>
<fsummary>Test whether Name refer to a (regular) file.</fsummary>
- <type>
- <v>Name = filename()</v>
- </type>
<desc>
- <p>The <c>is_regular/1</c> function returns <c>true</c> if <c>Name</c>
+ <p>The <c>is_regular/1</c> function returns <c>true</c> if <c><anno>Name</anno></c>
refers to a file (regular file), and <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>last_modified(Name) -> {{Year,Month,Day},{Hour,Min,Sec}} | 0</name>
+ <name name="last_modified" arity="1"/>
<fsummary>Return the local date and time when a file was last modified.</fsummary>
- <type>
- <v>Name = filename() | dirname()</v>
- </type>
<desc>
<p>The <c>last_modified/1</c> function returns the date and time the
given file or directory was last modified, or 0 if the file
@@ -159,14 +131,11 @@ dirname() = filename()</code>
</desc>
</func>
<func>
- <name>wildcard(Wildcard) -> list()</name>
+ <name name="wildcard" arity="1"/>
<fsummary>Match filenames using Unix-style wildcards.</fsummary>
- <type>
- <v>Wildcard = filename() | dirname()</v>
- </type>
<desc>
<p>The <c>wildcard/1</c> function returns a list of all files
- that match Unix-style wildcard-string <c>Wildcard</c>.</p>
+ that match Unix-style wildcard-string <c><anno>Wildcard</anno></c>.</p>
<p>The wildcard string looks like an ordinary filename, except
that certain "wildcard characters" are interpreted in a special
way. The following characters are special:
@@ -226,15 +195,11 @@ dirname() = filename()</code>
</desc>
</func>
<func>
- <name>wildcard(Wildcard, Cwd) -> list()</name>
+ <name name="wildcard" arity="2"/>
<fsummary>Match filenames using Unix-style wildcards starting at a specified directory.</fsummary>
- <type>
- <v>Wildcard = filename() | dirname()</v>
- <v>Cwd = dirname()</v>
- </type>
<desc>
<p>The <c>wildcard/2</c> function works like <c>wildcard/1</c>,
- except that instead of the actual working directory, <c>Cwd</c>
+ except that instead of the actual working directory, <c><anno>Cwd</anno></c>
will be used.</p>
</desc>
</func>
diff --git a/lib/stdlib/doc/src/filename.xml b/lib/stdlib/doc/src/filename.xml
index cdee6e4a81..bc3a616d39 100644
--- a/lib/stdlib/doc/src/filename.xml
+++ b/lib/stdlib/doc/src/filename.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1997</year><year>2010</year>
+ <year>1997</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -47,28 +47,12 @@
<seealso marker="kernel:file#native_name_encoding/0">file:native_name_encoding/0</seealso>, a raw file name will also be returned. For example filename:join/1 provided with a path component being a binary (and also not being possible to interpret under the current native file name encoding) will result in a raw file name being returned (the join operation will have been performed of course). For more information about raw file names, see the <seealso marker="kernel:file">file</seealso> module.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-name() = string() | atom() | DeepList | RawFilename
- DeepList = [char() | atom() | DeepList]
- RawFilename = binary()
- If VM is in unicode filename mode, string() and char() are allowed to be > 255.
- RawFilename is a filename not subject to Unicode translation, meaning that it
- can contain characters not conforming to the Unicode encoding expected from the
- filesystem (i.e. non-UTF-8 characters although the VM is started in Unicode
- filename mode).
- </code>
- </section>
<funcs>
<func>
- <name>absname(Filename) -> string()</name>
+ <name name="absname" arity="1"/>
<fsummary>Convert a filename to an absolute name, relative the working directory</fsummary>
- <type>
- <v>Filename = name()</v>
- </type>
<desc>
- <p>Converts a relative <c>Filename</c> and returns an absolute
+ <p>Converts a relative <c><anno>Filename</anno></c> and returns an absolute
name. No attempt is made to create the shortest absolute name,
because this can give incorrect results on file systems which
allow links.</p>
@@ -95,44 +79,33 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>absname(Filename, Dir) -> string()</name>
+ <name name="absname" arity="2"/>
<fsummary>Convert a filename to an absolute name, relative a specified directory</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Dir = string()</v>
- </type>
<desc>
<p>This function works like <c>absname/1</c>, except that
the directory to which the file name should be made relative
- is given explicitly in the <c>Dir</c> argument.</p>
+ is given explicitly in the <c><anno>Dir</anno></c> argument.</p>
</desc>
</func>
<func>
- <name>absname_join(Dir, Filename) -> string()</name>
+ <name name="absname_join" arity="2"/>
<fsummary>Join an absolute directory with a relative filename</fsummary>
- <type>
- <v>Dir = string()</v>
- <v>Filename = name()</v>
- </type>
<desc>
<p>Joins an absolute directory with a relative filename.
Similar to <c>join/2</c>, but on platforms with tight
restrictions on raw filename length and no support for
symbolic links (read: VxWorks), leading parent directory
- components in <c>Filename</c> are matched against trailing
- directory components in <c>Dir</c> so they can be removed
+ components in <c><anno>Filename</anno></c> are matched against trailing
+ directory components in <c><anno>Dir</anno></c> so they can be removed
from the result - minimizing its length.</p>
</desc>
</func>
<func>
- <name>basename(Filename) -> string()</name>
+ <name name="basename" arity="1"/>
<fsummary>Return the last component of a filename</fsummary>
- <type>
- <v>Filename = name()</v>
- </type>
<desc>
- <p>Returns the last component of <c>Filename</c>, or
- <c>Filename</c> itself if it does not contain any directory
+ <p>Returns the last component of <c><anno>Filename</anno></c>, or
+ <c><anno>Filename</anno></c> itself if it does not contain any directory
separators.</p>
<pre>
5> <input>filename:basename("foo").</input>
@@ -144,14 +117,11 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>basename(Filename, Ext) -> string()</name>
+ <name name="basename" arity="2"/>
<fsummary>Return the last component of a filename, stripped of the specified extension</fsummary>
- <type>
- <v>Filename = Ext = name()</v>
- </type>
<desc>
- <p>Returns the last component of <c>Filename</c> with the
- extension <c>Ext</c> stripped. This function should be used
+ <p>Returns the last component of <c><anno>Filename</anno></c> with the
+ extension <c><anno>Ext</anno></c> stripped. This function should be used
to remove a specific extension which might, or might not, be
there. Use <c>rootname(basename(Filename))</c> to remove an
extension that exists, but you are not sure which one it is.</p>
@@ -169,13 +139,10 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>dirname(Filename) -> string()</name>
+ <name name="dirname" arity="1"/>
<fsummary>Return the directory part of a path name</fsummary>
- <type>
- <v>Filename = name()</v>
- </type>
<desc>
- <p>Returns the directory part of <c>Filename</c>.</p>
+ <p>Returns the directory part of <c><anno>Filename</anno></c>.</p>
<pre>
13> <input>filename:dirname("/usr/src/kalle.erl").</input>
"/usr/src"
@@ -187,13 +154,10 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>extension(Filename) -> string()</name>
+ <name name="extension" arity="1"/>
<fsummary>Return the file extension</fsummary>
- <type>
- <v>Filename = name()</v>
- </type>
<desc>
- <p>Returns the file extension of <c>Filename</c>, including
+ <p>Returns the file extension of <c><anno>Filename</anno></c>, including
the period. Returns an empty string if there is no extension.</p>
<pre>
15> <input>filename:extension("foo.erl").</input>
@@ -203,11 +167,8 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>flatten(Filename) -> string()</name>
+ <name name="flatten" arity="1"/>
<fsummary>Convert a filename to a flat string</fsummary>
- <type>
- <v>Filename = name()</v>
- </type>
<desc>
<p>Converts a possibly deep list filename consisting of
characters and atoms into the corresponding flat string
@@ -215,14 +176,11 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>join(Components) -> string()</name>
+ <name name="join" arity="1"/>
<fsummary>Join a list of filename components with directory separators</fsummary>
- <type>
- <v>Components = [string()]</v>
- </type>
<desc>
- <p>Joins a list of file name <c>Components</c> with directory
- separators. If one of the elements of <c>Components</c>
+ <p>Joins a list of file name <c><anno>Components</anno></c> with directory
+ separators. If one of the elements of <c><anno>Components</anno></c>
includes an absolute path, for example <c>"/xxx"</c>,
the preceding elements, if any, are removed from the result.</p>
<p>The result is "normalized":</p>
@@ -242,24 +200,18 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>join(Name1, Name2) -> string()</name>
+ <name name="join" arity="2"/>
<fsummary>Join two filename components with directory separators</fsummary>
- <type>
- <v>Name1 = Name2 = string()</v>
- </type>
<desc>
<p>Joins two file name components with directory separators.
- Equivalent to <c>join([Name1, Name2])</c>.</p>
+ Equivalent to <c>join([<anno>Name1</anno>, <anno>Name2</anno>])</c>.</p>
</desc>
</func>
<func>
- <name>nativename(Path) -> string()</name>
+ <name name="nativename" arity="1"/>
<fsummary>Return the native form of a file path</fsummary>
- <type>
- <v>Path = string()</v>
- </type>
<desc>
- <p>Converts <c>Path</c> to a form accepted by the command shell
+ <p>Converts <c><anno>Path</anno></c> to a form accepted by the command shell
and native applications on the current platform. On Windows,
forward slashes is converted to backward slashes. On all
platforms, the name is normalized as done by <c>join/1</c>.</p>
@@ -272,7 +224,7 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>pathtype(Path) -> absolute | relative | volumerelative</name>
+ <name name="pathtype" arity="1"/>
<fsummary>Return the type of a path</fsummary>
<desc>
<p>Returns the type of path, one of <c>absolute</c>,
@@ -302,16 +254,13 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>rootname(Filename) -> string()</name>
- <name>rootname(Filename, Ext) -> string()</name>
+ <name name="rootname" arity="1"/>
+ <name name="rootname" arity="2"/>
<fsummary>Remove a filename extension</fsummary>
- <type>
- <v>Filename = Ext = name()</v>
- </type>
<desc>
<p>Remove a filename extension. <c>rootname/2</c> works as
<c>rootname/1</c>, except that the extension is removed only
- if it is <c>Ext</c>.</p>
+ if it is <c><anno>Ext</anno></c>.</p>
<pre>
20> <input>filename:rootname("/beam.src/kalle").</input>
/beam.src/kalle"
@@ -324,15 +273,11 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>split(Filename) -> Components</name>
+ <name name="split" arity="1"/>
<fsummary>Split a filename into its path components</fsummary>
- <type>
- <v>Filename = name()</v>
- <v>Components = [string()]</v>
- </type>
<desc>
<p>Returns a list whose elements are the path components of
- <c>Filename</c>.</p>
+ <c><anno>Filename</anno></c>.</p>
<pre>
24> <input>filename:split("/usr/local/bin").</input>
["/","usr","local","bin"]
@@ -343,47 +288,38 @@ name() = string() | atom() | DeepList | RawFilename
</desc>
</func>
<func>
- <name>find_src(Beam) -> {SourceFile, Options} | {error,{ErrorReason,Module}}</name>
- <name>find_src(Beam, Rules) -> {SourceFile, Options} | {error,{ErrorReason,Module}}</name>
+ <name name="find_src" arity="1"/>
+ <name name="find_src" arity="2"/>
<fsummary>Find the filename and compiler options for a module</fsummary>
- <type>
- <v>Beam = Module | Filename</v>
- <v>&nbsp;Module = atom()</v>
- <v>&nbsp;Filename = string() | atom()</v>
- <v>SourceFile = string()</v>
- <v>Options = [Opt]</v>
- <v>&nbsp;Opt = {i, string()} | {outdir, string()} | {d, atom()}</v>
- <v>ErrorReason = non_existing | preloaded | interpreted</v>
- </type>
<desc>
<p>Finds the source filename and compiler options for a module.
The result can be fed to <c>compile:file/2</c> in order to
compile the file again.</p>
- <p>The <c>Beam</c> argument, which can be a string or an atom,
+ <p>The <c><anno>Beam</anno></c> argument, which can be a string or an atom,
specifies either the module name or the path to the source
code, with or without the <c>".erl"</c> extension. In either
case, the module must be known by the code server, i.e.
- <c>code:which(Module)</c> must succeed.</p>
- <p><c>Rules</c> describes how the source directory can be found,
+ <c>code:which(<anno>Module</anno>)</c> must succeed.</p>
+ <p><c><anno>Rules</anno></c> describes how the source directory can be found,
when the object code directory is known. It is a list of
- tuples <c>{BinSuffix, SourceSuffix}</c> and is interpreted
+ tuples <c>{<anno>BinSuffix</anno>, <anno>SourceSuffix</anno>}</c> and is interpreted
as follows: If the end of the directory name where the object
- is located matches <c>BinSuffix</c>, then the source code
- directory has the same name, but with <c>BinSuffix</c>
- replaced by <c>SourceSuffix</c>. <c>Rules</c> defaults to:</p>
+ is located matches <c><anno>BinSuffix</anno></c>, then the source code
+ directory has the same name, but with <c><anno>BinSuffix</anno></c>
+ replaced by <c><anno>SourceSuffix</anno></c>. <c><anno>Rules</anno></c> defaults to:</p>
<code type="none">
[{"", ""}, {"ebin", "src"}, {"ebin", "esrc"}]</code>
<p>If the source file is found in the resulting directory, then
the function returns that location together with
- <c>Options</c>. Otherwise, the next rule is tried, and so on.</p>
+ <c><anno>Options</anno></c>. Otherwise, the next rule is tried, and so on.</p>
- <p>The function returns <c>{SourceFile, Options}</c> if it succeeds.
- <c>SourceFile</c> is the absolute path to the source file
- without the <c>".erl"</c> extension. <c>Options</c> include
+ <p>The function returns <c>{<anno>SourceFile</anno>, <anno>Options</anno>}</c> if it succeeds.
+ <c><anno>SourceFile</anno></c> is the absolute path to the source file
+ without the <c>".erl"</c> extension. <c><anno>Options</anno></c> include
the options which are necessary to recompile the file with
<c>compile:file/2</c>, but excludes options such as
<c>report</c> or <c>verbose</c> which do not change the way
- code is generated. The paths in the <c>{outdir, Path}</c>
+ code is generated. The paths in the <c>{outdir, <anno>Path</anno>}</c>
and <c>{i, Path}</c> options are guaranteed to be
absolute.</p>
diff --git a/lib/stdlib/doc/src/gb_sets.xml b/lib/stdlib/doc/src/gb_sets.xml
index 60d8bcbfa3..38de51322f 100644
--- a/lib/stdlib/doc/src/gb_sets.xml
+++ b/lib/stdlib/doc/src/gb_sets.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2001</year><year>2010</year>
+ <year>2001</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -114,34 +114,32 @@
</list>
</section>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-gb_set() = a GB set</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name><marker id="type-gb_set">gb_set()</marker></name>
+ <desc><p>A GB set.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="iter"/>
+ <desc><p>A GB set iterator.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>add(Element, Set1) -> Set2</name>
- <name>add_element(Element, Set1) -> Set2</name>
+ <name name="add" arity="2"/>
+ <name name="add_element" arity="2"/>
<fsummary>Add a (possibly existing) element to a gb_set</fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Returns a new gb_set formed from <c>Set1</c> with
- <c>Element</c> inserted. If <c>Element</c> is already an
- element in <c>Set1</c>, nothing is changed.</p>
+ <p>Returns a new gb_set formed from <c><anno>Set1</anno></c> with
+ <c><anno>Element</anno></c> inserted. If <c><anno>Element</anno></c> is already an
+ element in <c><anno>Set1</anno></c>, nothing is changed.</p>
</desc>
</func>
<func>
- <name>balance(Set1) -> Set2</name>
+ <name name="balance" arity="1"/>
<fsummary>Rebalance tree representation of a gb_set</fsummary>
- <type>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Rebalances the tree representation of <c>Set1</c>. Note that
+ <p>Rebalances the tree representation of <c><anno>Set1</anno></c>. Note that
this is rarely necessary, but may be motivated when a large
number of elements have been deleted from the tree without
further insertions. Rebalancing could then be forced in order
@@ -150,208 +148,144 @@ gb_set() = a GB set</code>
</desc>
</func>
<func>
- <name>delete(Element, Set1) -> Set2</name>
+ <name name="delete" arity="2"/>
<fsummary>Remove an element from a gb_set</fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Returns a new gb_set formed from <c>Set1</c> with
- <c>Element</c> removed. Assumes that <c>Element</c> is present
- in <c>Set1</c>.</p>
+ <p>Returns a new gb_set formed from <c><anno>Set1</anno></c> with
+ <c><anno>Element</anno></c> removed. Assumes that <c><anno>Element</anno></c> is present
+ in <c><anno>Set1</anno></c>.</p>
</desc>
</func>
<func>
- <name>delete_any(Element, Set1) -> Set2</name>
- <name>del_element(Element, Set1) -> Set2</name>
+ <name name="delete_any" arity="2"/>
+ <name name="del_element" arity="2"/>
<fsummary>Remove a (possibly non-existing) element from a gb_set</fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Returns a new gb_set formed from <c>Set1</c> with
- <c>Element</c> removed. If <c>Element</c> is not an element
- in <c>Set1</c>, nothing is changed.</p>
+ <p>Returns a new gb_set formed from <c><anno>Set1</anno></c> with
+ <c><anno>Element</anno></c> removed. If <c><anno>Element</anno></c> is not an element
+ in <c><anno>Set1</anno></c>, nothing is changed.</p>
</desc>
</func>
<func>
- <name>difference(Set1, Set2) -> Set3</name>
- <name>subtract(Set1, Set2) -> Set3</name>
+ <name name="difference" arity="2"/>
+ <name name="subtract" arity="2"/>
<fsummary>Return the difference of two gb_sets</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = gb_set()</v>
- </type>
<desc>
- <p>Returns only the elements of <c>Set1</c> which are not also
- elements of <c>Set2</c>.</p>
+ <p>Returns only the elements of <c><anno>Set1</anno></c> which are not also
+ elements of <c><anno>Set2</anno></c>.</p>
</desc>
</func>
<func>
- <name>empty() -> Set</name>
- <name>new() -> Set</name>
+ <name name="empty" arity="0"/>
+ <name name="new" arity="0"/>
<fsummary>Return an empty gb_set</fsummary>
- <type>
- <v>Set = gb_set()</v>
- </type>
<desc>
<p>Returns a new empty gb_set.</p>
</desc>
</func>
<func>
- <name>filter(Pred, Set1) -> Set2</name>
+ <name name="filter" arity="2"/>
<fsummary>Filter gb_set elements</fsummary>
- <type>
- <v>Pred = fun (E) -> bool()</v>
- <v>&nbsp;E = term()</v>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Filters elements in <c>Set1</c> using predicate function
- <c>Pred</c>.</p>
+ <p>Filters elements in <c><anno>Set1</anno></c> using predicate function
+ <c><anno>Pred</anno></c>.</p>
</desc>
</func>
<func>
- <name>fold(Function, Acc0, Set) -> Acc1</name>
+ <name name="fold" arity="3"/>
<fsummary>Fold over gb_set elements</fsummary>
- <type>
- <v>Function = fun (E, AccIn) -> AccOut</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>&nbsp;E = term()</v>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Folds <c>Function</c> over every element in <c>Set</c>
+ <p>Folds <c><anno>Function</anno></c> over every element in <c><anno>Set</anno></c>
returning the final value of the accumulator.</p>
</desc>
</func>
<func>
- <name>from_list(List) -> Set</name>
+ <name name="from_list" arity="1"/>
<fsummary>Convert a list into a gb_set</fsummary>
- <type>
- <v>List = [term()]</v>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Returns a gb_set of the elements in <c>List</c>, where
- <c>List</c> may be unordered and contain duplicates.</p>
+ <p>Returns a gb_set of the elements in <c><anno>List</anno></c>, where
+ <c><anno>List</anno></c> may be unordered and contain duplicates.</p>
</desc>
</func>
<func>
- <name>from_ordset(List) -> Set</name>
+ <name name="from_ordset" arity="1"/>
<fsummary>Make a gb_set from an ordset list</fsummary>
- <type>
- <v>List = [term()]</v>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Turns an ordered-set list <c>List</c> into a gb_set. The list
+ <p>Turns an ordered-set list <c><anno>List</anno></c> into a gb_set. The list
must not contain duplicates.</p>
</desc>
</func>
<func>
- <name>insert(Element, Set1) -> Set2</name>
+ <name name="insert" arity="2"/>
<fsummary>Add a new element to a gb_set</fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Returns a new gb_set formed from <c>Set1</c> with
- <c>Element</c> inserted. Assumes that <c>Element</c> is not
- present in <c>Set1</c>.</p>
+ <p>Returns a new gb_set formed from <c><anno>Set1</anno></c> with
+ <c><anno>Element</anno></c> inserted. Assumes that <c><anno>Element</anno></c> is not
+ present in <c><anno>Set1</anno></c>.</p>
</desc>
</func>
<func>
- <name>intersection(Set1, Set2) -> Set3</name>
+ <name name="intersection" arity="2"/>
<fsummary>Return the intersection of two gb_sets</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = gb_set()</v>
- </type>
<desc>
- <p>Returns the intersection of <c>Set1</c> and <c>Set2</c>.</p>
+ <p>Returns the intersection of <c><anno>Set1</anno></c> and <c><anno>Set2</anno></c>.</p>
</desc>
</func>
<func>
- <name>intersection(SetList) -> Set</name>
+ <name name="intersection" arity="1"/>
<fsummary>Return the intersection of a list of gb_sets</fsummary>
- <type>
- <v>SetList = [gb_set()]</v>
- <v>Set = gb_set()</v>
- </type>
<desc>
<p>Returns the intersection of the non-empty list of gb_sets.</p>
</desc>
</func>
<func>
- <name>is_disjoint(Set1, Set2) -> bool()</name>
+ <name name="is_disjoint" arity="2"/>
<fsummary>Check whether two gb_sets are disjoint</fsummary>
- <type>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Set1</c> and
- <c>Set2</c> are disjoint (have no elements in common),
+ <p>Returns <c>true</c> if <c><anno>Set1</anno></c> and
+ <c><anno>Set2</anno></c> are disjoint (have no elements in common),
and <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_empty(Set) -> bool()</name>
+ <name name="is_empty" arity="1"/>
<fsummary>Test for empty gb_set</fsummary>
- <type>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Set</c> is an empty set, and
+ <p>Returns <c>true</c> if <c><anno>Set</anno></c> is an empty set, and
<c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_member(Element, Set) -> bool()</name>
- <name>is_element(Element, Set) -> bool()</name>
+ <name name="is_member" arity="2"/>
+ <name name="is_element" arity="2"/>
<fsummary>Test for membership of a gb_set</fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Element</c> is an element of
- <c>Set</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>Element</anno></c> is an element of
+ <c><anno>Set</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>is_set(Term) -> bool()</name>
+ <name name="is_set" arity="1"/>
<fsummary>Test for a gb_set</fsummary>
- <type>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Set</c> appears to be a gb_set,
+ <p>Returns <c>true</c> if <c><anno>Term</anno></c> appears to be a gb_set,
otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>is_subset(Set1, Set2) -> bool()</name>
+ <name name="is_subset" arity="2"/>
<fsummary>Test for subset</fsummary>
- <type>
- <v>Set1 = Set2 = gb_set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> when every element of <c>Set1</c> is
- also a member of <c>Set2</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> when every element of <c><anno>Set1</anno></c> is
+ also a member of <c><anno>Set2</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>iterator(Set) -> Iter</name>
+ <name name="iterator" arity="1"/>
<fsummary>Return an iterator for a gb_set</fsummary>
- <type>
- <v>Set = gb_set()</v>
- <v>Iter = term()</v>
- </type>
<desc>
<p>Returns an iterator that can be used for traversing the
- entries of <c>Set</c>; see <c>next/1</c>. The implementation
+ entries of <c><anno>Set</anno></c>; see <c>next/1</c>. The implementation
of this is very efficient; traversing the whole set using
<c>next/1</c> is only slightly slower than getting the list
of all elements using <c>to_list/1</c> and traversing that.
@@ -361,118 +295,84 @@ gb_set() = a GB set</code>
</desc>
</func>
<func>
- <name>largest(Set) -> term()</name>
+ <name name="largest" arity="1"/>
<fsummary>Return largest element</fsummary>
- <type>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Returns the largest element in <c>Set</c>. Assumes that
- <c>Set</c> is nonempty.</p>
+ <p>Returns the largest element in <c><anno>Set</anno></c>. Assumes that
+ <c><anno>Set</anno></c> is nonempty.</p>
</desc>
</func>
<func>
- <name>next(Iter1) -> {Element, Iter2} | none</name>
+ <name name="next" arity="1"/>
<fsummary>Traverse a gb_set with an iterator</fsummary>
- <type>
- <v>Iter1 = Iter2 = Element = term()</v>
- </type>
<desc>
- <p>Returns <c>{Element, Iter2}</c> where <c>Element</c> is the
- smallest element referred to by the iterator <c>Iter1</c>,
- and <c>Iter2</c> is the new iterator to be used for
+ <p>Returns <c>{<anno>Element</anno>, <anno>Iter2</anno>}</c> where <c><anno>Element</anno></c> is the
+ smallest element referred to by the iterator <c><anno>Iter1</anno></c>,
+ and <c><anno>Iter2</anno></c> is the new iterator to be used for
traversing the remaining elements, or the atom <c>none</c> if
no elements remain.</p>
</desc>
</func>
<func>
- <name>singleton(Element) -> gb_set()</name>
+ <name name="singleton" arity="1"/>
<fsummary>Return a gb_set with one element</fsummary>
- <type>
- <v>Element = term()</v>
- </type>
<desc>
- <p>Returns a gb_set containing only the element <c>Element</c>.</p>
+ <p>Returns a gb_set containing only the element <c><anno>Element</anno></c>.</p>
</desc>
</func>
<func>
- <name>size(Set) -> int()</name>
+ <name name="size" arity="1"/>
<fsummary>Return the number of elements in a gb_set</fsummary>
- <type>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Returns the number of elements in <c>Set</c>.</p>
+ <p>Returns the number of elements in <c><anno>Set</anno></c>.</p>
</desc>
</func>
<func>
- <name>smallest(Set) -> term()</name>
+ <name name="smallest" arity="1"/>
<fsummary>Return smallest element</fsummary>
- <type>
- <v>Set = gb_set()</v>
- </type>
<desc>
- <p>Returns the smallest element in <c>Set</c>. Assumes that
- <c>Set</c> is nonempty.</p>
+ <p>Returns the smallest element in <c><anno>Set</anno></c>. Assumes that
+ <c><anno>Set</anno></c> is nonempty.</p>
</desc>
</func>
<func>
- <name>take_largest(Set1) -> {Element, Set2}</name>
+ <name name="take_largest" arity="1"/>
<fsummary>Extract largest element</fsummary>
- <type>
- <v>Set1 = Set2 = gb_set()</v>
- <v>Element = term()</v>
- </type>
<desc>
- <p>Returns <c>{Element, Set2}</c>, where <c>Element</c> is the
- largest element in <c>Set1</c>, and <c>Set2</c> is this set
- with <c>Element</c> deleted. Assumes that <c>Set1</c> is
+ <p>Returns <c>{<anno>Element</anno>, <anno>Set2</anno>}</c>, where <c><anno>Element</anno></c> is the
+ largest element in <c><anno>Set1</anno></c>, and <c><anno>Set2</anno></c> is this set
+ with <c><anno>Element</anno></c> deleted. Assumes that <c><anno>Set1</anno></c> is
nonempty.</p>
</desc>
</func>
<func>
- <name>take_smallest(Set1) -> {Element, Set2}</name>
+ <name name="take_smallest" arity="1"/>
<fsummary>Extract smallest element</fsummary>
- <type>
- <v>Set1 = Set2 = gb_set()</v>
- <v>Element = term()</v>
- </type>
<desc>
- <p>Returns <c>{Element, Set2}</c>, where <c>Element</c> is the
- smallest element in <c>Set1</c>, and <c>Set2</c> is this set
- with <c>Element</c> deleted. Assumes that <c>Set1</c> is
+ <p>Returns <c>{<anno>Element</anno>, <anno>Set2</anno>}</c>, where <c><anno>Element</anno></c> is the
+ smallest element in <c><anno>Set1</anno></c>, and <c><anno>Set2</anno></c> is this set
+ with <c><anno>Element</anno></c> deleted. Assumes that <c><anno>Set1</anno></c> is
nonempty.</p>
</desc>
</func>
<func>
- <name>to_list(Set) -> List</name>
+ <name name="to_list" arity="1"/>
<fsummary>Convert a gb_set into a list</fsummary>
- <type>
- <v>Set = gb_set()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns the elements of <c>Set</c> as a list.</p>
+ <p>Returns the elements of <c><anno>Set</anno></c> as a list.</p>
</desc>
</func>
<func>
- <name>union(Set1, Set2) -> Set3</name>
+ <name name="union" arity="2"/>
<fsummary>Return the union of two gb_sets</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = gb_set()</v>
- </type>
<desc>
- <p>Returns the merged (union) gb_set of <c>Set1</c> and
- <c>Set2</c>.</p>
+ <p>Returns the merged (union) gb_set of <c><anno>Set1</anno></c> and
+ <c><anno>Set2</anno></c>.</p>
</desc>
</func>
<func>
- <name>union(SetList) -> Set</name>
+ <name name="union" arity="1"/>
<fsummary>Return the union of a list of gb_sets</fsummary>
- <type>
- <v>SetList = [gb_set()]</v>
- <v>Set = gb_set()</v>
- </type>
<desc>
<p>Returns the merged (union) gb_set of the list of gb_sets.</p>
</desc>
diff --git a/lib/stdlib/doc/src/gb_trees.xml b/lib/stdlib/doc/src/gb_trees.xml
index 94f40c28bd..65c866efbe 100644
--- a/lib/stdlib/doc/src/gb_trees.xml
+++ b/lib/stdlib/doc/src/gb_trees.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2001</year><year>2010</year>
+ <year>2001</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -57,20 +57,22 @@
trees. Behaviour is logarithmic (as it should be).</p>
</section>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-gb_tree() = a GB tree</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name><marker id="type-gb_tree">gb_tree()</marker></name>
+ <desc><p>A GB tree.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="iter"/>
+ <desc><p>A GB tree iterator.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>balance(Tree1) -> Tree2</name>
+ <name name="balance" arity="1"/>
<fsummary>Rebalance a tree</fsummary>
- <type>
- <v>Tree1 = Tree2 = gb_tree()</v>
- </type>
<desc>
- <p>Rebalances <c>Tree1</c>. Note that this is rarely necessary,
+ <p>Rebalances <c><anno>Tree1</anno></c>. Note that this is rarely necessary,
but may be motivated when a large number of nodes have been
deleted from the tree without further insertions. Rebalancing
could then be forced in order to minimise lookup times, since
@@ -78,139 +80,97 @@ gb_tree() = a GB tree</code>
</desc>
</func>
<func>
- <name>delete(Key, Tree1) -> Tree2</name>
+ <name name="delete" arity="2"/>
<fsummary>Remove a node from a tree</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Tree1 = Tree2 = gb_tree()</v>
- </type>
<desc>
- <p>Removes the node with key <c>Key</c> from <c>Tree1</c>;
+ <p>Removes the node with key <c><anno>Key</anno></c> from <c><anno>Tree1</anno></c>;
returns new tree. Assumes that the key is present in the tree,
crashes otherwise.</p>
</desc>
</func>
<func>
- <name>delete_any(Key, Tree1) -> Tree2</name>
+ <name name="delete_any" arity="2"/>
<fsummary>Remove a (possibly non-existing) node from a tree</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Tree1 = Tree2 = gb_tree()</v>
- </type>
<desc>
- <p>Removes the node with key <c>Key</c> from <c>Tree1</c> if
+ <p>Removes the node with key <c><anno>Key</anno></c> from <c><anno>Tree1</anno></c> if
the key is present in the tree, otherwise does nothing;
returns new tree.</p>
</desc>
</func>
<func>
- <name>empty() -> Tree</name>
+ <name name="empty" arity="0"/>
<fsummary>Return an empty tree</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- </type>
<desc>
<p>Returns a new empty tree</p>
</desc>
</func>
<func>
- <name>enter(Key, Val, Tree1) -> Tree2</name>
+ <name name="enter" arity="3"/>
<fsummary>Insert or update key with value in a tree</fsummary>
- <type>
- <v>Key = Val = term()</v>
- <v>Tree1 = Tree2 = gb_tree()</v>
- </type>
<desc>
- <p>Inserts <c>Key</c> with value <c>Val</c> into <c>Tree1</c> if
+ <p>Inserts <c><anno>Key</anno></c> with value <c><anno>Val</anno></c> into <c><anno>Tree1</anno></c> if
the key is not present in the tree, otherwise updates
- <c>Key</c> to value <c>Val</c> in <c>Tree1</c>. Returns the
+ <c><anno>Key</anno></c> to value <c><anno>Val</anno></c> in <c><anno>Tree1</anno></c>. Returns the
new tree.</p>
</desc>
</func>
<func>
- <name>from_orddict(List) -> Tree</name>
+ <name name="from_orddict" arity="1"/>
<fsummary>Make a tree from an orddict</fsummary>
- <type>
- <v>List = [{Key, Val}]</v>
- <v>&nbsp;Key = Val = term()</v>
- <v>Tree = gb_tree()</v>
- </type>
<desc>
- <p>Turns an ordered list <c>List</c> of key-value tuples into a
+ <p>Turns an ordered list <c><anno>List</anno></c> of key-value tuples into a
tree. The list must not contain duplicate keys.</p>
</desc>
</func>
<func>
- <name>get(Key, Tree) -> Val</name>
+ <name name="get" arity="2"/>
<fsummary>Look up a key in a tree, if present</fsummary>
- <type>
- <v>Key = Val = term()</v>
- <v>Tree = gb_tree()</v>
- </type>
<desc>
- <p>Retrieves the value stored with <c>Key</c> in <c>Tree</c>.
+ <p>Retrieves the value stored with <c><anno>Key</anno></c> in <c><anno>Tree</anno></c>.
Assumes that the key is present in the tree, crashes
otherwise.</p>
</desc>
</func>
<func>
- <name>lookup(Key, Tree) -> {value, Val} | none</name>
+ <name name="lookup" arity="2"/>
<fsummary>Look up a key in a tree</fsummary>
- <type>
- <v>Key = Val = term()</v>
- <v>Tree = gb_tree()</v>
- </type>
<desc>
- <p>Looks up <c>Key</c> in <c>Tree</c>; returns
- <c>{value, Val}</c>, or <c>none</c> if <c>Key</c> is not
+ <p>Looks up <c><anno>Key</anno></c> in <c><anno>Tree</anno></c>; returns
+ <c>{value, <anno>Val</anno>}</c>, or <c>none</c> if <c><anno>Key</anno></c> is not
present.</p>
</desc>
</func>
<func>
- <name>insert(Key, Val, Tree1) -> Tree2</name>
+ <name name="insert" arity="3"/>
<fsummary>Insert a new key and value in a tree</fsummary>
- <type>
- <v>Key = Val = term()</v>
- <v>Tree1 = Tree2 = gb_tree()</v>
- </type>
<desc>
- <p>Inserts <c>Key</c> with value <c>Val</c> into <c>Tree1</c>;
+ <p>Inserts <c><anno>Key</anno></c> with value <c><anno>Val</anno></c> into <c><anno>Tree1</anno></c>;
returns the new tree. Assumes that the key is not present in
the tree, crashes otherwise.</p>
</desc>
</func>
<func>
- <name>is_defined(Key, Tree) -> bool()</name>
+ <name name="is_defined" arity="2"/>
<fsummary>Test for membership of a tree</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Key</c> is present in <c>Tree</c>,
+ <p>Returns <c>true</c> if <c><anno>Key</anno></c> is present in <c><anno>Tree</anno></c>,
otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>is_empty(Tree) -> bool()</name>
+ <name name="is_empty" arity="1"/>
<fsummary>Test for empty tree</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Tree</c> is an empty tree, and
+ <p>Returns <c>true</c> if <c><anno>Tree</anno></c> is an empty tree, and
<c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>iterator(Tree) -> Iter</name>
+ <name name="iterator" arity="1"/>
<fsummary>Return an iterator for a tree</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- <v>Iter = term()</v>
- </type>
<desc>
<p>Returns an iterator that can be used for traversing the
- entries of <c>Tree</c>; see <c>next/1</c>. The implementation
+ entries of <c><anno>Tree</anno></c>; see <c>next/1</c>. The implementation
of this is very efficient; traversing the whole tree using
<c>next/1</c> is only slightly slower than getting the list
of all elements using <c>to_list/1</c> and traversing that.
@@ -220,141 +180,99 @@ gb_tree() = a GB tree</code>
</desc>
</func>
<func>
- <name>keys(Tree) -> [Key]</name>
+ <name name="keys" arity="1"/>
<fsummary>Return a list of the keys in a tree</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- <v>Key = term()</v>
- </type>
<desc>
- <p>Returns the keys in <c>Tree</c> as an ordered list.</p>
+ <p>Returns the keys in <c><anno>Tree</anno></c> as an ordered list.</p>
</desc>
</func>
<func>
- <name>largest(Tree) -> {Key, Val}</name>
+ <name name="largest" arity="1"/>
<fsummary>Return largest key and value</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- <v>Key = Val = term()</v>
- </type>
<desc>
- <p>Returns <c>{Key, Val}</c>, where <c>Key</c> is the largest
- key in <c>Tree</c>, and <c>Val</c> is the value associated
+ <p>Returns <c>{<anno>Key</anno>, <anno>Val</anno>}</c>, where <c><anno>Key</anno></c> is the largest
+ key in <c><anno>Tree</anno></c>, and <c><anno>Val</anno></c> is the value associated
with this key. Assumes that the tree is nonempty.</p>
</desc>
</func>
<func>
- <name>map(Function, Tree1) -> Tree2</name>
+ <name name="map" arity="2"/>
<fsummary>Return largest key and value</fsummary>
- <type>
- <v>Function = fun(K, V1) -> V2</v>
- <v>Tree1 = Tree2 = gb_tree()</v>
- </type>
- <desc><p>maps the function F(K, V1) -> V2 to all key-value pairs
- of the tree Tree1 and returns a new tree Tree2 with the same set of keys
- as Tree1 and the new set of values V2.</p>
+ <desc><p>Maps the function F(<anno>K</anno>, <anno>V1</anno>) -> <anno>V2</anno> to all key-value pairs
+ of the tree <c><anno>Tree1</anno></c> and returns a new tree <c><anno>Tree2</anno></c> with the same set of keys
+ as <c><anno>Tree1</anno></c> and the new set of values <c><anno>V2</anno></c>.</p>
</desc>
</func>
<func>
- <name>next(Iter1) -> {Key, Val, Iter2} | none</name>
+ <name name="next" arity="1"/>
<fsummary>Traverse a tree with an iterator</fsummary>
- <type>
- <v>Iter1 = Iter2 = Key = Val = term()</v>
- </type>
<desc>
- <p>Returns <c>{Key, Val, Iter2}</c> where <c>Key</c> is the
- smallest key referred to by the iterator <c>Iter1</c>, and
- <c>Iter2</c> is the new iterator to be used for
+ <p>Returns <c>{<anno>Key</anno>, <anno>Val</anno>, <anno>Iter2</anno>}</c> where <c><anno>Key</anno></c> is the
+ smallest key referred to by the iterator <c><anno>Iter1</anno></c>, and
+ <c><anno>Iter2</anno></c> is the new iterator to be used for
traversing the remaining nodes, or the atom <c>none</c> if no
nodes remain.</p>
</desc>
</func>
<func>
- <name>size(Tree) -> int()</name>
+ <name name="size" arity="1"/>
<fsummary>Return the number of nodes in a tree</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- </type>
<desc>
- <p>Returns the number of nodes in <c>Tree</c>.</p>
+ <p>Returns the number of nodes in <c><anno>Tree</anno></c>.</p>
</desc>
</func>
<func>
- <name>smallest(Tree) -> {Key, Val}</name>
+ <name name="smallest" arity="1"/>
<fsummary>Return smallest key and value</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- <v>Key = Val = term()</v>
- </type>
<desc>
- <p>Returns <c>{Key, Val}</c>, where <c>Key</c> is the smallest
- key in <c>Tree</c>, and <c>Val</c> is the value associated
+ <p>Returns <c>{<anno>Key</anno>, <anno>Val</anno>}</c>, where <c><anno>Key</anno></c> is the smallest
+ key in <c><anno>Tree</anno></c>, and <c><anno>Val</anno></c> is the value associated
with this key. Assumes that the tree is nonempty.</p>
</desc>
</func>
<func>
- <name>take_largest(Tree1) -> {Key, Val, Tree2}</name>
+ <name name="take_largest" arity="1"/>
<fsummary>Extract largest key and value</fsummary>
- <type>
- <v>Tree1 = Tree2 = gb_tree()</v>
- <v>Key = Val = term()</v>
- </type>
<desc>
- <p>Returns <c>{Key, Val, Tree2}</c>, where <c>Key</c> is the
- largest key in <c>Tree1</c>, <c>Val</c> is the value
- associated with this key, and <c>Tree2</c> is this tree with
+ <p>Returns <c>{<anno>Key</anno>, <anno>Val</anno>, <anno>Tree2</anno>}</c>, where <c><anno>Key</anno></c> is the
+ largest key in <c><anno>Tree1</anno></c>, <c><anno>Val</anno></c> is the value
+ associated with this key, and <c><anno>Tree2</anno></c> is this tree with
the corresponding node deleted. Assumes that the tree is
nonempty.</p>
</desc>
</func>
<func>
- <name>take_smallest(Tree1) -> {Key, Val, Tree2}</name>
+ <name name="take_smallest" arity="1"/>
<fsummary>Extract smallest key and value</fsummary>
- <type>
- <v>Tree1 = Tree2 = gb_tree()</v>
- <v>Key = Val = term()</v>
- </type>
<desc>
- <p>Returns <c>{Key, Val, Tree2}</c>, where <c>Key</c> is the
- smallest key in <c>Tree1</c>, <c>Val</c> is the value
- associated with this key, and <c>Tree2</c> is this tree with
+ <p>Returns <c>{<anno>Key</anno>, <anno>Val</anno>, <anno>Tree2</anno>}</c>, where <c><anno>Key</anno></c> is the
+ smallest key in <c><anno>Tree1</anno></c>, <c><anno>Val</anno></c> is the value
+ associated with this key, and <c><anno>Tree2</anno></c> is this tree with
the corresponding node deleted. Assumes that the tree is
nonempty.</p>
</desc>
</func>
<func>
- <name>to_list(Tree) -> [{Key, Val}]</name>
+ <name name="to_list" arity="1"/>
<fsummary>Convert a tree into a list</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- <v>Key = Val = term()</v>
- </type>
<desc>
<p>Converts a tree into an ordered list of key-value tuples.</p>
</desc>
</func>
<func>
- <name>update(Key, Val, Tree1) -> Tree2</name>
+ <name name="update" arity="3"/>
<fsummary>Update a key to new value in a tree</fsummary>
- <type>
- <v>Key = Val = term()</v>
- <v>Tree1 = Tree2 = gb_tree()</v>
- </type>
<desc>
- <p>Updates <c>Key</c> to value <c>Val</c> in <c>Tree1</c>;
+ <p>Updates <c><anno>Key</anno></c> to value <c><anno>Val</anno></c> in <c><anno>Tree1</anno></c>;
returns the new tree. Assumes that the key is present in the
tree.</p>
</desc>
</func>
<func>
- <name>values(Tree) -> [Val]</name>
+ <name name="values" arity="1"/>
<fsummary>Return a list of the values in a tree</fsummary>
- <type>
- <v>Tree = gb_tree()</v>
- <v>Val = term()</v>
- </type>
<desc>
- <p>Returns the values in <c>Tree</c> as an ordered list, sorted
+ <p>Returns the values in <c><anno>Tree</anno></c> as an ordered list, sorted
by their corresponding keys. Duplicates are not removed.</p>
</desc>
</func>
diff --git a/lib/stdlib/doc/src/gen_event.xml b/lib/stdlib/doc/src/gen_event.xml
index 2234a62ac3..24bcb419fe 100644
--- a/lib/stdlib/doc/src/gen_event.xml
+++ b/lib/stdlib/doc/src/gen_event.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -100,6 +100,20 @@ gen_event:stop -----> Module:terminate/2
the specified event manager does not exist or if bad arguments are
given.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="handler"/>
+ </datatype>
+ <datatype>
+ <name name="handler_args"/>
+ </datatype>
+ <datatype>
+ <name name="add_handler_ret"/>
+ </datatype>
+ <datatype>
+ <name name="del_handler_ret"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
<name>start_link() -> Result</name>
diff --git a/lib/stdlib/doc/src/io.xml b/lib/stdlib/doc/src/io.xml
index 41e3e92c59..af9c75d546 100644
--- a/lib/stdlib/doc/src/io.xml
+++ b/lib/stdlib/doc/src/io.xml
@@ -43,7 +43,7 @@
<p>As of R13A, data supplied to the <seealso
marker="#put_chars/2">put_chars</seealso> function should be in the
- <c>chardata()</c> format described below. This means that programs
+ <seealso marker="unicode#type-chardata"><c>unicode:chardata()</c></seealso> format. This means that programs
supplying binaries to this function need to convert them to UTF-8
before trying to output the data on an
<c>io_device()</c>.</p>
@@ -64,76 +64,84 @@
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-io_device()
- as returned by file:open/2, a process handling IO protocols</code>
-
- <code type="none">
-unicode_binary() = binary() with characters encoded in UTF-8 coding standard
-unicode_char() = integer() representing valid unicode codepoint
-
-chardata() = charlist() | unicode_binary()
+ <datatypes>
+ <datatype>
+ <name name="device"/>
+ <desc>
+ <p>Either <c>standard_io</c>, <c>standard_error</c>, a
+ registered name, or a pid handling IO protocols (returned from
+ <seealso marker="file#open/2">file:open/2</seealso>).</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="opt_pair"/>
+ </datatype>
+ <datatype>
+ <name name="expand_fun"/>
+ </datatype>
+ <datatype>
+ <name name="encoding"/>
+ </datatype>
+ <datatype>
+ <name name="setopt"/>
+ </datatype>
+ <datatype>
+ <name name="format"/>
+ </datatype>
+ <datatype>
+ <name name="line"/>
+ </datatype>
+ <datatype>
+ <name name="prompt"/>
+ </datatype>
+ <datatype>
+ <name name="request_error"/>
+ </datatype>
+ <datatype>
+ <name name="error_description"/>
+ <desc><p>Whatever the I/O-server sends.</p></desc>
+ </datatype>
+ </datatypes>
-charlist() = [unicode_char() | unicode_binary() | charlist()]
- a unicode_binary is allowed as the tail of the list</code>
- </section>
<funcs>
<func>
- <name>columns() -> {ok,int()} | {error, enotsup}</name>
- <name>columns(IoDevice) -> {ok,int()} | {error, enotsup}</name>
+ <name name="columns" arity="0"/>
+ <name name="columns" arity="1"/>
<fsummary>Get the number of columns of a device</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- </type>
<desc>
<p>Retrieves the number of columns of the
- <c>IoDevice</c> (i.e. the width of a terminal). The function
+ <c><anno>IoDevice</anno></c> (i.e. the width of a terminal). The function
only succeeds for terminal devices, for all other devices
the function returns <c>{error, enotsup}</c></p>
</desc>
</func>
<func>
- <name>put_chars(IoData) -> ok</name>
- <name>put_chars(IoDevice, IoData) -> ok</name>
+ <name name="put_chars" arity="1"/>
+ <name name="put_chars" arity="2"/>
<fsummary>Write a list of characters</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>IoData = chardata()</v>
- </type>
<desc>
- <p>Writes the characters of <c>IoData</c> to the io_server()
- (<c>IoDevice</c>).</p>
+ <p>Writes the characters of <c><anno>CharData</anno></c> to the io_server()
+ (<c><anno>IoDevice</anno></c>).</p>
</desc>
</func>
<func>
- <name>nl() -> ok</name>
- <name>nl(IoDevice) -> ok</name>
+ <name name="nl" arity="0"/>
+ <name name="nl" arity="1"/>
<fsummary>Write a newline</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- </type>
<desc>
- <p>Writes new line to the standard output (<c>IoDevice</c>).</p>
+ <p>Writes new line to the standard output (<c><anno>IoDevice</anno></c>).</p>
</desc>
</func>
<func>
- <name>get_chars(Prompt, Count) -> Data | eof</name>
- <name>get_chars(IoDevice, Prompt, Count) -> Data | eof</name>
+ <name name="get_chars" arity="2"/>
+ <name name="get_chars" arity="3"/>
<fsummary>Read a specified number of characters</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>Count = int()</v>
- <v>Data = [ unicode_char() ] | unicode_binary()</v>
- </type>
<desc>
- <p>Reads <c>Count</c> characters from standard input
- (<c>IoDevice</c>), prompting it with <c>Prompt</c>. It
+ <p>Reads <c><anno>Count</anno></c> characters from standard input
+ (<c><anno>IoDevice</anno></c>), prompting it with <c><anno>Prompt</anno></c>. It
returns:</p>
<taglist>
- <tag><c>Data</c></tag>
+ <tag><c><anno>Data</anno></c></tag>
<item>
<p>The input characters. If the device supports Unicode,
the data may represent codepoints larger than 255 (the
@@ -145,7 +153,7 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error,Reason}</c></tag>
+ <tag><c>{error,<anno>Reason</anno>}</c></tag>
<item>
<p>Other (rare) error condition, for instance <c>{error,estale}</c>
if reading from an NFS file system.</p>
@@ -154,19 +162,14 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
</desc>
</func>
<func>
- <name>get_line(Prompt) -> Data | eof | {error,Reason}</name>
- <name>get_line(IoDevice, Prompt) -> Data | eof | {error,Reason}</name>
+ <name name="get_line" arity="1"/>
+ <name name="get_line" arity="2"/>
<fsummary>Read a line</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>Data = [ unicode_char() ] | unicode_binary()</v>
- </type>
<desc>
- <p>Reads a line from the standard input (<c>IoDevice</c>),
- prompting it with <c>Prompt</c>. It returns:</p>
+ <p>Reads a line from the standard input (<c><anno>IoDevice</anno></c>),
+ prompting it with <c><anno>Prompt</anno></c>. It returns:</p>
<taglist>
- <tag><c>Data</c></tag>
+ <tag><c><anno>Data</anno></c></tag>
<item>
<p>The characters in the line terminated by a LF (or end of
file). If the device supports Unicode,
@@ -179,7 +182,7 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error,Reason}</c></tag>
+ <tag><c>{error,<anno>Reason</anno>}</c></tag>
<item>
<p>Other (rare) error condition, for instance <c>{error,estale}</c>
if reading from an NFS file system.</p>
@@ -188,15 +191,9 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
</desc>
</func>
<func>
- <name>getopts() -> Opts</name>
- <name>getopts(IoDevice) -> Opts</name>
+ <name name="getopts" arity="0"/>
+ <name name="getopts" arity="1"/>
<fsummary>Get the supported options and values from an I/O-server</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Opts = [Opt]</v>
- <v>&nbsp;&nbsp;Opt = {atom(),Value}</v>
- <v>&nbsp;&nbsp;Value = term()</v>
- </type>
<desc>
<p>This function requests all available options and their current values for a specific io_device(). Example:</p>
<pre>
@@ -216,18 +213,11 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
</desc>
</func>
<func>
- <name>setopts(Opts) -> ok | {error, Reason}</name>
- <name>setopts(IoDevice, Opts) -> ok | {error, Reason}</name>
+ <name name="setopts" arity="1"/>
+ <name name="setopts" arity="2"/>
<fsummary>Set options</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Opts = [Opt]</v>
- <v>&nbsp;&nbsp;Opt = atom() | {atom(),Value}</v>
- <v>&nbsp;&nbsp;Value = term()</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>Set options for the io_device() (<c>IoDevice</c>).</p>
+ <p>Set options for the io_device() (<c><anno>IoDevice</anno></c>).</p>
<p>Possible options and values vary depending on the actual
io_device(). For a list of supported options and their current values
@@ -236,17 +226,17 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
<p>The options and values supported by the current OTP io_devices are:</p>
<taglist>
- <tag><c>binary, list or {binary, bool()}</c></tag>
+ <tag><c>binary, list or {binary, boolean()}</c></tag>
<item>
<p>If set in binary mode (binary or {binary,true}), the io_server() sends binary data (encoded in UTF-8) as answers to the get_line, get_chars and, if possible, get_until requests (see the I/O protocol description in STDLIB User's Guide for details). The immediate effect is that <c>get_chars/2,3</c> and <c>get_line/1,2</c> return UTF-8 binaries instead of lists of chars for the affected device.</p>
<p>By default, all io_devices in OTP are set in list mode, but the io functions can handle any of these modes and so should other, user written, modules behaving as clients to I/O-servers.</p>
<p>This option is supported by the standard shell (group.erl), the 'oldshell' (user.erl) and the file I/O servers.</p>
</item>
- <tag><c>{echo, bool()}</c></tag>
+ <tag><c>{echo, boolean()}</c></tag>
<item>
<p>Denotes if the terminal should echo input. Only supported for the standard shell I/O-server (group.erl)</p>
</item>
- <tag><c>{expand_fun, fun()}</c></tag>
+ <tag><c>{expand_fun, expand_fun()}</c></tag>
<item>
<p>Provide a function for tab-completion (expansion)
like the erlang shell. This function is called
@@ -288,35 +278,24 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
</desc>
</func>
<func>
- <name>write(Term) -> ok</name>
- <name>write(IoDevice, Term) -> ok</name>
+ <name name="write" arity="1"/>
+ <name name="write" arity="2"/>
<fsummary>Write a term</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Writes the term <c>Term</c> to the standard output
- (<c>IoDevice</c>).</p>
+ <p>Writes the term <c><anno>Term</anno></c> to the standard output
+ (<c><anno>IoDevice</anno></c>).</p>
</desc>
</func>
<func>
- <name>read(Prompt) -> Result</name>
- <name>read(IoDevice, Prompt) -> Result</name>
+ <name name="read" arity="1"/>
+ <name name="read" arity="2"/>
<fsummary>Read a term</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>Result = {ok, Term} | eof | {error, ErrorInfo}</v>
- <v>&nbsp;Term = term()</v>
- <v>&nbsp;ErrorInfo -- see section Error Information below</v>
- </type>
<desc>
- <p>Reads a term <c>Term</c> from the standard input
- (<c>IoDevice</c>), prompting it with <c>Prompt</c>. It
+ <p>Reads a term <c><anno>Term</anno></c> from the standard input
+ (<c><anno>IoDevice</anno></c>), prompting it with <c><anno>Prompt</anno></c>. It
returns:</p>
<taglist>
- <tag><c>{ok, Term}</c></tag>
+ <tag><c>{ok, <anno>Term</anno>}</c></tag>
<item>
<p>The parsing was successful.</p>
</item>
@@ -324,7 +303,7 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error, ErrorInfo}</c></tag>
+ <tag><c>{error, <anno>ErrorInfo</anno>}</c></tag>
<item>
<p>The parsing failed.</p>
</item>
@@ -332,31 +311,22 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
</desc>
</func>
<func>
- <name>read(IoDevice, Prompt, StartLine) -> Result</name>
+ <name name="read" arity="3"/>
<fsummary>Read a term</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>StartLine = int()</v>
- <v>Result = {ok, Term, EndLine} | {eof, EndLine} | {error, ErrorInfo, EndLine}</v>
- <v>&nbsp;Term = term()</v>
- <v>&nbsp;EndLine = int()</v>
- <v>&nbsp;ErrorInfo -- see section Error Information below</v>
- </type>
<desc>
- <p>Reads a term <c>Term</c> from <c>IoDevice</c>, prompting it
- with <c>Prompt</c>. Reading starts at line number
- <c>StartLine</c>. It returns:</p>
+ <p>Reads a term <c><anno>Term</anno></c> from <c><anno>IoDevice</anno></c>, prompting it
+ with <c><anno>Prompt</anno></c>. Reading starts at line number
+ <c><anno>StartLine</anno></c>. It returns:</p>
<taglist>
- <tag><c>{ok, Term, EndLine}</c></tag>
+ <tag><c>{ok, Term, <anno>EndLine</anno>}</c></tag>
<item>
<p>The parsing was successful.</p>
</item>
- <tag><c>{eof, EndLine}</c></tag>
+ <tag><c>{eof, <anno>EndLine</anno>}</c></tag>
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error, ErrorInfo, EndLine}</c></tag>
+ <tag><c>{error, <anno>ErrorInfo</anno>, <anno>ErrorLine</anno>}</c></tag>
<item>
<p>The parsing failed.</p>
</item>
@@ -364,24 +334,19 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
</desc>
</func>
<func>
- <name>fwrite(Format) -></name>
- <name>fwrite(Format, Data) -> ok</name>
- <name>fwrite(IoDevice, Format, Data) -> ok</name>
- <name>format(Format) -></name>
- <name>format(Format, Data) -> ok</name>
- <name>format(IoDevice, Format, Data) -> ok</name>
+ <name name="fwrite" arity="1"/>
+ <name name="fwrite" arity="2"/>
+ <name name="fwrite" arity="3"/>
+ <name name="format" arity="1"/>
+ <name name="format" arity="2"/>
+ <name name="format" arity="3"/>
<fsummary>Write formatted output</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Format = atom() | string() | binary()</v>
- <v>Data = [term()]</v>
- </type>
<desc>
- <p>Writes the items in <c>Data</c> (<c>[]</c>) on the standard
- output (<c>IoDevice</c>) in accordance with <c>Format</c>.
- <c>Format</c> contains plain characters which are copied to
+ <p>Writes the items in <c><anno>Data</anno></c> (<c>[]</c>) on the standard
+ output (<c><anno>IoDevice</anno></c>) in accordance with <c><anno>Format</anno></c>.
+ <c><anno>Format</anno></c> contains plain characters which are copied to
the output device, and control sequences for formatting, see
- below. If <c>Format</c> is an atom or a binary, it is first
+ below. If <c><anno>Format</anno></c> is an atom or a binary, it is first
converted to a list with the aid of <c>atom_to_list/1</c>
or <c>binary_to_list/1</c>.</p>
<pre>
@@ -474,7 +439,7 @@ ok</pre>
<item>
<p>Prints the argument with the <c>string</c> syntax. The
argument is, if no Unicode translation modifier is present, an
- <seealso marker="erts:erlang#iolist_definition">I/O list</seealso>, a binary, or an atom. If the Unicode translation modifier ('t') is in effect, the argument is chardata(), meaning that binaries are in UTF-8. The characters
+ <seealso marker="erts:erlang#iolist_definition">I/O list</seealso>, a binary, or an atom. If the Unicode translation modifier ('t') is in effect, the argument is unicode:chardata(), meaning that binaries are in UTF-8. The characters
are printed without quotes. The string is first truncated
by the given precision and then padded and justified
to the given field width. The default precision is the field width.</p>
@@ -673,23 +638,15 @@ ok
</desc>
</func>
<func>
- <name>fread(Prompt, Format) -> Result</name>
- <name>fread(IoDevice, Prompt, Format) -> Result</name>
+ <name name="fread" arity="2"/>
+ <name name="fread" arity="3"/>
<fsummary>Read formatted input</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>Format = string()</v>
- <v>Result = {ok, Terms} | eof | {error, What}</v>
- <v>&nbsp;Terms = [term()]</v>
- <v>&nbsp;What = term()</v>
- </type>
<desc>
- <p>Reads characters from the standard input (<c>IoDevice</c>),
- prompting it with <c>Prompt</c>. Interprets the characters in
- accordance with <c>Format</c>. <c>Format</c> contains control
+ <p>Reads characters from the standard input (<c><anno>IoDevice</anno></c>),
+ prompting it with <c><anno>Prompt</anno></c>. Interprets the characters in
+ accordance with <c><anno>Format</anno></c>. <c><anno>Format</anno></c> contains control
sequences which directs the interpretation of the input.</p>
- <p><c>Format</c> may contain:</p>
+ <p><c><anno>Format</anno></c> may contain:</p>
<list type="bulleted">
<item>
<p>White space characters (SPACE, TAB and NEWLINE) which
@@ -803,19 +760,19 @@ Prompt> <input>&lt;Character beyond latin1 range not printable in this medium&gt
</taglist>
<p>It returns:</p>
<taglist>
- <tag><c>{ok, Terms}</c></tag>
+ <tag><c>{ok, <anno>Terms</anno>}</c></tag>
<item>
- <p>The read was successful and <c>Terms</c> is the list
+ <p>The read was successful and <c><anno>Terms</anno></c> is the list
of successfully matched and read items.</p>
</item>
<tag><c>eof</c></tag>
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error, What}</c></tag>
+ <tag><c>{error, <anno>What</anno>}</c></tag>
<item>
<p>The read operation failed and the parameter
- <c>What</c> gives a hint about the error.</p>
+ <c><anno>What</anno></c> gives a hint about the error.</p>
</item>
</taglist>
</item>
@@ -834,33 +791,21 @@ enter><input>:</input> <input>alan</input> <input>:</input> <input>joe</in
</desc>
</func>
<func>
- <name>rows() -> {ok,int()} | {error, enotsup}</name>
- <name>rows(IoDevice) -> {ok,int()} | {error, enotsup}</name>
+ <name name="rows" arity="0"/>
+ <name name="rows" arity="1"/>
<fsummary>Get the number of rows of a device</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- </type>
<desc>
<p>Retrieves the number of rows of the
- <c>IoDevice</c> (i.e. the height of a terminal). The function
+ <c><anno>IoDevice</anno></c> (i.e. the height of a terminal). The function
only succeeds for terminal devices, for all other devices
the function returns <c>{error, enotsup}</c></p>
</desc>
</func>
<func>
- <name>scan_erl_exprs(Prompt) -></name>
- <name>scan_erl_exprs(Prompt, StartLine) -> Result</name>
- <name>scan_erl_exprs(IoDevice, Prompt, StartLine) -> Result</name>
+ <name name="scan_erl_exprs" arity="1"/>
+ <name name="scan_erl_exprs" arity="2"/>
+ <name name="scan_erl_exprs" arity="3"/>
<fsummary>Read and tokenize Erlang expressions</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>StartLine = int()</v>
- <v>Result = {ok, Tokens, EndLine} | {eof, EndLine} | {error, ErrorInfo, EndLine}</v>
- <v>&nbsp;Tokens -- see erl_scan(3)</v>
- <v>&nbsp;EndLine = int()</v>
- <v>&nbsp;ErrorInfo -- see section Error Information below</v>
- </type>
<desc>
<p>Reads data from the standard input (<c>IoDevice</c>),
prompting it with <c>Prompt</c>. Reading starts at line number
@@ -876,7 +821,7 @@ enter><input>:</input> <input>alan</input> <input>:</input> <input>joe</in
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error, ErrorInfo, EndLine}</c></tag>
+ <tag><c>{error, ErrorInfo, ErrorLine}</c></tag>
<item>
<p>An error occurred.</p>
</item>
@@ -892,23 +837,14 @@ enter><input>1.0er.</input>
</desc>
</func>
<func>
- <name>scan_erl_form(Prompt) -></name>
- <name>scan_erl_form(Prompt, StartLine) -> Result</name>
- <name>scan_erl_form(IoDevice, Prompt, StartLine) -> Result</name>
+ <name name="scan_erl_form" arity="1"/>
+ <name name="scan_erl_form" arity="2"/>
+ <name name="scan_erl_form" arity="3"/>
<fsummary>Read and tokenize an Erlang form</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>StartLine = int()</v>
- <v>Result = {ok, Tokens, EndLine} | {eof, EndLine} | {error, ErrorInfo, EndLine}</v>
- <v>&nbsp;Tokens -- see erl_scan(3)</v>
- <v>&nbsp;EndLine = int()</v>
- <v>&nbsp;ErrorInfo -- see section Error Information below</v>
- </type>
<desc>
- <p>Reads data from the standard input (<c>IoDevice</c>),
- prompting it with <c>Prompt</c>. Starts reading at line number
- <c>StartLine</c> (1). The data is tokenized as if it were an
+ <p>Reads data from the standard input (<c><anno>IoDevice</anno></c>),
+ prompting it with <c><anno>Prompt</anno></c>. Starts reading at line number
+ <c><anno>StartLine</anno></c> (1). The data is tokenized as if it were an
Erlang form - one of the valid Erlang expressions in an
Erlang source file - until a final <c>'.'</c> is reached.
This last token is also returned. The return values are the
@@ -916,27 +852,19 @@ enter><input>1.0er.</input>
</desc>
</func>
<func>
- <name>parse_erl_exprs(Prompt) -></name>
- <name>parse_erl_exprs(Prompt, StartLine) -> Result</name>
- <name>parse_erl_exprs(IoDevice, Prompt, StartLine) -> Result</name>
+ <name name="parse_erl_exprs" arity="1"/>
+ <name name="parse_erl_exprs" arity="2"/>
+ <name name="parse_erl_exprs" arity="3"/>
+ <type name="parse_ret"/>
<fsummary>Read, tokenize and parse Erlang expressions</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>StartLine = int()</v>
- <v>Result = {ok, Expr_list, EndLine} | {eof, EndLine} | {error, ErrorInfo, EndLine}</v>
- <v>&nbsp;Expr_list -- see erl_parse(3)</v>
- <v>&nbsp;EndLine = int()</v>
- <v>&nbsp;ErrorInfo -- see section Error Information below</v>
- </type>
<desc>
- <p>Reads data from the standard input (<c>IoDevice</c>),
- prompting it with <c>Prompt</c>. Starts reading at line number
- <c>StartLine</c> (1). The data is tokenized and parsed as if
+ <p>Reads data from the standard input (<c><anno>IoDevice</anno></c>),
+ prompting it with <c><anno>Prompt</anno></c>. Starts reading at line number
+ <c><anno>StartLine</anno></c> (1). The data is tokenized and parsed as if
it were a sequence of Erlang expressions until a final '.' is
reached. It returns:</p>
<taglist>
- <tag><c>{ok, Expr_list, EndLine}</c></tag>
+ <tag><c>{ok, ExprList, EndLine}</c></tag>
<item>
<p>The parsing was successful.</p>
</item>
@@ -944,7 +872,7 @@ enter><input>1.0er.</input>
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error, ErrorInfo, EndLine}</c></tag>
+ <tag><c>{error, ErrorInfo, ErrorLine}</c></tag>
<item>
<p>An error occurred.</p>
</item>
@@ -960,23 +888,15 @@ enter><input>abc("hey".</input>
</desc>
</func>
<func>
- <name>parse_erl_form(Prompt) -></name>
- <name>parse_erl_form(Prompt, StartLine) -> Result</name>
- <name>parse_erl_form(IoDevice, Prompt, StartLine) -> Result</name>
+ <name name="parse_erl_form" arity="1"/>
+ <name name="parse_erl_form" arity="2"/>
+ <name name="parse_erl_form" arity="3"/>
+ <type name="parse_form_ret"/>
<fsummary>Read, tokenize and parse an Erlang form</fsummary>
- <type>
- <v>IoDevice = io_device()</v>
- <v>Prompt = atom() | string()</v>
- <v>StartLine = int()</v>
- <v>Result = {ok, AbsForm, EndLine} | {eof, EndLine} | {error, ErrorInfo, EndLine}</v>
- <v>&nbsp;AbsForm -- see erl_parse(3)</v>
- <v>&nbsp;EndLine = int()</v>
- <v>&nbsp;ErrorInfo -- see section Error Information below</v>
- </type>
<desc>
- <p>Reads data from the standard input (<c>IoDevice</c>),
- prompting it with <c>Prompt</c>. Starts reading at line number
- <c>StartLine</c> (1). The data is tokenized and parsed as if
+ <p>Reads data from the standard input (<c><anno>IoDevice</anno></c>),
+ prompting it with <c><anno>Prompt</anno></c>. Starts reading at line number
+ <c><anno>StartLine</anno></c> (1). The data is tokenized and parsed as if
it were an Erlang form - one of the valid Erlang expressions
in an Erlang source file - until a final '.' is reached. It
returns:</p>
@@ -989,7 +909,7 @@ enter><input>abc("hey".</input>
<item>
<p>End of file was encountered.</p>
</item>
- <tag><c>{error, ErrorInfo, EndLine}</c></tag>
+ <tag><c>{error, ErrorInfo, ErrorLine}</c></tag>
<item>
<p>An error occurred.</p>
</item>
diff --git a/lib/stdlib/doc/src/io_lib.xml b/lib/stdlib/doc/src/io_lib.xml
index 399f968c5f..506c1792f1 100644
--- a/lib/stdlib/doc/src/io_lib.xml
+++ b/lib/stdlib/doc/src/io_lib.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -38,14 +38,22 @@
flattening deep lists.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-chars() = [char() | chars()]</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name name="chars"/>
+ </datatype>
+ <datatype>
+ <name name="continuation"/>
+ <desc><p>A continuation as returned by <seealso marker="#fread/3"><c>fread/3</c></seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="depth"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>nl() -> chars()</name>
+ <name name="nl" arity="0"/>
<fsummary>Write a newline</fsummary>
<desc>
<p>Returns a character list which represents a new line
@@ -53,16 +61,12 @@ chars() = [char() | chars()]</code>
</desc>
</func>
<func>
- <name>write(Term) -></name>
- <name>write(Term, Depth) -> chars()</name>
+ <name name="write" arity="1"/>
+ <name name="write" arity="2"/>
<fsummary>Write a term</fsummary>
- <type>
- <v>Term = term()</v>
- <v>Depth = int()</v>
- </type>
<desc>
- <p>Returns a character list which represents <c>Term</c>. The
- <c>Depth</c> (-1) argument controls the depth of the
+ <p>Returns a character list which represents <c><anno>Term</anno></c>. The
+ <c><anno>Depth</anno></c> (-1) argument controls the depth of the
structures written. When the specified depth is reached,
everything below this level is replaced by "...". For
example:</p>
@@ -74,36 +78,26 @@ chars() = [char() | chars()]</code>
</desc>
</func>
<func>
- <name>print(Term) -></name>
- <name>print(Term, Column, LineLength, Depth) -> chars()</name>
+ <name name="print" arity="1"/>
+ <name name="print" arity="4"/>
<fsummary>Pretty print a term</fsummary>
- <type>
- <v>Term = term()</v>
- <v>Column = LineLenght = Depth = int()</v>
- </type>
<desc>
<p>Also returns a list of characters which represents
- <c>Term</c>, but breaks representations which are longer than
+ <c><anno>Term</anno></c>, but breaks representations which are longer than
one line into many lines and indents each line sensibly. It
also tries to detect and output lists of printable characters
- as strings. <c>Column</c> is the starting column (1),
- <c>LineLength</c> the maximum line length (80), and
- <c>Depth</c> (-1) the maximum print depth.</p>
+ as strings. <c><anno>Column</anno></c> is the starting column (1),
+ <c><anno>LineLength</anno></c> the maximum line length (80), and
+ <c><anno>Depth</anno></c> (-1) the maximum print depth.</p>
</desc>
</func>
<func>
- <name>fwrite(Format, Data) -></name>
- <name>format(Format, Data) -> chars() | UnicodeList</name>
+ <name name="fwrite" arity="2"/>
+ <name name="format" arity="2"/>
<fsummary>Write formatted output</fsummary>
- <type>
- <v>Format = atom() | string() | binary()</v>
- <v>Data = [term()]</v>
- <v>UnicodeList = [Unicode]</v>
- <v>Unicode = int() representing valid unicode codepoint</v>
- </type>
<desc>
- <p>Returns a character list which represents <c>Data</c>
- formatted in accordance with <c>Format</c>. See
+ <p>Returns a character list which represents <c><anno>Data</anno></c>
+ formatted in accordance with <c><anno>Format</anno></c>. See
<seealso marker="io#fwrite/1">io:fwrite/1,2,3</seealso> for a detailed
description of the available formatting options. A fault is
generated if there is an error in the format string or
@@ -119,42 +113,32 @@ chars() = [char() | chars()]</code>
</desc>
</func>
<func>
- <name>fread(Format, String) -> Result</name>
+ <name name="fread" arity="2"/>
<fsummary>Read formatted input</fsummary>
- <type>
- <v>Format = String = string()</v>
- <v>Result = {ok, InputList, LeftOverChars} | {more, RestFormat, Nchars, InputStack} | {error, What}</v>
- <v>&nbsp;InputList = chars()</v>
- <v>&nbsp;LeftOverChars = string()</v>
- <v>&nbsp;RestFormat = string()</v>
- <v>&nbsp;Nchars = int()</v>
- <v>&nbsp;InputStack = chars()</v>
- <v>&nbsp;What = term()</v>
- </type>
<desc>
- <p>Tries to read <c>String</c> in accordance with the control
- sequences in <c>Format</c>. See
+ <p>Tries to read <c><anno>String</anno></c> in accordance with the control
+ sequences in <c><anno>Format</anno></c>. See
<seealso marker="io#fread/3">io:fread/3</seealso> for a detailed
description of the available formatting options. It is
- assumed that <c>String</c> contains whole lines. It returns:</p>
+ assumed that <c><anno>String</anno></c> contains whole lines. It returns:</p>
<taglist>
- <tag><c>{ok, InputList, LeftOverChars}</c></tag>
+ <tag><c>{ok, <anno>InputList</anno>, <anno>LeftOverChars</anno>}</c></tag>
<item>
- <p>The string was read. <c>InputList</c> is the list of
+ <p>The string was read. <c><anno>InputList</anno></c> is the list of
successfully matched and read items, and
- <c>LeftOverChars</c> are the input characters not used.</p>
+ <c><anno>LeftOverChars</anno></c> are the input characters not used.</p>
</item>
- <tag><c>{more, RestFormat, Nchars, InputStack}</c></tag>
+ <tag><c>{more, <anno>RestFormat</anno>, <anno>Nchars</anno>, <anno>InputStack</anno>}</c></tag>
<item>
<p>The string was read, but more input is needed in order
- to complete the original format string. <c>RestFormat</c>
- is the remaining format string, <c>NChars</c> the number
- of characters scanned, and <c>InputStack</c> is the
+ to complete the original format string. <c><anno>RestFormat</anno></c>
+ is the remaining format string, <c><anno>Nchars</anno></c> the number
+ of characters scanned, and <c><anno>InputStack</anno></c> is the
reversed list of inputs matched up to that point.</p>
</item>
- <tag><c>{error, What}</c></tag>
+ <tag><c>{error, <anno>What</anno>}</c></tag>
<item>
- <p>The read operation failed and the parameter <c>What</c>
+ <p>The read operation failed and the parameter <c><anno>What</anno></c>
gives a hint about the error.</p>
</item>
</taglist>
@@ -165,17 +149,8 @@ chars() = [char() | chars()]</code>
</desc>
</func>
<func>
- <name>fread(Continuation, String, Format) -> Return</name>
+ <name name="fread" arity="3"/>
<fsummary>Re-entrant formatted reader</fsummary>
- <type>
- <v>Continuation = see below</v>
- <v>String = Format = string()</v>
- <v>Return = {done, Result, LeftOverChars} | {more, Continuation}</v>
- <v>&nbsp;Result = {ok, InputList} | eof | {error, What}</v>
- <v>&nbsp;&nbsp;InputList = chars()</v>
- <v>&nbsp;&nbsp;What = term()()</v>
- <v>&nbsp;LeftOverChars = string()</v>
- </type>
<desc>
<p>This is the re-entrant formatted reader. The continuation of
the first call to the functions must be <c>[]</c>. Refer to
@@ -184,114 +159,92 @@ chars() = [char() | chars()]</code>
re-entrant input scheme works.</p>
<p>The function returns:</p>
<taglist>
- <tag><c>{done, Result, LeftOverChars}</c></tag>
+ <tag><c>{done, <anno>Result</anno>, <anno>LeftOverChars</anno>}</c></tag>
<item>
<p>The input is complete. The result is one of the
following:</p>
<taglist>
- <tag><c>{ok, InputList}</c></tag>
+ <tag><c>{ok, <anno>InputList</anno>}</c></tag>
<item>
- <p>The string was read. <c>InputList</c> is the list of
+ <p>The string was read. <c><anno>InputList</anno></c> is the list of
successfully matched and read items, and
- <c>LeftOverChars</c> are the remaining characters.</p>
+ <c><anno>LeftOverChars</anno></c> are the remaining characters.</p>
</item>
<tag><c>eof</c></tag>
<item>
<p>End of file has been encountered.
- <c>LeftOverChars</c> are the input characters not
+ <c><anno>LeftOverChars</anno></c> are the input characters not
used.</p>
</item>
- <tag><c>{error, What}</c></tag>
+ <tag><c>{error, <anno>What</anno>}</c></tag>
<item>
- <p>An error occurred and the parameter <c>What</c> gives
+ <p>An error occurred and the parameter <c><anno>What</anno></c> gives
a hint about the error.</p>
</item>
</taglist>
</item>
- <tag><c>{more, Continuation}</c></tag>
+ <tag><c>{more, <anno>Continuation</anno>}</c></tag>
<item>
<p>More data is required to build a term.
- <c>Continuation</c> must be passed to <c>fread/3</c>,
+ <c><anno>Continuation</anno></c> must be passed to <c>fread/3</c>,
when more data becomes available.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>write_atom(Atom) -> chars()</name>
+ <name name="write_atom" arity="1"/>
<fsummary>Write an atom</fsummary>
- <type>
- <v>Atom = atom()</v>
- </type>
<desc>
<p>Returns the list of characters needed to print the atom
- <c>Atom</c>.</p>
+ <c><anno>Atom</anno></c>.</p>
</desc>
</func>
<func>
- <name>write_string(String) -> chars()</name>
+ <name name="write_string" arity="1"/>
<fsummary>Write a string</fsummary>
- <type>
- <v>String = string()</v>
- </type>
<desc>
- <p>Returns the list of characters needed to print <c>String</c>
+ <p>Returns the list of characters needed to print <c><anno>String</anno></c>
as a string.</p>
</desc>
</func>
<func>
- <name>write_char(Integer) -> chars()</name>
+ <name name="write_char" arity="1"/>
<fsummary>Write a character</fsummary>
- <type>
- <v>Integer = int()</v>
- </type>
<desc>
<p>Returns the list of characters needed to print a character
constant in the ISO-latin-1 character set.</p>
</desc>
</func>
<func>
- <name>indentation(String, StartIndent) -> int()</name>
+ <name name="indentation" arity="2"/>
<fsummary>Indentation after printing string</fsummary>
- <type>
- <v>String = string()</v>
- <v>StartIndent = int()</v>
- </type>
<desc>
- <p>Returns the indentation if <c>String</c> has been printed,
- starting at <c>StartIndent</c>.</p>
+ <p>Returns the indentation if <c><anno>String</anno></c> has been printed,
+ starting at <c><anno>StartIndent</anno></c>.</p>
</desc>
</func>
<func>
- <name>char_list(Term) -> bool()</name>
+ <name name="char_list" arity="1"/>
<fsummary>Test for a list of characters</fsummary>
- <type>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Term</c> is a flat list of
+ <p>Returns <c>true</c> if <c><anno>Term</anno></c> is a flat list of
characters in the ISO-latin-1 range, otherwise it returns <c>false</c>.</p>
</desc>
</func>
<func>
- <name>deep_char_list(Term) -> bool()</name>
+ <name name="deep_char_list" arity="1"/>
<fsummary>Test for a deep list of characters</fsummary>
- <type>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Term</c> is a, possibly deep, list
+ <p>Returns <c>true</c> if <c><anno>Term</anno></c> is a, possibly deep, list
of characters in the ISO-latin-1 range, otherwise it returns <c>false</c>.</p>
</desc>
</func>
<func>
- <name>printable_list(Term) -> bool()</name>
+ <name name="printable_list" arity="1"/>
<fsummary>Test for a list of printable ISO-latin-1 characters</fsummary>
- <type>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Term</c> is a flat list of
+ <p>Returns <c>true</c> if <c><anno>Term</anno></c> is a flat list of
printable ISO-latin-1 characters, otherwise it returns <c>false</c>.</p>
</desc>
</func>
diff --git a/lib/stdlib/doc/src/lib.xml b/lib/stdlib/doc/src/lib.xml
index 046add48e8..19fb827cbf 100644
--- a/lib/stdlib/doc/src/lib.xml
+++ b/lib/stdlib/doc/src/lib.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -37,27 +37,23 @@
</description>
<funcs>
<func>
- <name>flush_receive() -> void()</name>
+ <name name="flush_receive" arity="0"/>
<fsummary>Flush messages</fsummary>
<desc>
<p>Flushes the message buffer of the current process.</p>
</desc>
</func>
<func>
- <name>error_message(Format, Args) -> ok</name>
+ <name name="error_message" arity="2"/>
<fsummary>Print error message</fsummary>
- <type>
- <v>Format = atom() | string() | binary()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
- <p>Prints error message <c>Args</c> in accordance with
- <c>Format</c>. Similar to <c>io:format/2</c>, see
+ <p>Prints error message <c><anno>Args</anno></c> in accordance with
+ <c><anno>Format</anno></c>. Similar to <c>io:format/2</c>, see
<seealso marker="io#fwrite/1">io(3)</seealso>.</p>
</desc>
</func>
<func>
- <name>progname() -> atom()</name>
+ <name name="progname" arity="0"/>
<fsummary>Return name of Erlang start script</fsummary>
<desc>
<p>Returns the name of the script that started the current
@@ -65,37 +61,24 @@
</desc>
</func>
<func>
- <name>nonl(String1) -> String2</name>
+ <name name="nonl" arity="1"/>
<fsummary>Remove last newline</fsummary>
- <type>
- <v>String1 = String2 = string()</v>
- </type>
<desc>
<p>Removes the last newline character, if any, in
- <c>String1</c>.</p>
+ <c><anno>String1</anno></c>.</p>
</desc>
</func>
<func>
- <name>send(To, Msg)</name>
+ <name name="send" arity="2"/>
<fsummary>Send a message</fsummary>
- <type>
- <v>To = pid() | Name | {Name,Node}</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>Msg = term()</v>
- </type>
<desc>
<p>This function to makes it possible to send a message using
the <c>apply/3</c> BIF.</p>
</desc>
</func>
<func>
- <name>sendw(To, Msg)</name>
+ <name name="sendw" arity="2"/>
<fsummary>Send a message and wait for an answer</fsummary>
- <type>
- <v>To = pid() | Name | {Name,Node}</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>Msg = term()</v>
- </type>
<desc>
<p>As <c>send/2</c>, but waits for an answer. It is implemented
as follows:</p>
diff --git a/lib/stdlib/doc/src/lists.xml b/lib/stdlib/doc/src/lists.xml
index 92c4eb4f4c..6f3ed7af98 100644
--- a/lib/stdlib/doc/src/lists.xml
+++ b/lib/stdlib/doc/src/lists.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -60,58 +60,41 @@
</description>
<funcs>
<func>
- <name>all(Pred, List) -> bool()</name>
+ <name name="all" arity="2"/>
<fsummary>Return true if all elements in the list satisfy<c>Pred</c></fsummary>
- <type>
- <v>Pred = fun(Elem) -> bool()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Pred(Elem)</c> returns
- <c>true</c> for all elements <c>Elem</c> in <c>List</c>,
+ <p>Returns <c>true</c> if <c><anno>Pred</anno>(<anno>Elem</anno>)</c> returns
+ <c>true</c> for all elements <c><anno>Elem</anno></c> in <c><anno>List</anno></c>,
otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>any(Pred, List) -> bool()</name>
+ <name name="any" arity="2"/>
<fsummary>Return true if any of the elements in the list satisfies<c>Pred</c></fsummary>
- <type>
- <v>Pred = fun(Elem) -> bool()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Pred(Elem)</c> returns
- <c>true</c> for at least one element <c>Elem</c> in
- <c>List</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>Pred</anno>(<anno>Elem</anno>)</c> returns
+ <c>true</c> for at least one element <c><anno>Elem</anno></c> in
+ <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>append(ListOfLists) -> List1</name>
+ <name name="append" arity="1"/>
<fsummary>Append a list of lists</fsummary>
- <type>
- <v>ListOfLists = [List]</v>
- <v>List = List1 = [term()]</v>
- </type>
<desc>
<p>Returns a list in which all the sub-lists of
- <c>ListOfLists</c> have been appended. For example:</p>
+ <c><anno>ListOfLists</anno></c> have been appended. For example:</p>
<pre>
> <input>lists:append([[1, 2, 3], [a, b], [4, 5, 6]]).</input>
[1,2,3,a,b,4,5,6]</pre>
</desc>
</func>
<func>
- <name>append(List1, List2) -> List3</name>
+ <name name="append" arity="2"/>
<fsummary>Append two lists</fsummary>
- <type>
- <v>List1 = List2 = List3 = [term()]</v>
- </type>
<desc>
- <p>Returns a new list <c>List3</c> which is made from
- the elements of <c>List1</c> followed by the elements of
- <c>List2</c>. For example:</p>
+ <p>Returns a new list <c><anno>List3</anno></c> which is made from
+ the elements of <c><anno>List1</anno></c> followed by the elements of
+ <c><anno>List2</anno></c>. For example:</p>
<pre>
> <input>lists:append("abc", "def").</input>
"abcdef"</pre>
@@ -119,15 +102,11 @@
</desc>
</func>
<func>
- <name>concat(Things) -> string()</name>
+ <name name="concat" arity="1"/>
<fsummary>Concatenate a list of atoms</fsummary>
- <type>
- <v>Things = [Thing]</v>
- <v>&nbsp;Thing = atom() | integer() | float() | string()</v>
- </type>
<desc>
<p>Concatenates the text representation of the elements
- of <c>Things</c>. The elements of <c>Things</c> can be atoms,
+ of <c><anno>Things</anno></c>. The elements of <c><anno>Things</anno></c> can be atoms,
integers, floats or strings.</p>
<pre>
> <input>lists:concat([doc, '/', file, '.', 3]).</input>
@@ -135,87 +114,59 @@
</desc>
</func>
<func>
- <name>delete(Elem, List1) -> List2</name>
+ <name name="delete" arity="2"/>
<fsummary>Delete an element from a list</fsummary>
- <type>
- <v>Elem = term()</v>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
- <p>Returns a copy of <c>List1</c> where the first element
- matching <c>Elem</c> is deleted, if there is such an
+ <p>Returns a copy of <c><anno>List1</anno></c> where the first element
+ matching <c><anno>Elem</anno></c> is deleted, if there is such an
element.</p>
</desc>
</func>
<func>
- <name>dropwhile(Pred, List1) -> List2</name>
+ <name name="dropwhile" arity="2"/>
<fsummary>Drop elements from a list while a predicate is true</fsummary>
- <type>
- <v>Pred = fun(Elem) -> bool()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
- <p>Drops elements <c>Elem</c> from <c>List1</c> while
- <c>Pred(Elem)</c> returns <c>true</c> and returns
+ <p>Drops elements <c><anno>Elem</anno></c> from <c><anno>List1</anno></c> while
+ <c><anno>Pred</anno>(<anno>Elem</anno>)</c> returns <c>true</c> and returns
the remaining list.</p>
</desc>
</func>
<func>
- <name>duplicate(N, Elem) -> List</name>
+ <name name="duplicate" arity="2"/>
<fsummary>Make N copies of element</fsummary>
- <type>
- <v>N = int()</v>
- <v>Elem = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns a list which contains N copies of the term
- <c>Elem</c>. For example:</p>
+ <p>Returns a list which contains <c><anno>N</anno></c> copies of the term
+ <c><anno>Elem</anno></c>. For example:</p>
<pre>
> <input>lists:duplicate(5, xx).</input>
[xx,xx,xx,xx,xx]</pre>
</desc>
</func>
<func>
- <name>filter(Pred, List1) -> List2</name>
+ <name name="filter" arity="2"/>
<fsummary>Choose elements which satisfy a predicate</fsummary>
- <type>
- <v>Pred = fun(Elem) -> bool()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
- <p><c>List2</c> is a list of all elements <c>Elem</c> in
- <c>List1</c> for which <c>Pred(Elem)</c> returns
+ <p><c><anno>List2</anno></c> is a list of all elements <c><anno>Elem</anno></c> in
+ <c><anno>List1</anno></c> for which <c><anno>Pred</anno>(<anno>Elem</anno>)</c> returns
<c>true</c>.</p>
</desc>
</func>
<func>
- <name>flatlength(DeepList) -> int()</name>
+ <name name="flatlength" arity="1"/>
<fsummary>Length of flattened deep list</fsummary>
- <type>
- <v>DeepList = [term() | DeepList]</v>
- </type>
<desc>
- <p>Equivalent to <c>length(flatten(DeepList))</c>, but more
+ <p>Equivalent to <c>length(flatten(<anno>DeepList</anno>))</c>, but more
efficient.</p>
</desc>
</func>
<func>
- <name>flatmap(Fun, List1) -> List2</name>
+ <name name="flatmap" arity="2"/>
<fsummary>Map and flatten in one pass</fsummary>
- <type>
- <v>Fun = fun(A) -> [B]</v>
- <v>List1 = [A]</v>
- <v>List2 = [B]</v>
- <v>&nbsp;A = B = term()</v>
- </type>
<desc>
- <p>Takes a function from <c>A</c>s to lists of <c>B</c>s, and a
- list of <c>A</c>s (<c>List1</c>) and produces a list of
- <c>B</c>s by applying the function to every element in
- <c>List1</c> and appending the resulting lists.</p>
+ <p>Takes a function from <c><anno>A</anno></c>s to lists of <c><anno>B</anno></c>s, and a
+ list of <c><anno>A</anno></c>s (<c><anno>List1</anno></c>) and produces a list of
+ <c><anno>B</anno></c>s by applying the function to every element in
+ <c><anno>List1</anno></c> and appending the resulting lists.</p>
<p>That is, <c>flatmap</c> behaves as if it had been defined as
follows:</p>
<code type="none">
@@ -228,43 +179,29 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>flatten(DeepList) -> List</name>
+ <name name="flatten" arity="1"/>
<fsummary>Flatten a deep list</fsummary>
- <type>
- <v>DeepList = [term() | DeepList]</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns a flattened version of <c>DeepList</c>.</p>
+ <p>Returns a flattened version of <c><anno>DeepList</anno></c>.</p>
</desc>
</func>
<func>
- <name>flatten(DeepList, Tail) -> List</name>
+ <name name="flatten" arity="2"/>
<fsummary>Flatten a deep list</fsummary>
- <type>
- <v>DeepList = [term() | DeepList]</v>
- <v>Tail = List = [term()]</v>
- </type>
<desc>
- <p>Returns a flattened version of <c>DeepList</c> with the tail
- <c>Tail</c> appended.</p>
+ <p>Returns a flattened version of <c><anno>DeepList</anno></c> with the tail
+ <c><anno>Tail</anno></c> appended.</p>
</desc>
</func>
<func>
- <name>foldl(Fun, Acc0, List) -> Acc1</name>
+ <name name="foldl" arity="3"/>
<fsummary>Fold a function over a list</fsummary>
- <type>
- <v>Fun = fun(Elem, AccIn) -> AccOut</v>
- <v>&nbsp;Elem = term()</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Calls <c>Fun(Elem, AccIn)</c> on successive elements <c>A</c>
- of <c>List</c>, starting with <c>AccIn == Acc0</c>.
- <c>Fun/2</c> must return a new accumulator which is passed to
+ <p>Calls <c><anno>Fun</anno>(<anno>Elem</anno>, <anno>AccIn</anno>)</c> on successive elements <c>A</c>
+ of <c><anno>List</anno></c>, starting with <c><anno>AccIn</anno> == <anno>Acc0</anno></c>.
+ <c><anno>Fun</anno>/2</c> must return a new accumulator which is passed to
the next call. The function returns the final value of
- the accumulator. <c>Acc0</c> is returned if the list is empty.
+ the accumulator. <c><anno>Acc0</anno></c> is returned if the list is empty.
For example:</p>
<pre>
> <input>lists:foldl(fun(X, Sum) -> X + Sum end, 0, [1,2,3,4,5]).</input>
@@ -274,14 +211,8 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>foldr(Fun, Acc0, List) -> Acc1</name>
+ <name name="foldr" arity="3"/>
<fsummary>Fold a function over a list</fsummary>
- <type>
- <v>Fun = fun(Elem, AccIn) -> AccOut</v>
- <v>&nbsp;Elem = term()</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Like <c>foldl/3</c>, but the list is traversed from right to
left. For example:</p>
@@ -297,33 +228,23 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>foreach(Fun, List) -> void()</name>
+ <name name="foreach" arity="2"/>
<fsummary>Apply a function to each element of a list</fsummary>
- <type>
- <v>Fun = fun(Elem) -> void()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Calls <c>Fun(Elem)</c> for each element <c>Elem</c> in
- <c>List</c>. This function is used for its side effects and
+ <p>Calls <c><anno>Fun</anno>(<anno>Elem</anno>)</c> for each element <c><anno>Elem</anno></c> in
+ <c><anno>List</anno></c>. This function is used for its side effects and
the evaluation order is defined to be the same as the order
of the elements in the list.</p>
</desc>
</func>
<func>
- <name>keydelete(Key, N, TupleList1) -> TupleList2</name>
+ <name name="keydelete" arity="3"/>
<fsummary>Delete an element from a list of tuples</fsummary>
- <type>
- <v>Key = term()</v>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = [Tuple]</v>
- <v>&nbsp;Tuple = tuple()</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
- <p>Returns a copy of <c>TupleList1</c> where the first
- occurrence of a tuple whose <c>N</c>th element compares equal to
- <c>Key</c> is deleted, if there is such a tuple.</p>
+ <p>Returns a copy of <c><anno>TupleList1</anno></c> where the first
+ occurrence of a tuple whose <c><anno>N</anno></c>th element compares equal to
+ <c><anno>Key</anno></c> is deleted, if there is such a tuple.</p>
</desc>
</func>
<func>
@@ -343,19 +264,14 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>keymap(Fun, N, TupleList1) -> TupleList2</name>
+ <name name="keymap" arity="3"/>
<fsummary>Map a function over a list of tuples</fsummary>
- <type>
- <v>Fun = fun(Term1) -> Term2</v>
- <v>&nbsp;Term1 = Term2 = term()</v>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = [tuple()]</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
<p>Returns a list of tuples where, for each tuple in
- <c>TupleList1</c>, the <c>N</c>th element <c>Term1</c> of the tuple
+ <c><anno>TupleList1</anno></c>, the <c><anno>N</anno></c>th element <c><anno>Term1</anno></c> of the tuple
has been replaced with the result of calling
- <c>Fun(Term1)</c>.</p>
+ <c><anno>Fun</anno>(<anno>Term1</anno>)</c>.</p>
<p>Examples:</p>
<pre>
> <input>Fun = fun(Atom) -> atom_to_list(Atom) end.</input>
@@ -365,7 +281,7 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>keymember(Key, N, TupleList) -> bool()</name>
+ <name>keymember(Key, N, TupleList) -> boolean()</name>
<fsummary>Test for membership of a list of tuples</fsummary>
<type>
<v>Key = term()</v>
@@ -380,37 +296,28 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>keymerge(N, TupleList1, TupleList2) -> TupleList3</name>
+ <name name="keymerge" arity="3"/>
<fsummary>Merge two key-sorted lists of tuples</fsummary>
- <type>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = TupleList3 = [Tuple]</v>
- <v>&nbsp;Tuple = tuple()</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
- <p>Returns the sorted list formed by merging <c>TupleList1</c>
- and <c>TupleList2</c>. The merge is performed on
- the <c>N</c>th element of each tuple. Both <c>TupleList1</c> and
- <c>TupleList2</c> must be key-sorted prior to evaluating this
+ <p>Returns the sorted list formed by merging <c><anno>TupleList1</anno></c>
+ and <c><anno>TupleList2</anno></c>. The merge is performed on
+ the <c><anno>N</anno></c>th element of each tuple. Both <c><anno>TupleList1</anno></c> and
+ <c><anno>TupleList2</anno></c> must be key-sorted prior to evaluating this
function. When two tuples compare equal, the tuple from
- <c>TupleList1</c> is picked before the tuple from
- <c>TupleList2</c>.</p>
+ <c><anno>TupleList1</anno></c> is picked before the tuple from
+ <c><anno>TupleList2</anno></c>.</p>
</desc>
</func>
<func>
- <name>keyreplace(Key, N, TupleList1, NewTuple) -> TupleList2</name>
+ <name name="keyreplace" arity="4"/>
<fsummary>Replace an element in a list of tuples</fsummary>
- <type>
- <v>Key = term()</v>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = [Tuple]</v>
- <v>NewTuple = Tuple = tuple()</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
- <p>Returns a copy of <c>TupleList1</c> where the first
- occurrence of a <c>T</c> tuple whose <c>N</c>th element
- compares equal to <c>Key</c> is replaced with
- <c>NewTuple</c>, if there is such a tuple <c>T</c>.</p>
+ <p>Returns a copy of <c><anno>TupleList1</anno></c> where the first
+ occurrence of a <c>T</c> tuple whose <c><anno>N</anno></c>th element
+ compares equal to <c><anno>Key</anno></c> is replaced with
+ <c><anno>NewTuple</anno></c>, if there is such a tuple <c>T</c>.</p>
</desc>
</func>
<func>
@@ -433,95 +340,63 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>keysort(N, TupleList1) -> TupleList2</name>
+ <name name="keysort" arity="2"/>
<fsummary>Sort a list of tuples</fsummary>
- <type>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = [Tuple]</v>
- <v>&nbsp;Tuple = tuple()</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
<p>Returns a list containing the sorted elements of the list
- <c>TupleList1</c>. Sorting is performed on the <c>N</c>th
+ <c><anno>TupleList1</anno></c>. Sorting is performed on the <c><anno>N</anno></c>th
element of the tuples. The sort is stable.</p>
</desc>
</func>
<func>
- <name>keystore(Key, N, TupleList1, NewTuple) -> TupleList2</name>
+ <name name="keystore" arity="4"/>
<fsummary>Store an element in a list of tuples</fsummary>
- <type>
- <v>Key = term()</v>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = [Tuple]</v>
- <v>NewTuple = Tuple = tuple()</v>
- </type>
- <desc>
- <p>Returns a copy of <c>TupleList1</c> where the first
- occurrence of a tuple <c>T</c> whose <c>N</c>th element
- compares equal to <c>Key</c> is replaced with
- <c>NewTuple</c>, if there is such a tuple <c>T</c>. If there
- is no such tuple <c>T</c> a copy of <c>TupleList1</c> where
- [<c>NewTuple</c>] has been appended to the end is
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
+ <desc>
+ <p>Returns a copy of <c><anno>TupleList1</anno></c> where the first
+ occurrence of a tuple <c>T</c> whose <c><anno>N</anno></c>th element
+ compares equal to <c><anno>Key</anno></c> is replaced with
+ <c><anno>NewTuple</anno></c>, if there is such a tuple <c>T</c>. If there
+ is no such tuple <c>T</c> a copy of <c><anno>TupleList1</anno></c> where
+ [<c><anno>NewTuple</anno></c>] has been appended to the end is
returned.</p>
</desc>
</func>
<func>
- <name>keytake(Key, N, TupleList1) -> {value, Tuple, TupleList2}
- | false</name>
+ <name name="keytake" arity="3"/>
<fsummary>Extract an element from a list of tuples</fsummary>
- <type>
- <v>Key = term()</v>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = [Tuple]</v>
- <v>Tuple = tuple()</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
- <p>Searches the list of tuples <c>TupleList1</c> for a tuple
- whose <c>N</c>th element compares equal to <c>Key</c>.
- Returns <c>{value, Tuple, TupleList2}</c> if such a tuple is
- found, otherwise <c>false</c>. <c>TupleList2</c> is a copy
- of <c>TupleList1</c> where the first occurrence of
- <c>Tuple</c> has been removed.</p>
+ <p>Searches the list of tuples <c><anno>TupleList1</anno></c> for a tuple
+ whose <c><anno>N</anno></c>th element compares equal to <c><anno>Key</anno></c>.
+ Returns <c>{value, <anno>Tuple</anno>, <anno>TupleList2</anno>}</c> if such a tuple is
+ found, otherwise <c>false</c>. <c><anno>TupleList2</anno></c> is a copy
+ of <c><anno>TupleList1</anno></c> where the first occurrence of
+ <c><anno>Tuple</anno></c> has been removed.</p>
</desc>
</func>
<func>
- <name>last(List) -> Last</name>
+ <name name="last" arity="1"/>
<fsummary>Return last element in a list</fsummary>
- <type>
- <v>List = [term()], length(List) > 0</v>
- <v>Last = term()</v>
- </type>
<desc>
- <p>Returns the last element in <c>List</c>.</p>
+ <p>Returns the last element in <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>map(Fun, List1) -> List2</name>
+ <name name="map" arity="2"/>
<fsummary>Map a function over a list</fsummary>
- <type>
- <v>Fun = fun(A) -> B</v>
- <v>List1 = [A]</v>
- <v>List2 = [B]</v>
- <v>&nbsp;A = B = term()</v>
- </type>
<desc>
- <p>Takes a function from <c>A</c>s to <c>B</c>s, and a list of
- <c>A</c>s and produces a list of <c>B</c>s by applying
+ <p>Takes a function from <c><anno>A</anno></c>s to <c><anno>B</anno></c>s, and a list of
+ <c><anno>A</anno></c>s and produces a list of <c><anno>B</anno></c>s by applying
the function to every element in the list. This function is
used to obtain the return values. The evaluation order is
implementation dependent.</p>
</desc>
</func>
<func>
- <name>mapfoldl(Fun, Acc0, List1) -> {List2, Acc1}</name>
+ <name name="mapfoldl" arity="3"/>
<fsummary>Map and fold in one pass</fsummary>
- <type>
- <v>Fun = fun(A, AccIn) -> {B, AccOut}</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>List1 = [A]</v>
- <v>List2 = [B]</v>
- <v>&nbsp;A = B = term()</v>
- </type>
<desc>
<p><c>mapfoldl</c> combines the operations of <c>map/2</c> and
<c>foldl/3</c> into one pass. An example, summing
@@ -533,35 +408,24 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>mapfoldr(Fun, Acc0, List1) -> {List2, Acc1}</name>
+ <name name="mapfoldr" arity="3"/>
<fsummary>Map and fold in one pass</fsummary>
- <type>
- <v>Fun = fun(A, AccIn) -> {B, AccOut}</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>List1 = [A]</v>
- <v>List2 = [B]</v>
- <v>&nbsp;A = B = term()</v>
- </type>
<desc>
<p><c>mapfoldr</c> combines the operations of <c>map/2</c> and
<c>foldr/3</c> into one pass.</p>
</desc>
</func>
<func>
- <name>max(List) -> Max</name>
+ <name name="max" arity="1"/>
<fsummary>Return maximum element of a list</fsummary>
- <type>
- <v>List = [term()], length(List) > 0</v>
- <v>Max = term()</v>
- </type>
<desc>
- <p>Returns the first element of <c>List</c> that compares
+ <p>Returns the first element of <c><anno>List</anno></c> that compares
greater than or equal to all other elements of
- <c>List</c>.</p>
+ <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>member(Elem, List) -> bool()</name>
+ <name>member(Elem, List) -> boolean()</name>
<fsummary>Test for membership of a list</fsummary>
<type>
<v>Elem = term()</v>
@@ -573,112 +437,84 @@ flatmap(Fun, List1) ->
</desc>
</func>
<func>
- <name>merge(ListOfLists) -> List1</name>
+ <name name="merge" arity="1"/>
<fsummary>Merge a list of sorted lists</fsummary>
- <type>
- <v>ListOfLists = [List]</v>
- <v>List = List1 = [term()]</v>
- </type>
<desc>
<p>Returns the sorted list formed by merging all the sub-lists
- of <c>ListOfLists</c>. All sub-lists must be sorted prior to
+ of <c><anno>ListOfLists</anno></c>. All sub-lists must be sorted prior to
evaluating this function. When two elements compare equal,
the element from the sub-list with the lowest position in
- <c>ListOfLists</c> is picked before the other element.</p>
+ <c><anno>ListOfLists</anno></c> is picked before the other element.</p>
</desc>
</func>
<func>
- <name>merge(List1, List2) -> List3</name>
+ <name name="merge" arity="2"/>
<fsummary>Merge two sorted lists</fsummary>
- <type>
- <v>List1 = List2 = List3 = [term()]</v>
- </type>
<desc>
- <p>Returns the sorted list formed by merging <c>List1</c> and
- <c>List2</c>. Both <c>List1</c> and <c>List2</c> must be
+ <p>Returns the sorted list formed by merging <c><anno>List1</anno></c> and
+ <c><anno>List2</anno></c>. Both <c><anno>List1</anno></c> and <c><anno>List2</anno></c> must be
sorted prior to evaluating this function. When two elements
- compare equal, the element from <c>List1</c> is picked
- before the element from <c>List2</c>.</p>
+ compare equal, the element from <c><anno>List1</anno></c> is picked
+ before the element from <c><anno>List2</anno></c>.</p>
</desc>
</func>
<func>
- <name>merge(Fun, List1, List2) -> List3</name>
+ <name name="merge" arity="3"/>
<fsummary>Merge two sorted list</fsummary>
- <type>
- <v>Fun = fun(A, B) -> bool()</v>
- <v>List1 = [A]</v>
- <v>List2 = [B]</v>
- <v>List3 = [A | B]</v>
- <v>&nbsp;A = B = term()</v>
- </type>
<desc>
- <p>Returns the sorted list formed by merging <c>List1</c> and
- <c>List2</c>. Both <c>List1</c> and <c>List2</c> must be
+ <p>Returns the sorted list formed by merging <c><anno>List1</anno></c> and
+ <c><anno>List2</anno></c>. Both <c><anno>List1</anno></c> and <c><anno>List2</anno></c> must be
sorted according to the <seealso
marker="#ordering_function">ordering function</seealso>
- <c>Fun</c> prior to evaluating this function. <c>Fun(A,
- B)</c> should return <c>true</c> if <c>A</c> compares less
- than or equal to <c>B</c> in the ordering, <c>false</c>
+ <c><anno>Fun</anno></c> prior to evaluating this function. <c><anno>Fun</anno>(<anno>A</anno>,
+ <anno>B</anno>)</c> should return <c>true</c> if <c><anno>A</anno></c> compares less
+ than or equal to <c><anno>B</anno></c> in the ordering, <c>false</c>
otherwise. When two elements compare equal, the element from
- <c>List1</c> is picked before the element from
- <c>List2</c>.</p>
+ <c><anno>List1</anno></c> is picked before the element from
+ <c><anno>List2</anno></c>.</p>
</desc>
</func>
<func>
- <name>merge3(List1, List2, List3) -> List4</name>
+ <name name="merge3" arity="3"/>
<fsummary>Merge three sorted lists</fsummary>
- <type>
- <v>List1 = List2 = List3 = List4 = [term()]</v>
- </type>
<desc>
- <p>Returns the sorted list formed by merging <c>List1</c>,
- <c>List2</c> and <c>List3</c>. All of <c>List1</c>,
- <c>List2</c> and <c>List3</c> must be sorted prior to
+ <p>Returns the sorted list formed by merging <c><anno>List1</anno></c>,
+ <c><anno>List2</anno></c> and <c><anno>List3</anno></c>. All of <c><anno>List1</anno></c>,
+ <c><anno>List2</anno></c> and <c><anno>List3</anno></c> must be sorted prior to
evaluating this function. When two elements compare equal,
- the element from <c>List1</c>, if there is such an element,
+ the element from <c><anno>List1</anno></c>, if there is such an element,
is picked before the other element, otherwise the element
- from <c>List2</c> is picked before the element from
- <c>List3</c>.</p>
+ from <c><anno>List2</anno></c> is picked before the element from
+ <c><anno>List3</anno></c>.</p>
</desc>
</func>
<func>
- <name>min(List) -> Min</name>
+ <name name="min" arity="1"/>
<fsummary>Return minimum element of a list</fsummary>
- <type>
- <v>List = [term()], length(List) > 0</v>
- <v>Min = term()</v>
- </type>
<desc>
- <p>Returns the first element of <c>List</c> that compares
+ <p>Returns the first element of <c><anno>List</anno></c> that compares
less than or equal to all other elements of
- <c>List</c>.</p>
+ <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>nth(N, List) -> Elem</name>
+ <name name="nth" arity="2"/>
<fsummary>Return the Nth element of a list</fsummary>
- <type>
- <v>N = 1..length(List)</v>
- <v>List = [term()]</v>
- <v>Elem = term()</v>
- </type>
+ <type_desc variable="N">1..length(List)</type_desc>
<desc>
- <p>Returns the <c>N</c>th element of <c>List</c>. For example:</p>
+ <p>Returns the <c><anno>N</anno></c>th element of <c><anno>List</anno></c>. For example:</p>
<pre>
> <input>lists:nth(3, [a, b, c, d, e]).</input>
c</pre>
</desc>
</func>
<func>
- <name>nthtail(N, List1) -> Tail</name>
+ <name name="nthtail" arity="2"/>
<fsummary>Return the Nth tail of a list</fsummary>
- <type>
- <v>N = 0..length(List1)</v>
- <v>List1 = Tail = [term()]</v>
- </type>
+ <type_desc variable="N">0..length(List)</type_desc>
<desc>
- <p>Returns the <c>N</c>th tail of <c>List</c>, that is, the sublist of
- <c>List</c> starting at <c>N+1</c> and continuing up to
+ <p>Returns the <c><anno>N</anno></c>th tail of <c><anno>List</anno></c>, that is, the sublist of
+ <c><anno>List</anno></c> starting at <c><anno>N</anno>+1</c> and continuing up to
the end of the list. For example:</p>
<pre>
> <input>lists:nthtail(3, [a, b, c, d, e]).</input>
@@ -692,18 +528,13 @@ c</pre>
</desc>
</func>
<func>
- <name>partition(Pred, List) -> {Satisfying, NonSatisfying}</name>
+ <name name="partition" arity="2"/>
<fsummary>Partition a list into two lists based on a predicate</fsummary>
- <type>
- <v>Pred = fun(Elem) -> bool()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List = Satisfying = NonSatisfying = [term()]</v>
- </type>
<desc>
- <p>Partitions <c>List</c> into two lists, where the first list
- contains all elements for which <c>Pred(Elem)</c> returns
+ <p>Partitions <c><anno>List</anno></c> into two lists, where the first list
+ contains all elements for which <c><anno>Pred</anno>(<anno>Elem</anno>)</c> returns
<c>true</c>, and the second list contains all elements for
- which <c>Pred(Elem)</c> returns <c>false</c>.</p>
+ which <c><anno>Pred</anno>(<anno>Elem</anno>)</c> returns <c>false</c>.</p>
<p>Examples:</p>
<pre>
> <input>lists:partition(fun(A) -> A rem 2 == 1 end, [1,2,3,4,5,6,7]).</input>
@@ -715,24 +546,18 @@ c</pre>
</desc>
</func>
<func>
- <name>prefix(List1, List2) -> bool()</name>
+ <name name="prefix" arity="2"/>
<fsummary>Test for list prefix</fsummary>
- <type>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>List1</c> is a prefix of
- <c>List2</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>List1</anno></c> is a prefix of
+ <c><anno>List2</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>reverse(List1) -> List2</name>
+ <name name="reverse" arity="1"/>
<fsummary>Reverse a list</fsummary>
- <type>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
- <p>Returns a list with the top level elements in <c>List1</c>
+ <p>Returns a list with the elements in <c><anno>List1</anno></c>
in reverse order.</p>
</desc>
</func>
@@ -743,7 +568,7 @@ c</pre>
<v>List1 = Tail = List2 = [term()]</v>
</type>
<desc>
- <p>Returns a list with the top level elements in <c>List1</c>
+ <p>Returns a list with the elements in <c>List1</c>
in reverse order, with the tail <c>Tail</c> appended. For
example:</p>
<pre>
@@ -752,22 +577,18 @@ c</pre>
</desc>
</func>
<func>
- <name>seq(From, To) -> Seq</name>
- <name>seq(From, To, Incr) -> Seq</name>
+ <name name="seq" arity="2"/>
+ <name name="seq" arity="3"/>
<fsummary>Generate a sequence of integers</fsummary>
- <type>
- <v>From = To = Incr = int()</v>
- <v>Seq = [int()]</v>
- </type>
<desc>
- <p>Returns a sequence of integers which starts with <c>From</c>
- and contains the successive results of adding <c>Incr</c> to
- the previous element, until <c>To</c> has been reached or
- passed (in the latter case, <c>To</c> is not an element of
- the sequence). <c>Incr</c> defaults to 1.</p>
- <p>Failure: If <c><![CDATA[To<From-Incr]]></c> and <c>Incr</c>
- is positive, or if <c>To>From-Incr</c> and <c>Incr</c> is
- negative, or if <c>Incr==0</c> and <c>From/=To</c>.</p>
+ <p>Returns a sequence of integers which starts with <c><anno>From</anno></c>
+ and contains the successive results of adding <c><anno>Incr</anno></c> to
+ the previous element, until <c><anno>To</anno></c> has been reached or
+ passed (in the latter case, <c><anno>To</anno></c> is not an element of
+ the sequence). <c><anno>Incr</anno></c> defaults to 1.</p>
+ <p>Failure: If <c><anno>To</anno>&lt;<anno>From</anno>-<anno>Incr</anno></c> and <c><anno>Incr</anno></c>
+ is positive, or if <c><anno>To</anno>><anno>From</anno>-<anno>Incr</anno></c> and <c><anno>Incr</anno></c> is
+ negative, or if <c><anno>Incr</anno>==0</c> and <c><anno>From</anno>/=<anno>To</anno></c>.</p>
<p>The following equalities hold for all sequences:</p>
<code type="none">
length(lists:seq(From, To)) == To-From+1
@@ -787,57 +608,41 @@ length(lists:seq(From, To, Incr)) == (To-From+Incr) div Incr</code>
</desc>
</func>
<func>
- <name>sort(List1) -> List2</name>
+ <name name="sort" arity="1"/>
<fsummary>Sort a list</fsummary>
- <type>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
<p>Returns a list containing the sorted elements of
- <c>List1</c>.</p>
+ <c><anno>List1</anno></c>.</p>
</desc>
</func>
<func>
- <name>sort(Fun, List1) -> List2</name>
+ <name name="sort" arity="2"/>
<fsummary>Sort a list</fsummary>
- <type>
- <v>Fun = fun(Elem1, Elem2) -> bool()</v>
- <v>&nbsp;Elem1 = Elem2 = term()</v>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
<p>Returns a list containing the sorted elements of
- <c>List1</c>, according to the <seealso
+ <c><anno>List1</anno></c>, according to the <seealso
marker="#ordering_function">ordering function</seealso>
- <c>Fun</c>. <c>Fun(A, B)</c> should return <c>true</c> if
- <c>A</c> compares less than or equal to <c>B</c> in the
+ <c><anno>Fun</anno></c>. <c><anno>Fun</anno>(<anno>A</anno>, <anno>B</anno>)</c> should return <c>true</c> if
+ <c><anno>A</anno></c> compares less than or equal to <c><anno>B</anno></c> in the
ordering, <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>split(N, List1) -> {List2, List3}</name>
+ <name name="split" arity="2"/>
<fsummary>Split a list into two lists</fsummary>
- <type>
- <v>N = 0..length(List1)</v>
- <v>List1 = List2 = List3 = [term()]</v>
- </type>
+ <type_desc variable="N">0..length(List1)</type_desc>
<desc>
- <p>Splits <c>List1</c> into <c>List2</c> and <c>List3</c>.
- <c>List2</c> contains the first <c>N</c> elements and
- <c>List3</c> the rest of the elements (the <c>N</c>th tail).</p>
+ <p>Splits <c><anno>List1</anno></c> into <c><anno>List2</anno></c> and <c><anno>List3</anno></c>.
+ <c><anno>List2</anno></c> contains the first <c><anno>N</anno></c> elements and
+ <c><anno>List3</anno></c> the rest of the elements (the <c><anno>N</anno></c>th tail).</p>
</desc>
</func>
<func>
- <name>splitwith(Pred, List) -> {List1, List2}</name>
+ <name name="splitwith" arity="2"/>
<fsummary>Split a list into two lists based on a predicate</fsummary>
- <type>
- <v>Pred = fun(Elem) -> bool()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List = List1 = List2 = [term()]</v>
- </type>
<desc>
- <p>Partitions <c>List</c> into two lists according to
- <c>Pred</c>. <c>splitwith/2</c> behaves as if it is defined
+ <p>Partitions <c><anno>List</anno></c> into two lists according to
+ <c><anno>Pred</anno></c>. <c>splitwith/2</c> behaves as if it is defined
as follows:</p>
<code type="none">
splitwith(Pred, List) ->
@@ -853,31 +658,23 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>sublist(List1, Len) -> List2</name>
+ <name name="sublist" arity="2"/>
<fsummary>Return a sub-list of a certain length, starting at the first position</fsummary>
- <type>
- <v>List1 = List2 = [term()]</v>
- <v>Len = int()</v>
- </type>
<desc>
- <p>Returns the sub-list of <c>List1</c> starting at position 1
- and with (max) <c>Len</c> elements. It is not an error for
- <c>Len</c> to exceed the length of the list -- in that case
+ <p>Returns the sub-list of <c><anno>List1</anno></c> starting at position 1
+ and with (max) <c><anno>Len</anno></c> elements. It is not an error for
+ <c><anno>Len</anno></c> to exceed the length of the list -- in that case
the whole list is returned.</p>
</desc>
</func>
<func>
- <name>sublist(List1, Start, Len) -> List2</name>
+ <name name="sublist" arity="3"/>
<fsummary>Return a sub-list starting at a given position and with a given number of elements</fsummary>
- <type>
- <v>List1 = List2 = [term()]</v>
- <v>Start = 1..(length(List1)+1)</v>
- <v>Len = int()</v>
- </type>
+ <type_desc variable="Start">1..(length(List1)+1)</type_desc>
<desc>
- <p>Returns the sub-list of <c>List1</c> starting at <c>Start</c>
- and with (max) <c>Len</c> elements. It is not an error for
- <c>Start+Len</c> to exceed the length of the list.</p>
+ <p>Returns the sub-list of <c><anno>List1</anno></c> starting at <c><anno>Start</anno></c>
+ and with (max) <c><anno>Len</anno></c> elements. It is not an error for
+ <c><anno>Start</anno>+<anno>Len</anno></c> to exceed the length of the list.</p>
<pre>
> <input>lists:sublist([1,2,3,4], 2, 2).</input>
[2,3]
@@ -888,15 +685,12 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>subtract(List1, List2) -> List3</name>
+ <name name="subtract" arity="2"/>
<fsummary>Subtract the element in one list from another list</fsummary>
- <type>
- <v>List1 = List2 = List3 = [term()]</v>
- </type>
<desc>
- <p>Returns a new list <c>List3</c> which is a copy of
- <c>List1</c>, subjected to the following procedure: for each
- element in <c>List2</c>, its first occurrence in <c>List1</c>
+ <p>Returns a new list <c><anno>List3</anno></c> which is a copy of
+ <c><anno>List1</anno></c>, subjected to the following procedure: for each
+ element in <c><anno>List2</anno></c>, its first occurrence in <c><anno>List1</anno></c>
is deleted. For example:</p>
<pre>
> <input>lists:subtract("123212", "212").</input>
@@ -911,151 +705,112 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>suffix(List1, List2) -> bool()</name>
+ <name name="suffix" arity="2"/>
<fsummary>Test for list suffix</fsummary>
<desc>
- <p>Returns <c>true</c> if <c>List1</c> is a suffix of
- <c>List2</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>List1</anno></c> is a suffix of
+ <c><anno>List2</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>sum(List) -> number()</name>
+ <name name="sum" arity="1"/>
<fsummary>Return sum of elements in a list</fsummary>
- <type>
- <v>List = [number()]</v>
- </type>
<desc>
- <p>Returns the sum of the elements in <c>List</c>.</p>
+ <p>Returns the sum of the elements in <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>takewhile(Pred, List1) -> List2</name>
+ <name name="takewhile" arity="2"/>
<fsummary>Take elements from a list while a predicate is true</fsummary>
- <type>
- <v>Pred = fun(Elem) -> bool()</v>
- <v>&nbsp;Elem = term()</v>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
- <p>Takes elements <c>Elem</c> from <c>List1</c> while
- <c>Pred(Elem)</c> returns <c>true</c>, that is,
+ <p>Takes elements <c><anno>Elem</anno></c> from <c><anno>List1</anno></c> while
+ <c><anno>Pred</anno>(<anno>Elem</anno>)</c> returns <c>true</c>, that is,
the function returns the longest prefix of the list for which
all elements satisfy the predicate.</p>
</desc>
</func>
<func>
- <name>ukeymerge(N, TupleList1, TupleList2) -> TupleList3</name>
+ <name name="ukeymerge" arity="3"/>
<fsummary>Merge two key-sorted lists of tuples, removing duplicates</fsummary>
- <type>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = TupleList3 = [Tuple]</v>
- <v>&nbsp;Tuple = tuple()</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
- <p>Returns the sorted list formed by merging <c>TupleList1</c>
- and <c>TupleList2</c>. The merge is performed on the
- <c>N</c>th element of each tuple. Both <c>TupleList1</c> and
- <c>TupleList2</c> must be key-sorted without duplicates
+ <p>Returns the sorted list formed by merging <c><anno>TupleList1</anno></c>
+ and <c><anno>TupleList2</anno></c>. The merge is performed on the
+ <c><anno>N</anno></c>th element of each tuple. Both <c><anno>TupleList1</anno></c> and
+ <c><anno>TupleList2</anno></c> must be key-sorted without duplicates
prior to evaluating this function. When two tuples compare
- equal, the tuple from <c>TupleList1</c> is picked and the
- one from <c>TupleList2</c> deleted.</p>
+ equal, the tuple from <c><anno>TupleList1</anno></c> is picked and the
+ one from <c><anno>TupleList2</anno></c> deleted.</p>
</desc>
</func>
<func>
- <name>ukeysort(N, TupleList1) -> TupleList2</name>
+ <name name="ukeysort" arity="2"/>
<fsummary>Sort a list of tuples, removing duplicates</fsummary>
- <type>
- <v>N = 1..tuple_size(Tuple)</v>
- <v>TupleList1 = TupleList2 = [Tuple]</v>
- <v>&nbsp;Tuple = tuple()</v>
- </type>
+ <type_desc variable="N">1..tuple_size(Tuple)</type_desc>
<desc>
<p>Returns a list containing the sorted elements of the list
- <c>TupleList1</c> where all but the first tuple of the
+ <c><anno>TupleList1</anno></c> where all but the first tuple of the
tuples comparing equal have been deleted. Sorting is
- performed on the <c>N</c>th element of the tuples.</p>
+ performed on the <c><anno>N</anno></c>th element of the tuples.</p>
</desc>
</func>
<func>
- <name>umerge(ListOfLists) -> List1</name>
+ <name name="umerge" arity="1"/>
<fsummary>Merge a list of sorted lists, removing duplicates</fsummary>
- <type>
- <v>ListOfLists = [List]</v>
- <v>List = List1 = [term()]</v>
- </type>
<desc>
<p>Returns the sorted list formed by merging all the sub-lists
- of <c>ListOfLists</c>. All sub-lists must be sorted and
+ of <c><anno>ListOfLists</anno></c>. All sub-lists must be sorted and
contain no duplicates prior to evaluating this function.
When two elements compare equal, the element from the
- sub-list with the lowest position in <c>ListOfLists</c> is
+ sub-list with the lowest position in <c><anno>ListOfLists</anno></c> is
picked and the other one deleted.</p>
</desc>
</func>
<func>
- <name>umerge(List1, List2) -> List3</name>
+ <name name="umerge" arity="2"/>
<fsummary>Merge two sorted lists, removing duplicates</fsummary>
- <type>
- <v>List1 = List2 = List3 = [term()]</v>
- </type>
<desc>
- <p>Returns the sorted list formed by merging <c>List1</c> and
- <c>List2</c>. Both <c>List1</c> and <c>List2</c> must be
+ <p>Returns the sorted list formed by merging <c><anno>List1</anno></c> and
+ <c><anno>List2</anno></c>. Both <c><anno>List1</anno></c> and <c><anno>List2</anno></c> must be
sorted and contain no duplicates prior to evaluating this
function. When two elements compare equal, the element from
- <c>List1</c> is picked and the one from <c>List2</c>
+ <c><anno>List1</anno></c> is picked and the one from <c><anno>List2</anno></c>
deleted.</p>
</desc>
</func>
<func>
- <name>umerge(Fun, List1, List2) -> List3</name>
+ <name name="umerge" arity="3"/>
<fsummary>Merge two sorted lists, removing duplicates</fsummary>
- <type>
- <v>Fun = fun(A, B) -> bool()</v>
- <v>List1 = [A]</v>
- <v>List2 = [B]</v>
- <v>List3 = [A | B]</v>
- <v>&nbsp;A = B = term()</v>
- </type>
<desc>
- <p>Returns the sorted list formed by merging <c>List1</c> and
- <c>List2</c>. Both <c>List1</c> and <c>List2</c> must be
+ <p>Returns the sorted list formed by merging <c><anno>List1</anno></c> and
+ <c><anno>List2</anno></c>. Both <c><anno>List1</anno></c> and <c><anno>List2</anno></c> must be
sorted according to the <seealso
marker="#ordering_function">ordering function</seealso>
<c>Fun</c> and contain no duplicates prior to evaluating
- this function. <c>Fun(A, B)</c> should return <c>true</c> if
- <c>A</c> compares less than or equal to <c>B</c> in the
+ this function. <c><anno>Fun</anno>(<anno>A</anno>, <anno>B</anno>)</c> should return <c>true</c> if
+ <c><anno>A</anno></c> compares less than or equal to <c><anno>B</anno></c> in the
ordering, <c>false</c> otherwise. When two elements compare
equal, the element from
- <c>List1</c> is picked and the one from <c>List2</c>
+ <c><anno>List1</anno></c> is picked and the one from <c><anno>List2</anno></c>
deleted.</p>
</desc>
</func>
<func>
- <name>umerge3(List1, List2, List3) -> List4</name>
+ <name name="umerge3" arity="3"/>
<fsummary>Merge three sorted lists, removing duplicates</fsummary>
- <type>
- <v>List1 = List2 = List3 = List4 = [term()]</v>
- </type>
<desc>
- <p>Returns the sorted list formed by merging <c>List1</c>,
- <c>List2</c> and <c>List3</c>. All of <c>List1</c>,
- <c>List2</c> and <c>List3</c> must be sorted and contain no
+ <p>Returns the sorted list formed by merging <c><anno>List1</anno></c>,
+ <c><anno>List2</anno></c> and <c><anno>List3</anno></c>. All of <c><anno>List1</anno></c>,
+ <c><anno>List2</anno></c> and <c><anno>List3</anno></c> must be sorted and contain no
duplicates prior to evaluating this function. When two
- elements compare equal, the element from <c>List1</c> is
+ elements compare equal, the element from <c><anno>List1</anno></c> is
picked if there is such an element, otherwise the element
- from <c>List2</c> is picked, and the other one deleted.</p>
+ from <c><anno>List2</anno></c> is picked, and the other one deleted.</p>
</desc>
</func>
<func>
- <name>unzip(List1) -> {List2, List3}</name>
+ <name name="unzip" arity="1"/>
<fsummary>Unzip a list of two-tuples into two lists</fsummary>
- <type>
- <v>List1 = [{X, Y}]</v>
- <v>List2 = [X]</v>
- <v>List3 = [Y]</v>
- <v>&nbsp;X = Y = term()</v>
- </type>
<desc>
<p>"Unzips" a list of two-tuples into two lists, where the first
list contains the first element of each tuple, and the second
@@ -1063,15 +818,8 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>unzip3(List1) -> {List2, List3, List4}</name>
+ <name name="unzip3" arity="1"/>
<fsummary>Unzip a list of three-tuples into three lists</fsummary>
- <type>
- <v>List1 = [{X, Y, Z}]</v>
- <v>List2 = [X]</v>
- <v>List3 = [Y]</v>
- <v>List4 = [Z]</v>
- <v>&nbsp;X = Y = Z = term()</v>
- </type>
<desc>
<p>"Unzips" a list of three-tuples into three lists, where
the first list contains the first element of each tuple,
@@ -1080,44 +828,30 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>usort(List1) -> List2</name>
+ <name name="usort" arity="1"/>
<fsummary>Sort a list, removing duplicates</fsummary>
- <type>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
<p>Returns a list containing the sorted elements of
- <c>List1</c> where all but the first element of the elements
+ <c><anno>List1</anno></c> where all but the first element of the elements
comparing equal have been deleted.</p>
</desc>
</func>
<func>
- <name>usort(Fun, List1) -> List2</name>
+ <name name="usort" arity="2"/>
<fsummary>Sort a list, removing duplicates</fsummary>
- <type>
- <v>Fun = fun(Elem1, Elem2) -> bool()</v>
- <v>&nbsp;Elem1 = Elem2 = term()</v>
- <v>List1 = List2 = [term()]</v>
- </type>
<desc>
<p>Returns a list which contains the sorted elements of
- <c>List1</c> where all but the first element of the elements
+ <c><anno>List1</anno></c> where all but the first element of the elements
comparing equal according to the <seealso
marker="#ordering_function">ordering function</seealso>
- <c>Fun</c> have been deleted. <c>Fun(A, B)</c> should return
+ <c><anno>Fun</anno></c> have been deleted. <c><anno>Fun</anno>(A, B)</c> should return
<c>true</c> if <c>A</c> compares less than or equal to
<c>B</c> in the ordering, <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>zip(List1, List2) -> List3</name>
+ <name name="zip" arity="2"/>
<fsummary>Zip two lists into a list of two-tuples</fsummary>
- <type>
- <v>List1 = [X]</v>
- <v>List2 = [Y]</v>
- <v>List3 = [{X, Y}]</v>
- <v>&nbsp;X = Y = term()</v>
- </type>
<desc>
<p>"Zips" two lists of equal length into one list of two-tuples,
where the first element of each tuple is taken from the first
@@ -1126,15 +860,8 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>zip3(List1, List2, List3) -> List4</name>
+ <name name="zip3" arity="3"/>
<fsummary>Zip three lists into a list of three-tuples</fsummary>
- <type>
- <v>List1 = [X]</v>
- <v>List2 = [Y]</v>
- <v>List3 = [Z]</v>
- <v>List3 = [{X, Y, Z}]</v>
- <v>&nbsp;X = Y = Z = term()</v>
- </type>
<desc>
<p>"Zips" three lists of equal length into one list of
three-tuples, where the first element of each tuple is taken
@@ -1145,20 +872,13 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>zipwith(Combine, List1, List2) -> List3</name>
+ <name name="zipwith" arity="3"/>
<fsummary>Zip two lists into one list according to a fun</fsummary>
- <type>
- <v>Combine = fun(X, Y) -> T</v>
- <v>List1 = [X]</v>
- <v>List2 = [Y]</v>
- <v>List3 = [T]</v>
- <v>&nbsp;X = Y = T = term()</v>
- </type>
<desc>
<p>Combine the elements of two lists of equal length into one
- list. For each pair <c>X, Y</c> of list elements from the two
+ list. For each pair <c><anno>X</anno>, <anno>Y</anno></c> of list elements from the two
lists, the element in the result list will be
- <c>Combine(X, Y)</c>.</p>
+ <c><anno>Combine</anno>(<anno>X</anno>, <anno>Y</anno>)</c>.</p>
<p><c>zipwith(fun(X, Y) -> {X,Y} end, List1, List2)</c> is
equivalent to <c>zip(List1, List2)</c>.</p>
<p>Example:</p>
@@ -1168,21 +888,13 @@ splitwith(Pred, List) ->
</desc>
</func>
<func>
- <name>zipwith3(Combine, List1, List2, List3) -> List4</name>
+ <name name="zipwith3" arity="4"/>
<fsummary>Zip three lists into one list according to a fun</fsummary>
- <type>
- <v>Combine = fun(X, Y, Z) -> T</v>
- <v>List1 = [X]</v>
- <v>List2 = [Y]</v>
- <v>List3 = [Z]</v>
- <v>List4 = [T]</v>
- <v>&nbsp;X = Y = Z = T = term()</v>
- </type>
<desc>
<p>Combine the elements of three lists of equal length into one
- list. For each triple <c>X, Y, Z</c> of list elements from
+ list. For each triple <c><anno>X</anno>, <anno>Y</anno>, <anno>Z</anno></c> of list elements from
the three lists, the element in the result list will be
- <c>Combine(X, Y, Z)</c>.</p>
+ <c><anno>Combine</anno>(<anno>X</anno>, <anno>Y</anno>, <anno>Z</anno>)</c>.</p>
<p><c>zipwith3(fun(X, Y, Z) -> {X,Y,Z} end, List1, List2, List3)</c> is equivalent to <c>zip3(List1, List2, List3)</c>.</p>
<p>Examples:</p>
<pre>
diff --git a/lib/stdlib/doc/src/log_mf_h.xml b/lib/stdlib/doc/src/log_mf_h.xml
index f8e11339a7..f2b09b58eb 100644
--- a/lib/stdlib/doc/src/log_mf_h.xml
+++ b/lib/stdlib/doc/src/log_mf_h.xml
@@ -43,28 +43,27 @@
report files <c>1, 2, ....</c>.
</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="args"/>
+ <desc><p>Term to be sent to <seealso marker="gen_event#add_handler/3">
+ gen_event:add_handler/3</seealso>.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>init(Dir, MaxBytes, MaxFiles)</name>
- <name>init(Dir, MaxBytes, MaxFiles, Pred) -> Args</name>
+ <name name="init" arity="3"/>
+ <name name="init" arity="4"/>
<fsummary>Initiate the event handler</fsummary>
- <type>
- <v>Dir = string()</v>
- <v>MaxBytes = integer()</v>
- <v>MaxFiles = 0 &lt; integer() &lt; 256</v>
- <v>Pred = fun(Event) -> boolean()</v>
- <v>Event = term()</v>
- <v>Args = args()</v>
- </type>
<desc>
<p>Initiates the event handler. This function returns
- <c>Args</c>, which should be used in a call to
- <c>gen_event:add_handler(EventMgr, log_mf_h, Args)</c>.
+ <c><anno>Args</anno></c>, which should be used in a call to
+ <c>gen_event:add_handler(EventMgr, log_mf_h, <anno>Args</anno>)</c>.
</p>
- <p><c>Dir</c> specifies which directory to use for the log
- files. <c>MaxBytes</c> specifies the size of each individual
- file. <c>MaxFiles</c> specifies how many files are
- used. <c>Pred</c> is a predicate function used to filter the
+ <p><c><anno>Dir</anno></c> specifies which directory to use for the log
+ files. <c><anno>MaxBytes</anno></c> specifies the size of each individual
+ file. <c><anno>MaxFiles</anno></c> specifies how many files are
+ used. <c><anno>Pred</anno></c> is a predicate function used to filter the
events. If no predicate function is specified, all events are
logged.</p>
</desc>
diff --git a/lib/stdlib/doc/src/math.xml b/lib/stdlib/doc/src/math.xml
index 02e4d6e495..518457d5d8 100644
--- a/lib/stdlib/doc/src/math.xml
+++ b/lib/stdlib/doc/src/math.xml
@@ -45,7 +45,7 @@
</description>
<funcs>
<func>
- <name>pi() -> float()</name>
+ <name name="pi" arity="0"/>
<fsummary>A useful number</fsummary>
<desc>
<p>A useful number.</p>
diff --git a/lib/stdlib/doc/src/ms_transform.xml b/lib/stdlib/doc/src/ms_transform.xml
index ba9f89685b..f81f8bda96 100644
--- a/lib/stdlib/doc/src/ms_transform.xml
+++ b/lib/stdlib/doc/src/ms_transform.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2002</year><year>2010</year>
+ <year>2002</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -599,12 +599,9 @@ ets:select(Table, [{{'$1',test,'$2'},[],['$_']}]).</code>
</description>
<funcs>
<func>
- <name>parse_transform(Forms,_Options) -> Forms</name>
+ <name name="parse_transform" arity="2"/>
<fsummary>Transforms Erlang abstract format containing calls to ets/dbg:fun2ms into literal match specifications.</fsummary>
- <type>
- <v>Forms = Erlang abstract code format, see the erl_parse module description </v>
- <v>_Options = Option list, required but not used</v>
- </type>
+ <type_desc variable="Options">Option list, required but not used.</type_desc>
<desc>
<p>Implements the actual transformation at compile time. This
function is called by the compiler to do the source code
@@ -617,29 +614,21 @@ ets:select(Table, [{{'$1',test,'$2'},[],['$_']}]).</code>
</desc>
</func>
<func>
- <name>transform_from_shell(Dialect,Clauses,BoundEnvironment) -> term()</name>
+ <name name="transform_from_shell" arity="3"/>
<fsummary>Used when transforming fun's created in the shell into match_specifications.</fsummary>
- <type>
- <v>Dialect = ets | dbg</v>
- <v>Clauses = Erlang abstract form for a single fun</v>
- <v>BoundEnvironment = [{atom(), term()}, ...], list of variable bindings in the shell environment</v>
- </type>
+ <type_desc variable="BoundEnvironment">List of variable bindings in the shell environment.</type_desc>
<desc>
<p>Implements the actual transformation when the <c>fun2ms</c>
functions are called from the shell. In this case the abstract
form is for one single fun (parsed by the Erlang shell), and
all imported variables should be in the key-value list passed
- as <c>BoundEnvironment</c>. The result is a term, normalized,
+ as <c><anno>BoundEnvironment</anno></c>. The result is a term, normalized,
i.e. not in abstract format.</p>
</desc>
</func>
<func>
- <name>format_error(Errcode) -> ErrMessage</name>
+ <name name="format_error" arity="1"/>
<fsummary>Error formatting function as required by the parse_transform interface.</fsummary>
- <type>
- <v>Errcode = term()</v>
- <v>ErrMessage = string()</v>
- </type>
<desc>
<p>Takes an error code returned by one of the other functions
in the module and creates a textual description of the
diff --git a/lib/stdlib/doc/src/notes.xml b/lib/stdlib/doc/src/notes.xml
index 8cd499f960..c2676b1de5 100644
--- a/lib/stdlib/doc/src/notes.xml
+++ b/lib/stdlib/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/stdlib/doc/src/orddict.xml b/lib/stdlib/doc/src/orddict.xml
index 1b8b74534b..319083d35b 100644
--- a/lib/stdlib/doc/src/orddict.xml
+++ b/lib/stdlib/doc/src/orddict.xml
@@ -46,176 +46,123 @@
(<c>==</c>).</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-ordered_dictionary()
- as returned by new/0</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name name="orddict"/>
+ <desc><p>As returned by new/0.</p></desc>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
- <name>append(Key, Value, Orddict1) -> Orddict2</name>
+ <name name="append" arity="3"/>
<fsummary>Append a value to keys in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p>This function appends a new <c>Value</c> to the current list
- of values associated with <c>Key</c>. An exception is
- generated if the initial value associated with <c>Key</c> is
+ <p>This function appends a new <c><anno>Value</anno></c> to the current list
+ of values associated with <c><anno>Key</anno></c>. An exception is
+ generated if the initial value associated with <c><anno>Key</anno></c> is
not a list of values.</p>
</desc>
</func>
<func>
- <name>append_list(Key, ValList, Orddict1) -> Orddict2</name>
+ <name name="append_list" arity="3"/>
<fsummary>Append new values to keys in a dictionary</fsummary>
- <type>
- <v>ValList = [Value]</v>
- <v>Key = Value = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p>This function appends a list of values <c>ValList</c> to
- the current list of values associated with <c>Key</c>. An
+ <p>This function appends a list of values <c><anno>ValList</anno></c> to
+ the current list of values associated with <c><anno>Key</anno></c>. An
exception is generated if the initial value associated with
- <c>Key</c> is not a list of values.</p>
+ <c><anno>Key</anno></c> is not a list of values.</p>
</desc>
</func>
<func>
- <name>erase(Key, Orddict1) -> Orddict2</name>
+ <name name="erase" arity="2"/>
<fsummary>Erase a key from a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
<p>This function erases all items with a given key from a
dictionary.</p>
</desc>
</func>
<func>
- <name>fetch(Key, Orddict) -> Value</name>
+ <name name="fetch" arity="2"/>
<fsummary>Look-up values in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Orddict = ordered_dictionary()</v>
- </type>
<desc>
- <p>This function returns the value associated with <c>Key</c>
- in the dictionary <c>Orddict</c>. <c>fetch</c> assumes that
- the <c>Key</c> is present in the dictionary and an exception
- is generated if <c>Key</c> is not in the dictionary.</p>
+ <p>This function returns the value associated with <c><anno>Key</anno></c>
+ in the dictionary <c><anno>Orddict</anno></c>. <c>fetch</c> assumes that
+ the <c><anno>Key</anno></c> is present in the dictionary and an exception
+ is generated if <c><anno>Key</anno></c> is not in the dictionary.</p>
</desc>
</func>
<func>
- <name>fetch_keys(Orddict) -> Keys</name>
+ <name name="fetch_keys" arity="1"/>
<fsummary>Return all keys in a dictionary</fsummary>
- <type>
- <v>Orddict = ordered_dictionary()</v>
- <v>Keys = [term()]</v>
- </type>
<desc>
<p>This function returns a list of all keys in the dictionary.</p>
</desc>
</func>
<func>
- <name>filter(Pred, Orddict1) -> Orddict2</name>
+ <name name="filter" arity="2"/>
<fsummary>Choose elements which satisfy a predicate</fsummary>
- <type>
- <v>Pred = fun(Key, Value) -> bool()</v>
- <v>&nbsp;Key = Value = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p><c>Orddict2</c> is a dictionary of all keys and values in
- <c>Orddict1</c> for which <c>Pred(Key, Value)</c> is <c>true</c>.</p>
+ <p><c><anno>Orddict2</anno></c> is a dictionary of all keys and values in
+ <c><anno>Orddict1</anno></c> for which <c><anno>Pred</anno>(<anno>Key</anno>, <anno>Value</anno>)</c> is <c>true</c>.</p>
</desc>
</func>
<func>
- <name>find(Key, Orddict) -> {ok, Value} | error</name>
+ <name name="find" arity="2"/>
<fsummary>Search for a key in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Orddict = ordered_dictionary()</v>
- </type>
<desc>
<p>This function searches for a key in a dictionary. Returns
- <c>{ok, Value}</c> where <c>Value</c> is the value associated
- with <c>Key</c>, or <c>error</c> if the key is not present in
+ <c>{ok, <anno>Value</anno>}</c> where <c><anno>Value</anno></c> is the value associated
+ with <c><anno>Key</anno></c>, or <c>error</c> if the key is not present in
the dictionary.</p>
</desc>
</func>
<func>
- <name>fold(Fun, Acc0, Orddict) -> Acc1</name>
+ <name name="fold" arity="3"/>
<fsummary>Fold a function over a dictionary</fsummary>
- <type>
- <v>Fun = fun(Key, Value, AccIn) -> AccOut</v>
- <v>Key = Value = term()</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Orddict = ordered_dictionary()</v>
- </type>
<desc>
- <p>Calls <c>Fun</c> on successive keys and values of
- <c>Orddict</c> together with an extra argument <c>Acc</c>
- (short for accumulator). <c>Fun</c> must return a new
- accumulator which is passed to the next call. <c>Acc0</c> is
+ <p>Calls <c><anno>Fun</anno></c> on successive keys and values of
+ <c><anno>Orddict</anno></c> together with an extra argument <c>Acc</c>
+ (short for accumulator). <c><anno>Fun</anno></c> must return a new
+ accumulator which is passed to the next call. <c><anno>Acc0</anno></c> is
returned if the list is empty. The evaluation order is
undefined.</p>
</desc>
</func>
<func>
- <name>from_list(List) -> Orddict</name>
+ <name name="from_list" arity="1"/>
<fsummary>Convert a list of pairs to a dictionary</fsummary>
- <type>
- <v>List = [{Key, Value}]</v>
- <v>Orddict = ordered_dictionary()</v>
- </type>
<desc>
- <p>This function converts the <c>Key</c> - <c>Value</c> list
- <c>List</c> to a dictionary.</p>
+ <p>This function converts the <c><anno>Key</anno></c> - <c><anno>Value</anno></c> list
+ <c><anno>List</anno></c> to a dictionary.</p>
</desc>
</func>
<func>
- <name>is_key(Key, Orddict) -> bool()</name>
+ <name name="is_key" arity="2"/>
<fsummary>Test if a key is in a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Orddict = ordered_dictionary()</v>
- </type>
<desc>
- <p>This function tests if <c>Key</c> is contained in
- the dictionary <c>Orddict</c>.</p>
+ <p>This function tests if <c><anno>Key</anno></c> is contained in
+ the dictionary <c><anno>Orddict</anno></c>.</p>
</desc>
</func>
<func>
- <name>map(Fun, Orddict1) -> Orddict2</name>
+ <name name="map" arity="2"/>
<fsummary>Map a function over a dictionary</fsummary>
- <type>
- <v>Fun = fun(Key, Value1) -> Value2</v>
- <v>&nbsp;Key = Value1 = Value2 = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p><c>map</c> calls <c>Func</c> on successive keys and values
- of <c>Orddict</c> to return a new value for each key.
+ <p><c>map</c> calls <c><anno>Fun</anno></c> on successive keys and values
+ of <c><anno>Orddict1</anno></c> to return a new value for each key.
The evaluation order is undefined.</p>
</desc>
</func>
<func>
- <name>merge(Fun, Orddict1, Orddict2) -> Orddict3</name>
+ <name name="merge" arity="3"/>
<fsummary>Merge two dictionaries</fsummary>
- <type>
- <v>Fun = fun(Key, Value1, Value2) -> Value</v>
- <v>&nbsp;Key = Value1 = Value2 = Value3 = term()</v>
- <v>Orddict1 = Orddict2 = Orddict3 = ordered_dictionary()</v>
- </type>
<desc>
- <p><c>merge</c> merges two dictionaries, <c>Orddict1</c> and
- <c>Orddict2</c>, to create a new dictionary. All the <c>Key</c>
- - <c>Value</c> pairs from both dictionaries are included in
+ <p><c>merge</c> merges two dictionaries, <c><anno>Orddict1</anno></c> and
+ <c><anno>Orddict2</anno></c>, to create a new dictionary. All the <c><anno>Key</anno></c>
+ - <c><anno>Value</anno></c> pairs from both dictionaries are included in
the new dictionary. If a key occurs in both dictionaries then
- <c>Fun</c> is called with the key and both values to return a
+ <c><anno>Fun</anno></c> is called with the key and both values to return a
new value. <c>merge</c> could be defined as:</p>
<code type="none">
merge(Fun, D1, D2) ->
@@ -226,75 +173,52 @@ merge(Fun, D1, D2) ->
</desc>
</func>
<func>
- <name>new() -> ordered_dictionary()</name>
+ <name name="new" arity="0"/>
<fsummary>Create a dictionary</fsummary>
<desc>
<p>This function creates a new dictionary.</p>
</desc>
</func>
<func>
- <name>size(Orddict) -> int()</name>
+ <name name="size" arity="1"/>
<fsummary>Return the number of elements in an ordered dictionary</fsummary>
- <type>
- <v>Orddict = ordered_dictionary()</v>
- </type>
<desc>
- <p>Returns the number of elements in an <c>Orddict</c>.</p>
+ <p>Returns the number of elements in an <c><anno>Orddict</anno></c>.</p>
</desc>
</func>
<func>
- <name>store(Key, Value, Orddict1) -> Orddict2</name>
+ <name name="store" arity="3"/>
<fsummary>Store a value in a dictionary</fsummary>
- <type>
- <v>Key = Value = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p>This function stores a <c>Key</c> - <c>Value</c> pair in a
- dictionary. If the <c>Key</c> already exists in <c>Orddict1</c>,
- the associated value is replaced by <c>Value</c>.</p>
+ <p>This function stores a <c><anno>Key</anno></c> - <c><anno>Value</anno></c> pair in a
+ dictionary. If the <c><anno>Key</anno></c> already exists in <c><anno>Orddict1</anno></c>,
+ the associated value is replaced by <c><anno>Value</anno></c>.</p>
</desc>
</func>
<func>
- <name>to_list(Orddict) -> List</name>
+ <name name="to_list" arity="1"/>
<fsummary>Convert a dictionary to a list of pairs</fsummary>
- <type>
- <v>Orddict = ordered_dictionary()</v>
- <v>List = [{Key, Value}]</v>
- </type>
<desc>
<p>This function converts the dictionary to a list
representation.</p>
</desc>
</func>
<func>
- <name>update(Key, Fun, Orddict1) -> Orddict2</name>
+ <name name="update" arity="3"/>
<fsummary>Update a value in a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Fun = fun(Value1) -> Value2</v>
- <v>&nbsp;Value1 = Value2 = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p>Update a value in a dictionary by calling <c>Fun</c> on
+ <p>Update a value in a dictionary by calling <c><anno>Fun</anno></c> on
the value to get a new value. An exception is generated if
- <c>Key</c> is not present in the dictionary.</p>
+ <c><anno>Key</anno></c> is not present in the dictionary.</p>
</desc>
</func>
<func>
- <name>update(Key, Fun, Initial, Orddict1) -> Orddict2</name>
+ <name name="update" arity="4"/>
<fsummary>Update a value in a dictionary</fsummary>
- <type>
- <v>Key = Initial = term()</v>
- <v>Fun = fun(Value1) -> Value2</v>
- <v>&nbsp;Value1 = Value2 = term()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p>Update a value in a dictionary by calling <c>Fun</c> on
- the value to get a new value. If <c>Key</c> is not present
- in the dictionary then <c>Initial</c> will be stored as
+ <p>Update a value in a dictionary by calling <c><anno>Fun</anno></c> on
+ the value to get a new value. If <c><anno>Key</anno></c> is not present
+ in the dictionary then <c><anno>Initial</anno></c> will be stored as
the first value. For example <c>append/3</c> could be defined
as:</p>
<code type="none">
@@ -303,17 +227,12 @@ append(Key, Val, D) ->
</desc>
</func>
<func>
- <name>update_counter(Key, Increment, Orddict1) -> Orddict2</name>
+ <name name="update_counter" arity="3"/>
<fsummary>Increment a value in a dictionary</fsummary>
- <type>
- <v>Key = term()</v>
- <v>Increment = number()</v>
- <v>Orddict1 = Orddict2 = ordered_dictionary()</v>
- </type>
<desc>
- <p>Add <c>Increment</c> to the value associated with <c>Key</c>
- and store this value. If <c>Key</c> is not present in
- the dictionary then <c>Increment</c> will be stored as
+ <p>Add <c><anno>Increment</anno></c> to the value associated with <c><anno>Key</anno></c>
+ and store this value. If <c><anno>Key</anno></c> is not present in
+ the dictionary then <c><anno>Increment</anno></c> will be stored as
the first value.</p>
<p>This could be defined as:</p>
<code type="none">
diff --git a/lib/stdlib/doc/src/ordsets.xml b/lib/stdlib/doc/src/ordsets.xml
index a20ab2d879..1e26fc2022 100644
--- a/lib/stdlib/doc/src/ordsets.xml
+++ b/lib/stdlib/doc/src/ordsets.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -45,202 +45,141 @@
different if and only if they do not compare equal (<c>==</c>).</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-ordered_set()
- as returned by new/0</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name name="ordset" n_vars="1"/>
+ <desc><p>As returned by new/0.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>new() -> Ordset</name>
+ <name name="new" arity="0"/>
<fsummary>Return an empty set</fsummary>
- <type>
- <v>Ordset = ordered_set()</v>
- </type>
<desc>
<p>Returns a new empty ordered set.</p>
</desc>
</func>
<func>
- <name>is_set(Ordset) -> bool()</name>
+ <name name="is_set" arity="1"/>
<fsummary>Test for an <c>Ordset</c></fsummary>
- <type>
- <v>Ordset = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Ordset</c> is an ordered set of
+ <p>Returns <c>true</c> if <c><anno>Ordset</anno></c> is an ordered set of
elements, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>size(Ordset) -> int()</name>
+ <name name="size" arity="1"/>
<fsummary>Return the number of elements in a set</fsummary>
- <type>
- <v>Ordset = term()</v>
- </type>
<desc>
- <p>Returns the number of elements in <c>Ordset</c>.</p>
+ <p>Returns the number of elements in <c><anno>Ordset</anno></c>.</p>
</desc>
</func>
<func>
- <name>to_list(Ordset) -> List</name>
+ <name name="to_list" arity="1"/>
<fsummary>Convert an <c>Ordset</c>into a list</fsummary>
- <type>
- <v>Ordset = ordered_set()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns the elements of <c>Ordset</c> as a list.</p>
+ <p>Returns the elements of <c><anno>Ordset</anno></c> as a list.</p>
</desc>
</func>
<func>
- <name>from_list(List) -> Ordset</name>
+ <name name="from_list" arity="1"/>
<fsummary>Convert a list into an <c>Ordset</c></fsummary>
- <type>
- <v>List = [term()]</v>
- <v>Ordset = ordered_set()</v>
- </type>
<desc>
- <p>Returns an ordered set of the elements in <c>List</c>.</p>
+ <p>Returns an ordered set of the elements in <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>is_element(Element, Ordset) -> bool()</name>
+ <name name="is_element" arity="2"/>
<fsummary>Test for membership of an <c>Ordset</c></fsummary>
- <type>
- <v>Element = term()</v>
- <v>Ordset = ordered_set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Element</c> is an element of
- <c>Ordset</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>Element</anno></c> is an element of
+ <c><anno>Ordset</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>add_element(Element, Ordset1) -> Ordset2</name>
+ <name name="add_element" arity="2"/>
<fsummary>Add an element to an <c>Ordset</c></fsummary>
- <type>
- <v>Element = term()</v>
- <v>Ordset1 = Ordset2 = ordered_set()</v>
- </type>
<desc>
- <p>Returns a new ordered set formed from <c>Ordset1</c> with
- <c>Element</c> inserted.</p>
+ <p>Returns a new ordered set formed from <c><anno>Ordset1</anno></c> with
+ <c><anno>Element</anno></c> inserted.</p>
</desc>
</func>
<func>
- <name>del_element(Element, Ordset1) -> Ordset2</name>
+ <name name="del_element" arity="2"/>
<fsummary>Remove an element from an <c>Ordset</c></fsummary>
- <type>
- <v>Element = term()</v>
- <v>Ordset1 = Ordset2 = ordered_set()</v>
- </type>
<desc>
- <p>Returns <c>Ordset1</c>, but with <c>Element</c> removed.</p>
+ <p>Returns <c><anno>Ordset1</anno></c>, but with <c><anno>Element</anno></c> removed.</p>
</desc>
</func>
<func>
- <name>union(Ordset1, Ordset2) -> Ordset3</name>
+ <name name="union" arity="2"/>
<fsummary>Return the union of two <c>Ordsets</c></fsummary>
- <type>
- <v>Ordset1 = Ordset2 = Ordset3 = ordered_set()</v>
- </type>
<desc>
- <p>Returns the merged (union) set of <c>Ordset1</c> and
- <c>Ordset2</c>.</p>
+ <p>Returns the merged (union) set of <c><anno>Ordset1</anno></c> and
+ <c><anno>Ordset2</anno></c>.</p>
</desc>
</func>
<func>
- <name>union(OrdsetList) -> Ordset</name>
+ <name name="union" arity="1"/>
<fsummary>Return the union of a list of <c>Ordsets</c></fsummary>
- <type>
- <v>OrdsetList = [ordered_set()]</v>
- <v>Ordset = ordered_set()</v>
- </type>
<desc>
<p>Returns the merged (union) set of the list of sets.</p>
</desc>
</func>
<func>
- <name>intersection(Ordset1, Ordset2) -> Ordset3</name>
+ <name name="intersection" arity="2"/>
<fsummary>Return the intersection of two <c>Ordsets</c></fsummary>
- <type>
- <v>Ordset1 = Ordset2 = Ordset3 = ordered_set()</v>
- </type>
<desc>
- <p>Returns the intersection of <c>Ordset1</c> and
- <c>Ordset2</c>.</p>
+ <p>Returns the intersection of <c><anno>Ordset1</anno></c> and
+ <c><anno>Ordset2</anno></c>.</p>
</desc>
</func>
<func>
- <name>intersection(OrdsetList) -> Ordset</name>
+ <name name="intersection" arity="1"/>
<fsummary>Return the intersection of a list of <c>Ordsets</c></fsummary>
- <type>
- <v>OrdsetList = [ordered_set()]</v>
- <v>Ordset = ordered_set()</v>
- </type>
<desc>
<p>Returns the intersection of the non-empty list of sets.</p>
</desc>
</func>
<func>
- <name>is_disjoint(Ordset1, Ordset2) -> bool()</name>
+ <name name="is_disjoint" arity="2"/>
<fsummary>Check whether two <c>Ordsets</c> are disjoint</fsummary>
- <type>
- <v>Ordset1 = Ordset2 = ordered_set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Ordset1</c> and
- <c>Ordset2</c> are disjoint (have no elements in common),
+ <p>Returns <c>true</c> if <c><anno>Ordset1</anno></c> and
+ <c><anno>Ordset2</anno></c> are disjoint (have no elements in common),
and <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>subtract(Ordset1, Ordset2) -> Ordset3</name>
+ <name name="subtract" arity="2"/>
<fsummary>Return the difference of two <c>Ordsets</c></fsummary>
- <type>
- <v>Ordset1 = Ordset2 = Ordset3 = ordered_set()</v>
- </type>
<desc>
- <p>Returns only the elements of <c>Ordset1</c> which are not
- also elements of <c>Ordset2</c>.</p>
+ <p>Returns only the elements of <c><anno>Ordset1</anno></c> which are not
+ also elements of <c><anno>Ordset2</anno></c>.</p>
</desc>
</func>
<func>
- <name>is_subset(Ordset1, Ordset2) -> bool()</name>
+ <name name="is_subset" arity="2"/>
<fsummary>Test for subset</fsummary>
- <type>
- <v>Ordset1 = Ordset2 = ordered_set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> when every element of <c>Ordset</c>1 is
- also a member of <c>Ordset2</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> when every element of <c><anno>Ordset1</anno></c> is
+ also a member of <c><anno>Ordset2</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>fold(Function, Acc0, Ordset) -> Acc1</name>
+ <name name="fold" arity="3"/>
<fsummary>Fold over set elements</fsummary>
- <type>
- <v>Function = fun (E, AccIn) -> AccOut</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Ordset = ordered_set()</v>
- </type>
<desc>
- <p>Fold <c>Function</c> over every element in <c>Ordset</c>
+ <p>Fold <c><anno>Function</anno></c> over every element in <c><anno>Ordset</anno></c>
returning the final value of the accumulator.</p>
</desc>
</func>
<func>
- <name>filter(Pred, Ordset1) -> Set2</name>
+ <name name="filter" arity="2"/>
<fsummary>Filter set elements</fsummary>
- <type>
- <v>Pred = fun (E) -> bool()</v>
- <v>Set1 = Set2 = ordered_set()</v>
- </type>
<desc>
- <p>Filter elements in <c>Set1</c> with boolean function
- <c>Fun</c>.</p>
+ <p>Filter elements in <c><anno>Ordset1</anno></c> with boolean function
+ <c><anno>Pred</anno></c>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/pg.xml b/lib/stdlib/doc/src/pg.xml
index b174d4f7d4..c56db8c6e6 100644
--- a/lib/stdlib/doc/src/pg.xml
+++ b/lib/stdlib/doc/src/pg.xml
@@ -51,77 +51,56 @@
</description>
<funcs>
<func>
- <name>create(PgName) -> ok | {error, Reason}</name>
+ <name name="create" arity="1"/>
<fsummary>Create an empty group</fsummary>
- <type>
- <v>PgName = term()</v>
- <v>Reason = already_created | term()</v>
- </type>
<desc>
- <p>Creates an empty group named <c>PgName</c> on the current
+ <p>Creates an empty group named <c><anno>PgName</anno></c> on the current
node.</p>
</desc>
</func>
<func>
- <name>create(PgName, Node) -> ok | {error, Reason}</name>
+ <name name="create" arity="2"/>
<fsummary>Create an empty group on another node</fsummary>
- <type>
- <v>PgName = term()</v>
- <v>Node = node()</v>
- <v>Reason = already_created | term()</v>
- </type>
<desc>
- <p>Creates an empty group named <c>PgName</c> on the node
- <c>Node</c>.</p>
+ <p>Creates an empty group named <c><anno>PgName</anno></c> on the node
+ <c><anno>Node</anno></c>.</p>
</desc>
</func>
<func>
- <name>join(PgName, Pid) -> Members</name>
+ <name name="join" arity="2"/>
<fsummary>Join a pid to a process group</fsummary>
- <type>
- <v>PgName = term()</v>
- <v>Pid = pid()</v>
- <v>Members = [pid()]</v>
- </type>
<desc>
- <p>Joins the pid <c>Pid</c> to the process group <c>PgName</c>.
+ <p>Joins the pid <c><anno>Pid</anno></c> to the process group
+ <c><anno>PgName</anno></c>.
Returns a list of all old members of the group.</p>
</desc>
</func>
<func>
- <name>send(PgName, Msg) -> void()</name>
+ <name name="send" arity="2"/>
<fsummary>Send a message to all members of a process group</fsummary>
- <type>
- <v>PgName = Msg = term()</v>
- </type>
<desc>
<p>Sends the tuple <c>{pg_message, From, PgName, Msg}</c> to
- all members of the process group <c>PgName</c>.</p>
- <p>Failure: <c>{badarg, {PgName, Msg}}</c> if <c>PgName</c> is
+ all members of the process group <c><anno>PgName</anno></c>.</p>
+ <p>Failure: <c>{badarg, {<anno>PgName</anno>, <anno>Msg</anno>}}</c>
+ if <c><anno>PgName</anno></c> is
not a process group (a globally registered name).</p>
</desc>
</func>
<func>
- <name>esend(PgName, Msg) -> void()</name>
+ <name name="esend" arity="2"/>
<fsummary>Send a message to all members of a process group, except ourselves</fsummary>
- <type>
- <v>PgName = Msg = term()</v>
- </type>
<desc>
<p>Sends the tuple <c>{pg_message, From, PgName, Msg}</c> to
- all members of the process group <c>PgName</c>, except
+ all members of the process group <c><anno>PgName</anno></c>, except
ourselves.</p>
- <p>Failure: <c>{badarg, {PgName, Msg}}</c> if <c>PgName</c> is
+ <p>Failure: <c>{badarg, {<anno>PgName</anno>, <anno>Msg</anno>}}</c>
+ if <c><anno>PgName</anno></c> is
not a process group (a globally registered name).</p>
</desc>
</func>
<func>
- <name>members(PgName) -> Members</name>
+ <name name="members" arity="1"/>
<fsummary>Return a list of all members of a process group</fsummary>
- <type>
- <v>PgName = term()</v>
- <v>Members = [pid()]</v>
- </type>
<desc>
<p>Returns a list of all members of the process group
<c>PgName</c>.</p>
diff --git a/lib/stdlib/doc/src/pool.xml b/lib/stdlib/doc/src/pool.xml
index 2b890352eb..39a79e5dc5 100644
--- a/lib/stdlib/doc/src/pool.xml
+++ b/lib/stdlib/doc/src/pool.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -48,23 +48,19 @@
</description>
<funcs>
<func>
- <name>start(Name) -></name>
- <name>start(Name, Args) -> Nodes</name>
+ <name name="start" arity="1"/>
+ <name name="start" arity="2"/>
<fsummary>>Start a new pool</fsummary>
- <type>
- <v>Name = atom()</v>
- <v>Args = string()</v>
- <v>Nodes = [node()]</v>
- </type>
<desc>
<p>Starts a new pool. The file <c>.hosts.erlang</c> is read to
find host names where the pool nodes can be started. See
section <seealso marker="#files">Files</seealso> below. The
start-up procedure fails if the file is not found.</p>
<p>The slave nodes are started with <c>slave:start/2,3</c>,
- passing along <c>Name</c> and, if provided, <c>Args</c>.
- <c>Name</c> is used as the first part of the node names,
- <c>Args</c> is used to specify command line arguments. See
+ passing along <c><anno>Name</anno></c> and, if provided,
+ <c><anno>Args</anno></c>.
+ <c><anno>Name</anno></c> is used as the first part of the node names,
+ <c><anno>Args</anno></c> is used to specify command line arguments. See
<seealso marker="slave#start/2">slave(3)</seealso>.</p>
<p>Access rights must be set so that all nodes in the pool have
the authority to access each other.</p>
@@ -73,59 +69,45 @@
</desc>
</func>
<func>
- <name>attach(Node) -> already_attached | attached</name>
+ <name name="attach" arity="1"/>
<fsummary>Ensure that a pool master is running</fsummary>
- <type>
- <v>Node = node()</v>
- </type>
<desc>
<p>This function ensures that a pool master is running and
- includes <c>Node</c> in the pool master's pool of nodes.</p>
+ includes <c><anno>Node</anno></c> in the pool master's pool of nodes.</p>
</desc>
</func>
<func>
- <name>stop() -> stopped</name>
+ <name name="stop" arity="0"/>
<fsummary>Stop the pool and kill all the slave nodes</fsummary>
<desc>
<p>Stops the pool and kills all the slave nodes.</p>
</desc>
</func>
<func>
- <name>get_nodes() -> Nodes</name>
+ <name name="get_nodes" arity="0"/>
<fsummary>Return a list of the current member nodes of the pool</fsummary>
- <type>
- <v>Nodes = [node()]</v>
- </type>
<desc>
<p>Returns a list of the current member nodes of the pool.</p>
</desc>
</func>
<func>
- <name>pspawn(Mod, Fun, Args) -> pid()</name>
+ <name name="pspawn" arity="3"/>
<fsummary>Spawn a process on the pool node with expected lowest future load</fsummary>
- <type>
- <v>Mod = Fun = atom()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
<p>Spawns a process on the pool node which is expected to have
the lowest future load.</p>
</desc>
</func>
<func>
- <name>pspawn_link(Mod, Fun, Args) -> pid()</name>
+ <name name="pspawn_link" arity="3"/>
<fsummary>Spawn and link to a process on the pool node with expected lowest future load</fsummary>
- <type>
- <v>Mod = Fun = atom()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
<p>Spawn links a process on the pool node which is expected to
have the lowest future load.</p>
</desc>
</func>
<func>
- <name>get_node() -> node()</name>
+ <name name="get_node" arity="0"/>
<fsummary>Return the node with the expected lowest future load</fsummary>
<desc>
<p>Returns the node with the expected lowest future load.</p>
diff --git a/lib/stdlib/doc/src/proc_lib.xml b/lib/stdlib/doc/src/proc_lib.xml
index 791001cb52..abc17c4a91 100644
--- a/lib/stdlib/doc/src/proc_lib.xml
+++ b/lib/stdlib/doc/src/proc_lib.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -60,19 +60,33 @@
information regarding other processes which terminate as a result
of this process terminating.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="spawn_option"/>
+ <desc>
+ <p>See <seealso marker="erts:erlang#spawn_opt/4">
+ erlang:spawn_opt/2,3,4,5</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="priority_level"/>
+ </datatype>
+ <datatype>
+ <name name="dict_or_pid"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>spawn(Fun) -> pid()</name>
- <name>spawn(Node, Fun) -> pid()</name>
- <name>spawn(Module, Function, Args) -> pid()</name>
- <name>spawn(Node, Module, Function, Args) -> pid()</name>
+ <name name="spawn" arity="1"/>
+ <name name="spawn" arity="2"/>
+ <name name="spawn" arity="3"/>
+ <name name="spawn" arity="4"/>
<fsummary>Spawn a new process.</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Fun = fun() -> void()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- </type>
+ <type variable="Node"/>
+ <type variable="Fun" name_i="1"/>
+ <type variable="Module"/>
+ <type variable="Function"/>
+ <type variable="Args"/>
<desc>
<p>Spawns a new process and initializes it as described above.
The process is spawned using the
@@ -80,17 +94,16 @@
</desc>
</func>
<func>
- <name>spawn_link(Fun) -> pid()</name>
- <name>spawn_link(Node, Fun) -> pid()</name>
- <name>spawn_link(Module, Function, Args) -> pid()</name>
- <name>spawn_link(Node, Module, Function, Args) -> pid()</name>
+ <name name="spawn_link" arity="1"/>
+ <name name="spawn_link" arity="2"/>
+ <name name="spawn_link" arity="3"/>
+ <name name="spawn_link" arity="4"/>
<fsummary>Spawn and link to a new process.</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Fun = fun() -> void()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- </type>
+ <type variable="Node"/>
+ <type variable="Fun" name_i="1"/>
+ <type variable="Module"/>
+ <type variable="Function"/>
+ <type variable="Args"/>
<desc>
<p>Spawns a new process and initializes it as described above.
The process is spawned using the
@@ -99,18 +112,17 @@
</desc>
</func>
<func>
- <name>spawn_opt(Fun, SpawnOpts) -> pid()</name>
- <name>spawn_opt(Node, Fun, SpawnOpts) -> pid()</name>
- <name>spawn_opt(Module, Function, Args, SpawnOpts) -> pid()</name>
- <name>spawn_opt(Node, Module, Func, Args, SpawnOpts) -> pid()</name>
+ <name name="spawn_opt" arity="2"/>
+ <name name="spawn_opt" arity="3"/>
+ <name name="spawn_opt" arity="4"/>
+ <name name="spawn_opt" arity="5"/>
<fsummary>Spawn a new process with given options.</fsummary>
- <type>
- <v>Node = node()</v>
- <v>Fun = fun() -> void()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>SpawnOpts -- see erlang:spawn_opt/2,3,4,5</v>
- </type>
+ <type variable="Node"/>
+ <type variable="Fun" name_i="1"/>
+ <type variable="Module"/>
+ <type variable="Function"/>
+ <type variable="Args"/>
+ <type variable="SpawnOpts"/>
<desc>
<p>Spawns a new process and initializes it as described above.
The process is spawned using the
@@ -124,20 +136,13 @@
</desc>
</func>
<func>
- <name>start(Module, Function, Args) -> Ret</name>
- <name>start(Module, Function, Args, Time) -> Ret</name>
- <name>start(Module, Function, Args, Time, SpawnOpts) -> Ret</name>
- <name>start_link(Module, Function, Args) -> Ret</name>
- <name>start_link(Module, Function, Args, Time) -> Ret</name>
- <name>start_link(Module, Function, Args, Time, SpawnOpts) -> Ret</name>
+ <name name="start" arity="3"/>
+ <name name="start" arity="4"/>
+ <name name="start" arity="5"/>
+ <name name="start_link" arity="3"/>
+ <name name="start_link" arity="4"/>
+ <name name="start_link" arity="5"/>
<fsummary>Start a new process synchronously.</fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- <v>Time = int() >= 0 | infinity</v>
- <v>SpawnOpts -- see erlang:spawn_opt/2,3,4,5</v>
- <v>Ret = term() | {error, Reason}</v>
- </type>
<desc>
<p>Starts a new process synchronously. Spawns the process and
waits for it to start. When the process has started, it
@@ -148,13 +153,13 @@
function. At this time, <c>Ret</c> is returned.</p>
<p>If the <c>start_link/3,4,5</c> function is used and
the process crashes before it has called <c>init_ack/1,2</c>,
- <c>{error, Reason}</c> is returned if the calling process
+ <c>{error, <anno>Reason</anno>}</c> is returned if the calling process
traps exits.</p>
- <p>If <c>Time</c> is specified as an integer, this function
- waits for <c>Time</c> milliseconds for the new process to call
+ <p>If <c><anno>Time</anno></c> is specified as an integer, this function
+ waits for <c><anno>Time</anno></c> milliseconds for the new process to call
<c>init_ack</c>, or <c>{error, timeout}</c> is returned, and
the process is killed.</p>
- <p>The <c>SpawnOpts</c> argument, if given, will be passed
+ <p>The <c><anno>SpawnOpts</anno></c> argument, if given, will be passed
as the last argument to the <c>spawn_opt/2,3,4,5</c> BIF.</p>
<note>
<p>Using the spawn option <c>monitor</c> is currently not
@@ -164,17 +169,13 @@
</desc>
</func>
<func>
- <name>init_ack(Parent, Ret) -> void()</name>
- <name>init_ack(Ret) -> void()</name>
+ <name name="init_ack" arity="1"/>
+ <name name="init_ack" arity="2"/>
<fsummary>Used by a process when it has started.</fsummary>
- <type>
- <v>Parent = pid()</v>
- <v>Ret = term()</v>
- </type>
<desc>
<p>This function must used by a process that has been started by
a <seealso marker="#start/3">start[_link]/3,4,5</seealso>
- function. It tells <c>Parent</c> that the process has
+ function. It tells <c><anno>Parent</anno></c> that the process has
initialized itself, has started, or has failed to initialize
itself.</p>
<p>The <c>init_ack/1</c> function uses the parent value
@@ -205,40 +206,30 @@ init(Parent) ->
</desc>
</func>
<func>
- <name>format(CrashReport) -> string()</name>
+ <name name="format" arity="1"/>
<fsummary>Format a crash report.</fsummary>
- <type>
- <v>CrashReport = term()</v>
- </type>
<desc>
<p>This function can be used by a user defined event handler to
format a crash report. The crash report is sent using
- <c>error_logger:error_report(crash_report, CrashReport)</c>.
+ <c>error_logger:error_report(crash_report, <anno>CrashReport</anno>)</c>.
That is, the event to be handled is of the format
- <c>{error_report, GL, {Pid, crash_report, CrashReport}}</c>
+ <c>{error_report, GL, {Pid, crash_report, <anno>CrashReport</anno>}}</c>
where <c>GL</c> is the group leader pid of the process
<c>Pid</c> which sent the crash report.</p>
</desc>
</func>
<func>
- <name>initial_call(Process) -> {Module,Function,Args} | false</name>
+ <name name="initial_call" arity="1"/>
<fsummary>Extract the initial call of a <c>proc_lib</c>spawned process.</fsummary>
- <type>
- <v>Process = pid() | {X,Y,Z} | ProcInfo</v>
- <v>&nbsp;X = Y = Z = int()</v>
- <v>&nbsp;ProcInfo = term()</v>
- <v>Module = Function = atom()</v>
- <v>Args = [atom()]</v>
- </type>
<desc>
<p>Extracts the initial call of a process that was started
using one of the spawn or start functions described above.
- <c>Process</c> can either be a pid, an integer tuple (from
+ <c><anno>Process</anno></c> can either be a pid, an integer tuple (from
which a pid can be created), or the process information of a
process <c>Pid</c> fetched through an
<c>erlang:process_info(Pid)</c> function call.</p>
- <note><p>The list <c>Args</c> no longer contains the actual arguments,
+ <note><p>The list <c><anno>Args</anno></c> no longer contains the actual arguments,
but the same number of atoms as the number of arguments; the first atom
is always <c>'Argument__1'</c>, the second <c>'Argument__2'</c>, and
so on. The reason is that the argument list could waste a significant
@@ -256,23 +247,15 @@ init(Parent) ->
</desc>
</func>
<func>
- <name>translate_initial_call(Process) -> {Module,Function,Arity} | Fun</name>
+ <name name="translate_initial_call" arity="1"/>
<fsummary>Extract and translate the initial call of a <c>proc_lib</c>spawned process.</fsummary>
- <type>
- <v>Process = pid() | {X,Y,Z} | ProcInfo</v>
- <v>&nbsp;X = Y = Z = int()</v>
- <v>&nbsp;ProcInfo = term()</v>
- <v>Module = Function = atom()</v>
- <v>Arity = int()</v>
- <v>Fun = fun() -> void()</v>
- </type>
<desc>
<p>This function is used by the <c>c:i/0</c> and
<c>c:regs/0</c> functions in order to present process
information.</p>
<p>Extracts the initial call of a process that was started
using one of the spawn or start functions described above,
- and translates it to more useful information. <c>Process</c>
+ and translates it to more useful information. <c><anno>Process</anno></c>
can either be a pid, an integer tuple (from which a pid can
be created), or the process information of a process
<c>Pid</c> fetched through an <c>erlang:process_info(Pid)</c>
@@ -280,15 +263,15 @@ init(Parent) ->
<p>If the initial call is to one of the system defined behaviors
such as <c>gen_server</c> or <c>gen_event</c>, it is
translated to more useful information. If a <c>gen_server</c>
- is spawned, the returned <c>Module</c> is the name of
- the callback module and <c>Function</c> is <c>init</c>
+ is spawned, the returned <c><anno>Module</anno></c> is the name of
+ the callback module and <c><anno>Function</anno></c> is <c>init</c>
(the function that initiates the new server).</p>
<p>A <c>supervisor</c> and a <c>supervisor_bridge</c> are also
<c>gen_server</c> processes. In order to return information
that this process is a supervisor and the name of the
- call-back module, <c>Module</c> is <c>supervisor</c> and
- <c>Function</c> is the name of the supervisor callback
- module. <c>Arity</c> is <c>1</c> since the <c>init/1</c>
+ call-back module, <c><anno>Module</anno></c> is <c>supervisor</c> and
+ <c><anno>Function</anno></c> is the name of the supervisor callback
+ module. <c><anno>Arity</anno></c> is <c>1</c> since the <c>init/1</c>
function is called initially in the callback module.</p>
<p>By default, <c>{proc_lib,init_p,5}</c> is returned if no
information about the initial call can be found. It is
@@ -297,12 +280,8 @@ init(Parent) ->
</desc>
</func>
<func>
- <name>hibernate(Module, Function, Args)</name>
+ <name name="hibernate" arity="3"/>
<fsummary>Hibernate a process until a message is sent to it</fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
<p>This function does the same as (and does call) the BIF
<seealso marker="erts:erlang#erlang:hibernate/3">hibernate/3</seealso>,
diff --git a/lib/stdlib/doc/src/proplists.xml b/lib/stdlib/doc/src/proplists.xml
index 9f1c5b24ad..225c5e97eb 100644
--- a/lib/stdlib/doc/src/proplists.xml
+++ b/lib/stdlib/doc/src/proplists.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2002</year><year>2010</year>
+ <year>2002</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -48,14 +48,15 @@
words, numbers are compared literally rather than by value, so that,
for instance, <c>1</c> and <c>1.0</c> are different keys.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="property"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>append_values(Key, List) -> List</name>
+ <name name="append_values" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Similar to <c>get_all_values/2</c>, but each value is
wrapped in a list unless it is already itself a list, and the
@@ -65,11 +66,8 @@
</desc>
</func>
<func>
- <name>compact(List) -> List</name>
+ <name name="compact" arity="1"/>
<fsummary></fsummary>
- <type>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Minimizes the representation of all entries in the list. This is
equivalent to <c><![CDATA[[property(P) || P <- List]]]></c>.</p>
@@ -77,33 +75,24 @@
</desc>
</func>
<func>
- <name>delete(Key, List) -> List</name>
+ <name name="delete" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Deletes all entries associated with <c>Key</c> from
- <c>List</c>.</p>
+ <p>Deletes all entries associated with <c><anno>Key</anno></c> from
+ <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>expand(Expansions, List) -> List</name>
+ <name name="expand" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>Expansions = [{Property,[term()]}]</v>
- <v>Property = atom() | tuple()</v>
- </type>
<desc>
<p>Expands particular properties to corresponding sets of
- properties (or other terms). For each pair <c>{Property, Expansion}</c> in <c>Expansions</c>, if <c>E</c> is
- the first entry in <c>List</c> with the same key as
- <c>Property</c>, and <c>E</c> and <c>Property</c>
+ properties (or other terms). For each pair <c>{<anno>Property</anno>, <anno>Expansion</anno>}</c> in <c><anno>Expansions</anno></c>, if <c>E</c> is
+ the first entry in <c><anno>List</anno></c> with the same key as
+ <c><anno>Property</anno></c>, and <c>E</c> and <c><anno>Property</anno></c>
have equivalent normal forms, then <c>E</c> is replaced with
- the terms in <c>Expansion</c>, and any following entries with
- the same key are deleted from <c>List</c>.</p>
+ the terms in <c><anno>Expansion</anno></c>, and any following entries with
+ the same key are deleted from <c><anno>List</anno></c>.</p>
<p>For example, the following expressions all return <c>[fie, bar, baz, fum]</c>:</p>
<code type="none">
expand([{foo, [bar, baz]}],
@@ -120,103 +109,75 @@
<p>Note that if the original property term is to be preserved in the
result when expanded, it must be included in the expansion list. The
inserted terms are not expanded recursively. If
- <c>Expansions</c> contains more than one property with the same
+ <c><anno>Expansions</anno></c> contains more than one property with the same
key, only the first occurrence is used.</p>
<p>See also: <c>normalize/2</c>.</p>
</desc>
</func>
<func>
- <name>get_all_values(Key, List) -> [term()]</name>
+ <name name="get_all_values" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Similar to <c>get_value/2</c>, but returns the list of
values for <em>all</em> entries <c>{Key, Value}</c> in
- <c>List</c>. If no such entry exists, the result is the empty
+ <c><anno>List</anno></c>. If no such entry exists, the result is the empty
list.</p>
<p>See also: <c>get_value/2</c>.</p>
</desc>
</func>
<func>
- <name>get_bool(Key, List) -> bool()</name>
+ <name name="get_bool" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Returns the value of a boolean key/value option. If
- <c>lookup(Key, List)</c> would yield <c>{Key, true}</c>,
+ <c>lookup(<anno>Key</anno>, <anno>List</anno>)</c> would yield <c>{<anno>Key</anno>, true}</c>,
this function returns <c>true</c>; otherwise <c>false</c>
is returned.</p>
<p>See also: <c>get_value/2</c>, <c>lookup/2</c>.</p>
</desc>
</func>
<func>
- <name>get_keys(List) -> [term()]</name>
+ <name name="get_keys" arity="1"/>
<fsummary></fsummary>
- <type>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns an unordered list of the keys used in <c>List</c>,
+ <p>Returns an unordered list of the keys used in <c><anno>List</anno></c>,
not containing duplicates.</p>
</desc>
</func>
<func>
- <name>get_value(Key, List) -> term()</name>
+ <name name="get_value" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Equivalent to <c>get_value(Key, List, undefined)</c>.</p>
+ <p>Equivalent to <c>get_value(<anno>Key</anno>, <anno>List</anno>, undefined)</c>.</p>
</desc>
</func>
<func>
- <name>get_value(Key, List, Default) -> term()</name>
+ <name name="get_value" arity="3"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>Default = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Returns the value of a simple key/value property in
- <c>List</c>. If <c>lookup(Key, List)</c> would yield
- <c>{Key, Value}</c>, this function returns the corresponding
- <c>Value</c>, otherwise <c>Default</c> is returned.</p>
+ <c><anno>List</anno></c>. If <c>lookup(<anno>Key</anno>, <anno>List</anno>)</c> would yield
+ <c>{<anno>Key</anno>, Value}</c>, this function returns the corresponding
+ <c>Value</c>, otherwise <c><anno>Default</anno></c> is returned.</p>
<p>See also: <c>get_all_values/2</c>, <c>get_bool/2</c>,
<c>get_value/2</c>, <c>lookup/2</c>.</p>
</desc>
</func>
<func>
- <name>is_defined(Key, List) -> bool()</name>
+ <name name="is_defined" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>List</c> contains at least
- one entry associated with <c>Key</c>, otherwise
+ <p>Returns <c>true</c> if <c><anno>List</anno></c> contains at least
+ one entry associated with <c><anno>Key</anno></c>, otherwise
<c>false</c> is returned.</p>
</desc>
</func>
<func>
- <name>lookup(Key, List) -> none | tuple()</name>
+ <name name="lookup" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns the first entry associated with <c>Key</c> in
- <c>List</c>, if one exists, otherwise returns
+ <p>Returns the first entry associated with <c><anno>Key</anno></c> in
+ <c><anno>List</anno></c>, if one exists, otherwise returns
<c>none</c>. For an atom <c>A</c> in the list, the tuple
<c>{A, true}</c> is the entry associated with <c>A</c>.</p>
<p>See also: <c>get_bool/2</c>, <c>get_value/2</c>,
@@ -224,34 +185,20 @@
</desc>
</func>
<func>
- <name>lookup_all(Key, List) -> [tuple()]</name>
+ <name name="lookup_all" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns the list of all entries associated with <c>Key</c>
- in <c>List</c>. If no such entry exists, the result is the
+ <p>Returns the list of all entries associated with <c><anno>Key</anno></c>
+ in <c><anno>List</anno></c>. If no such entry exists, the result is the
empty list.</p>
<p>See also: <c>lookup/2</c>.</p>
</desc>
</func>
<func>
- <name>normalize(List, Stages) -> List</name>
+ <name name="normalize" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>List = [term()]</v>
- <v>Stages = [Operation]</v>
- <v>Operation = {aliases, Aliases} | {negations, Negations} | {expand, Expansions}</v>
- <v>Aliases = [{Key, Key}]</v>
- <v>Negations = [{Key, Key}]</v>
- <v>Key = term()</v>
- <v>Expansions = [{Property, [term()]}]</v>
- <v>Property = atom() | tuple()</v>
- </type>
<desc>
- <p>Passes <c>List</c> through a sequence of
+ <p>Passes <c><anno>List</anno></c> through a sequence of
substitution/expansion stages. For an <c>aliases</c> operation,
the function <c>substitute_aliases/2</c> is applied using the
given list of aliases; for a <c>negations</c> operation,
@@ -270,51 +217,37 @@
</desc>
</func>
<func>
- <name>property(Property) -> Property</name>
+ <name name="property" arity="1"/>
<fsummary></fsummary>
- <type>
- <v>Property = atom() | tuple()</v>
- </type>
<desc>
<p>Creates a normal form (minimal) representation of a property. If
- <c>Property</c> is <c>{Key, true}</c> where <c>Key</c> is
+ <c><anno>Property</anno></c> is <c>{Key, true}</c> where <c>Key</c> is
an atom, this returns <c>Key</c>, otherwise the whole term
- <c>Property</c> is returned.</p>
+ <c><anno>Property</anno></c> is returned.</p>
<p>See also: <c>property/2</c>.</p>
</desc>
</func>
<func>
- <name>property(Key, Value) -> Property</name>
+ <name name="property" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Key = term()</v>
- <v>Value = term()</v>
- <v>Property = atom() | tuple()</v>
- </type>
<desc>
<p>Creates a normal form (minimal) representation of a simple
- key/value property. Returns <c>Key</c> if <c>Value</c> is
- <c>true</c> and <c>Key</c> is an atom, otherwise a tuple
- <c>{Key, Value}</c> is returned.</p>
+ key/value property. Returns <c><anno>Key</anno></c> if <c><anno>Value</anno></c> is
+ <c>true</c> and <c><anno>Key</anno></c> is an atom, otherwise a tuple
+ <c>{<anno>Key</anno>, <anno>Value</anno>}</c> is returned.</p>
<p>See also: <c>property/1</c>.</p>
</desc>
</func>
<func>
- <name>split(List, Keys) -> {Lists, Rest}</name>
+ <name name="split" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>List = [term()]</v>
- <v>Keys = [term()]</v>
- <v>Lists = [[term()]]</v>
- <v>Rest = [term()]</v>
- </type>
<desc>
- <p>Partitions <c>List</c> into a list of sublists and a
- remainder. <c>Lists</c> contains one sublist for each key in
- <c>Keys</c>, in the corresponding order. The relative order of
+ <p>Partitions <c><anno>List</anno></c> into a list of sublists and a
+ remainder. <c><anno>Lists</anno></c> contains one sublist for each key in
+ <c><anno>Keys</anno></c>, in the corresponding order. The relative order of
the elements in each sublist is preserved from the original
- <c>List</c>. <c>Rest</c> contains the elements in
- <c>List</c> that are not associated with any of the given keys,
+ <c><anno>List</anno></c>. <c><anno>Rest</anno></c> contains the elements in
+ <c><anno>List</anno></c> that are not associated with any of the given keys,
also with their original relative order preserved.</p>
<p>Example:
split([{c, 2}, {e, 1}, a, {c, 3, 4}, d, {b, 5}, b], [a, b, c])</p>
@@ -323,19 +256,14 @@
</desc>
</func>
<func>
- <name>substitute_aliases(Aliases, List) -> List</name>
+ <name name="substitute_aliases" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Aliases = [{Key, Key}]</v>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Substitutes keys of properties. For each entry in
- <c>List</c>, if it is associated with some key <c>K1</c>
- such that <c>{K1, K2}</c> occurs in <c>Aliases</c>, the
- key of the entry is changed to <c>Key2</c>. If the same
- <c>K1</c> occurs more than once in <c>Aliases</c>, only
+ <c><anno>List</anno></c>, if it is associated with some key <c>K1</c>
+ such that <c>{K1, K2}</c> occurs in <c><anno>Aliases</anno></c>, the
+ key of the entry is changed to <c>K2</c>. If the same
+ <c>K1</c> occurs more than once in <c><anno>Aliases</anno></c>, only
the first occurrence is used.</p>
<p>Example: <c>substitute_aliases([{color, colour}], L)</c>
will replace all tuples <c>{color, ...}</c> in <c>L</c>
@@ -345,24 +273,19 @@
</desc>
</func>
<func>
- <name>substitute_negations(Negations, List) -> List</name>
+ <name name="substitute_negations" arity="2"/>
<fsummary></fsummary>
- <type>
- <v>Negations = [{Key, Key}]</v>
- <v>Key = term()</v>
- <v>List = [term()]</v>
- </type>
<desc>
<p>Substitutes keys of boolean-valued properties and
simultaneously negates their values. For each entry in
- <c>List</c>, if it is associated with some key <c>K1</c>
- such that <c>{K1, K2}</c> occurs in <c>Negations</c>, then
+ <c><anno>List</anno></c>, if it is associated with some key <c>K1</c>
+ such that <c>{K1, K2}</c> occurs in <c><anno>Negations</anno></c>, then
if the entry was <c>{K1, true}</c> it will be replaced with
<c>{K2, false}</c>, otherwise it will be replaced with
<c>{K2, true}</c>, thus changing the name of the option and
simultaneously negating the value given by
<c>get_bool(List)</c>. If the same <c>K1</c> occurs more
- than once in <c>Negations</c>, only the first occurrence is
+ than once in <c><anno>Negations</anno></c>, only the first occurrence is
used.</p>
<p>Example: <c>substitute_negations([{no_foo, foo}], L)</c>
will replace any atom <c>no_foo</c> or tuple
@@ -374,13 +297,10 @@
</desc>
</func>
<func>
- <name>unfold(List) -> List</name>
+ <name name="unfold" arity="1"/>
<fsummary></fsummary>
- <type>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Unfolds all occurrences of atoms in <c>List</c> to tuples
+ <p>Unfolds all occurrences of atoms in <c><anno>List</anno></c> to tuples
<c>{Atom, true}</c>.</p>
</desc>
</func>
diff --git a/lib/stdlib/doc/src/qlc.xml b/lib/stdlib/doc/src/qlc.xml
index da24ee9914..6a45ade447 100644
--- a/lib/stdlib/doc/src/qlc.xml
+++ b/lib/stdlib/doc/src/qlc.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2004</year><year>2009</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -45,7 +45,9 @@
tables</em>. Typical QLC tables are ETS, Dets, and Mnesia
tables. There is also support for user defined tables, see the
<seealso marker="#implementing_a_qlc_table">Implementing a QLC
- table</seealso> section. A <em>query</em> is stated using
+ table</seealso> section. <marker
+ id="query_list_comprehension"></marker>
+ A <em>query</em> is stated using
<em>Query List Comprehensions</em> (QLCs). The answers to a
query are determined by data in QLC tables that fulfill the
constraints expressed by the QLCs of the query. QLCs are similar
@@ -55,10 +57,11 @@
fact, in the absence of optimizations and options such as
<c>cache</c> and <c>unique</c> (see below), every QLC free of
QLC tables evaluates to the same list of answers as the
- identical ordinary list comprehension. </p>
+ identical ordinary list comprehension.</p>
<p>While ordinary list comprehensions evaluate to lists, calling
- <seealso marker="#q">qlc:q/1,2</seealso> returns a <em>Query
+ <seealso marker="#q">qlc:q/1,2</seealso> returns a <marker
+ id="query_handle"></marker><em> Query
Handle</em>. To obtain all the answers to a query, <seealso
marker="#eval">qlc:eval/1,2</seealso> should be called with the
query handle as first argument. Query handles are essentially
@@ -69,7 +72,8 @@
Code replacement is described in the <seealso
marker="doc/reference_manual:code_loading">Erlang Reference
Manual</seealso>. The list of answers can also be traversed in
- chunks by use of a <em>Query Cursor</em>. Query cursors are
+ chunks by use of a <marker
+ id="query_cursor"></marker><em>Query Cursor</em>. Query cursors are
created by calling <seealso
marker="#cursor">qlc:cursor/1,2</seealso> with a query handle as
first argument. Query cursors are essentially Erlang processes.
@@ -226,75 +230,6 @@
</section>
- <section><title>Common data types</title>
-
- <list type="bulleted">
- <item><p><c>QueryCursor = {qlc_cursor, term()}</c></p>
- </item>
- <item><p><c>QueryHandle = {qlc_handle, term()}</c></p>
- </item>
- <item><p><c>QueryHandleOrList = QueryHandle | list()</c></p>
- </item>
- <item><p><c>Answers = [Answer]</c></p>
- </item>
- <item><p><c>Answer = term()</c></p>
- </item>
- <item><p><c>AbstractExpression =&nbsp;</c> -&nbsp;parse trees
- for Erlang expressions, see the <seealso
- marker="erts:absform">abstract format</seealso>
- documentation in the ERTS User's Guide&nbsp;-</p>
- </item>
- <item><p><c>MatchExpression =&nbsp;</c>
- -&nbsp;match&nbsp;specifications, see the <seealso
- marker="erts:match_spec">match specification</seealso>
- documentation in the ERTS User's Guide and <seealso
- marker="ms_transform">ms_transform(3)</seealso>&nbsp;-</p>
- </item>
- <item><p><c>SpawnOptions = default | spawn_options()</c></p>
- </item>
- <item><p><c>SortOptions = [SortOption] | SortOption</c></p>
- </item>
- <item><p><c>SortOption = {compressed, bool()}
- | {no_files, NoFiles}
- | {order, Order}
- | {size, Size}
- | {tmpdir, TempDirectory}
- | {unique, bool()}&nbsp;</c>
- -&nbsp;see <seealso
- marker="file_sorter">file_sorter(3)</seealso>&nbsp;-</p>
- </item>
- <item><p><c>Order = ascending | descending | OrderFun</c></p>
- </item>
- <item><p><c>OrderFun = fun(term(), term()) -> bool()</c></p>
- </item>
- <item><p><c>TempDirectory = "" | filename()</c></p>
- </item>
- <item><p><c>Size = int() > 0</c></p>
- </item>
- <item><p><c>NoFiles = int() > 1</c></p>
- </item>
- <item><p><c>KeyPos = int() > 0 | [int() > 0]</c></p>
- </item>
- <item><p><c>MaxListSize = int() >= 0</c></p>
- </item>
- <item><p><c>bool() = true | false</c></p>
- </item>
- <item><p><c>Cache = ets | list | no</c></p>
- </item>
- <item><p><c>TmpFileUsage = allowed | not_allowed | info_msg
- | warning_msg | error_msg</c></p>
- </item>
- <item><p><c>filename() =&nbsp;</c> -&nbsp;see <seealso
- marker="filename">filename(3)</seealso>&nbsp;-</p>
- </item>
- <item><p><c>spawn_options() =&nbsp;</c> -&nbsp;see <seealso
- marker="erts:erlang">erlang(3)</seealso>&nbsp;-</p>
- </item>
-
- </list>
-
- </section>
-
<section><title>Getting started</title>
<p><marker id="getting_started"></marker> As already mentioned
@@ -679,34 +614,105 @@ ets:match_spec_run(ets:lookup(86033, {2,2}),
</section>
+ <datatypes>
+ <datatype>
+ <name name="abstract_expr"></name>
+ <desc><p>Parse trees for Erlang expression, see the <seealso
+ marker="erts:absform">abstract format</seealso>
+ documentation in the ERTS User's Guide.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="answer"></name>
+ </datatype>
+ <datatype>
+ <name name="answers"></name>
+ </datatype>
+ <datatype>
+ <name name="cache"></name>
+ </datatype>
+ <datatype>
+ <name name="match_expression"></name>
+ <desc><p>Match&nbsp;specification, see the <seealso
+ marker="erts:match_spec">match specification</seealso>
+ documentation in the ERTS User's Guide and <seealso
+ marker="ms_transform">ms_transform(3).</seealso></p></desc>
+ </datatype>
+ <datatype>
+ <name name="no_files"></name>
+ <desc><p>Actually an integer > 1.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="key_pos"></name>
+ </datatype>
+ <datatype>
+ <name name="max_list_size"></name>
+ </datatype>
+ <datatype>
+ <name name="order"></name>
+ </datatype>
+ <datatype>
+ <name name="order_fun"></name>
+ </datatype>
+ <datatype>
+ <name name="query_cursor"></name>
+ <desc><p>A <seealso marker="#query_cursor">query cursor</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="query_handle"></name>
+ <desc><p>A <seealso marker="#query_handle">query handle</seealso>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="query_handle_or_list"></name>
+ </datatype>
+ <datatype>
+ <name name="query_list_comprehension"></name>
+ <desc><p>A literal
+ <seealso marker="#query_list_comprehension">query
+ list comprehension</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="spawn_options"></name>
+ </datatype>
+ <datatype>
+ <name name="sort_options"></name>
+ </datatype>
+ <datatype>
+ <name name="sort_option"></name>
+ <desc><p>See <seealso
+ marker="file_sorter">file_sorter(3)</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="tmp_directory"></name>
+ </datatype>
+ <datatype>
+ <name name="tmp_file_usage"></name>
+ <desc><p></p></desc>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
- <name>append(QHL) -> QH</name>
+ <name name="append" arity="1"/>
<fsummary>Return a query handle.</fsummary>
- <type>
- <v>QHL = [QueryHandleOrList]</v>
- <v>QH = QueryHandle</v>
- </type>
<desc>
<p>Returns a query handle. When evaluating the query handle
- <c>QH</c> all answers to the first query handle in
- <c>QHL</c> is returned followed by all answers to the rest
- of the query handles in <c>QHL</c>.</p>
+ <c><anno>QH</anno></c> all answers to the first query handle in
+ <c><anno>QHL</anno></c> are returned followed by all answers
+ to the rest of the query handles in <c><anno>QHL</anno></c>.</p>
</desc>
</func>
<func>
- <name>append(QH1, QH2) -> QH3</name>
+ <name name="append" arity="2"/>
<fsummary>Return a query handle.</fsummary>
- <type>
- <v>QH1 = QH2 = QueryHandleOrList</v>
- <v>QH3 = QueryHandle</v>
- </type>
<desc>
<p>Returns a query handle. When evaluating the query handle
- <c>QH3</c> all answers to <c>QH1</c> are returned followed
- by all answers to <c>QH2</c>.</p>
+ <c><anno>QH3</anno></c> all answers to
+ <c><anno>QH1</anno></c> are returned followed by all answers
+ to <c><anno>QH2</anno></c>.</p>
<p><c>append(QH1,&nbsp;QH2)</c> is equivalent to
<c>append([QH1,&nbsp;QH2])</c>.</p>
@@ -714,17 +720,9 @@ ets:match_spec_run(ets:lookup(86033, {2,2}),
</func>
<func>
- <name>cursor(QueryHandleOrList [, Options]) -> QueryCursor</name>
+ <name name="cursor" arity="1"/>
+ <name name="cursor" arity="2"/>
<fsummary>Create a query cursor.</fsummary>
- <type>
- <v>Options = [Option] | Option</v>
- <v>Option = {cache_all, Cache} | cache_all
- | {max_list_size, MaxListSize}
- | {spawn_options, SpawnOptions}
- | {tmpdir_usage, TmpFileUsage}
- | {tmpdir, TempDirectory}
- | {unique_all, bool()} | unique_all</v>
- </type>
<desc>
<p><marker id="cursor"></marker>Creates a query cursor and
makes the calling process the owner of the cursor. The
@@ -746,11 +744,13 @@ ets:match_spec_run(ets:lookup(86033, {2,2}),
[{b,1},{b,2}]
4> <input>qlc:delete_cursor(QC).</input>
ok</pre>
+ <p><c>cursor(<anno>QH</anno>)</c> is equivalent to
+ <c>cursor(<anno>QH</anno>, [])</c>.</p>
</desc>
</func>
<func>
- <name>delete_cursor(QueryCursor) -> ok</name>
+ <name name="delete_cursor" arity="1"/>
<fsummary>Delete a query cursor.</fsummary>
<desc>
<p>Deletes a query cursor. Only the owner of the cursor can
@@ -759,19 +759,11 @@ ok</pre>
</func>
<func>
- <name>eval(QueryHandleOrList [, Options]) -> Answers | Error</name>
- <name>e(QueryHandleOrList [, Options]) -> Answers</name>
+ <name name="eval" arity="1"/>
+ <name name="eval" arity="2"/>
+ <name name="e" arity="1"/>
+ <name name="e" arity="2"/>
<fsummary>Return all answers to a query.</fsummary>
- <type>
- <v>Options = [Option] | Option</v>
- <v>Option = {cache_all, Cache} | cache_all
- | {max_list_size, MaxListSize}
- | {tmpdir_usage, TmpFileUsage}
- | {tmpdir, TempDirectory}
- | {unique_all, bool()} | unique_all</v>
- <v>Error = {error, module(), Reason}</v>
- <v>Reason =&nbsp;-&nbsp;as returned by file_sorter(3)&nbsp;-</v>
- </type>
<desc>
<p><marker id="eval"></marker>Evaluates a query handle in the
calling process and collects all answers in a list.</p>
@@ -780,47 +772,39 @@ ok</pre>
1> <input>QH = qlc:q([{X,Y} || X &lt;- [a,b], Y &lt;- [1,2]]),</input>
<input>qlc:eval(QH).</input>
[{a,1},{a,2},{b,1},{b,2}]</pre>
+ <p><c>eval(<anno>QH</anno>)</c> is equivalent to
+ <c>eval(<anno>QH</anno>, [])</c>.</p>
</desc>
</func>
<func>
- <name>fold(Function, Acc0, QueryHandleOrList [, Options]) ->
- Acc1 | Error</name>
+ <name name="fold" arity="3"/>
+ <name name="fold" arity="4"/>
<fsummary>Fold a function over the answers to a query.</fsummary>
- <type>
- <v>Function = fun(Answer, AccIn) -> AccOut</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Options = [Option] | Option</v>
- <v>Option = {cache_all, Cache} | cache_all
- | {max_list_size, MaxListSize}
- | {tmpdir_usage, TmpFileUsage}
- | {tmpdir, TempDirectory}
- | {unique_all, bool()} | unique_all</v>
- <v>Error = {error, module(), Reason}</v>
- <v>Reason =&nbsp;-&nbsp;as returned by file_sorter(3)&nbsp;-</v>
- </type>
<desc>
- <p>Calls <c>Function</c> on successive answers to the query
- handle together with an extra argument <c>AccIn</c>. The
- query handle and the function are evaluated in the calling
- process. <c>Function</c> must return a new accumulator which
- is passed to the next call. <c>Acc0</c> is returned if there
- are no answers to the query handle.</p>
+ <p>Calls <c><anno>Function</anno></c> on successive answers to
+ the query handle together with an extra argument
+ <c><anno>AccIn</anno></c>. The query handle and the function
+ are evaluated in the calling process.
+ <c><anno>Function</anno></c> must return a new accumulator
+ which is passed to the next call.
+ <c><anno>Acc0</anno></c> is returned if there are no answers
+ to the query handle.</p>
<pre>
1> <input>QH = [1,2,3,4,5,6],</input>
<input>qlc:fold(fun(X, Sum) -> X + Sum end, 0, QH).</input>
21</pre>
+ <p><c>fold(<anno>Function</anno>, <anno>Acc0</anno>,
+ <anno>QH</anno>)</c> is equivalent to
+ <c>fold(<anno>Function</anno>, <anno>Acc0</anno>,
+ <anno>QH</anno>, [])</c>.</p>
</desc>
</func>
<func>
- <name>format_error(Error) -> Chars</name>
+ <name name="format_error" arity="1"/>
<fsummary>Return an English description of a an error tuple.</fsummary>
- <type>
- <v>Error = {error, module(), term()}</v>
- <v>Chars = [char() | Chars]</v>
- </type>
<desc>
<p>Returns a descriptive string in English of an error tuple
returned by some of the functions of the <c>qlc</c> module
@@ -830,25 +814,9 @@ ok</pre>
</func>
<func>
- <name>info(QueryHandleOrList [, Options]) -> Info</name>
+ <name name="info" arity="1"/>
+ <name name="info" arity="2"/>
<fsummary>Return code describing a query handle.</fsummary>
- <type>
- <v>Options = [Option] | Option</v>
- <v>Option = EvalOption | ReturnOption</v>
- <v>EvalOption = {cache_all, Cache} | cache_all
- | {max_list_size, MaxListSize}
- | {tmpdir_usage, TmpFileUsage}
- | {tmpdir, TempDirectory}
- | {unique_all, bool()} | unique_all</v>
- <v>ReturnOption = {depth, Depth}
- | {flat, bool()}
- | {format, Format}
- | {n_elements, NElements}</v>
- <v>Depth = infinity | int() >= 0</v>
- <v>Format = abstract_code | string</v>
- <v>NElements = infinity | int() > 0</v>
- <v>Info = AbstractExpression | string()</v>
- </type>
<desc>
<p><marker id="info"></marker>Returns information about a
query handle. The information describes the simplifications
@@ -879,18 +847,18 @@ ok</pre>
<input>io:format("~s~n", [qlc:info(QH, unique_all)]).</input>
begin
V1 =
- qlc:q([
+ qlc:q([
SQV ||
SQV &lt;- [x,y]
],
[{unique,true}]),
V2 =
- qlc:q([
+ qlc:q([
SQV ||
SQV &lt;- [a,b]
],
[{unique,true}]),
- qlc:q([
+ qlc:q([
{X,Y} ||
X &lt;- V1,
Y &lt;- V2
@@ -913,19 +881,19 @@ end</pre>
<input>io:format("~s~n", [qlc:info(Q)]).</input>
begin
V1 =
- qlc:q([
+ qlc:q([
P0 ||
P0 = {W,Y} &lt;- ets:table(17)
]),
V2 =
- qlc:q([
+ qlc:q([
[G1|G2] ||
G2 &lt;- V1,
G1 &lt;- ets:table(16),
element(2, G1) =:= element(1, G2)
],
[{join,lookup}]),
- qlc:q([
+ qlc:q([
{X,Z,W} ||
[{X,Z}|{W,Y}] &lt;- V2
])
@@ -936,44 +904,43 @@ end</pre>
method chosen. A convention is used for lookup join: the
first generator (<c>G2</c>) is the one traversed, the second
one (<c>G1</c>) is the table where constants are looked up.</p>
+
+ <p><c>info(<anno>QH</anno>)</c> is equivalent to
+ <c>info(<anno>QH</anno>, [])</c>.</p>
</desc>
</func>
<func>
- <name>keysort(KeyPos, QH1 [, SortOptions]) -> QH2</name>
+ <name name="keysort" arity="2"/>
+ <name name="keysort" arity="3"/>
<fsummary>Return a query handle.</fsummary>
- <type>
- <v>QH1 = QueryHandleOrList</v>
- <v>QH2 = QueryHandle</v>
- </type>
<desc>
<p>Returns a query handle. When evaluating the query handle
- <c>QH2</c> the answers to the query handle <c>QH1</c> are
- sorted by <seealso
+ <c><anno>QH2</anno></c> the answers to the query handle
+ <c><anno>QH1</anno></c> are sorted by <seealso
marker="file_sorter">file_sorter:keysort/4</seealso>
according to the options.</p>
- <p>The sorter will use temporary files only if <c>QH1</c> does
- not evaluate to a list and the size of the binary
- representation of the answers exceeds <c>Size</c> bytes,
- where <c>Size</c> is the value of the <c>size</c> option.</p>
+ <p>The sorter will use temporary files only if
+ <c><anno>QH1</anno></c> does not evaluate to a list and the
+ size of the binary representation of the answers exceeds
+ <c>Size</c> bytes, where <c>Size</c> is the value of the
+ <c>size</c> option.</p>
+
+ <p><c>keysort(<anno>KeyPos</anno>, <anno>QH1</anno>)</c>
+ is equivalent to
+ <c>keysort(<anno>KeyPos</anno>, <anno>QH1</anno>, [])</c>.</p>
</desc>
</func>
<func>
- <name>next_answers(QueryCursor [, NumberOfAnswers]) ->
- Answers | Error</name>
+ <name name="next_answers" arity="1"/>
+ <name name="next_answers" arity="2"/>
<fsummary>Return some or all answers to a query.</fsummary>
- <type>
- <v>NumberOfAnswers = all_remaining | int() > 0</v>
- <v>Error = {error, module(), Reason}</v>
- <v>Reason =&nbsp;-&nbsp;as returned by file_sorter(3)&nbsp;-</v>
- </type>
<desc>
<p>Returns some or all of the remaining answers to a query
- cursor. Only the owner of <c>Cursor</c> can retrieve
- answers.</p>
-
+ cursor. Only the owner of <c><anno>QueryCursor</anno></c> can
+ retrieve answers.</p>
<p>The optional argument <c>NumberOfAnswers</c>determines the
maximum number of answers returned. The default value is
<c>10</c>. If less than the requested number of answers is
@@ -983,21 +950,9 @@ end</pre>
</func>
<func>
- <name>q(QueryListComprehension [, Options]) -> QueryHandle</name>
+ <name name="q" arity="1"/>
+ <name name="q" arity="2"/>
<fsummary>Return a handle for a query list comprehension.</fsummary>
- <type>
- <v>QueryListComprehension =&nbsp;
- -&nbsp;literal query listcomprehension&nbsp;-</v>
- <v>Options = [Option] | Option</v>
- <v>Option = {max_lookup, MaxLookup}
- | {cache, Cache} | cache
- | {join, Join}
- | {lookup, Lookup}
- | {unique, bool()} | unique</v>
- <v>MaxLookup = int() >= 0 | infinity</v>
- <v>Join = any | lookup | merge | nested_loop</v>
- <v>Lookup = bool() | any</v>
- </type>
<desc>
<p><marker id="q"></marker>Returns a query handle for a query
list comprehension. The query list comprehension must be the
@@ -1024,7 +979,7 @@ end</pre>
<pre>
...
-A = [X || {X} &lt;- [{1},{2}]],
+A = [X || {X} &lt;- [{1},{2}]],
QH = qlc:q(A),
...</pre>
@@ -1034,6 +989,9 @@ QH = qlc:q(A),
list comprehension"); the shell process stops with a
<c>badarg</c> reason.</p>
+ <p><c>q(<anno>QLC</anno>)</c> is equivalent to
+ <c>q(<anno>QLC</anno>, [])</c>.</p>
+
<p>The <c>{cache,&nbsp;ets}</c> option can be used to cache
the answers to a query list comprehension. The answers are
stored in one ETS table for each cached query list
@@ -1092,26 +1050,26 @@ QH = qlc:q(A),
<input>io:format("~s~n", [qlc:info(Q)]).</input>
begin
V1 =
- qlc:q([
+ qlc:q([
P0 ||
P0 = {X,Z} &lt;-
qlc:keysort(1, [{a,1},{b,4},{c,6}], [])
]),
V2 =
- qlc:q([
+ qlc:q([
P0 ||
P0 = {W,Y} &lt;-
qlc:keysort(2, [{2,a},{3,b},{4,c}], [])
]),
V3 =
- qlc:q([
+ qlc:q([
[G1|G2] ||
G1 &lt;- V1,
G2 &lt;- V2,
element(1, G1) == element(2, G2)
],
[{join,merge},{cache,list}]),
- qlc:q([
+ qlc:q([
{A,X,Z,W} ||
A &lt;- [a,b,c],
[{X,Z}|{W,Y}] &lt;- V3,
@@ -1170,7 +1128,7 @@ ets:match_spec_run(
elements of the key {X,&nbsp;Y} are compared separately.</p>
<p>The <c>{lookup,&nbsp;true}</c> option can be used to ensure
- that the <c>qlc</c> module will look up constants in some
+ that the <c>qlc</c> module will look up constants in some
QLC table. If there
are more than one QLC table among the generators' list
expressions, constants have to be looked up in at least one
@@ -1190,7 +1148,7 @@ ets:match_spec_run(
<c>{join,&nbsp;nested_loop}</c> invokes the method of
matching every pair of objects from two handles. The last
method is mostly very slow. The evaluation of the query
- fails if the <c>qlc</c> module cannot carry out the chosen
+ fails if the <c>qlc</c> module cannot carry out the chosen
join method. The
default value is <c>any</c> which means that some fast join
method will be used if possible.</p>
@@ -1198,47 +1156,33 @@ ets:match_spec_run(
</func>
<func>
- <name>sort(QH1 [, SortOptions]) -> QH2</name>
+ <name name="sort" arity="1"/>
+ <name name="sort" arity="2"/>
<fsummary>Return a query handle.</fsummary>
- <type>
- <v>QH1 = QueryHandleOrList</v>
- <v>QH2 = QueryHandle</v>
- </type>
<desc>
<p>Returns a query handle. When evaluating the query handle
- <c>QH2</c> the answers to the query handle <c>QH1</c> are
- sorted by <seealso
+ <c><anno>QH2</anno></c> the answers to the query handle
+ <c><anno>QH1</anno></c> are sorted by <seealso
marker="file_sorter">file_sorter:sort/3</seealso> according
to the options.</p>
- <p>The sorter will use temporary files only if <c>QH1</c> does
- not evaluate to a list and the size of the binary
- representation of the answers exceeds <c>Size</c> bytes,
- where <c>Size</c> is the value of the <c>size</c> option.</p>
+ <p>The sorter will use temporary files only if
+ <c><anno>QH1</anno></c> does not evaluate to a list and the
+ size of the binary representation of the answers exceeds
+ <c>Size</c> bytes, where <c>Size</c> is the value of the
+ <c>size</c> option.</p>
+
+ <p><c>sort(<anno>QH1</anno>)</c> is equivalent to
+ <c>sort(<anno>QH1</anno>, [])</c>.</p>
+
</desc>
</func>
<func>
- <name>string_to_handle(QueryString [, Options [, Bindings]]) ->
- QueryHandle | Error</name>
+ <name name="string_to_handle" arity="1"/>
+ <name name="string_to_handle" arity="2"/>
+ <name name="string_to_handle" arity="3"/>
<fsummary>Return a handle for a query list comprehension.</fsummary>
- <type>
- <v>QueryString = string()</v>
- <v>Options = [Option] | Option</v>
- <v>Option = {max_lookup, MaxLookup}
- | {cache, Cache} | cache
- | {join, Join}
- | {lookup, Lookup}
- | {unique, bool()} | unique</v>
- <v>MaxLookup = int() >= 0 | infinity</v>
- <v>Join = any | lookup | merge | nested_loop</v>
- <v>Lookup = bool() | any</v>
- <v>Bindings =&nbsp;-&nbsp;as returned by
- erl_eval:bindings/1&nbsp;-</v>
- <v>Error = {error, module(), Reason}</v>
- <v>Reason = &nbsp;-&nbsp;ErrorInfo as returned by
- erl_scan:string/1 or erl_parse:parse_exprs/1&nbsp;-</v>
- </type>
<desc>
<p>A string version of <c>qlc:q/1,2</c>. When the query handle
is evaluated the fun created by the parse transform is
@@ -1253,57 +1197,24 @@ ets:match_spec_run(
<input>qlc:eval(QH).</input>
[2,3,4]</pre>
+ <p><c>string_to_handle(<anno>QueryString</anno>)</c>
+ is equivalent to
+ <c>string_to_handle(<anno>QueryString</anno>, [])</c>.</p>
+
+ <p><c>string_to_handle(<anno>QueryString</anno>,
+ <anno>Options</anno>)</c>
+ is equivalent to
+ <c>string_to_handle(<anno>QueryString</anno>,
+ <anno>Options</anno>, erl_eval:new_bindings())</c>.</p>
+
<p>This function is probably useful mostly when called from
outside of Erlang, for instance from a driver written in C.</p>
</desc>
</func>
<func>
- <name>table(TraverseFun, Options) -> QueryHandle</name>
+ <name name="table" arity="2"/>
<fsummary>Return a query handle for a table.</fsummary>
- <type>
- <v>TraverseFun = TraverseFun0 | TraverseFun1</v>
- <v>TraverseFun0 = fun() -> TraverseResult</v>
- <v>TraverseFun1 = fun(MatchExpression) -> TraverseResult</v>
- <v>TraverseResult = Objects | term()</v>
- <v>Objects = [] | [term() | ObjectList]</v>
- <v>ObjectList = TraverseFun0 | Objects</v>
- <v>Options = [Option] | Option</v>
- <v>Option = {format_fun, FormatFun}
- | {info_fun, InfoFun}
- | {lookup_fun, LookupFun}
- | {parent_fun, ParentFun}
- | {post_fun, PostFun}
- | {pre_fun, PreFun}
- | {key_equality, KeyComparison}</v>
- <v>FormatFun = undefined | fun(SelectedObjects) -> FormatedTable</v>
- <v>SelectedObjects = all
- | {all, NElements, DepthFun}
- | {match_spec, MatchExpression}
- | {lookup, Position, Keys}
- | {lookup, Position, Keys, NElements, DepthFun}</v>
- <v>NElements = infinity | int() > 0</v>
- <v>DepthFun = fun(term()) -> term()</v>
- <v>FormatedTable = {Mod, Fun, Args}
- | AbstractExpression
- | character_list()</v>
- <v>InfoFun = undefined | fun(InfoTag) -> InfoValue</v>
- <v>InfoTag = indices | is_unique_objects | keypos | num_of_objects</v>
- <v>InfoValue = undefined | term()</v>
- <v>LookupFun = undefined | fun(Position, Keys) -> LookupResult</v>
- <v>LookupResult = [term()] | term()</v>
- <v>ParentFun = undefined | fun() -> ParentFunValue</v>
- <v>PostFun = undefined | fun() -> void()</v>
- <v>PreFun = undefined | fun([PreArg]) -> void()</v>
- <v>PreArg = {parent_value, ParentFunValue} | {stop_fun, StopFun}</v>
- <v>ParentFunValue = undefined | term()</v>
- <v>StopFun = undefined | fun() -> void()</v>
- <v>KeyComparison = '=:=' | '=='</v>
- <v>Position = int() > 0</v>
- <v>Keys = [term()]</v>
- <v>Mod = Fun = atom()</v>
- <v>Args = [term()]</v>
- </type>
<desc>
<p><marker id="table"></marker>Returns a query handle for a
QLC table. In Erlang/OTP there is support for ETS, Dets and
@@ -1315,77 +1226,90 @@ ets:match_spec_run(
as well as properties of the table are handled by callback
functions provided as options to <c>qlc:table/2</c>.</p>
- <p>The callback function <c>TraverseFun</c> is used for
- traversing the table. It is to return a list of objects
- terminated by either <c>[]</c> or a nullary fun to be used
- for traversing the not yet traversed objects of the table.
- Any other return value is immediately returned as value of
- the query evaluation. Unary <c>TraverseFun</c>s are to
- accept a match specification as argument. The match
- specification is created by the parse transform by analyzing
- the pattern of the generator calling <c>qlc:table/2</c> and
- filters using variables introduced in the pattern. If the
- parse transform cannot find a match specification equivalent
- to the pattern and filters, <c>TraverseFun</c> will be
- called with a match specification returning every object.
- Modules that can utilize match specifications for optimized
+ <p>The callback function <c><anno>TraverseFun</anno></c> is
+ used for traversing the table. It is to return a list of
+ objects terminated by either <c>[]</c> or a nullary fun to
+ be used for traversing the not yet traversed objects of the
+ table. Any other return value is immediately returned as
+ value of the query evaluation. Unary
+ <c><anno>TraverseFun</anno></c>s are to accept a match
+ specification as argument. The match specification is
+ created by the parse transform by analyzing the pattern of
+ the generator calling <c>qlc:table/2</c> and filters using
+ variables introduced in the pattern. If the parse transform
+ cannot find a match specification equivalent to the pattern
+ and filters, <c><anno>TraverseFun</anno></c> will be called
+ with a match specification returning every object. Modules
+ that can utilize match specifications for optimized
traversal of tables should call <c>qlc:table/2</c> with a
- unary <c>TraverseFun</c> while other modules can provide a
- nullary <c>TraverseFun</c>. <c>ets:table/2</c> is an example
- of the former; <c>gb_table:table/1</c> in the <seealso
- marker="#implementing_a_qlc_table">Implementing a QLC
- table</seealso> section is an example of the latter.</p>
-
- <p><c>PreFun</c> is a unary callback function that is called
- once before the table is read for the first time. If the
- call fails, the query evaluation fails. Similarly, the
- nullary callback function <c>PostFun</c> is called once
- after the table was last read. The return value, which is
- caught, is ignored. If <c>PreFun</c> has been called for a
- table, <c>PostFun</c> is guaranteed to be called for that
- table, even if the evaluation of the query fails for some
- reason. The order in which pre (post) functions for
+ unary
+ <c><anno>TraverseFun</anno></c> while other modules can
+ provide a nullary
+ <c><anno>TraverseFun</anno></c>. <c>ets:table/2</c> is an
+ example of the former; <c>gb_table:table/1</c> in the
+ <seealso marker="#implementing_a_qlc_table">Implementing a
+ QLC table</seealso> section is an example of the latter.</p>
+
+ <p><c><anno>PreFun</anno></c> is a unary callback function
+ that is called once before the table is read for the first
+ time. If the call fails, the query evaluation fails.
+ Similarly, the nullary callback function
+ <c><anno>PostFun</anno></c> is called once after the table
+ was last read. The return value, which is caught, is
+ ignored. If <c><anno>PreFun</anno></c> has been called for a
+ table,
+ <c><anno>PostFun</anno></c> is guaranteed to be called for
+ that table, even if the evaluation of the query fails for
+ some reason. The order in which pre (post) functions for
different tables are evaluated is not specified. Other table
- access than reading, such as calling <c>InfoFun</c>, is
- assumed to be OK at any time. The argument <c>PreArgs</c> is
- a list of tagged values. Currently there are two tags,
+ access than reading, such as calling
+ <c><anno>InfoFun</anno></c>, is assumed to be OK at any
+ time. The argument <c><anno>PreArgs</anno></c> is a list of
+ tagged values. Currently there are two tags,
<c>parent_value</c> and <c>stop_fun</c>, used by Mnesia for
managing transactions. The value of <c>parent_value</c> is
- the value returned by <c>ParentFun</c>, or <c>undefined</c>
- if there is no <c>ParentFun</c>. <c>ParentFun</c> is called
- once just before the call of <c>PreFun</c> in the context of
- the process calling <c>eval</c>, <c>fold</c>, or
+ the value returned by <c><anno>ParentFun</anno></c>, or
+ <c>undefined</c> if there is no <c>ParentFun</c>.
+ <c><anno>ParentFun</anno></c> is called once just before the
+ call of
+ <c><anno>PreFun</anno></c> in the context of the process
+ calling
+ <c>eval</c>, <c>fold</c>, or
<c>cursor</c>. The value of <c>stop_fun</c> is a nullary fun
that deletes the cursor if called from the parent, or
<c>undefined</c> if there is no cursor.</p>
<p><marker id="lookup_fun"></marker>The binary callback
- function <c>LookupFun</c> is used for looking up objects in
- the table. The first argument <c>Position</c> is the key
- position or an indexed position and the second argument
- <c>Keys</c> is a sorted list of unique values. The return
- value is to be a list of all objects (tuples) such that the
- element at <c>Position</c> is a member of <c>Keys</c>. Any
- other return value is immediately returned as value of the
- query evaluation. <c>LookupFun</c> is called instead of
+ function <c><anno>LookupFun</anno></c> is used for looking
+ up objects in the table. The first argument
+ <c><anno>Position</anno></c> is the key position or an
+ indexed position and the second argument
+ <c><anno>Keys</anno></c> is a sorted list of unique values.
+ The return value is to be a list of all objects (tuples)
+ such that the element at <c>Position</c> is a member of
+ <c><anno>Keys</anno></c>. Any other return value is
+ immediately returned as value of the query evaluation.
+ <c><anno>LookupFun</anno></c> is called instead of
traversing the table if the parse transform at compile time
can find out that the filters match and compare the element
- at <c>Position</c> in such a way that only <c>Keys</c> need
- to be looked up in order to find all potential answers. The
- key position is obtained by calling <c>InfoFun(keypos)</c>
- and the indexed positions by calling
- <c>InfoFun(indices)</c>. If the key position can be used for
- lookup it is always chosen, otherwise the indexed position
- requiring the least number of lookups is chosen. If there is
- a tie between two indexed positions the one occurring first
- in the list returned by <c>InfoFun</c> is chosen. Positions
- requiring more than <seealso
- marker="#max_lookup">max_lookup</seealso> lookups are
- ignored.</p>
-
- <p>The unary callback function <c>InfoFun</c> is to return
- information about the table. <c>undefined</c> should be
- returned if the value of some tag is unknown:</p>
+ at <c><anno>Position</anno></c> in such a way that only
+ <c><anno>Keys</anno></c> need to be looked up in order to
+ find all potential answers. The key position is obtained by
+ calling
+ <c><anno>InfoFun</anno>(keypos)</c> and the indexed
+ positions by calling
+ <c><anno>InfoFun</anno>(indices)</c>. If the key position
+ can be used for lookup it is always chosen, otherwise the
+ indexed position requiring the least number of lookups is
+ chosen. If there is a tie between two indexed positions the
+ one occurring first in the list returned by
+ <c><anno>InfoFun</anno></c> is chosen. Positions requiring
+ more than <seealso marker="#max_lookup">max_lookup</seealso>
+ lookups are ignored.</p>
+
+ <p>The unary callback function <c><anno>InfoFun</anno></c> is
+ to return information about the table. <c>undefined</c>
+ should be returned if the value of some tag is unknown:</p>
<list type="bulleted">
<item><c>indices</c>. Returns a list of indexed
@@ -1406,20 +1330,22 @@ ets:match_spec_run(
</item>
</list>
- <p>The unary callback function <c>FormatFun</c> is used by
- <seealso marker="#info">qlc:info/1,2</seealso> for
- displaying the call that created the table's query handle.
- The default value, <c>undefined</c>, means that
+ <p>The unary callback function <c><anno>FormatFun</anno></c>
+ is used by <seealso marker="#info">qlc:info/1,2</seealso>
+ for displaying the call that created the table's query
+ handle. The default value, <c>undefined</c>, means that
<c>info/1,2</c> displays a call to <c>'$MOD':'$FUN'/0</c>.
- It is up to <c>FormatFun</c> to present the selected objects
- of the table in a suitable way. However, if a character list
- is chosen for presentation it must be an Erlang expression
- that can be scanned and parsed (a trailing dot will be added
- by <c>qlc:info</c> though). <c>FormatFun</c> is called with
- an argument that describes the selected objects based on
- optimizations done as a result of analyzing the filters of
- the QLC where the call to <c>qlc:table/2</c> occurs. The
- possible values of the argument are:</p>
+ It is up to <c><anno>FormatFun</anno></c> to present the
+ selected objects of the table in a suitable way. However, if
+ a character list is chosen for presentation it must be an
+ Erlang expression that can be scanned and parsed (a trailing
+ dot will be added by <c>qlc:info</c> though).
+ <c><anno>FormatFun</anno></c> is called with an argument
+ that describes the selected objects based on optimizations
+ done as a result of analyzing the filters of the QLC where
+ the call to
+ <c>qlc:table/2</c> occurs. The possible values of the
+ argument are:</p>
<list type="bulleted">
<item><c>{lookup, Position, Keys, NElements, DepthFun}</c>.
@@ -1443,10 +1369,12 @@ ets:match_spec_run(
can be used for limiting the size of terms; calling
<c>DepthFun(Term)</c> substitutes <c>'...'</c> for parts of
<c>Term</c> below the depth specified by the <c>info/1,2</c>
- option <c>depth</c>. If calling <c>FormatFun</c> with an
- argument including <c>NElements</c> and <c>DepthFun</c>
- fails, <c>FormatFun</c> is called once again with an
- argument excluding <c>NElements</c> and <c>DepthFun</c>
+ option <c>depth</c>. If calling
+ <c><anno>FormatFun</anno></c> with an argument including
+ <c>NElements</c> and <c>DepthFun</c> fails,
+ <c><anno>FormatFun</anno></c> is called once again with an
+ argument excluding
+ <c>NElements</c> and <c>DepthFun</c>
(<c>{lookup,&nbsp;Position,&nbsp;Keys}</c> or
<c>all</c>).</p>
@@ -1458,7 +1386,7 @@ ets:match_spec_run(
<p>See <seealso marker="ets#qlc_table">ets(3)</seealso>,
<seealso marker="dets#qlc_table">dets(3)</seealso> and
- <seealso marker="mnesia:mnesia#qlc_table">mnesia(3)</seealso>
+ <seealso marker="mnesia:mnesia#qlc_table">mnesia(3)</seealso>
for the various options recognized by <c>table/1,2</c> in
respective module.</p>
</desc>
@@ -1472,12 +1400,12 @@ ets:match_spec_run(
<seealso marker="doc/reference_manual:users_guide">
Erlang Reference Manual</seealso>,
<seealso marker="erl_eval">erl_eval(3)</seealso>,
- <seealso marker="erts:erlang">erlang(3)</seealso>,
+ <seealso marker="erts:erlang">erlang(3)</seealso>,
<seealso marker="ets">ets(3)</seealso>,
- <seealso marker="kernel:file">file(3)</seealso>,
- <seealso marker="error_logger:file">error_logger(3)</seealso>,
+ <seealso marker="kernel:file">file(3)</seealso>,
+ <seealso marker="error_logger:file">error_logger(3)</seealso>,
<seealso marker="file_sorter">file_sorter(3)</seealso>,
- <seealso marker="mnesia:mnesia">mnesia(3)</seealso>,
+ <seealso marker="mnesia:mnesia">mnesia(3)</seealso>,
<seealso marker="doc/programming_examples:users_guide">
Programming Examples</seealso>,
<seealso marker="shell">shell(3)</seealso></p>
diff --git a/lib/stdlib/doc/src/queue.xml b/lib/stdlib/doc/src/queue.xml
index 5ada1c2c57..383f52d10d 100644
--- a/lib/stdlib/doc/src/queue.xml
+++ b/lib/stdlib/doc/src/queue.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -88,122 +88,94 @@
<title>Original API</title>
</section>
+ <datatypes>
+ <datatype>
+ <name><marker id="type-queue">queue()</marker></name>
+ <desc><p>As returned by <c>new/0</c>.</p></desc>
+ </datatype>
+ </datatypes>
+
<funcs>
<func>
- <name>new() -> Q</name>
+ <name name="new" arity="0"/>
<fsummary>Create an empty queue</fsummary>
- <type>
- <v>Q = queue()</v>
- </type>
<desc>
<p>Returns an empty queue.</p>
</desc>
</func>
<func>
- <name>is_queue(Term) -> true | false</name>
+ <name name="is_queue" arity="1"/>
<fsummary>Test if a term is a queue</fsummary>
- <type>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Tests if <c>Q</c> is a queue and returns <c>true</c> if so and
+ <p>Tests if <c><anno>Term</anno></c> is a queue and returns <c>true</c> if so and
<c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_empty(Q) -> true | false</name>
+ <name name="is_empty" arity="1"/>
<fsummary>Test if a queue is empty</fsummary>
- <type>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Tests if <c>Q</c> is empty and returns <c>true</c> if so and
+ <p>Tests if <c><anno>Q</anno></c> is empty and returns <c>true</c> if so and
<c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>len(Q) -> N</name>
+ <name name="len" arity="1"/>
<fsummary>Get the length of a queue</fsummary>
- <type>
- <v>Q = queue()</v>
- <v>N = integer()</v>
- </type>
<desc>
- <p>Calculates and returns the length of queue <c>Q</c>.</p>
+ <p>Calculates and returns the length of queue <c><anno>Q</anno></c>.</p>
</desc>
</func>
<func>
- <name>in(Item, Q1) -> Q2</name>
+ <name name="in" arity="2"/>
<fsummary>Insert an item at the rear of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Inserts <c>Item</c> at the rear of queue <c>Q1</c>.
- Returns the resulting queue <c>Q2</c>.</p>
+ <p>Inserts <c><anno>Item</anno></c> at the rear of queue <c><anno>Q1</anno></c>.
+ Returns the resulting queue <c><anno>Q2</anno></c>.</p>
</desc>
</func>
<func>
- <name>in_r(Item, Q1) -> Q2</name>
+ <name name="in_r" arity="2"/>
<fsummary>Insert an item at the front of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Inserts <c>Item</c> at the front of queue <c>Q1</c>.
- Returns the resulting queue <c>Q2</c>.</p>
+ <p>Inserts <c><anno>Item</anno></c> at the front of queue <c><anno>Q1</anno></c>.
+ Returns the resulting queue <c><anno>Q2</anno></c>.</p>
</desc>
</func>
<func>
- <name>out(Q1) -> Result</name>
+ <name name="out" arity="1"/>
<fsummary>Remove the front item from a queue</fsummary>
- <type>
- <v>Result = {{value, Item}, Q2} | {empty, Q1}</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Removes the item at the front of queue <c>Q1</c>. Returns the
- tuple <c>{{value, Item}, Q2}</c>, where <c>Item</c> is the
- item removed and <c>Q2</c> is the resulting queue. If <c>Q1</c> is
- empty, the tuple <c>{empty, Q1}</c> is returned.</p>
+ <p>Removes the item at the front of queue <c><anno>Q1</anno></c>. Returns the
+ tuple <c>{{value, <anno>Item</anno>}, <anno>Q2</anno>}</c>, where <c><anno>Item</anno></c> is the
+ item removed and <c><anno>Q2</anno></c> is the resulting queue. If <c><anno>Q1</anno></c> is
+ empty, the tuple <c>{empty, <anno>Q1</anno>}</c> is returned.</p>
</desc>
</func>
<func>
- <name>out_r(Q1) -> Result</name>
+ <name name="out_r" arity="1"/>
<fsummary>Remove the rear item from a queue</fsummary>
- <type>
- <v>Result = {{value, Item}, Q2} | {empty, Q1}</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Removes the item at the rear of the queue <c>Q1</c>. Returns the
- tuple <c>{{value, Item}, Q2}</c>, where <c>Item</c> is the
- item removed and <c>Q2</c> is the new queue. If <c>Q1</c> is
- empty, the tuple <c>{empty, Q1}</c> is returned. </p>
+ <p>Removes the item at the rear of the queue <c><anno>Q1</anno></c>. Returns the
+ tuple <c>{{value, <anno>Item</anno>}, <anno>Q2</anno>}</c>, where <c><anno>Item</anno></c> is the
+ item removed and <c><anno>Q2</anno></c> is the new queue. If <c><anno>Q1</anno></c> is
+ empty, the tuple <c>{empty, <anno>Q1</anno>}</c> is returned. </p>
</desc>
</func>
<func>
- <name>from_list(L) -> queue()</name>
+ <name name="from_list" arity="1"/>
<fsummary>Convert a list to a queue</fsummary>
- <type>
- <v>L = list()</v>
- </type>
<desc>
- <p>Returns a queue containing the items in <c>L</c> in the
+ <p>Returns a queue containing the items in <c><anno>L</anno></c> in the
same order; the head item of the list will become the front
item of the queue.</p>
</desc>
</func>
<func>
- <name>to_list(Q) -> list()</name>
+ <name name="to_list" arity="1"/>
<fsummary>Convert a queue to a list</fsummary>
- <type>
- <v>Q = queue()</v>
- </type>
<desc>
<p>Returns a list of the items in the queue in the same order;
the front item of the queue will become the head of the list.</p>
@@ -211,57 +183,43 @@
</func>
<func>
- <name>reverse(Q1) -> Q2</name>
+ <name name="reverse" arity="1"/>
<fsummary>Reverse a queue</fsummary>
- <type>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Returns a queue <c>Q2</c> that contains the items of
- <c>Q1</c> in the reverse order.</p>
+ <p>Returns a queue <c><anno>Q2</anno></c> that contains the items of
+ <c><anno>Q1</anno></c> in the reverse order.</p>
</desc>
</func>
<func>
- <name>split(N, Q1) -> {Q2,Q3}</name>
+ <name name="split" arity="2"/>
<fsummary>Split a queue in two</fsummary>
- <type>
- <v>N = integer()</v>
- <v>Q1 = Q2 = Q3 = queue()</v>
- </type>
<desc>
- <p>Splits <c>Q1</c> in two. The <c>N</c> front items
- are put in <c>Q2</c> and the rest in <c>Q3</c></p>
+ <p>Splits <c><anno>Q1</anno></c> in two. The <c><anno>N</anno></c> front items
+ are put in <c><anno>Q2</anno></c> and the rest in <c><anno>Q3</anno></c></p>
</desc>
</func>
<func>
- <name>join(Q1, Q2) -> Q3</name>
+ <name name="join" arity="2"/>
<fsummary>Join two queues</fsummary>
- <type>
- <v>Q1 = Q2 = Q3 = queue()</v>
- </type>
<desc>
- <p>Returns a queue <c>Q3</c> that is the result of joining
- <c>Q1</c> and <c>Q2</c> with <c>Q1</c> in front of
- <c>Q2</c>.</p>
+ <p>Returns a queue <c><anno>Q3</anno></c> that is the result of joining
+ <c><anno>Q1</anno></c> and <c><anno>Q2</anno></c> with <c><anno>Q1</anno></c> in front of
+ <c><anno>Q2</anno></c>.</p>
</desc>
</func>
<func>
- <name>filter(Fun, Q1) -> Q2</name>
+ <name name="filter" arity="2"/>
<fsummary>Filter a queue</fsummary>
- <type>
- <v>Fun = fun(Item) -> bool() | list()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Returns a queue <c>Q2</c> that is the result of calling
- <c>Fun(Item)</c> on all items in <c>Q1</c>,
+ <p>Returns a queue <c><anno>Q2</anno></c> that is the result of calling
+ <c><anno>Fun</anno>(<anno>Item</anno>)</c> on all items in <c><anno>Q1</anno></c>,
in order from front to rear.</p>
- <p>If <c>Fun(Item)</c> returns <c>true</c>, <c>Item</c>
+ <p>If <c><anno>Fun</anno>(<anno>Item</anno>)</c> returns <c>true</c>, <c>Item</c>
is copied to the result queue. If it returns <c>false</c>,
- <c>Item</c> is not copied. If it returns a list
+ <c><anno>Item</anno></c> is not copied. If it returns a list
the list elements are inserted instead of <c>Item</c> in the
result queue.</p>
- <p>So, <c>Fun(Item)</c> returning <c>[Item]</c> is thereby
+ <p>So, <c><anno>Fun</anno>(<anno>Item</anno>)</c> returning <c>[<anno>Item</anno>]</c> is thereby
semantically equivalent to returning <c>true</c>, just
as returning <c>[]</c> is semantically equivalent to
returning <c>false</c>. But returning a list builds
@@ -269,15 +227,11 @@
</desc>
</func>
<func>
- <name>member(Item, Q) -> bool()</name>
+ <name name="member" arity="2"/>
<fsummary>Test if an item is in a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Item</c> matches some element
- in <c>Q</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>Item</anno></c> matches some element
+ in <c><anno>Q</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
</funcs>
@@ -290,77 +244,53 @@
<funcs>
<func>
- <name>get(Q) -> Item</name>
+ <name name="get" arity="1"/>
<fsummary>Return the front item of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Returns <c>Item</c> at the front of queue <c>Q</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q</c> is empty.</p>
+ <p>Returns <c><anno>Item</anno></c> at the front of queue <c><anno>Q</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>get_r(Q) -> Item</name>
+ <name name="get_r" arity="1"/>
<fsummary>Return the rear item of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Returns <c>Item</c> at the rear of queue <c>Q</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q</c> is empty.</p>
+ <p>Returns <c><anno>Item</anno></c> at the rear of queue <c><anno>Q</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>drop(Q1) -> Q2</name>
+ <name name="drop" arity="1"/>
<fsummary>Remove the front item from a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Returns a queue <c>Q2</c> that is the result of removing
- the front item from <c>Q1</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q1</c> is empty.</p>
+ <p>Returns a queue <c><anno>Q2</anno></c> that is the result of removing
+ the front item from <c><anno>Q1</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q1</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>drop_r(Q1) -> Q2</name>
+ <name name="drop_r" arity="1"/>
<fsummary>Remove the rear item from a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Returns a queue <c>Q2</c> that is the result of removing
- the rear item from <c>Q1</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q1</c> is empty.</p>
+ <p>Returns a queue <c><anno>Q2</anno></c> that is the result of removing
+ the rear item from <c><anno>Q1</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q1</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>peek(Q) -> {value,Item} | empty</name>
+ <name name="peek" arity="1"/>
<fsummary>Return the front item of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Returns the tuple <c>{value, Item}</c> where <c>Item</c> is the
- front item of <c>Q</c>, or <c>empty</c> if <c>Q1</c> is empty.</p>
+ <p>Returns the tuple <c>{value, <anno>Item</anno>}</c> where <c><anno>Item</anno></c> is the
+ front item of <c><anno>Q</anno></c>, or <c>empty</c> if <c><anno>Q</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>peek_r(Q) -> {value,Item} | empty</name>
+ <name name="peek_r" arity="1"/>
<fsummary>Return the rear item of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Returns the tuple <c>{value, Item}</c> where <c>Item</c> is the
- rear item of <c>Q</c>, or <c>empty</c> if <c>Q1</c> is empty.</p>
+ <p>Returns the tuple <c>{value, <anno>Item</anno>}</c> where <c><anno>Item</anno></c> is the
+ rear item of <c><anno>Q</anno></c>, or <c>empty</c> if <c><anno>Q</anno></c> is empty.</p>
</desc>
</func>
</funcs>
@@ -372,80 +302,56 @@
<funcs>
<func>
- <name>cons(Item, Q1) -> Q2</name>
+ <name name="cons" arity="2"/>
<fsummary>Insert an item at the head of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Inserts <c>Item</c> at the head of queue <c>Q1</c>. Returns
- the new queue <c>Q2</c>.</p>
+ <p>Inserts <c><anno>Item</anno></c> at the head of queue <c><anno>Q1</anno></c>. Returns
+ the new queue <c><anno>Q2</anno></c>.</p>
</desc>
</func>
<func>
- <name>head(Q) -> Item</name>
+ <name name="head" arity="1"/>
<fsummary>Return the item at the head of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Returns <c>Item</c> from the head of queue <c>Q</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q</c> is empty.</p>
+ <p>Returns <c><anno>Item</anno></c> from the head of queue <c><anno>Q</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>tail(Q1) -> Q2</name>
+ <name name="tail" arity="1"/>
<fsummary>Remove the head item from a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Returns a queue <c>Q2</c> that is the result of removing
- the head item from <c>Q1</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q1</c> is empty.</p>
+ <p>Returns a queue <c><anno>Q2</anno></c> that is the result of removing
+ the head item from <c><anno>Q1</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q1</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>snoc(Q1, Item) -> Q2</name>
+ <name name="snoc" arity="2"/>
<fsummary>Insert an item at the tail of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Inserts <c>Item</c> as the tail item of queue <c>Q1</c>. Returns
- the new queue <c>Q2</c>.</p>
+ <p>Inserts <c><anno>Item</anno></c> as the tail item of queue <c><anno>Q1</anno></c>. Returns
+ the new queue <c><anno>Q2</anno></c>.</p>
</desc>
</func>
<func>
- <name>daeh(Q) -> Item</name>
- <name>last(Q) -> Item</name>
+ <name name="daeh" arity="1"/>
+ <name name="last" arity="1"/>
<fsummary>Return the tail item of a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q = queue()</v>
- </type>
<desc>
- <p>Returns the tail item of queue <c>Q</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q</c> is empty.</p>
+ <p>Returns the tail item of queue <c><anno>Q</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q</anno></c> is empty.</p>
</desc>
</func>
<func>
- <name>liat(Q1) -> Q2</name>
- <name>init(Q1) -> Q2</name>
- <name>lait(Q1) -> Q2</name>
+ <name name="liat" arity="1"/>
+ <name name="init" arity="1"/>
+ <name name="lait" arity="1"/>
<fsummary>Remove the tail item from a queue</fsummary>
- <type>
- <v>Item = term()</v>
- <v>Q1 = Q2 = queue()</v>
- </type>
<desc>
- <p>Returns a queue <c>Q2</c> that is the result of removing
- the tail item from <c>Q1</c>.</p>
- <p>Fails with reason <c>empty</c> if <c>Q1</c> is empty.</p>
+ <p>Returns a queue <c><anno>Q2</anno></c> that is the result of removing
+ the tail item from <c><anno>Q1</anno></c>.</p>
+ <p>Fails with reason <c>empty</c> if <c><anno>Q1</anno></c> is empty.</p>
<p>The name <c>lait/1</c> is a misspelling - do not use it anymore.</p>
</desc>
</func>
diff --git a/lib/stdlib/doc/src/random.xml b/lib/stdlib/doc/src/random.xml
index dcc6d756e1..93affc3191 100644
--- a/lib/stdlib/doc/src/random.xml
+++ b/lib/stdlib/doc/src/random.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -49,9 +49,15 @@
strong. If a strong cryptographic random number generator is needed for
example <c>crypto:rand_bytes/1</c> could be used instead.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="ran"/>
+ <desc><p>The state.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>seed() -> ran()</name>
+ <name name="seed" arity="0"/>
<fsummary>Seeds random number generation with default values</fsummary>
<desc>
<p>Seeds random number generation with default (fixed) values
@@ -59,11 +65,8 @@
</desc>
</func>
<func>
- <name>seed(A1, A2, A3) -> undefined | ran()</name>
+ <name name="seed" arity="3"/>
<fsummary>Seeds random number generator</fsummary>
- <type>
- <v>A1 = A2 = A3 = integer()</v>
- </type>
<desc>
<p>Seeds random number generation with integer values in the process
dictionary, and returns the old state.</p>
@@ -76,26 +79,23 @@
</desc>
</func>
<func>
- <name>seed({A1, A2, A3}) -> undefined | ran()</name>
+ <name name="seed" arity="1"/>
<fsummary>Seeds random number generator</fsummary>
- <type>
- <v>A1 = A2 = A3 = integer()</v>
- </type>
<desc>
<p>
- <c>seed({A1, A2, A3})</c> is equivalent to <c>seed(A1, A2, A3)</c>.
+ <c>seed({<anno>A1</anno>, <anno>A2</anno>, <anno>A3</anno>})</c> is equivalent to <c>seed(<anno>A1</anno>, <anno>A2</anno>, <anno>A3</anno>)</c>.
</p>
</desc>
</func>
<func>
- <name>seed0() -> ran()</name>
+ <name name="seed0" arity="0"/>
<fsummary>Return default state for random number generation</fsummary>
<desc>
<p>Returns the default state.</p>
</desc>
</func>
<func>
- <name>uniform()-> float()</name>
+ <name name="uniform" arity="0"/>
<fsummary>Return a random float</fsummary>
<desc>
<p>Returns a random float uniformly distributed between <c>0.0</c>
@@ -103,39 +103,29 @@
</desc>
</func>
<func>
- <name>uniform(N) -> integer()</name>
+ <name name="uniform" arity="1"/>
<fsummary>Return a random integer</fsummary>
- <type>
- <v>N = integer()</v>
- </type>
<desc>
- <p>Given an integer <c>N >= 1</c>, <c>uniform/1</c> returns a
+ <p>Given an integer <c><anno>N</anno> >= 1</c>, <c>uniform/1</c> returns a
random integer uniformly distributed between <c>1</c> and
- <c>N</c>, updating the state in the process dictionary.</p>
+ <c><anno>N</anno></c>, updating the state in the process dictionary.</p>
</desc>
</func>
<func>
- <name>uniform_s(State0) -> {float(), State1}</name>
+ <name name="uniform_s" arity="1"/>
<fsummary>Return a random float</fsummary>
- <type>
- <v>State0 = State1 = ran()</v>
- </type>
<desc>
<p>Given a state, <c>uniform_s/1</c>returns a random float uniformly
distributed between <c>0.0</c> and <c>1.0</c>, and a new state.</p>
</desc>
</func>
<func>
- <name>uniform_s(N, State0) -> {integer(), State1}</name>
+ <name name="uniform_s" arity="2"/>
<fsummary>Return a random integer</fsummary>
- <type>
- <v>N = integer()</v>
- <v>State0 = State1 = ran()</v>
- </type>
<desc>
- <p>Given an integer <c>N >= 1</c> and a state, <c>uniform_s/2</c>
+ <p>Given an integer <c><anno>N</anno> >= 1</c> and a state, <c>uniform_s/2</c>
returns a random integer uniformly distributed between <c>1</c> and
- <c>N</c>, and a new state.</p>
+ <c><anno>N</anno></c>, and a new state.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/re.xml b/lib/stdlib/doc/src/re.xml
index 9091035392..8c9e08ac3a 100644
--- a/lib/stdlib/doc/src/re.xml
+++ b/lib/stdlib/doc/src/re.xml
@@ -59,28 +59,24 @@
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
- iodata() = iolist() | binary()
- iolist() = [char() | binary() | iolist()]
- - a binary is allowed as the tail of the list</code>
- <code type="none">
- unicode_binary() = binary() with characters encoded in UTF-8 coding standard
- unicode_char() = integer() representing a valid unicode codepoint
-
- chardata() = charlist() | unicode_binary()
-
- charlist() = [unicode_char() | unicode_binary() | charlist()]
- - a unicode_binary is allowed as the tail of the list</code>
-
- <code type="none">
- mp() = Opaque datatype containing a compiled regular expression.
- - The mp() is guaranteed to be a tuple() having the atom
+ <datatypes>
+ <datatype>
+ <name name="mp"/>
+ <desc>
+ <p>Opaque datatype containing a compiled regular expression.
+ The mp() is guaranteed to be a tuple() having the atom
're_pattern' as its first element, to allow for matching in
guards. The arity of the tuple() or the content of the other fields
- may change in future releases.</code>
- </section>
+ may change in future releases.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="nl_spec"/>
+ </datatype>
+ <datatype>
+ <name name="compile_option"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
<name>compile(Regexp) -> {ok, MP} | {error, ErrSpec}</name>
@@ -96,14 +92,14 @@
<name>compile(Regexp,Options) -> {ok, MP} | {error, ErrSpec}</name>
<fsummary>Compile a regular expression into a match program</fsummary>
<type>
- <v>Regexp = iodata() | charlist()</v>
+ <v>Regexp = iodata() | <seealso marker="unicode#type-charlist">io:charlist()</seealso></v>
<v>Options = [ Option ]</v>
<v>Option = unicode | anchored | caseless | dollar_endonly | dotall | extended | firstline | multiline | no_auto_capture | dupnames | ungreedy | {newline, NLSpec}| bsr_anycrlf | bsr_unicode</v>
- <v>NLSpec = cr | crlf | lf | anycrlf | any </v>
- <v>MP = mp()</v>
+ <v>NLSpec = <seealso marker="#type-nl_spec">nl_spec()</seealso></v>
+ <v>MP = <seealso marker="#type-mp">mp()</seealso></v>
<v>ErrSpec = {ErrString, Position}</v>
<v>ErrString = string()</v>
- <v>Position = int()</v>
+ <v>Position = non_neg_integer()</v>
</type>
<desc>
<p>This function compiles a regular expression with the syntax
@@ -116,7 +112,7 @@
time one wants to match.</p>
<p>When the unicode option is given, the regular expression should be given as a valid unicode <c>charlist()</c>, otherwise as any valid <c>iodata()</c>.</p>
- <p>The options have the following meanings:</p>
+ <p><marker id="compile_options"/>The options have the following meanings:</p>
<taglist>
<tag><c>unicode</c></tag>
<item>The regular expression is given as a unicode <c>charlist()</c> and the resulting regular expression code is to be run against a valid unicode <c>charlist()</c> subject.</item>
@@ -137,7 +133,7 @@ This option makes it possible to include comments inside complicated patterns. N
<tag><c>multiline</c></tag>
<item><p>By default, PCRE treats the subject string as consisting of a single line of characters (even if it actually contains newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless <c>dollar_endonly</c> is given). This is the same as Perl.</p>
-<p>When <c>multiline</c> it is given, the "start of line" and "end of line" constructs match immediately following or immediately before internal newlines in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m option, and it can be changed within a pattern by a (?m) option setting. If there are no newlines in a subject string, or no occurrences of ^ or $ in a pattern, setting <c>multiline</c> has no effect.</p> </item>
+<p>When <c>multiline</c> is given, the "start of line" and "end of line" constructs match immediately following or immediately before internal newlines in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m option, and it can be changed within a pattern by a (?m) option setting. If there are no newlines in a subject string, or no occurrences of ^ or $ in a pattern, setting <c>multiline</c> has no effect.</p> </item>
<tag><c>no_auto_capture</c></tag>
<item>Disables the use of numbered capturing parentheses in the pattern. Any opening parenthesis that is not followed by ? behaves as if it were followed by ?: but named parentheses can still be used for capturing (and they acquire numbers in the usual way). There is no equivalent of this option in Perl.
</item>
@@ -173,10 +169,10 @@ This option makes it possible to include comments inside complicated patterns. N
<name>run(Subject,RE) -> {match, Captured} | nomatch</name>
<fsummary>Match a subject against regular expression and capture subpatterns</fsummary>
<type>
- <v>Subject = iodata() | charlist()</v>
- <v>RE = mp() | iodata() | charlist()</v>
+ <v>Subject = iodata() | <seealso marker="unicode#type-charlist">io:charlist()</seealso></v>
+ <v>RE = <seealso marker="#type-mp">mp()</seealso> | iodata() | <seealso marker="unicode#type-charlist">io:charlist()</seealso></v>
<v>Captured = [ CaptureData ]</v>
- <v>CaptureData = {int(),int()}</v>
+ <v>CaptureData = {integer(),integer()}</v>
</type>
<desc>
<p>The same as <c>run(Subject,RE,[])</c>.</p>
@@ -186,18 +182,19 @@ This option makes it possible to include comments inside complicated patterns. N
<name>run(Subject,RE,Options) -> {match, Captured} | match | nomatch</name>
<fsummary>Match a subject against regular expression and capture subpatterns</fsummary>
<type>
- <v>Subject = iodata() | charlist()</v>
- <v>RE = mp() | iodata() | charlist()</v>
+ <v>Subject = iodata() | <seealso marker="unicode#type-charlist">io:charlist()</seealso></v>
+ <v>RE = <seealso marker="#type-mp">mp()</seealso> | iodata() | <seealso marker="unicode#type-charlist">io:charlist()</seealso></v>
<v>Options = [ Option ]</v>
- <v>Option = anchored | global | notbol | noteol | notempty | {offset, int()} | {newline, NLSpec} | bsr_anycrlf | bsr_unicode | {capture, ValueSpec} | {capture, ValueSpec, Type} | CompileOpt</v>
+ <v>Option = anchored | global | notbol | noteol | notempty | {offset, integer() >= 0} | {newline, NLSpec} | bsr_anycrlf | bsr_unicode | {capture, ValueSpec} | {capture, ValueSpec, Type} | CompileOpt</v>
<v>Type = index | list | binary</v>
<v>ValueSpec = all | all_but_first | first | none | ValueList</v>
<v>ValueList = [ ValueID ]</v>
- <v>ValueID = int() | string() | atom()</v>
- <v>CompileOpt = see compile/2 above</v>
- <v>NLSpec = cr | crlf | lf | anycrlf | any</v>
+ <v>ValueID = integer() | string() | atom()</v>
+ <v>CompileOpt = <seealso marker="#type-compile_option">compile_option()</seealso></v>
+ <d>See <seealso marker="#compile_options">compile/2</seealso> above.</d>
+ <v>NLSpec = <seealso marker="#type-nl_spec">nl_spec()</seealso></v>
<v>Captured = [ CaptureData ] | [ [ CaptureData ] ... ]</v>
- <v>CaptureData = {int(),int()} | ListConversionData | binary()</v>
+ <v>CaptureData = {integer(),integer()} | ListConversionData | binary()</v>
<v>ListConversionData = string() | {error, string(), binary()} | {incomplete, string(), binary()}</v>
</type>
<desc>
@@ -217,7 +214,7 @@ This option makes it possible to include comments inside complicated patterns. N
<p>If the regular expression is previously compiled, the option
list can only contain the options <c>anchored</c>,
<c>global</c>, <c>notbol</c>, <c>noteol</c>,
- <c>notempty</c>, <c>{offset, int()}</c>, <c>{newline,
+ <c>notempty</c>, <c>{offset, integer() >= 0}</c>, <c>{newline,
NLSpec}</c> and <c>{capture, ValueSpec}/{capture, ValueSpec,
Type}</c>. Otherwise all options valid for the
<c>re:compile/2</c> function are allowed as well. Options
@@ -360,7 +357,7 @@ This option makes it possible to include comments inside complicated patterns. N
behavior of the dollar metacharacter. It does not affect \Z or
\z.</item>
- <tag><c>{offset, int()}</c></tag>
+ <tag><c>{offset, integer() >= 0}</c></tag>
<item>Start matching at the offset (position) given in the
subject string. The offset is zero-based, so that the default is
@@ -503,42 +500,27 @@ This option makes it possible to include comments inside complicated patterns. N
</desc>
</func>
<func>
- <name>replace(Subject,RE,Replacement) -> iodata() | charlist()</name>
+ <name name="replace" arity="3"/>
<fsummary>Match a subject against regular expression and replace matching elements with Replacement</fsummary>
- <type>
- <v>Subject = iodata() | charlist()</v>
- <v>RE = mp() | iodata()</v>
- <v>Replacement = iodata() | charlist()</v>
- </type>
<desc>
- <p>The same as <c>replace(Subject,RE,Replacement,[])</c>.</p>
+ <p>The same as <c>replace(<anno>Subject</anno>,<anno>RE</anno>,<anno>Replacement</anno>,[])</c>.</p>
</desc>
</func>
<func>
- <name>replace(Subject,RE,Replacement,Options) -> iodata() | charlist() | binary() | list()</name>
+ <name name="replace" arity="4"/>
<fsummary>Match a subject against regular expression and replace matching elements with Replacement</fsummary>
- <type>
- <v>Subject = iodata() | charlist()</v>
- <v>RE = mp() | iodata() | charlist()</v>
- <v>Replacement = iodata() | charlist()</v>
- <v>Options = [ Option ]</v>
- <v>Option = anchored | global | notbol | noteol | notempty | {offset, int()} | {newline, NLSpec} | bsr_anycrlf | bsr_unicode | {return, ReturnType} | CompileOpt</v>
- <v>ReturnType = iodata | list | binary</v>
- <v>CompileOpt = see compile/2 above</v>
- <v>NLSpec = cr | crlf | lf | anycrlf | any </v>
- </type>
<desc>
- <p>Replaces the matched part of the <c>Subject</c> string with the contents of <c>Replacement</c>.</p>
+ <p>Replaces the matched part of the <c><anno>Subject</anno></c> string with the contents of <c><anno>Replacement</anno></c>.</p>
<p>The permissible options are the same as for <c>re:run/3</c>, except that the <c>capture</c> option is not allowed.
- Instead a <c>{return, ReturnType}</c> is present. The default return type is <c>iodata</c>, constructed in a
+ Instead a <c>{return, <anno>ReturnType</anno>}</c> is present. The default return type is <c>iodata</c>, constructed in a
way to minimize copying. The <c>iodata</c> result can be used directly in many i/o-operations. If a flat <c>list()</c> is
desired, specify <c>{return, list}</c> and if a binary is preferred, specify <c>{return, binary}</c>.</p>
<p>As in the <c>re:run/3</c> function, an <c>mp()</c> compiled
- with the <c>unicode</c> option requires the <c>Subject</c> to be
+ with the <c>unicode</c> option requires the <c><anno>Subject</anno></c> to be
a Unicode <c>charlist()</c>. If compilation is done implicitly
and the <c>unicode</c> compilation option is given to this
- function, both the regular expression and the <c>Subject</c>
+ function, both the regular expression and the <c><anno>Subject</anno></c>
should be given as valid Unicode <c>charlist()</c>s.</p>
<p>The replacement string can contain the special character
@@ -565,34 +547,17 @@ This option makes it possible to include comments inside complicated patterns. N
</desc>
</func>
<func>
- <name>split(Subject,RE) -> SplitList</name>
+ <name name="split" arity="2"/>
<fsummary>Split a string by tokens specified as a regular expression</fsummary>
- <type>
- <v>Subject = iodata() | charlist()</v>
- <v>RE = mp() | iodata()</v>
- <v>SplitList = [ iodata() | charlist() ]</v>
- </type>
<desc>
- <p>The same as <c>split(Subject,RE,[])</c>.</p>
+ <p>The same as <c>split(<anno>Subject</anno>,<anno>RE</anno>,[])</c>.</p>
</desc>
</func>
<func>
- <name>split(Subject,RE,Options) -> SplitList</name>
+ <name name="split" arity="3"/>
<fsummary>Split a string by tokens specified as a regular expression</fsummary>
- <type>
- <v>Subject = iodata() | charlist()</v>
- <v>RE = mp() | iodata() | charlist()</v>
- <v>Options = [ Option ]</v>
- <v>Option = anchored | global | notbol | noteol | notempty | {offset, int()} | {newline, NLSpec} | bsr_anycrlf | bsr_unicode | {return, ReturnType} | {parts, NumParts} | group | trim | CompileOpt</v>
- <v>NumParts = int() | infinity</v>
- <v>ReturnType = iodata | list | binary</v>
- <v>CompileOpt = see compile/2 above</v>
- <v>NLSpec = cr | crlf | lf | anycrlf | any </v>
- <v>SplitList = [ RetData ] | [ GroupedRetData ]</v>
- <v>GroupedRetData = [ RetData ]</v>
- <v>RetData = iodata() | charlist() | binary() | list()</v>
- </type>
+ <type_desc variable="CompileOpt">See <seealso marker="#compile_options">compile/2</seealso> above.</type_desc>
<desc>
<p>This function splits the input into parts by finding tokens
according to the regular expression supplied.</p>
@@ -602,10 +567,10 @@ This option makes it possible to include comments inside complicated patterns. N
of the string is removed from the output.</p>
<p>As in the <c>re:run/3</c> function, an <c>mp()</c> compiled
- with the <c>unicode</c> option requires the <c>Subject</c> to be
+ with the <c>unicode</c> option requires the <c><anno>Subject</anno></c> to be
a Unicode <c>charlist()</c>. If compilation is done implicitly
and the <c>unicode</c> compilation option is given to this
- function, both the regular expression and the <c>Subject</c>
+ function, both the regular expression and the <c><anno>Subject</anno></c>
should be given as valid Unicode <c>charlist()</c>s.</p>
<p>The result is given as a list of &quot;strings&quot;, the
@@ -722,7 +687,7 @@ This option makes it possible to include comments inside complicated patterns. N
<p>Summary of options not previously described for the <c>re:run/3</c> function:</p>
<taglist>
- <tag>{return,ReturnType}</tag>
+ <tag>{return,<anno>ReturnType</anno>}</tag>
<item><p>Specifies how the parts of the original string are presented in the result list. The possible types are:</p>
<taglist>
<tag>iodata</tag>
diff --git a/lib/stdlib/doc/src/regexp.xml b/lib/stdlib/doc/src/regexp.xml
index 8c4191c88f..35d8e1c3f8 100644
--- a/lib/stdlib/doc/src/regexp.xml
+++ b/lib/stdlib/doc/src/regexp.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -40,176 +40,150 @@
<p>This module contains functions for regular expression
matching and substitution.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="errordesc"></name>
+ </datatype>
+ <datatype>
+ <name name="regexp"></name>
+ <desc><p>Internal representation of a regular expression.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>match(String, RegExp) -> MatchRes</name>
+ <name name="match" arity="2"/>
<fsummary>Match a regular expression</fsummary>
- <type>
- <v>String = RegExp = string()</v>
- <v>MatchRes = {match,Start,Length} | nomatch | {error,errordesc()}</v>
- <v>Start = Length = integer()</v>
- </type>
<desc>
- <p>Finds the first, longest match of the regular expression <c>RegExp</c> in <c>String</c>. This function searches for the longest possible match and returns the first one found if there are several expressions of the same length. It returns as follows:</p>
+ <p>Finds the first, longest match of the regular expression <c><anno>RegExp</anno></c> in <c><anno>String</anno></c>. This function searches for the longest possible match and returns the first one found if there are several expressions of the same length. It returns as follows:</p>
<taglist>
- <tag><c>{match,Start,Length}</c></tag>
+ <tag><c>{match,<anno>Start</anno>,<anno>Length</anno>}</c></tag>
<item>
- <p>if the match succeeded. <c>Start</c> is the starting
- position of the match, and <c>Length</c> is the length of
+ <p>if the match succeeded. <c><anno>Start</anno></c> is the starting
+ position of the match, and <c><anno>Length</anno></c> is the length of
the matching string.</p>
</item>
<tag><c>nomatch</c></tag>
<item>
<p>if there were no matching characters.</p>
</item>
- <tag><c>{error,Error}</c></tag>
+ <tag><c>{error,<anno>Error</anno>}</c></tag>
<item>
- <p>if there was an error in <c>RegExp</c>.</p>
+ <p>if there was an error in <c><anno>RegExp</anno></c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>first_match(String, RegExp) -> MatchRes</name>
+ <name name="first_match" arity="2"/>
<fsummary>Match a regular expression</fsummary>
- <type>
- <v>String = RegExp = string()</v>
- <v>MatchRes = {match,Start,Length} | nomatch | {error,errordesc()}</v>
- <v>Start = Length = integer()</v>
- </type>
<desc>
- <p>Finds the first match of the regular expression <c>RegExp</c> in <c>String</c>. This call is
+ <p>Finds the first match of the regular expression <c><anno>RegExp</anno></c> in <c><anno>String</anno></c>. This call is
usually faster than <c>match</c> and it is also a useful way to ascertain that a match exists. It returns as follows:</p>
<taglist>
- <tag><c>{match,Start,Length}</c></tag>
+ <tag><c>{match,<anno>Start</anno>,<anno>Length</anno>}</c></tag>
<item>
- <p>if the match succeeded. <c>Start</c> is the starting
- position of the match and <c>Length</c> is the length of
+ <p>if the match succeeded. <c><anno>Start</anno></c> is the starting
+ position of the match and <c><anno>Length</anno></c> is the length of
the matching string.</p>
</item>
<tag><c>nomatch</c></tag>
<item>
<p>if there were no matching characters.</p>
</item>
- <tag><c>{error,Error}</c></tag>
+ <tag><c>{error,<anno>Error</anno>}</c></tag>
<item>
- <p>if there was an error in <c>RegExp</c>.</p>
+ <p>if there was an error in <c><anno>RegExp</anno></c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>matches(String, RegExp) -> MatchRes</name>
+ <name name="matches" arity="2"/>
<fsummary>Match a regular expression</fsummary>
- <type>
- <v>String = RegExp = string()</v>
- <v>MatchRes = {match, Matches} | {error, errordesc()}</v>
- <v>Matches = list()</v>
- </type>
<desc>
<p>Finds all non-overlapping matches of the
- expression <c>RegExp</c> in <c>String</c>.
+ expression <c><anno>RegExp</anno></c> in <c><anno>String</anno></c>.
It returns as follows:</p>
<taglist>
- <tag><c>{match, Matches}</c></tag>
+ <tag><c>{match, <anno>Matches</anno>}</c></tag>
<item>
<p>if the regular expression was correct.
- The list will be empty if there was no match. Each element in the list looks like <c>{Start, Length}</c>, where <c>Start</c> is the starting position of the match, and <c>Length</c> is the length of the matching string.</p>
+ The list will be empty if there was no match. Each element in the list looks like <c>{<anno>Start</anno>, <anno>Length</anno>}</c>, where <c><anno>Start</anno></c> is the starting position of the match, and <c><anno>Length</anno></c> is the length of the matching string.</p>
</item>
- <tag><c>{error,Error}</c></tag>
+ <tag><c>{error,<anno>Error</anno>}</c></tag>
<item>
- <p>if there was an error in <c>RegExp</c>.</p>
+ <p>if there was an error in <c><anno>RegExp</anno></c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>sub(String, RegExp, New) -> SubRes</name>
+ <name name="sub" arity="3"/>
<fsummary>Substitute the first occurrence of a regular expression</fsummary>
- <type>
- <v>String = RegExp = New = string()</v>
- <v>SubRes = {ok,NewString,RepCount} | {error,errordesc()}</v>
- <v>RepCount = integer()</v>
- </type>
<desc>
- <p>Substitutes the first occurrence of a substring matching <c>RegExp</c> in <c>String</c> with the string <c>New</c>. A <c><![CDATA[&]]></c> in the string <c>New</c> is replaced by the matched substring of <c>String</c>. <c><![CDATA[\&]]></c> puts a literal <c><![CDATA[&]]></c> into the replacement string. It returns as follows:</p>
+ <p>Substitutes the first occurrence of a substring matching <c><anno>RegExp</anno></c> in <c><anno>String</anno></c> with the string <c><anno>New</anno></c>. A <c><![CDATA[&]]></c> in the string <c><anno>New</anno></c> is replaced by the matched substring of <c><anno>String</anno></c>. <c><![CDATA[\&]]></c> puts a literal <c><![CDATA[&]]></c> into the replacement string. It returns as follows:</p>
<taglist>
- <tag><c>{ok,NewString,RepCount}</c></tag>
+ <tag><c>{ok,<anno>NewString</anno>,<anno>RepCount</anno>}</c></tag>
<item>
- <p>if <c>RegExp</c> is correct. <c>RepCount</c> is the number of replacements which have been made
+ <p>if <c><anno>RegExp</anno></c> is correct. <c><anno>RepCount</anno></c> is the number of replacements which have been made
(this will be either 0 or 1).</p>
</item>
- <tag><c>{error, Error}</c></tag>
+ <tag><c>{error, <anno>Error</anno>}</c></tag>
<item>
- <p>if there is an error in <c>RegExp</c>.</p>
+ <p>if there is an error in <c><anno>RegExp</anno></c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>gsub(String, RegExp, New) -> SubRes</name>
+ <name name="gsub" arity="3"/>
<fsummary>Substitute all occurrences of a regular expression</fsummary>
- <type>
- <v>String = RegExp = New = string()</v>
- <v>SubRes = {ok,NewString,RepCount} | {error,errordesc()}</v>
- <v>RepCount = integer()</v>
- </type>
<desc>
<p>The same as <c>sub</c>, except that all non-overlapping
occurrences of a substring matching
- <c>RegExp</c> in <c>String</c> are replaced by the string <c>New</c>. It returns:</p>
+ <c><anno>RegExp</anno></c> in <c><anno>String</anno></c> are replaced by the string <c><anno>New</anno></c>. It returns:</p>
<taglist>
- <tag><c>{ok,NewString,RepCount}</c></tag>
+ <tag><c>{ok,<anno>NewString</anno>,<anno>RepCount</anno>}</c></tag>
<item>
- <p>if <c>RegExp</c> is correct. <c>RepCount</c> is the number of replacements which have been made.</p>
+ <p>if <c><anno>RegExp</anno></c> is correct. <c><anno>RepCount</anno></c> is the number of replacements which have been made.</p>
</item>
- <tag><c>{error, Error}</c></tag>
+ <tag><c>{error, <anno>Error</anno>}</c></tag>
<item>
- <p>if there is an error in <c>RegExp</c>.</p>
+ <p>if there is an error in <c><anno>RegExp</anno></c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>split(String, RegExp) -> SplitRes</name>
+ <name name="split" arity="2"/>
<fsummary>Split a string into fields</fsummary>
- <type>
- <v>String = RegExp = string()</v>
- <v>SubRes = {ok,FieldList} | {error,errordesc()}</v>
- <v>Fieldlist = [string()]</v>
- </type>
<desc>
- <p><c>String</c> is split into fields (sub-strings) by the
- regular expression <c>RegExp</c>.</p>
+ <p><c><anno>String</anno></c> is split into fields (sub-strings) by the
+ regular expression <c><anno>RegExp</anno></c>.</p>
<p>If the separator expression is <c>" "</c> (a single space),
then the fields are separated by blanks and/or tabs and
leading and trailing blanks and tabs are discarded. For all
other values of the separator, leading and trailing blanks
and tabs are not discarded. It returns:</p>
<taglist>
- <tag><c>{ok, FieldList}</c></tag>
+ <tag><c>{ok, <anno>FieldList</anno>}</c></tag>
<item>
<p>to indicate that the string has been split up into the fields of
- <c>FieldList</c>.</p>
+ <c><anno>FieldList</anno></c>.</p>
</item>
- <tag><c>{error, Error}</c></tag>
+ <tag><c>{error, <anno>Error</anno>}</c></tag>
<item>
- <p>if there is an error in <c>RegExp</c>.</p>
+ <p>if there is an error in <c><anno>RegExp</anno></c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>sh_to_awk(ShRegExp) -> AwkRegExp</name>
+ <name name="sh_to_awk" arity="1"/>
<fsummary>Convert an <c>sh</c>regular expression into an <c>AWK</c>one</fsummary>
- <type>
- <v>ShRegExp AwkRegExp = string()</v>
- <v>SubRes = {ok,NewString,RepCount} | {error,errordesc()}</v>
- <v>RepCount = integer()</v>
- </type>
<desc>
<p>Converts the <c>sh</c> type regular expression
- <c>ShRegExp</c> into a full <c>AWK</c> regular
+ <c><anno>ShRegExp</anno></c> into a full <c>AWK</c> regular
expression. Returns the converted regular expression
string. <c>sh</c> expressions are used in the shell for
matching file names and have the following special
@@ -236,40 +210,32 @@
</desc>
</func>
<func>
- <name>parse(RegExp) -> ParseRes</name>
+ <name name="parse" arity="1"/>
<fsummary>Parse a regular expression</fsummary>
- <type>
- <v>RegExp = string()</v>
- <v>ParseRes = {ok,RE} | {error,errordesc()}</v>
- </type>
<desc>
- <p>Parses the regular expression <c>RegExp</c> and builds the
+ <p>Parses the regular expression <c><anno>RegExp</anno></c> and builds the
internal representation used in the other regular expression
functions. Such representations can be used in all of the
other functions instead of a regular expression string. This
is more efficient when the same regular expression is used
in many strings. It returns:</p>
<taglist>
- <tag><c>{ok, RE}</c>if <c>RegExp</c>is correct and <c>RE</c>is the internal representation.</tag>
+ <tag><c>{ok, <anno>RE</anno>}</c></tag>
<item>
- <p></p>
+ <p>if <c>RegExp</c> is correct and <c><anno>RE</anno></c> is the internal representation.</p>
</item>
- <tag><c>{error, Error}</c>if there is an error in <c>RegExpString</c>.</tag>
+ <tag><c>{error, <anno>Error</anno>}</c></tag>
<item>
- <p></p>
+ <p>if there is an error in <c><anno>RegExp</anno></c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>format_error(ErrorDescriptor) -> Chars</name>
+ <name name="format_error" arity="1"/>
<fsummary>Format an error descriptor</fsummary>
- <type>
- <v>ErrorDescriptor = errordesc()</v>
- <v>Chars = [char() | Chars]</v>
- </type>
<desc>
- <p>Returns a string which describes the error <c>ErrorDescriptor</c>
+ <p>Returns a string which describes the error <c><anno>ErrorDescriptor</anno></c>
returned when there is an error in a regular expression.</p>
</desc>
</func>
diff --git a/lib/stdlib/doc/src/sets.xml b/lib/stdlib/doc/src/sets.xml
index 3610bb0184..071ee437cb 100644
--- a/lib/stdlib/doc/src/sets.xml
+++ b/lib/stdlib/doc/src/sets.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2000</year><year>2009</year>
+ <year>2000</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -43,202 +43,141 @@
different if and only if they do not compare equal (<c>==</c>).</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-set()
- as returned by new/0</code>
- </section>
+ <datatypes>
+ <datatype>
+ <name><marker id="type-dict">set()</marker></name>
+ <desc><p>As returned by <c>new/0</c>.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>new() -> Set</name>
+ <name name="new" arity="0"/>
<fsummary>Return an empty set</fsummary>
- <type>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns a new empty set.</p>
</desc>
</func>
<func>
- <name>is_set(Set) -> bool()</name>
+ <name name="is_set" arity="1"/>
<fsummary>Test for an <c>Set</c></fsummary>
- <type>
- <v>Set = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Set</c> is a set of
+ <p>Returns <c>true</c> if <c><anno>Set</anno></c> is a set of
elements, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>size(Set) -> int()</name>
+ <name name="size" arity="1"/>
<fsummary>Return the number of elements in a set</fsummary>
- <type>
- <v>Set = term()</v>
- </type>
<desc>
- <p>Returns the number of elements in <c>Set</c>.</p>
+ <p>Returns the number of elements in <c><anno>Set</anno></c>.</p>
</desc>
</func>
<func>
- <name>to_list(Set) -> List</name>
+ <name name="to_list" arity="1"/>
<fsummary>Convert an <c>Set</c>into a list</fsummary>
- <type>
- <v>Set = set()</v>
- <v>List = [term()]</v>
- </type>
<desc>
- <p>Returns the elements of <c>Set</c> as a list.</p>
+ <p>Returns the elements of <c><anno>Set</anno></c> as a list.</p>
</desc>
</func>
<func>
- <name>from_list(List) -> Set</name>
+ <name name="from_list" arity="1"/>
<fsummary>Convert a list into an <c>Set</c></fsummary>
- <type>
- <v>List = [term()]</v>
- <v>Set = set()</v>
- </type>
<desc>
- <p>Returns an set of the elements in <c>List</c>.</p>
+ <p>Returns an set of the elements in <c><anno>List</anno></c>.</p>
</desc>
</func>
<func>
- <name>is_element(Element, Set) -> bool()</name>
+ <name name="is_element" arity="2"/>
<fsummary>Test for membership of an <c>Set</c></fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set = set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Element</c> is an element of
- <c>Set</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> if <c><anno>Element</anno></c> is an element of
+ <c><anno>Set</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>add_element(Element, Set1) -> Set2</name>
+ <name name="add_element" arity="2"/>
<fsummary>Add an element to an <c>Set</c></fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns a new set formed from <c>Set1</c> with
- <c>Element</c> inserted.</p>
+ <p>Returns a new set formed from <c><anno>Set1</anno></c> with
+ <c><anno>Element</anno></c> inserted.</p>
</desc>
</func>
<func>
- <name>del_element(Element, Set1) -> Set2</name>
+ <name name="del_element" arity="2"/>
<fsummary>Remove an element from an <c>Set</c></fsummary>
- <type>
- <v>Element = term()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns <c>Set1</c>, but with <c>Element</c> removed.</p>
+ <p>Returns <c><anno>Set1</anno></c>, but with <c><anno>Element</anno></c> removed.</p>
</desc>
</func>
<func>
- <name>union(Set1, Set2) -> Set3</name>
+ <name name="union" arity="2"/>
<fsummary>Return the union of two <c>Sets</c></fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
- <p>Returns the merged (union) set of <c>Set1</c> and
- <c>Set2</c>.</p>
+ <p>Returns the merged (union) set of <c><anno>Set1</anno></c> and
+ <c><anno>Set2</anno></c>.</p>
</desc>
</func>
<func>
- <name>union(SetList) -> Set</name>
+ <name name="union" arity="1"/>
<fsummary>Return the union of a list of <c>Sets</c></fsummary>
- <type>
- <v>SetList = [set()]</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the merged (union) set of the list of sets.</p>
</desc>
</func>
<func>
- <name>intersection(Set1, Set2) -> Set3</name>
+ <name name="intersection" arity="2"/>
<fsummary>Return the intersection of two <c>Sets</c></fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
- <p>Returns the intersection of <c>Set1</c> and
- <c>Set2</c>.</p>
+ <p>Returns the intersection of <c><anno>Set1</anno></c> and
+ <c><anno>Set2</anno></c>.</p>
</desc>
</func>
<func>
- <name>intersection(SetList) -> Set</name>
+ <name name="intersection" arity="1"/>
<fsummary>Return the intersection of a list of <c>Sets</c></fsummary>
- <type>
- <v>SetList = [set()]</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the intersection of the non-empty list of sets.</p>
</desc>
</func>
<func>
- <name>is_disjoint(Set1, Set2) -> bool()</name>
+ <name name="is_disjoint" arity="2"/>
<fsummary>Check whether two <c>Sets</c> are disjoint</fsummary>
- <type>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if <c>Set1</c> and
- <c>Set2</c> are disjoint (have no elements in common),
+ <p>Returns <c>true</c> if <c><anno>Set1</anno></c> and
+ <c><anno>Set2</anno></c> are disjoint (have no elements in common),
and <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>subtract(Set1, Set2) -> Set3</name>
+ <name name="subtract" arity="2"/>
<fsummary>Return the difference of two <c>Sets</c></fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
- <p>Returns only the elements of <c>Set1</c> which are not
- also elements of <c>Set2</c>.</p>
+ <p>Returns only the elements of <c><anno>Set1</anno></c> which are not
+ also elements of <c><anno>Set2</anno></c>.</p>
</desc>
</func>
<func>
- <name>is_subset(Set1, Set2) -> bool()</name>
+ <name name="is_subset" arity="2"/>
<fsummary>Test for subset</fsummary>
- <type>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> when every element of <c>Set</c>1 is
- also a member of <c>Set2</c>, otherwise <c>false</c>.</p>
+ <p>Returns <c>true</c> when every element of <c><anno>Set1</anno></c>1 is
+ also a member of <c><anno>Set2</anno></c>, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>fold(Function, Acc0, Set) -> Acc1</name>
+ <name name="fold" arity="3"/>
<fsummary>Fold over set elements</fsummary>
- <type>
- <v>Function = fun (E, AccIn) -> AccOut</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Set = set()</v>
- </type>
<desc>
- <p>Fold <c>Function</c> over every element in <c>Set</c>
+ <p>Fold <c><anno>Function</anno></c> over every element in <c><anno>Set</anno></c>
returning the final value of the accumulator.</p>
</desc>
</func>
<func>
- <name>filter(Pred, Set1) -> Set2</name>
+ <name name="filter" arity="2"/>
<fsummary>Filter set elements</fsummary>
- <type>
- <v>Pred = fun (E) -> bool()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Filter elements in <c>Set1</c> with boolean function
- <c>Fun</c>.</p>
+ <p>Filter elements in <c><anno>Set1</anno></c> with boolean function
+ <c><anno>Pred</anno></c>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/shell.xml b/lib/stdlib/doc/src/shell.xml
index 73cc1b33bd..bc2120c37d 100644
--- a/lib/stdlib/doc/src/shell.xml
+++ b/lib/stdlib/doc/src/shell.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2010</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -763,26 +763,20 @@ loop(N) ->
<funcs>
<func>
- <name>history(N) -> integer()</name>
+ <name name="history" arity="1"/>
<fsummary>Sets the number of previous commands to keep</fsummary>
- <type>
- <v>N = integer()</v>
- </type>
<desc>
<p>Sets the number of previous commands to keep in the
- history list to <c>N</c>. The previous number is returned.
+ history list to <c><anno>N</anno></c>. The previous number is returned.
The default number is 20.</p>
</desc>
</func>
<func>
- <name>results(N) -> integer()</name>
+ <name name="results" arity="1"/>
<fsummary>Sets the number of previous results to keep</fsummary>
- <type>
- <v>N = integer()</v>
- </type>
<desc>
<p>Sets the number of results from previous commands to keep in
- the history list to <c>N</c>. The previous number is returned.
+ the history list to <c><anno>N</anno></c>. The previous number is returned.
The default number is 20.</p>
</desc>
</func>
@@ -790,7 +784,7 @@ loop(N) ->
<name>catch_exception(Bool) -> Bool</name>
<fsummary>Sets the exception handling of the shell</fsummary>
<type>
- <v>Bool = bool()</v>
+ <v>Bool = boolean()</v>
</type>
<desc>
<p>Sets the exception handling of the evaluator process. The
@@ -804,38 +798,29 @@ loop(N) ->
</desc>
</func>
<func>
- <name>prompt_func(PromptFunc) -> prompt_func()</name>
+ <name name="prompt_func" arity="1"/>
<fsummary>Sets the shell prompt</fsummary>
- <type>
- <v>PromptFunc = prompt_func()</v>
- <v>prompt_func() = default | {Mod, Func}</v>
- <v>Mod = Func = atom()</v>
- </type>
<desc>
<p>Sets the shell prompt function to <c>PromptFunc</c>. The
previous prompt function is returned.</p>
</desc>
</func>
<func>
- <name>start_restricted(Module) -> ok | {error, Reason}</name>
+ <name name="start_restricted" arity="1"/>
<fsummary>Exits a normal shell and starts a restricted shell.</fsummary>
- <type>
- <v>Module = atom()</v>
- <v>Reason = atom()</v>
- </type>
<desc>
<p>Exits a normal shell and starts a restricted
- shell. <c>Module</c> specifies the callback module for the
+ shell. <c><anno>Module</anno></c> specifies the callback module for the
functions <c>local_allowed/3</c> and <c>non_local_allowed/3</c>.
The function is meant to be called from the shell.</p>
<p>If the callback module cannot be loaded, an error tuple is
- returned. The <c>Reason</c> in the error tuple is the one
+ returned. The <c><anno>Reason</anno></c> in the error tuple is the one
returned by the code loader when trying to load the code of the callback
module.</p>
</desc>
</func>
<func>
- <name>stop_restricted() -> ok</name>
+ <name name="stop_restricted" arity="0"/>
<fsummary>Exits a restricted shell and starts a normal shell.</fsummary>
<desc>
<p>Exits a restricted shell and starts a normal shell. The function
diff --git a/lib/stdlib/doc/src/slave.xml b/lib/stdlib/doc/src/slave.xml
index 168d83f301..15b6711731 100644
--- a/lib/stdlib/doc/src/slave.xml
+++ b/lib/stdlib/doc/src/slave.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -56,22 +56,16 @@
</description>
<funcs>
<func>
- <name>start(Host) -></name>
- <name>start(Host, Name) -></name>
- <name>start(Host, Name, Args) -> {ok, Node} | {error, Reason}</name>
+ <name name="start" arity="1"/>
+ <name name="start" arity="2"/>
+ <name name="start" arity="3"/>
<fsummary>Start a slave node on a host</fsummary>
- <type>
- <v>Host = Name = atom()</v>
- <v>Args = string()</v>
- <v>Node = node()</v>
- <v>Reason = timeout | no_rsh | {already_running, Node}</v>
- </type>
<desc>
- <p>Starts a slave node on the host <c>Host</c>. Host names need
+ <p>Starts a slave node on the host <c><anno>Host</anno></c>. Host names need
not necessarily be specified as fully qualified names; short
names can also be used. This is the same condition that
applies to names of distributed Erlang nodes.</p>
- <p>The name of the started node will be <c>Name@Host</c>. If no
+ <p>The name of the started node will be <c><anno>Name</anno>@<anno>Host</anno></c>. If no
name is provided, the name will be the same as the node which
executes the call (with the exception of the host name part of
the node name).</p>
@@ -79,7 +73,7 @@
terminal I/O which is produced at the slave is automatically
relayed to the master. Also, the file process will be relayed
to the master.</p>
- <p>The <c>Args</c> argument is used to set <c>erl</c> command
+ <p>The <c><anno>Args</anno></c> argument is used to set <c>erl</c> command
line arguments. If provided, it is passed to the new node and
can be used for a variety of purposes. See
<seealso marker="erts:erl#erl">erl(1)</seealso></p>
@@ -103,9 +97,9 @@
E = " -env DISPLAY " ++ net_adm:localhost() ++ ":0 ",
Arg = "-mnesia_dir " ++ M ++ " -pa " ++ Dir ++ E,
slave:start(H, Name, Arg).</code>
- <p>If successful, the function returns <c>{ok, Node}</c>,
- where <c>Node</c> is the name of the new node. Otherwise it
- returns <c>{error, Reason}</c>, where <c>Reason</c> can be
+ <p>If successful, the function returns <c>{ok, <anno>Node</anno>}</c>,
+ where <c><anno>Node</anno></c> is the name of the new node. Otherwise it
+ returns <c>{error, <anno>Reason</anno>}</c>, where <c><anno>Reason</anno></c> can be
one of:</p>
<taglist>
<tag><c>timeout</c></tag>
@@ -123,24 +117,18 @@ slave:start(H, Name, Arg).</code>
<item>
<p>There is no <c>rsh</c> program on the computer.</p>
</item>
- <tag><c>{already_running, Node}</c></tag>
+ <tag><c>{already_running, <anno>Node</anno>}</c></tag>
<item>
- <p>A node with the name <c>Name@Host</c> already exists.</p>
+ <p>A node with the name <c><anno>Name</anno>@<anno>Host</anno></c> already exists.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>start_link(Host) -></name>
- <name>start_link(Host, Name) -></name>
- <name>start_link(Host, Name, Args) -> {ok, Node} | {error, Reason}</name>
+ <name name="start_link" arity="1"/>
+ <name name="start_link" arity="2"/>
+ <name name="start_link" arity="3"/>
<fsummary>Start and link to a slave node on a host</fsummary>
- <type>
- <v>Host = Name = atom()</v>
- <v>Args = string()</v>
- <v>Node = node()</v>
- <v>Reason = timeout | no_rsh | {already_running, Node}</v>
- </type>
<desc>
<p>Starts a slave node in the same way as <c>start/1,2,3</c>,
except that the slave node is linked to the currently
@@ -151,11 +139,8 @@ slave:start(H, Name, Arg).</code>
</desc>
</func>
<func>
- <name>stop(Node) -> ok</name>
+ <name name="stop" arity="1"/>
<fsummary>Stop (kill) a node</fsummary>
- <type>
- <v>Node = node()</v>
- </type>
<desc>
<p>Stops (kills) a node.</p>
</desc>
@@ -177,12 +162,8 @@ slave:start(H, Name, Arg).</code>
</desc>
</func>
<func>
- <name>pseudo(Master, ServerList) -> ok</name>
+ <name name="pseudo" arity="2"/>
<fsummary>Start a number of pseudo servers</fsummary>
- <type>
- <v>Master = node()</v>
- <v>ServerList = [atom()]</v>
- </type>
<desc>
<p>Starts a number of pseudo servers. A pseudo server is a
server with a registered name which does absolutely nothing
@@ -198,16 +179,13 @@ rpc:call(N, slave, pseudo, [node(), [pxw_server]]).</code>
</desc>
</func>
<func>
- <name>relay(Pid)</name>
+ <name name="relay" arity="1"/>
<fsummary>Run a pseudo server</fsummary>
- <type>
- <v>Pid = pid()</v>
- </type>
<desc>
<p>Runs a pseudo server. This function never returns any value
and the process which executes the function will receive
messages. All messages received will simply be passed on to
- <c>Pid</c>.</p>
+ <c><anno>Pid</anno></c>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/sofs.xml b/lib/stdlib/doc/src/sofs.xml
index 729df1e678..2e7768a1df 100644
--- a/lib/stdlib/doc/src/sofs.xml
+++ b/lib/stdlib/doc/src/sofs.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2001</year><year>2010</year>
+ <year>2001</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -181,10 +181,11 @@
the <marker id="canonical_map"></marker><em>canonical map</em> is
the function that maps every element of X onto its equivalence class.
</p>
- <p>Relations as defined above (as sets of ordered pairs) will from
- now on be referred to as <em>binary relations</em>. We call a
- set of ordered sets (x[1],&nbsp;...,&nbsp;x[n])
- an <em>(n-ary) relation</em>, and say that the relation is a subset of
+ <p><marker id="binary_relation"></marker>Relations as defined above
+ (as sets of ordered pairs) will from now on be referred to as
+ <em>binary relations</em>. We call a set of ordered sets
+ (x[1],&nbsp;...,&nbsp;x[n]) an <marker id="n_ary_relation"></marker>
+ <em>(n-ary) relation</em>, and say that the relation is a subset of
the <marker id="Cartesian_product_tuple"></marker>Cartesian product
X[1]&nbsp;&times;&nbsp;...&nbsp;&times;&nbsp;X[n] where x[i] is
an element of X[i], 1&nbsp;&lt;=&nbsp;i&nbsp;&lt;=&nbsp;n.
@@ -293,7 +294,8 @@
<c>partition_family/2</c>, <c>projection/2</c>,
<c>restriction/3</c>, <c>substitution/2</c>) accept an Erlang
function as a means to modify each element of a given unordered
- set. Such a function, called SetFun in the following, can be
+ set. <marker id="set_fun"></marker>Such a function, called
+ SetFun in the following, can be
specified as a functional object (fun), a tuple
<c>{external,&nbsp;Fun}</c>, or an integer. If SetFun is
specified as a fun, the fun is applied to each element of the
@@ -337,34 +339,73 @@ fun(S) -> sofs:partition(1, S) end
message when given badly formed arguments or sets the types of
which are not compatible.</p>
<p>When comparing external sets the operator <c>==/2</c> is used.</p>
- <p><em>Types</em></p>
- <pre>
-anyset() = -&nbsp;an unordered, ordered or atomic set&nbsp;-
-binary_relation() = -&nbsp;a binary relation&nbsp;-
-bool() = true | false
-external_set() = -&nbsp;an external set&nbsp;-
-family() = -&nbsp;a family (of subsets)&nbsp;-
-function() = -&nbsp;a function&nbsp;-
-ordset() = -&nbsp;an ordered set&nbsp;-
-relation() = -&nbsp;an n-ary relation&nbsp;-
-set() = -&nbsp;an unordered set&nbsp;-
-set_of_sets() = -&nbsp;an unordered set of set()&nbsp;-
-set_fun() = integer() >= 1
- | {external, fun(external_set()) -> external_set()}
- | fun(anyset()) -> anyset()
-spec_fun() = {external, fun(external_set()) -> bool()}
- | fun(anyset()) -> bool()
-type() = -&nbsp;a type&nbsp;- </pre>
</description>
+ <datatypes>
+ <datatype>
+ <name name="anyset"></name>
+ <desc><p>Any kind of set (also included are the atomic sets).</p></desc>
+ </datatype>
+ <datatype>
+ <name name="binary_relation"></name>
+ <desc><p>A <seealso marker="#binary_relation">binary
+ relation</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="external_set"></name>
+ <desc><p>An <seealso marker="#external_set">external
+ set</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="family"></name>
+ <desc><p>A <seealso marker="#family">family</seealso> (of subsets).</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="a_function"></name>
+ <desc><p>A <seealso marker="#function">function</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="ordset"></name>
+ <desc><p>An <seealso marker="#sets_definition">ordered
+ set</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="relation"></name>
+ <desc><p>An <seealso marker="#n_ary_relation">n-ary relation</seealso>.
+ </p></desc>
+ </datatype>
+ <datatype>
+ <name name="a_set"></name>
+ <desc><p>An <seealso marker="#sets_definition">unordered
+ set</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="set_of_sets"></name>
+ <desc><p>An <seealso marker="#sets_definition">unordered
+ set</seealso> of unordered sets.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="set_fun"></name>
+ <desc><p>A <seealso marker="#set_fun">SetFun</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="spec_fun"></name>
+ </datatype>
+ <datatype>
+ <name name="type"></name>
+ <desc><p>A <seealso marker="#type">type</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <!-- Parameterized opaque types are NYI: -->
+ <name><marker id="type-tuple_of">tuple_of(T)</marker></name>
+ <desc><p>A tuple where the elements are of type <c>T</c>.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>a_function(Tuples [, Type]) -> Function</name>
+ <name name="a_function" arity="1"/>
+ <name name="a_function" arity="2"/>
<fsummary>Create a function.</fsummary>
- <type>
- <v>Function = function()</v>
- <v>Tuples = [tuple()]</v>
- <v>Type = type()</v>
- </type>
<desc>
<p>Creates a <seealso marker="#function">function</seealso>.
<c>a_function(F,&nbsp;T)</c> is equivalent to
@@ -375,16 +416,12 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>canonical_relation(SetOfSets) -> BinRel</name>
+ <name name="canonical_relation" arity="1"/>
<fsummary>Return the canonical map.</fsummary>
- <type>
- <v>BinRel = binary_relation()</v>
- <v>SetOfSets = set_of_sets()</v>
- </type>
<desc>
<p>Returns the binary relation containing the elements
- (E,&nbsp;Set) such that Set belongs to SetOfSets and E
- belongs to Set. If SetOfSets is
+ (E,&nbsp;Set) such that Set belongs to <anno>SetOfSets</anno> and E
+ belongs to Set. If SetOfSets is
a <seealso marker="#partition">partition</seealso> of a set X and
R is the equivalence relation in X induced by SetOfSets, then the
returned relation is
@@ -398,14 +435,12 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>composite(Function1, Function2) -> Function3</name>
+ <name name="composite" arity="2"/>
<fsummary>Return the composite of two functions.</fsummary>
- <type>
- <v>Function1 = Function2 = Function3 = function()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#composite">composite</seealso> of
- the functions Function1 and Function2.</p>
+ the functions <anno>Function1</anno> and
+ <anno>Function2</anno>.</p>
<pre>
1> <input>F1 = sofs:a_function([{a,1},{b,2},{c,2}]),</input>
<input>F2 = sofs:a_function([{1,x},{2,y},{3,z}]),</input>
@@ -415,14 +450,9 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>constant_function(Set, AnySet) -> Function</name>
+ <name name="constant_function" arity="2"/>
<fsummary>Create the function that maps each element of a
set onto another set.</fsummary>
- <type>
- <v>AnySet = anyset()</v>
- <v>Function = function()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Creates the <seealso marker="#function">function</seealso>
that maps each element of the set Set onto AnySet.</p>
@@ -435,14 +465,11 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>converse(BinRel1) -> BinRel2</name>
+ <name name="converse" arity="1"/>
<fsummary>Return the converse of a binary relation.</fsummary>
- <type>
- <v>BinRel1 = BinRel2 = binary_relation()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#converse">converse</seealso>
- of the binary relation BinRel1.</p>
+ of the binary relation <anno>BinRel1</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{1,a},{2,b},{3,a}]),</input>
<input>R2 = sofs:converse(R1),</input>
@@ -451,31 +478,25 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>difference(Set1, Set2) -> Set3</name>
+ <name name="difference" arity="2"/>
<fsummary>Return the difference of two sets.</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#difference">difference</seealso> of
- the sets Set1 and Set2.</p>
+ the sets <anno>Set1</anno> and <anno>Set2</anno>.</p>
</desc>
</func>
<func>
- <name>digraph_to_family(Graph [, Type]) -> Family</name>
+ <name name="digraph_to_family" arity="1"/>
+ <name name="digraph_to_family" arity="2"/>
<fsummary>Create a family from a directed graph.</fsummary>
- <type>
- <v>Graph = digraph() -&nbsp;see digraph(3)&nbsp;-</v>
- <v>Family = family()</v>
- <v>Type = type()</v>
- </type>
<desc>
<p>Creates a <seealso marker="#family">family</seealso> from
- the directed graph Graph. Each vertex a of Graph is
+ the directed graph <anno>Graph</anno>. Each vertex a of
+ <anno>Graph</anno> is
represented by a pair (a,&nbsp;{b[1],&nbsp;...,&nbsp;b[n]})
where the b[i]'s are the out-neighbours of a. If no type is
explicitly given, [{atom,&nbsp;[atom]}] is used as type of
- the family. It is assumed that Type is
+ the family. It is assumed that <anno>Type</anno> is
a <seealso marker="#valid_type">valid type</seealso> of the
external set of the family.</p>
<p>If G is a directed graph, it holds that the vertices and
@@ -484,15 +505,11 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>domain(BinRel) -> Set</name>
+ <name name="domain" arity="1"/>
<fsummary>Return the domain of a binary relation.</fsummary>
- <type>
- <v>BinRel = binary_relation()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#domain">domain</seealso> of
- the binary relation BinRel.</p>
+ the binary relation <anno>BinRel</anno>.</p>
<pre>
1> <input>R = sofs:relation([{1,a},{1,b},{2,b},{2,c}]),</input>
<input>S = sofs:domain(R),</input>
@@ -501,16 +518,13 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>drestriction(BinRel1, Set) -> BinRel2</name>
+ <name name="drestriction" arity="2"/>
<fsummary>Return a restriction of a binary relation.</fsummary>
- <type>
- <v>BinRel1 = BinRel2 = binary_relation()</v>
- <v>Set = set()</v>
- </type>
<desc>
- <p>Returns the difference between the binary relation BinRel1
+ <p>Returns the difference between the binary relation
+ <anno>BinRel1</anno>
and the <seealso marker="#restriction">restriction</seealso>
- of BinRel1 to Set.</p>
+ of <anno>BinRel1</anno> to <anno>Set</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{1,a},{2,b},{3,c}]),</input>
<input>S = sofs:set([2,4,6]),</input>
@@ -522,16 +536,13 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>drestriction(SetFun, Set1, Set2) -> Set3</name>
+ <name name="drestriction" arity="3"/>
<fsummary>Return a restriction of a relation.</fsummary>
- <type>
- <v>SetFun = set_fun()</v>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
- <desc>
- <p>Returns a subset of Set1 containing those elements that do
- not yield an element in Set2 as the result of applying
- SetFun.</p>
+ <desc>
+ <p>Returns a subset of <anno>Set1</anno> containing those elements
+ that do
+ not yield an element in <anno>Set2</anno> as the result of applying
+ <anno>SetFun</anno>.</p>
<pre>
1> <input>SetFun = {external, fun({_A,B,C}) -> {B,C} end},</input>
<input>R1 = sofs:relation([{a,aa,1},{b,bb,2},{c,cc,3}]),</input>
@@ -544,11 +555,8 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>empty_set() -> Set</name>
+ <name name="empty_set" arity="0"/>
<fsummary>Return the untyped empty set.</fsummary>
- <type>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#sets_definition">untyped empty
set</seealso>. <c>empty_set()</c> is equivalent to
@@ -556,19 +564,14 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>extension(BinRel1, Set, AnySet) -> BinRel2</name>
+ <name name="extension" arity="3"/>
<fsummary>Extend the domain of a binary relation.</fsummary>
- <type>
- <v>AnySet = anyset()</v>
- <v>BinRel1 = BinRel2 = binary_relation()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#extension">extension</seealso> of
- BinRel1 such that
- for each element E in Set that does not belong to the
- <seealso marker="#domain">domain</seealso> of BinRel1,
- BinRel2 contains the pair (E,&nbsp;AnySet).</p>
+ <anno>BinRel1</anno> such that
+ for each element E in <anno>Set</anno> that does not belong to the
+ <seealso marker="#domain">domain</seealso> of <anno>BinRel1</anno>,
+ <anno>BinRel2</anno> contains the pair (E,&nbsp;AnySet).</p>
<pre>
1> <input>S = sofs:set([b,c]),</input>
<input>A = sofs:empty_set(),</input>
@@ -579,13 +582,9 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family(Tuples [, Type]) -> Family</name>
+ <name name="family" arity="1"/>
+ <name name="family" arity="2"/>
<fsummary>Create a family of subsets.</fsummary>
- <type>
- <v>Family = family()</v>
- <v>Tuples = [tuple()]</v>
- <v>Type = type()</v>
- </type>
<desc>
<p>Creates a <seealso marker="#family">family of subsets</seealso>.
<c>family(F,&nbsp;T)</c> is equivalent to
@@ -596,18 +595,17 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_difference(Family1, Family2) -> Family3</name>
+ <name name="family_difference" arity="2"/>
<fsummary>Return the difference of two families.</fsummary>
- <type>
- <v>Family1 = Family2 = Family3 = family()</v>
- </type>
<desc>
- <p>If Family1 and Family2
+ <p>If <anno>Family1</anno> and <anno>Family2</anno>
are <seealso marker="#family">families</seealso>, then
- Family3 is the family
+ <anno>Family3</anno> is the family
such that the index set is equal to the index set of
- Family1, and Family3[i] is the difference between Family1[i]
- and Family2[i] if Family2 maps i, Family1[i] otherwise.</p>
+ <anno>Family1</anno>, and <anno>Family3</anno>[i] is the
+ difference between <anno>Family1</anno>[i]
+ and <anno>Family2</anno>[i] if <anno>Family2</anno> maps i,
+ <anno>Family1</anno>[i] otherwise.</p>
<pre>
1> <input>F1 = sofs:family([{a,[1,2]},{b,[3,4]}]),</input>
<input>F2 = sofs:family([{b,[4,5]},{c,[6,7]}]),</input>
@@ -617,17 +615,18 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_domain(Family1) -> Family2</name>
+ <name name="family_domain" arity="1"/>
<fsummary>Return a family of domains.</fsummary>
- <type>
- <v>Family1 = Family2 = family()</v>
- </type>
- <desc>
- <p>If Family1 is a <seealso marker="#family">family</seealso>
- and Family1[i] is a binary relation for every i in the index
- set of Family1, then Family2 is the family with the same
- index set as Family1 such that Family2[i] is
- the <seealso marker="#domain">domain</seealso> of Family1[i].</p>
+ <desc>
+ <p>If <anno>Family1</anno> is
+ a <seealso marker="#family">family</seealso>
+ and <anno>Family1</anno>[i] is a binary relation for every i
+ in the index set of <anno>Family1</anno>,
+ then <anno>Family2</anno> is the family with the same index
+ set as <anno>Family1</anno> such
+ that <anno>Family2</anno>[i] is
+ the <seealso marker="#domain">domain</seealso> of
+ <anno>Family1</anno>[i].</p>
<pre>
1> <input>FR = sofs:from_term([{a,[{1,a},{2,b},{3,c}]},{b,[]},{c,[{4,d},{5,e}]}]),</input>
<input>F = sofs:family_domain(FR),</input>
@@ -636,17 +635,18 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_field(Family1) -> Family2</name>
+ <name name="family_field" arity="1"/>
<fsummary>Return a family of fields.</fsummary>
- <type>
- <v>Family1 = Family2 = family()</v>
- </type>
- <desc>
- <p>If Family1 is a <seealso marker="#family">family</seealso>
- and Family1[i] is a binary relation for every i in the index
- set of Family1, then Family2 is the family with the same
- index set as Family1 such that Family2[i] is
- the <seealso marker="#field">field</seealso> of Family1[i].</p>
+ <desc>
+ <p>If <anno>Family1</anno> is
+ a <seealso marker="#family">family</seealso>
+ and <anno>Family1</anno>[i] is a binary relation for every i
+ in the index set of <anno>Family1</anno>,
+ then <anno>Family2</anno> is the family with the same index
+ set as <anno>Family1</anno> such
+ that <anno>Family2</anno>[i] is
+ the <seealso marker="#field">field</seealso> of
+ <anno>Family1</anno>[i].</p>
<pre>
1> <input>FR = sofs:from_term([{a,[{1,a},{2,b},{3,c}]},{b,[]},{c,[{4,d},{5,e}]}]),</input>
<input>F = sofs:family_field(FR),</input>
@@ -657,21 +657,21 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_intersection(Family1) -> Family2</name>
+ <name name="family_intersection" arity="1"/>
<fsummary>Return the intersection of a family
of sets of sets.</fsummary>
- <type>
- <v>Family1 = Family2 = family()</v>
- </type>
- <desc>
- <p>If Family1 is a <seealso marker="#family">family</seealso>
- and Family1[i] is a set of sets for every i in the index set
- of Family1, then Family2 is the family with the same index
- set as Family1 such that Family2[i] is
- the <seealso marker="#intersection_n">intersection</seealso> of
- Family1[i].</p>
- <p>If Family1[i] is an empty set for some i, then the process
- exits with a <c>badarg</c> message.</p>
+ <desc>
+ <p>If <anno>Family1</anno> is
+ a <seealso marker="#family">family</seealso>
+ and <anno>Family1</anno>[i] is a set of sets for every i in
+ the index set of <anno>Family1</anno>,
+ then <anno>Family2</anno> is the family with the same index
+ set as <anno>Family1</anno> such
+ that <anno>Family2</anno>[i] is
+ the <seealso marker="#intersection_n">intersection</seealso>
+ of <anno>Family1</anno>[i].</p>
+ <p>If <anno>Family1</anno>[i] is an empty set for some i, then
+ the process exits with a <c>badarg</c> message.</p>
<pre>
1> <input>F1 = sofs:from_term([{a,[[1,2,3],[2,3,4]]},{b,[[x,y,z],[x,y]]}]),</input>
<input>F2 = sofs:family_intersection(F1),</input>
@@ -680,17 +680,16 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_intersection(Family1, Family2) -> Family3</name>
+ <name name="family_intersection" arity="2"/>
<fsummary>Return the intersection of two families.</fsummary>
- <type>
- <v>Family1 = Family2 = Family3 = family()</v>
- </type>
- <desc>
- <p>If Family1 and Family2
- are <seealso marker="#family">families</seealso>, then Family3
- is the family such that the index set is the intersection of
- Family1's and Family2's index sets, and Family3[i] is the
- intersection of Family1[i] and Family2[i].</p>
+ <desc>
+ <p>If <anno>Family1</anno> and <anno>Family2</anno>
+ are <seealso marker="#family">families</seealso>,
+ then <anno>Family3</anno> is the family such that the index
+ set is the intersection of <anno>Family1</anno>'s and
+ <anno>Family2</anno>'s index sets,
+ and <anno>Family3</anno>[i] is the intersection of
+ <anno>Family1</anno>[i] and <anno>Family2</anno>[i].</p>
<pre>
1> <input>F1 = sofs:family([{a,[1,2]},{b,[3,4]},{c,[5,6]}]),</input>
<input>F2 = sofs:family([{b,[4,5]},{c,[7,8]},{d,[9,10]}]),</input>
@@ -700,18 +699,16 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_projection(SetFun, Family1) -> Family2</name>
+ <name name="family_projection" arity="2"/>
<fsummary>Return a family of modified subsets.</fsummary>
- <type>
- <v>SetFun = set_fun()</v>
- <v>Family1 = Family2 = family()</v>
- <v>Set = set()</v>
- </type>
- <desc>
- <p>If Family1 is a <seealso marker="#family">family</seealso>
- then Family2 is the family with the same index set as
- Family1 such that Family2[i] is the result of calling SetFun
- with Family1[i] as argument.</p>
+ <desc>
+ <p>If <anno>Family1</anno> is
+ a <seealso marker="#family">family</seealso>
+ then <anno>Family2</anno> is the family with the same index
+ set as <anno>Family1</anno> such
+ that <anno>Family2</anno>[i] is the result of
+ calling <anno>SetFun</anno> with <anno>Family1</anno>[i] as
+ argument.</p>
<pre>
1> <input>F1 = sofs:from_term([{a,[[1,2],[2,3]]},{b,[[]]}]),</input>
<input>F2 = sofs:family_projection({sofs, union}, F1),</input>
@@ -720,17 +717,18 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_range(Family1) -> Family2</name>
+ <name name="family_range" arity="1"/>
<fsummary>Return a family of ranges.</fsummary>
- <type>
- <v>Family1 = Family2 = family()</v>
- </type>
- <desc>
- <p>If Family1 is a <seealso marker="#family">family</seealso>
- and Family1[i] is a binary relation for every i in the index
- set of Family1, then Family2 is the family with the same
- index set as Family1 such that Family2[i] is
- the <seealso marker="#range">range</seealso> of Family1[i].</p>
+ <desc>
+ <p>If <anno>Family1</anno> is
+ a <seealso marker="#family">family</seealso>
+ and <anno>Family1</anno>[i] is a binary relation for every i
+ in the index set of <anno>Family1</anno>,
+ then <anno>Family2</anno> is the family with the same index
+ set as <anno>Family1</anno> such
+ that <anno>Family2</anno>[i] is
+ the <seealso marker="#range">range</seealso> of
+ <anno>Family1</anno>[i].</p>
<pre>
1> <input>FR = sofs:from_term([{a,[{1,a},{2,b},{3,c}]},{b,[]},{c,[{4,d},{5,e}]}]),</input>
<input>F = sofs:family_range(FR),</input>
@@ -739,22 +737,21 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_specification(Fun, Family1) -> Family2</name>
+ <name name="family_specification" arity="2"/>
<fsummary>Select a subset of a family using a predicate.</fsummary>
- <type>
- <v>Fun = spec_fun()</v>
- <v>Family1 = Family2 = family()</v>
- </type>
- <desc>
- <p>If Family1 is a <seealso marker="#family">family</seealso>,
- then Family2 is
- the <seealso marker="#restriction">restriction</seealso> of
- Family1 to those elements i of the
- index set for which Fun applied to Family1[i] returns
- <c>true</c>. If Fun is a tuple <c>{external,&nbsp;Fun2}</c>,
- Fun2 is applied to
- the <seealso marker="#external_set">external set</seealso> of
- Family1[i], otherwise Fun is applied to Family1[i].</p>
+ <desc>
+ <p>If <anno>Family1</anno> is
+ a <seealso marker="#family">family</seealso>,
+ then <anno>Family2</anno> is
+ the <seealso marker="#restriction">restriction</seealso> of
+ <anno>Family1</anno> to those elements i of the index set
+ for which <anno>Fun</anno> applied
+ to <anno>Family1</anno>[i] returns
+ <c>true</c>. If <anno>Fun</anno> is a
+ tuple <c>{external,&nbsp;Fun2}</c>, Fun2 is applied to
+ the <seealso marker="#external_set">external set</seealso>
+ of <anno>Family1</anno>[i], otherwise <anno>Fun</anno> is
+ applied to <anno>Family1</anno>[i].</p>
<pre>
1> <input>F1 = sofs:family([{a,[1,2,3]},{b,[1,2]},{c,[1]}]),</input>
<input>SpecFun = fun(S) -> sofs:no_elements(S) =:= 2 end,</input>
@@ -764,24 +761,22 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_to_digraph(Family [, GraphType]) -> Graph</name>
+ <name name="family_to_digraph" arity="1"/>
+ <name name="family_to_digraph" arity="2"/>
<fsummary>Create a directed graph from a family.</fsummary>
- <type>
- <v>Graph = digraph()</v>
- <v>Family = family()</v>
- <v>GraphType = -&nbsp;see digraph(3)&nbsp;-</v>
- </type>
<desc>
<p>Creates a directed graph from
- the <seealso marker="#family">family</seealso> Family. For each
- pair (a,&nbsp;{b[1],&nbsp;...,&nbsp;b[n]}) of Family, the vertex
+ the <seealso marker="#family">family</seealso> <anno>Family</anno>.
+ For each pair (a,&nbsp;{b[1],&nbsp;...,&nbsp;b[n]})
+ of <anno>Family</anno>, the vertex
a as well the edges (a,&nbsp;b[i]) for
1&nbsp;&lt;=&nbsp;i&nbsp;&lt;=&nbsp;n are added to a newly
created directed graph.</p>
- <p>If no graph type is given, <c>digraph:new/1</c> is used for
- creating the directed graph, otherwise the GraphType
+ <p>If no graph type is given <seealso marker="digraph#new/0">
+ digraph:new/0</seealso> is used for
+ creating the directed graph, otherwise the <anno>GraphType</anno>
argument is passed on as second argument to
- <c>digraph:new/2</c>.</p>
+ <seealso marker="digraph#new/1">digraph:new/1</seealso>.</p>
<p>It F is a family, it holds that F is a subset of
<c>digraph_to_family(family_to_digraph(F),&nbsp;type(F))</c>.
Equality holds if <c>union_of_family(F)</c> is a subset of
@@ -791,17 +786,15 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_to_relation(Family) -> BinRel</name>
+ <name name="family_to_relation" arity="1"/>
<fsummary>Create a binary relation from a family.</fsummary>
- <type>
- <v>Family = family()</v>
- <v>BinRel = binary_relation()</v>
- </type>
- <desc>
- <p>If Family is a <seealso marker="#family">family</seealso>,
- then BinRel is the binary relation containing all pairs
- (i,&nbsp;x) such that i belongs to the index set of Family
- and x belongs to Family[i].</p>
+ <desc>
+ <p>If <anno>Family</anno> is
+ a <seealso marker="#family">family</seealso>,
+ then <anno>BinRel</anno> is the binary relation containing
+ all pairs (i,&nbsp;x) such that i belongs to the index set
+ of <anno>Family</anno> and x belongs
+ to <anno>Family</anno>[i].</p>
<pre>
1> <input>F = sofs:family([{a,[]}, {b,[1]}, {c,[2,3]}]),</input>
<input>R = sofs:family_to_relation(F),</input>
@@ -810,17 +803,18 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_union(Family1) -> Family2</name>
+ <name name="family_union" arity="1"/>
<fsummary>Return the union of a family of sets of sets.</fsummary>
- <type>
- <v>Family1 = Family2 = family()</v>
- </type>
- <desc>
- <p>If Family1 is a <seealso marker="#family">family</seealso>
- and Family1[i] is a set of sets for each i in the index set
- of Family1, then Family2 is the family with the same index
- set as Family1 such that Family2[i] is
- the <seealso marker="#union_n">union</seealso> of Family1[i].</p>
+ <desc>
+ <p>If <anno>Family1</anno> is
+ a <seealso marker="#family">family</seealso>
+ and <anno>Family1</anno>[i] is a set of sets for each i in
+ the index set of <anno>Family1</anno>,
+ then <anno>Family2</anno> is the family with the same index
+ set as <anno>Family1</anno> such
+ that <anno>Family2</anno>[i] is
+ the <seealso marker="#union_n">union</seealso> of
+ <anno>Family1</anno>[i].</p>
<pre>
1> <input>F1 = sofs:from_term([{a,[[1,2],[2,3]]},{b,[[]]}]),</input>
<input>F2 = sofs:family_union(F1),</input>
@@ -831,18 +825,18 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>family_union(Family1, Family2) -> Family3</name>
+ <name name="family_union" arity="2"/>
<fsummary>Return the union of two families.</fsummary>
- <type>
- <v>Family1 = Family2 = Family3 = family()</v>
- </type>
- <desc>
- <p>If Family1 and Family2
- are <seealso marker="#family">families</seealso>, then Family3
- is the family such that the index set is the union of Family1's
- and Family2's index sets, and Family3[i] is the union of
- Family1[i] and Family2[i] if both maps i, Family1[i] or
- Family2[i] otherwise.</p>
+ <desc>
+ <p>If <anno>Family1</anno> and <anno>Family2</anno>
+ are <seealso marker="#family">families</seealso>,
+ then <anno>Family3</anno> is the family such that the index
+ set is the union of <anno>Family1</anno>'s
+ and <anno>Family2</anno>'s index sets,
+ and <anno>Family3</anno>[i] is the union
+ of <anno>Family1</anno>[i] and <anno>Family2</anno>[i] if
+ both maps i, <anno>Family1</anno>[i]
+ or <anno>Family2</anno>[i] otherwise.</p>
<pre>
1> <input>F1 = sofs:family([{a,[1,2]},{b,[3,4]},{c,[5,6]}]),</input>
<input>F2 = sofs:family([{b,[4,5]},{c,[7,8]},{d,[9,10]}]),</input>
@@ -852,15 +846,11 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>field(BinRel) -> Set</name>
+ <name name="field" arity="1"/>
<fsummary>Return the field of a binary relation.</fsummary>
- <type>
- <v>BinRel = binary_relation()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#field">field</seealso> of the
- binary relation BinRel.</p>
+ binary relation <anno>BinRel</anno>.</p>
<pre>
1> <input>R = sofs:relation([{1,a},{1,b},{2,b},{2,c}]),</input>
<input>S = sofs:field(R),</input>
@@ -871,31 +861,24 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>from_external(ExternalSet, Type) -> AnySet</name>
+ <name name="from_external" arity="2"/>
<fsummary>Create a set.</fsummary>
- <type>
- <v>ExternalSet = external_set()</v>
- <v>AnySet = anyset()</v>
- <v>Type = type()</v>
- </type>
<desc>
<p>Creates a set from the <seealso marker="#external_set">external
- set</seealso> ExternalSet
- and the <seealso marker="#type">type</seealso> Type. It is
- assumed that Type is a <seealso marker="#valid_type">valid
- type</seealso> of ExternalSet.</p>
+ set</seealso> <anno>ExternalSet</anno>
+ and the <seealso marker="#type">type</seealso> <anno>Type</anno>.
+ It is assumed that <anno>Type</anno> is
+ a <seealso marker="#valid_type">valid
+ type</seealso> of <anno>ExternalSet</anno>.</p>
</desc>
</func>
<func>
- <name>from_sets(ListOfSets) -> Set</name>
+ <name name="from_sets" arity="1" clause_i="1"/>
<fsummary>Create a set out of a list of sets.</fsummary>
- <type>
- <v>Set = set()</v>
- <v>ListOfSets = [anyset()]</v>
- </type>
<desc>
<p>Returns the <seealso marker="#sets_definition">unordered
- set</seealso> containing the sets of the list ListOfSets.</p>
+ set</seealso> containing the sets of the list
+ <anno>ListOfSets</anno>.</p>
<pre>
1> <input>S1 = sofs:relation([{a,1},{b,2}]),</input>
<input>S2 = sofs:relation([{x,3},{y,4}]),</input>
@@ -905,38 +888,33 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>from_sets(TupleOfSets) -> Ordset</name>
+ <name name="from_sets" arity="1" clause_i="2"/>
<fsummary>Create an ordered set out of a tuple of sets.</fsummary>
- <type>
- <v>Ordset = ordset()</v>
- <v>TupleOfSets = tuple-of(anyset())</v>
- </type>
<desc>
<p>Returns the <seealso marker="#sets_definition">ordered
set</seealso> containing the sets of the non-empty tuple
- TupleOfSets.</p>
+ <anno>TupleOfSets</anno>.</p>
</desc>
</func>
<func>
- <name>from_term(Term [, Type]) -> AnySet</name>
+ <name name="from_term" arity="1"/>
+ <name name="from_term" arity="2"/>
<fsummary>Create a set.</fsummary>
- <type>
- <v>AnySet = anyset()</v>
- <v>Term = term()</v>
- <v>Type = type()</v>
- </type>
<desc>
<p><marker id="from_term"></marker>Creates an element
of <seealso marker="#sets_definition">Sets</seealso> by
- traversing the term Term, sorting lists, removing duplicates and
+ traversing the term <anno>Term</anno>, sorting lists,
+ removing duplicates and
deriving or verifying a <seealso marker="#valid_type">valid
type</seealso> for the so obtained external set. An
- explicitly given <seealso marker="#type">type</seealso> Type
+ explicitly given <seealso marker="#type">type</seealso>
+ <anno>Type</anno>
can be used to limit the depth of the traversal; an atomic
type stops the traversal, as demonstrated by this example
where "foo" and {"foo"} are left unmodified:</p>
<pre>
-1> <input>S = sofs:from_term([{{"foo"},[1,1]},{"foo",[2,2]}], [{atom,[atom]}]),</input>
+1> <input>S = sofs:from_term([{{"foo"},[1,1]},{"foo",[2,2]}],
+[{atom,[atom]}]),</input>
<input>sofs:to_external(S).</input>
[{{"foo"},[1]},{"foo",[2]}]</pre>
<p><c>from_term</c> can be used for creating atomic or ordered
@@ -963,15 +941,12 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>image(BinRel, Set1) -> Set2</name>
+ <name name="image" arity="2"/>
<fsummary>Return the image of a set under a binary relation.</fsummary>
- <type>
- <v>BinRel = binary_relation()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#image">image</seealso> of the
- set Set1 under the binary relation BinRel.</p>
+ set <anno>Set1</anno> under the binary
+ relation <anno>BinRel</anno>.</p>
<pre>
1> <input>R = sofs:relation([{1,a},{2,b},{2,c},{3,d}]),</input>
<input>S1 = sofs:set([1,2]),</input>
@@ -981,42 +956,32 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>intersection(SetOfSets) -> Set</name>
+ <name name="intersection" arity="1"/>
<fsummary>Return the intersection of a set of sets.</fsummary>
- <type>
- <v>Set = set()</v>
- <v>SetOfSets = set_of_sets()</v>
- </type>
<desc>
<p>Returns
the <seealso marker="#intersection_n">intersection</seealso> of
- the set of sets SetOfSets.</p>
+ the set of sets <anno>SetOfSets</anno>.</p>
<p>Intersecting an empty set of sets exits the process with a
<c>badarg</c> message.</p>
</desc>
</func>
<func>
- <name>intersection(Set1, Set2) -> Set3</name>
+ <name name="intersection" arity="2"/>
<fsummary>Return the intersection of two sets.</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
<p>Returns
the <seealso marker="#intersection">intersection</seealso> of
- Set1 and Set2.</p>
+ <anno>Set1</anno> and <anno>Set2</anno>.</p>
</desc>
</func>
<func>
- <name>intersection_of_family(Family) -> Set</name>
+ <name name="intersection_of_family" arity="1"/>
<fsummary>Return the intersection of a family.</fsummary>
- <type>
- <v>Family = family()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the intersection of
- the <seealso marker="#family">family</seealso> Family.</p>
+ the <seealso marker="#family">family</seealso> <anno>Family</anno>.
+ </p>
<p>Intersecting an empty family exits the process with a
<c>badarg</c> message.</p>
<pre>
@@ -1027,14 +992,11 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>inverse(Function1) -> Function2</name>
+ <name name="inverse" arity="1"/>
<fsummary>Return the inverse of a function.</fsummary>
- <type>
- <v>Function1 = Function2 = function()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#inverse">inverse</seealso>
- of the function Function1.</p>
+ of the function <anno>Function1</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{1,a},{2,b},{3,c}]),</input>
<input>R2 = sofs:inverse(R1),</input>
@@ -1043,16 +1005,13 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>inverse_image(BinRel, Set1) -> Set2</name>
+ <name name="inverse_image" arity="2"/>
<fsummary>Return the inverse image of a set under
a binary relation.</fsummary>
- <type>
- <v>BinRel = binary_relation()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns the <seealso marker="#inverse_image">inverse
- image</seealso> of Set1 under the binary relation BinRel.</p>
+ <p>Returns the <seealso marker="#inverse_image">inverse
+ image</seealso> of <anno>Set1</anno> under the binary
+ relation <anno>BinRel</anno>.</p>
<pre>
1> <input>R = sofs:relation([{1,a},{2,b},{2,c},{3,d}]),</input>
<input>S1 = sofs:set([c,d,e]),</input>
@@ -1062,52 +1021,38 @@ type() = -&nbsp;a type&nbsp;- </pre>
</desc>
</func>
<func>
- <name>is_a_function(BinRel) -> Bool</name>
+ <name name="is_a_function" arity="1"/>
<fsummary>Test for a function.</fsummary>
- <type>
- <v>Bool = bool()</v>
- <v>BinRel = binary_relation()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if the binary relation BinRel is a
- <seealso marker="#function">function</seealso> or the
+ <p>Returns <c>true</c> if the binary relation <anno>BinRel</anno>
+ is a <seealso marker="#function">function</seealso> or the
untyped empty set, <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_disjoint(Set1, Set2) -> Bool</name>
+ <name name="is_disjoint" arity="2"/>
<fsummary>Test for disjoint sets.</fsummary>
- <type>
- <v>Bool = bool()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if Set1 and Set2
+ <p>Returns <c>true</c> if <anno>Set1</anno>
+ and <anno>Set2</anno>
are <seealso marker="#disjoint">disjoint</seealso>, <c>false</c>
otherwise.</p>
</desc>
</func>
<func>
- <name>is_empty_set(AnySet) -> Bool</name>
+ <name name="is_empty_set" arity="1"/>
<fsummary>Test for an empty set.</fsummary>
- <type>
- <v>AnySet = anyset()</v>
- <v>Bool = bool()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if Set is an empty unordered set,
- <c>false</c> otherwise.</p>
+ <p>Returns <c>true</c> if <anno>AnySet</anno> is an empty
+ unordered set, <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_equal(AnySet1, AnySet2) -> Bool</name>
+ <name name="is_equal" arity="2"/>
<fsummary>Test two sets for equality.</fsummary>
- <type>
- <v>AnySet1 = AnySet2 = anyset()</v>
- <v>Bool = bool()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if the AnySet1 and AnySet2
+ <p>Returns <c>true</c> if the <anno>AnySet1</anno>
+ and <anno>AnySet2</anno>
are <seealso marker="#equal">equal</seealso>, <c>false</c>
otherwise. This example shows that <c>==/2</c> is used when
comparing sets for equality:</p>
@@ -1119,67 +1064,49 @@ true</pre>
</desc>
</func>
<func>
- <name>is_set(AnySet) -> Bool</name>
+ <name name="is_set" arity="1"/>
<fsummary>Test for an unordered set.</fsummary>
- <type>
- <v>AnySet = anyset()</v>
- <v>Bool = bool()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if AnySet is
+ <p>Returns <c>true</c> if <anno>AnySet</anno> is
an <seealso marker="#sets_definition">unordered set</seealso>, and
- <c>false</c> if AnySet is an ordered set or an atomic set.</p>
+ <c>false</c> if <anno>AnySet</anno> is an ordered set or an
+ atomic set.</p>
</desc>
</func>
<func>
- <name>is_sofs_set(Term) -> Bool</name>
+ <name name="is_sofs_set" arity="1"/>
<fsummary>Test for an unordered set.</fsummary>
- <type>
- <v>Bool = bool()</v>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if Term is
+ <p>Returns <c>true</c> if <anno>Term</anno> is
an <seealso marker="#sets_definition">unordered set</seealso>, an
ordered set or an atomic set, <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_subset(Set1, Set2) -> Bool</name>
+ <name name="is_subset" arity="2"/>
<fsummary>Test two sets for subset.</fsummary>
- <type>
- <v>Bool = bool()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if Set1 is
- a <seealso marker="#subset">subset</seealso> of Set2, <c>false</c>
- otherwise.</p>
+ <p>Returns <c>true</c> if <anno>Set1</anno> is
+ a <seealso marker="#subset">subset</seealso>
+ of <anno>Set2</anno>, <c>false</c> otherwise.</p>
</desc>
</func>
<func>
- <name>is_type(Term) -> Bool</name>
+ <name name="is_type" arity="1"/>
<fsummary>Test for a type.</fsummary>
- <type>
- <v>Bool = bool()</v>
- <v>Term = term()</v>
- </type>
<desc>
- <p>Returns <c>true</c> if the term Term is
+ <p>Returns <c>true</c> if the term <anno>Term</anno> is
a <seealso marker="#type">type</seealso>.</p>
</desc>
</func>
<func>
- <name>join(Relation1, I, Relation2, J) -> Relation3</name>
+ <name name="join" arity="4"/>
<fsummary>Return the join of two relations.</fsummary>
- <type>
- <v>Relation1 = Relation2 = Relation3 = relation()</v>
- <v>I = J = integer() > 0</v>
- </type>
<desc>
<p>Returns the <seealso marker="#natural_join">natural
- join</seealso> of the relations Relation1 and Relation2 on
- coordinates I and J.</p>
+ join</seealso> of the relations <anno>Relation1</anno>
+ and <anno>Relation2</anno> on coordinates <anno>I</anno> and
+ <anno>J</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{a,x,1},{b,y,2}]),</input>
<input>R2 = sofs:relation([{1,f,g},{1,h,i},{2,3,4}]),</input>
@@ -1189,20 +1116,17 @@ true</pre>
</desc>
</func>
<func>
- <name>multiple_relative_product(TupleOfBinRels, BinRel1) -> BinRel2</name>
+ <name name="multiple_relative_product" arity="2"/>
<fsummary>Return the multiple relative product of a tuple of binary
relations and a relation.</fsummary>
- <type>
- <v>TupleOfBinRels = tuple-of(BinRel)</v>
- <v>BinRel = BinRel1 = BinRel2 = binary_relation()</v>
- </type>
- <desc>
- <p>If TupleOfBinRels is a non-empty tuple
- {R[1],&nbsp;...,&nbsp;R[n]} of binary relations and BinRel1
- is a binary relation, then BinRel2 is
+ <desc>
+ <p>If <anno>TupleOfBinRels</anno> is a non-empty tuple
+ {R[1],&nbsp;...,&nbsp;R[n]} of binary relations
+ and <anno>BinRel1</anno> is a binary relation,
+ then <anno>BinRel2</anno> is
the <seealso marker="#multiple_relative_product">multiple relative
product</seealso> of the ordered set
- (R[i],&nbsp;...,&nbsp;R[n]) and BinRel1.</p>
+ (R[i],&nbsp;...,&nbsp;R[n]) and <anno>BinRel1</anno>.</p>
<pre>
1> <input>Ri = sofs:relation([{a,1},{b,2},{c,3}]),</input>
<input>R = sofs:relation([{a,b},{b,c},{c,a}]),</input>
@@ -1212,29 +1136,21 @@ true</pre>
</desc>
</func>
<func>
- <name>no_elements(ASet) -> NoElements</name>
+ <name name="no_elements" arity="1"/>
<fsummary>Return the number of elements of a set.</fsummary>
- <type>
- <v>ASet = set() | ordset()</v>
- <v>NoElements = integer() >= 0 </v>
- </type>
<desc>
<p>Returns the number of elements of the ordered or unordered
- set ASet.</p>
+ set <anno>ASet</anno>.</p>
</desc>
</func>
<func>
- <name>partition(SetOfSets) -> Partition</name>
+ <name name="partition" arity="1"/>
<fsummary>Return the coarsest partition given a set of sets.</fsummary>
- <type>
- <v>SetOfSets = set_of_sets()</v>
- <v>Partition = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#partition">partition</seealso> of
- the union of the set of sets SetOfSets such that two
+ the union of the set of sets <anno>SetOfSets</anno> such that two
elements are considered equal if they belong to the same
- elements of SetOfSets.</p>
+ elements of <anno>SetOfSets</anno>.</p>
<pre>
1> <input>Sets1 = sofs:from_term([[a,b,c],[d,e,f],[g,h,i]]),</input>
<input>Sets2 = sofs:from_term([[b,c,d],[e,f,g],[h,i,j]]),</input>
@@ -1244,17 +1160,12 @@ true</pre>
</desc>
</func>
<func>
- <name>partition(SetFun, Set) -> Partition</name>
+ <name name="partition" arity="2"/>
<fsummary>Return a partition of a set.</fsummary>
- <type>
- <v>SetFun = set_fun()</v>
- <v>Partition = set()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#partition">partition</seealso> of
- Set such that two elements are considered equal if the
- results of applying SetFun are equal.</p>
+ <anno>Set</anno> such that two elements are considered equal
+ if the results of applying <anno>SetFun</anno> are equal.</p>
<pre>
1> <input>Ss = sofs:from_term([[a],[b],[c,d],[e,f]]),</input>
<input>SetFun = fun(S) -> sofs:from_term(sofs:no_elements(S)) end,</input>
@@ -1264,19 +1175,16 @@ true</pre>
</desc>
</func>
<func>
- <name>partition(SetFun, Set1, Set2) -> {Set3, Set4}</name>
+ <name name="partition" arity="3"/>
<fsummary>Return a partition of a set.</fsummary>
- <type>
- <v>SetFun = set_fun()</v>
- <v>Set1 = Set2 = Set3 = Set4 = set()</v>
- </type>
<desc>
<p>Returns a pair of sets that, regarded as constituting a
set, forms a <seealso marker="#partition">partition</seealso> of
- Set1. If the
- result of applying SetFun to an element of Set1 yields an
- element in Set2, the element belongs to Set3, otherwise the
- element belongs to Set4.</p>
+ <anno>Set1</anno>. If the
+ result of applying <anno>SetFun</anno> to an element
+ of <anno>Set1</anno> yields an element in <anno>Set2</anno>,
+ the element belongs to <anno>Set3</anno>, otherwise the
+ element belongs to <anno>Set4</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{1,a},{2,b},{3,c}]),</input>
<input>S = sofs:set([2,4,6]),</input>
@@ -1289,21 +1197,17 @@ true</pre>
</desc>
</func>
<func>
- <name>partition_family(SetFun, Set) -> Family</name>
+ <name name="partition_family" arity="2"/>
<fsummary>Return a family indexing a partition.</fsummary>
- <type>
- <v>Family = family()</v>
- <v>SetFun = set_fun()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#family">family</seealso>
- Family where the indexed set is
- a <seealso marker="#partition">partition</seealso> of Set
- such that two elements are considered equal if the results
- of applying SetFun are the same value i. This i is the index
- that Family maps onto
- the <seealso marker="#equivalence_class">equivalence
+ <anno>Family</anno> where the indexed set is
+ a <seealso marker="#partition">partition</seealso>
+ of <anno>Set</anno> such that two elements are considered
+ equal if the results of applying <anno>SetFun</anno> are the
+ same value i. This i is the index that <anno>Family</anno>
+ maps onto
+ the <seealso marker="#equivalence_class">equivalence
class</seealso>.</p>
<pre>
1> <input>S = sofs:relation([{a,a,a,a},{a,a,b,b},{a,b,b,b}]),</input>
@@ -1314,18 +1218,15 @@ true</pre>
</desc>
</func>
<func>
- <name>product(TupleOfSets) -> Relation</name>
+ <name name="product" arity="1"/>
<fsummary>Return the Cartesian product of a tuple of sets.</fsummary>
- <type>
- <v>Relation = relation()</v>
- <v>TupleOfSets = tuple-of(set())</v>
- </type>
<desc>
<p>Returns the <seealso marker="#Cartesian_product_tuple">Cartesian
product</seealso> of the non-empty tuple of sets
- TupleOfSets. If (x[1],&nbsp;...,&nbsp;x[n]) is an element of
- the n-ary relation Relation, then x[i] is drawn from element
- i of TupleOfSets.</p>
+ <anno>TupleOfSets</anno>. If (x[1],&nbsp;...,&nbsp;x[n]) is
+ an element of the n-ary relation <anno>Relation</anno>, then
+ x[i] is drawn from element i
+ of <anno>TupleOfSets</anno>.</p>
<pre>
1> <input>S1 = sofs:set([a,b]),</input>
<input>S2 = sofs:set([1,2]),</input>
@@ -1336,15 +1237,12 @@ true</pre>
</desc>
</func>
<func>
- <name>product(Set1, Set2) -> BinRel</name>
+ <name name="product" arity="2"/>
<fsummary>Return the Cartesian product of two sets.</fsummary>
- <type>
- <v>BinRel = binary_relation()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#Cartesian_product">Cartesian
- product</seealso> of Set1 and Set2.</p>
+ product</seealso> of <anno>Set1</anno>
+ and <anno>Set2</anno>.</p>
<pre>
1> <input>S1 = sofs:set([1,2]),</input>
<input>S2 = sofs:set([a,b]),</input>
@@ -1356,19 +1254,16 @@ true</pre>
</desc>
</func>
<func>
- <name>projection(SetFun, Set1) -> Set2</name>
+ <name name="projection" arity="2"/>
<fsummary>Return a set of substituted elements.</fsummary>
- <type>
- <v>SetFun = set_fun()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
<p>Returns the set created by substituting each element of
- Set1 by the result of applying SetFun to the element.</p>
- <p>If SetFun is a number i&nbsp;&gt;=&nbsp;1 and Set1 is a
- relation, then the returned set is
- the <seealso marker="#projection">projection</seealso> of Set1
- onto coordinate i.</p>
+ <anno>Set1</anno> by the result of
+ applying <anno>SetFun</anno> to the element.</p>
+ <p>If <anno>SetFun</anno> is a number i&nbsp;&gt;=&nbsp;1 and
+ <anno>Set1</anno> is a relation, then the returned set is
+ the <seealso marker="#projection">projection</seealso> of
+ <anno>Set1</anno> onto coordinate i.</p>
<pre>
1> <input>S1 = sofs:from_term([{1,a},{2,b},{3,a}]),</input>
<input>S2 = sofs:projection(2, S1),</input>
@@ -1377,15 +1272,11 @@ true</pre>
</desc>
</func>
<func>
- <name>range(BinRel) -> Set</name>
+ <name name="range" arity="1"/>
<fsummary>Return the range of a binary relation.</fsummary>
- <type>
- <v>BinRel = binary_relation()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#range">range</seealso> of the
- binary relation BinRel.</p>
+ binary relation <anno>BinRel</anno>.</p>
<pre>
1> <input>R = sofs:relation([{1,a},{1,b},{2,b},{2,c}]),</input>
<input>S = sofs:range(R),</input>
@@ -1394,41 +1285,33 @@ true</pre>
</desc>
</func>
<func>
- <name>relation(Tuples [, Type]) -> Relation</name>
+ <name name="relation" arity="1"/>
+ <name name="relation" arity="2"/>
<fsummary>Create a relation.</fsummary>
- <type>
- <v>N = integer()</v>
- <v>Type = N | type()</v>
- <v>Relation = relation()</v>
- <v>Tuples = [tuple()]</v>
- </type>
<desc>
<p>Creates a <seealso marker="#relation">relation</seealso>.
<c>relation(R,&nbsp;T)</c> is equivalent to
<c>from_term(R,&nbsp;T)</c>, if T is
a <seealso marker="#type">type</seealso> and the result is a
- relation. If Type is an integer N, then
+ relation. If <anno>Type</anno> is an integer N, then
<c>[{atom,&nbsp;...,&nbsp;atom}])</c>, where the size of the
tuple is N, is used as type of the relation. If no type is
- explicitly given, the size of the first tuple of Tuples is
+ explicitly given, the size of the first tuple of
+ <anno>Tuples</anno> is
used if there is such a tuple. <c>relation([])</c> is
equivalent to <c>relation([],&nbsp;2)</c>.</p>
</desc>
</func>
<func>
- <name>relation_to_family(BinRel) -> Family</name>
+ <name name="relation_to_family" arity="1"/>
<fsummary>Create a family from a binary relation.</fsummary>
- <type>
- <v>Family = family()</v>
- <v>BinRel = binary_relation()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#family">family</seealso>
- Family such that the index set is equal to
+ <anno>Family</anno> such that the index set is equal to
the <seealso marker="#domain">domain</seealso> of the binary
- relation BinRel, and Family[i] is
+ relation <anno>BinRel</anno>, and <anno>Family</anno>[i] is
the <seealso marker="#image">image</seealso> of the set of i
- under BinRel.</p>
+ under <anno>BinRel</anno>.</p>
<pre>
1> <input>R = sofs:relation([{b,1},{c,2},{c,3}]),</input>
<input>F = sofs:relation_to_family(R),</input>
@@ -1437,63 +1320,57 @@ true</pre>
</desc>
</func>
<func>
- <name>relative_product(TupleOfBinRels [, BinRel1]) -> BinRel2</name>
- <fsummary>Return the relative product of a tuple of binary relations
+ <name name="relative_product" arity="1"/>
+ <name name="relative_product" arity="2" clause_i="1"/>
+ <fsummary>Return the relative product of a list of binary relations
and a binary relation.</fsummary>
- <type>
- <v>TupleOfBinRels = tuple-of(BinRel)</v>
- <v>BinRel = BinRel1 = BinRel2 = binary_relation()</v>
- </type>
- <desc>
- <p>If TupleOfBinRels is a non-empty tuple
- {R[1],&nbsp;...,&nbsp;R[n]} of binary relations and BinRel1
- is a binary relation, then BinRel2 is
- the <seealso marker="#tuple_relative_product">relative
- product</seealso> of the ordered set (R[i],&nbsp;...,&nbsp;R[n])
- and BinRel1.</p>
- <p>If BinRel1 is omitted, the relation of equality between the
- elements of
- the <seealso marker="#Cartesian_product_tuple">Cartesian
- product</seealso> of the ranges of R[i],
+ <desc>
+ <p>If <anno>ListOfBinRels</anno> is a non-empty list
+ [R[1],&nbsp;...,&nbsp;R[n]] of binary relations and
+ <anno>BinRel1</anno>
+ is a binary relation, then <anno>BinRel2</anno> is the <seealso
+ marker="#tuple_relative_product">relative product</seealso>
+ of the ordered set (R[i],&nbsp;...,&nbsp;R[n]) and
+ <anno>BinRel1</anno>.</p>
+ <p>If <anno>BinRel1</anno> is omitted, the relation of equality
+ between the elements of
+ the <seealso marker="#Cartesian_product_tuple">Cartesian
+ product</seealso> of the ranges of R[i],
range&nbsp;R[1]&nbsp;&times;&nbsp;...&nbsp;&times;&nbsp;range&nbsp;R[n],
is used instead (intuitively, nothing is "lost").</p>
<pre>
1> <input>TR = sofs:relation([{1,a},{1,aa},{2,b}]),</input>
<input>R1 = sofs:relation([{1,u},{2,v},{3,c}]),</input>
-<input>R2 = sofs:relative_product({TR, R1}),</input>
+<input>R2 = sofs:relative_product([TR, R1]),</input>
<input>sofs:to_external(R2).</input>
[{1,{a,u}},{1,{aa,u}},{2,{b,v}}]</pre>
- <p>Note that <c>relative_product({R1},&nbsp;R2)</c> is
+ <p>Note that <c>relative_product([R1],&nbsp;R2)</c> is
different from <c>relative_product(R1,&nbsp;R2)</c>; the
- tuple of one element is not identified with the element
+ list of one element is not identified with the element
itself.</p>
</desc>
</func>
<func>
- <name>relative_product(BinRel1, BinRel2) -> BinRel3</name>
+ <name name="relative_product" arity="2" clause_i="2"/>
<fsummary>Return the relative product of
two binary relations.</fsummary>
- <type>
- <v>BinRel1 = BinRel2 = BinRel3 = binary_relation()</v>
- </type>
<desc>
<p><marker id="relprod_impl"></marker>Returns
the <seealso marker="#relative_product">relative
- product</seealso> of the binary relations BinRel1 and BinRel2.</p>
+ product</seealso> of the binary relations <anno>BinRel1</anno>
+ and <anno>BinRel2</anno>.</p>
</desc>
</func>
<func>
- <name>relative_product1(BinRel1, BinRel2) -> BinRel3</name>
+ <name name="relative_product1" arity="2"/>
<fsummary>Return the relative_product of
two binary relations.</fsummary>
- <type>
- <v>BinRel1 = BinRel2 = BinRel3 = binary_relation()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#relative_product">relative
product</seealso> of
the <seealso marker="#converse">converse</seealso> of the
- binary relation BinRel1 and the binary relation BinRel2.</p>
+ binary relation <anno>BinRel1</anno> and the binary
+ relation <anno>BinRel2</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{1,a},{1,aa},{2,b}]),</input>
<input>R2 = sofs:relation([{1,u},{2,v},{3,c}]),</input>
@@ -1505,15 +1382,12 @@ true</pre>
</desc>
</func>
<func>
- <name>restriction(BinRel1, Set) -> BinRel2</name>
+ <name name="restriction" arity="2"/>
<fsummary>Return a restriction of a binary relation.</fsummary>
- <type>
- <v>BinRel1 = BinRel2 = binary_relation()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#restriction">restriction</seealso> of
- the binary relation BinRel1 to Set.</p>
+ the binary relation <anno>BinRel1</anno>
+ to <anno>Set</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{1,a},{2,b},{3,c}]),</input>
<input>S = sofs:set([1,2,4]),</input>
@@ -1523,15 +1397,12 @@ true</pre>
</desc>
</func>
<func>
- <name>restriction(SetFun, Set1, Set2) -> Set3</name>
+ <name name="restriction" arity="3"/>
<fsummary>Return a restriction of a set.</fsummary>
- <type>
- <v>SetFun = set_fun()</v>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
- <p>Returns a subset of Set1 containing those elements that
- yield an element in Set2 as the result of applying SetFun.</p>
+ <p>Returns a subset of <anno>Set1</anno> containing those
+ elements that yield an element in <anno>Set2</anno> as the
+ result of applying <anno>SetFun</anno>.</p>
<pre>
1> <input>S1 = sofs:relation([{1,a},{2,b},{3,c}]),</input>
<input>S2 = sofs:set([b,c,d]),</input>
@@ -1541,13 +1412,9 @@ true</pre>
</desc>
</func>
<func>
- <name>set(Terms [, Type]) -> Set</name>
+ <name name="set" arity="1"/>
+ <name name="set" arity="2"/>
<fsummary>Create a set of atoms or any type of sets.</fsummary>
- <type>
- <v>Set = set()</v>
- <v>Terms = [term()]</v>
- <v>Type = type()</v>
- </type>
<desc>
<p>Creates an <seealso marker="#sets_definition">unordered
set</seealso>. <c>set(L,&nbsp;T)</c> is equivalent to
@@ -1557,18 +1424,16 @@ true</pre>
</desc>
</func>
<func>
- <name>specification(Fun, Set1) -> Set2</name>
+ <name name="specification" arity="2"/>
<fsummary>Select a subset using a predicate.</fsummary>
- <type>
- <v>Fun = spec_fun()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
<desc>
- <p>Returns the set containing every element of Set1 for which
- Fun returns <c>true</c>. If Fun is a tuple
+ <p>Returns the set containing every element
+ of <anno>Set1</anno> for which <anno>Fun</anno>
+ returns <c>true</c>. If <anno>Fun</anno> is a tuple
<c>{external,&nbsp;Fun2}</c>, Fun2 is applied to the
<seealso marker="#external_set">external set</seealso> of
- each element, otherwise Fun is applied to each element.</p>
+ each element, otherwise <anno>Fun</anno> is applied to each
+ element.</p>
<pre>
1> <input>R1 = sofs:relation([{a,1},{b,2}]),</input>
<input>R2 = sofs:relation([{x,1},{x,2},{y,3}]),</input>
@@ -1579,15 +1444,13 @@ true</pre>
</desc>
</func>
<func>
- <name>strict_relation(BinRel1) -> BinRel2</name>
+ <name name="strict_relation" arity="1"/>
<fsummary>Return the strict relation corresponding to
a given relation.</fsummary>
- <type>
- <v>BinRel1 = BinRel2 = binary_relation()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#strict_relation">strict
- relation</seealso> corresponding to the binary relation BinRel1.</p>
+ relation</seealso> corresponding to the binary
+ relation <anno>BinRel1</anno>.</p>
<pre>
1> <input>R1 = sofs:relation([{1,1},{1,2},{2,1},{2,2}]),</input>
<input>R2 = sofs:strict_relation(R1),</input>
@@ -1596,16 +1459,13 @@ true</pre>
</desc>
</func>
<func>
- <name>substitution(SetFun, Set1) -> Set2</name>
+ <name name="substitution" arity="2"/>
<fsummary>Return a function with a given set as domain.</fsummary>
- <type>
- <v>SetFun = set_fun()</v>
- <v>Set1 = Set2 = set()</v>
- </type>
- <desc>
- <p>Returns a function, the domain of which is Set1. The value
- of an element of the domain is the result of applying SetFun
- to the element.</p>
+ <desc>
+ <p>Returns a function, the domain of which
+ is <anno>Set1</anno>. The value of an element of the domain
+ is the result of applying <anno>SetFun</anno> to the
+ element.</p>
<pre>
1> <input>L = [{a,1},{b,2}].</input>
[{a,1},{b,2}]
@@ -1647,14 +1507,12 @@ images2(SetOfSets, BinRel) ->
</desc>
</func>
<func>
- <name>symdiff(Set1, Set2) -> Set3</name>
+ <name name="symdiff" arity="2"/>
<fsummary>Return the symmetric difference of two sets.</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#symmetric_difference">symmetric
- difference</seealso> (or the Boolean sum) of Set1 and Set2.</p>
+ difference</seealso> (or the Boolean sum)
+ of <anno>Set1</anno> and <anno>Set2</anno>.</p>
<pre>
1> <input>S1 = sofs:set([1,2,3]),</input>
<input>S2 = sofs:set([2,3,4]),</input>
@@ -1664,88 +1522,67 @@ images2(SetOfSets, BinRel) ->
</desc>
</func>
<func>
- <name>symmetric_partition(Set1, Set2) -> {Set3, Set4, Set5}</name>
+ <name name="symmetric_partition" arity="2"/>
<fsummary>Return a partition of two sets.</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = Set4 = Set5 = set()</v>
- </type>
<desc>
- <p>Returns a triple of sets: Set3 contains the elements
- of Set1 that do not belong to Set2; Set4 contains the
- elements of Set1 that belong to Set2; Set5 contains the
- elements of Set2 that do not belong to Set1.</p>
+ <p>Returns a triple of sets: <anno>Set3</anno> contains the
+ elements of <anno>Set1</anno> that do not belong
+ to <anno>Set2</anno>; <anno>Set4</anno> contains the
+ elements of <anno>Set1</anno> that belong
+ to <anno>Set2</anno>; <anno>Set5</anno> contains the
+ elements of <anno>Set2</anno> that do not belong
+ to <anno>Set1</anno>.</p>
</desc>
</func>
<func>
- <name>to_external(AnySet) -> ExternalSet</name>
+ <name name="to_external" arity="1"/>
<fsummary>Return the elements of a set.</fsummary>
- <type>
- <v>ExternalSet = external_set()</v>
- <v>AnySet = anyset()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#external_set">external
set</seealso> of an atomic, ordered or unordered set.</p>
</desc>
</func>
<func>
- <name>to_sets(ASet) -> Sets</name>
+ <name name="to_sets" arity="1"/>
<fsummary>Return a list or a tuple of the elements of set.</fsummary>
- <type>
- <v>ASet = set() | ordset()</v>
- <v>Sets = tuple_of(AnySet) | [AnySet]</v>
- </type>
<desc>
- <p>Returns the elements of the ordered set ASet as a tuple of
- sets, and the elements of the unordered set ASet as a sorted
- list of sets without duplicates.</p>
+ <p>Returns the elements of the ordered set <anno>ASet</anno>
+ as a tuple of sets, and the elements of the unordered set
+ <anno>ASet</anno> as a sorted list of sets without
+ duplicates.</p>
</desc>
</func>
<func>
- <name>type(AnySet) -> Type</name>
+ <name name="type" arity="1"/>
<fsummary>Return the type of a set.</fsummary>
- <type>
- <v>AnySet = anyset()</v>
- <v>Type = type()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#type">type</seealso> of an
atomic, ordered or unordered set.</p>
</desc>
</func>
<func>
- <name>union(SetOfSets) -> Set</name>
+ <name name="union" arity="1"/>
<fsummary>Return the union of a set of sets.</fsummary>
- <type>
- <v>Set = set()</v>
- <v>SetOfSets = set_of_sets()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#union_n">union</seealso> of the
- set of sets SetOfSets.</p>
+ set of sets <anno>SetOfSets</anno>.</p>
</desc>
</func>
<func>
- <name>union(Set1, Set2) -> Set3</name>
+ <name name="union" arity="2"/>
<fsummary>Return the union of two sets.</fsummary>
- <type>
- <v>Set1 = Set2 = Set3 = set()</v>
- </type>
<desc>
<p>Returns the <seealso marker="#union">union</seealso> of
- Set1 and Set2.</p>
+ <anno>Set1</anno> and <anno>Set2</anno>.</p>
</desc>
</func>
<func>
- <name>union_of_family(Family) -> Set</name>
+ <name name="union_of_family" arity="1"/>
<fsummary>Return the union of a family.</fsummary>
- <type>
- <v>Family = family()</v>
- <v>Set = set()</v>
- </type>
<desc>
<p>Returns the union of
- the <seealso marker="#family">family</seealso> Family.</p>
+ the <seealso marker="#family">family</seealso> <anno>Family</anno>.
+ </p>
<pre>
1> <input>F = sofs:family([{a,[0,2,4]},{b,[0,1,2]},{c,[2,3]}]),</input>
<input>S = sofs:union_of_family(F),</input>
@@ -1754,17 +1591,15 @@ images2(SetOfSets, BinRel) ->
</desc>
</func>
<func>
- <name>weak_relation(BinRel1) -> BinRel2</name>
+ <name name="weak_relation" arity="1"/>
<fsummary>Return the weak relation corresponding to
a given relation.</fsummary>
- <type>
- <v>BinRel1 = BinRel2 = binary_relation()</v>
- </type>
<desc>
<p>Returns a subset S of the <seealso marker="#weak_relation">weak
relation</seealso> W
- corresponding to the binary relation BinRel1. Let F be the
- <seealso marker="#field">field</seealso> of BinRel1. The
+ corresponding to the binary relation <anno>BinRel1</anno>.
+ Let F be the <seealso marker="#field">field</seealso> of
+ <anno>BinRel1</anno>. The
subset S is defined so that x S y if x W y for some x in F
and for some y in F.</p>
<pre>
diff --git a/lib/stdlib/doc/src/specs.xml b/lib/stdlib/doc/src/specs.xml
new file mode 100644
index 0000000000..98338b5ec2
--- /dev/null
+++ b/lib/stdlib/doc/src/specs.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="latin1" ?>
+<specs xmlns:xi="http://www.w3.org/2001/XInclude">
+ <xi:include href="../specs/specs_array.xml"/>
+ <xi:include href="../specs/specs_base64.xml"/>
+ <xi:include href="../specs/specs_beam_lib.xml"/>
+ <xi:include href="../specs/specs_binary.xml"/>
+ <xi:include href="../specs/specs_c.xml"/>
+ <xi:include href="../specs/specs_calendar.xml"/>
+ <xi:include href="../specs/specs_dets.xml"/>
+ <xi:include href="../specs/specs_dict.xml"/>
+ <xi:include href="../specs/specs_digraph.xml"/>
+ <xi:include href="../specs/specs_digraph_utils.xml"/>
+ <xi:include href="../specs/specs_epp.xml"/>
+ <xi:include href="../specs/specs_erl_eval.xml"/>
+ <xi:include href="../specs/specs_erl_expand_records.xml"/>
+ <xi:include href="../specs/specs_erl_id_trans.xml"/>
+ <xi:include href="../specs/specs_erl_internal.xml"/>
+ <xi:include href="../specs/specs_erl_lint.xml"/>
+ <xi:include href="../specs/specs_erl_parse.xml"/>
+ <xi:include href="../specs/specs_erl_pp.xml"/>
+ <xi:include href="../specs/specs_erl_scan.xml"/>
+ <xi:include href="../specs/specs_erl_tar.xml"/>
+ <xi:include href="../specs/specs_ets.xml"/>
+ <xi:include href="../specs/specs_file_sorter.xml"/>
+ <xi:include href="../specs/specs_filelib.xml"/>
+ <xi:include href="../specs/specs_filename.xml"/>
+ <xi:include href="../specs/specs_gb_sets.xml"/>
+ <xi:include href="../specs/specs_gb_trees.xml"/>
+ <xi:include href="../specs/specs_gen_event.xml"/>
+ <xi:include href="../specs/specs_gen_fsm.xml"/>
+ <xi:include href="../specs/specs_gen_server.xml"/>
+ <xi:include href="../specs/specs_io.xml"/>
+ <xi:include href="../specs/specs_io_lib.xml"/>
+ <xi:include href="../specs/specs_lib.xml"/>
+ <xi:include href="../specs/specs_lists.xml"/>
+ <xi:include href="../specs/specs_log_mf_h.xml"/>
+ <xi:include href="../specs/specs_math.xml"/>
+ <xi:include href="../specs/specs_ms_transform.xml"/>
+ <xi:include href="../specs/specs_orddict.xml"/>
+ <xi:include href="../specs/specs_ordsets.xml"/>
+ <xi:include href="../specs/specs_pg.xml"/>
+ <xi:include href="../specs/specs_pool.xml"/>
+ <xi:include href="../specs/specs_proc_lib.xml"/>
+ <xi:include href="../specs/specs_proplists.xml"/>
+ <xi:include href="../specs/specs_qlc.xml"/>
+ <xi:include href="../specs/specs_queue.xml"/>
+ <xi:include href="../specs/specs_random.xml"/>
+ <xi:include href="../specs/specs_re.xml"/>
+ <xi:include href="../specs/specs_regexp.xml"/>
+ <xi:include href="../specs/specs_sets.xml"/>
+ <xi:include href="../specs/specs_shell.xml"/>
+ <xi:include href="../specs/specs_shell_default.xml"/>
+ <xi:include href="../specs/specs_slave.xml"/>
+ <xi:include href="../specs/specs_sofs.xml"/>
+ <xi:include href="../specs/specs_string.xml"/>
+ <xi:include href="../specs/specs_supervisor.xml"/>
+ <xi:include href="../specs/specs_supervisor_bridge.xml"/>
+ <xi:include href="../specs/specs_sys.xml"/>
+ <xi:include href="../specs/specs_timer.xml"/>
+ <xi:include href="../specs/specs_unicode.xml"/>
+ <xi:include href="../specs/specs_win32reg.xml"/>
+ <xi:include href="../specs/specs_zip.xml"/>
+</specs>
diff --git a/lib/stdlib/doc/src/string.xml b/lib/stdlib/doc/src/string.xml
index de1b99a2d5..48867ffe72 100644
--- a/lib/stdlib/doc/src/string.xml
+++ b/lib/stdlib/doc/src/string.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>1996</year><year>2009</year>
+ <year>1996</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -38,65 +38,46 @@
</description>
<funcs>
<func>
- <name>len(String) -> Length</name>
+ <name name="len" arity="1"/>
<fsummary>Return the length of a string</fsummary>
- <type>
- <v>String = string()</v>
- <v>Length = integer()</v>
- </type>
<desc>
<p>Returns the number of characters in the string.</p>
</desc>
</func>
<func>
- <name>equal(String1, String2) -> bool()</name>
+ <name name="equal" arity="2"/>
<fsummary>Test string equality</fsummary>
- <type>
- <v>String1 = String2 = string()</v>
- </type>
<desc>
<p>Tests whether two strings are equal. Returns <c>true</c> if
they are, otherwise <c>false</c>.</p>
</desc>
</func>
<func>
- <name>concat(String1, String2) -> String3</name>
+ <name name="concat" arity="2"/>
<fsummary>Concatenate two strings</fsummary>
- <type>
- <v>String1 = String2 = String3 = string()</v>
- </type>
<desc>
<p>Concatenates two strings to form a new string. Returns the
new string.</p>
</desc>
</func>
<func>
- <name>chr(String, Character) -> Index</name>
- <name>rchr(String, Character) -> Index</name>
+ <name name="chr" arity="2"/>
+ <name name="rchr" arity="2"/>
<fsummary>Return the index of the first/last occurrence of<c>Character</c>in <c>String</c></fsummary>
- <type>
- <v>String = string()</v>
- <v>Character = char()</v>
- <v>Index = integer()</v>
- </type>
<desc>
<p>Returns the index of the first/last occurrence of
- <c>Character</c> in <c>String</c>. <c>0</c> is returned if <c>Character</c> does not
+ <c><anno>Character</anno></c> in <c><anno>String</anno></c>. <c>0</c> is returned if <c><anno>Character</anno></c> does not
occur.</p>
</desc>
</func>
<func>
- <name>str(String, SubString) -> Index</name>
- <name>rstr(String, SubString) -> Index</name>
+ <name name="str" arity="2"/>
+ <name name="rstr" arity="2"/>
<fsummary>Find the index of a substring</fsummary>
- <type>
- <v>String = SubString = string()</v>
- <v>Index = integer()</v>
- </type>
<desc>
<p>Returns the position where the first/last occurrence of
- <c>SubString</c> begins in <c>String</c>. <c>0</c> is returned if <c>SubString</c>
- does not exist in <c>String</c>.
+ <c><anno>SubString</anno></c> begins in <c><anno>String</anno></c>. <c>0</c> is returned if <c><anno>SubString</anno></c>
+ does not exist in <c><anno>String</anno></c>.
For example:</p>
<code type="none">
> string:str(" Hello Hello World World ", "Hello World").
@@ -104,17 +85,13 @@
</desc>
</func>
<func>
- <name>span(String, Chars) -> Length </name>
- <name>cspan(String, Chars) -> Length</name>
+ <name name="span" arity="2"/>
+ <name name="cspan" arity="2"/>
<fsummary>Span characters at start of string</fsummary>
- <type>
- <v>String = Chars = string()</v>
- <v>Length = integer()</v>
- </type>
<desc>
<p>Returns the length of the maximum initial segment of
- String, which consists entirely of characters from (not
- from) Chars.</p>
+ <c><anno>String</anno></c>, which consists entirely of characters from (not
+ from) <c><anno>Chars</anno></c>.</p>
<p>For example:</p>
<code type="none">
> string:span("\t abcdef", " \t").
@@ -124,17 +101,13 @@
</desc>
</func>
<func>
- <name>substr(String, Start) -> SubString</name>
- <name>substr(String, Start, Length) -> Substring</name>
+ <name name="substr" arity="2"/>
+ <name name="substr" arity="3"/>
<fsummary>Return a substring of <c>String</c></fsummary>
- <type>
- <v>String = SubString = string()</v>
- <v>Start = Length = integer()</v>
- </type>
<desc>
- <p>Returns a substring of <c>String</c>, starting at the
- position <c>Start</c>, and ending at the end of the string or
- at length <c>Length</c>.</p>
+ <p>Returns a substring of <c><anno>String</anno></c>, starting at the
+ position <c><anno>Start</anno></c>, and ending at the end of the string or
+ at length <c><anno>Length</anno></c>.</p>
<p>For example:</p>
<code type="none">
> substr("Hello World", 4, 5).
@@ -142,15 +115,11 @@
</desc>
</func>
<func>
- <name>tokens(String, SeparatorList) -> Tokens</name>
+ <name name="tokens" arity="2"/>
<fsummary>Split string into tokens</fsummary>
- <type>
- <v>String = SeparatorList = string()</v>
- <v>Tokens = [string()]</v>
- </type>
<desc>
- <p>Returns a list of tokens in <c>String</c>, separated by the
- characters in <c>SeparatorList</c>.</p>
+ <p>Returns a list of tokens in <c><anno>String</anno></c>, separated by the
+ characters in <c><anno>SeparatorList</anno></c>.</p>
<p>For example:</p>
<code type="none">
> tokens("abc defxxghix jkl", "x ").
@@ -158,15 +127,11 @@
</desc>
</func>
<func>
- <name>join(StringList, Separator) -> String</name>
+ <name name="join" arity="2"/>
<fsummary>Join a list of strings with separator</fsummary>
- <type>
- <v>StringList = [string()]</v>
- <v>Separator = string()</v>
- </type>
<desc>
- <p>Returns a string with the elements of <c>StringList</c>
- separated by the string in <c>Seperator</c>.</p>
+ <p>Returns a string with the elements of <c><anno>StringList</anno></c>
+ separated by the string in <c><anno>Separator</anno></c>.</p>
<p>For example:</p>
<code type="none">
> join(["one", "two", "three"], ", ").
@@ -174,44 +139,30 @@
</desc>
</func>
<func>
- <name>chars(Character, Number) -> String</name>
- <name>chars(Character, Number, Tail) -> String</name>
+ <name name="chars" arity="2"/>
+ <name name="chars" arity="3"/>
<fsummary>Returns a string consisting of numbers of characters</fsummary>
- <type>
- <v>Character = char()</v>
- <v>Number = integer()</v>
- <v>String = string()</v>
- </type>
<desc>
- <p>Returns a string consisting of <c>Number</c> of characters
- <c>Character</c>. Optionally, the string can end with the
- string <c>Tail</c>.</p>
+ <p>Returns a string consisting of <c><anno>Number</anno></c> of characters
+ <c><anno>Character</anno></c>. Optionally, the string can end with the
+ string <c><anno>Tail</anno></c>.</p>
</desc>
</func>
<func>
- <name>copies(String, Number) -> Copies</name>
+ <name name="copies" arity="2"/>
<fsummary>Copy a string</fsummary>
- <type>
- <v>String = Copies = string()</v>
- <v>Number = integer()</v>
- </type>
<desc>
- <p>Returns a string containing <c>String</c> repeated
- <c>Number</c> times.</p>
+ <p>Returns a string containing <c><anno>String</anno></c> repeated
+ <c><anno>Number</anno></c> times.</p>
</desc>
</func>
<func>
- <name>words(String) -> Count</name>
- <name>words(String, Character) -> Count</name>
+ <name name="words" arity="1"/>
+ <name name="words" arity="2"/>
<fsummary>Count blank separated words</fsummary>
- <type>
- <v>String = string()</v>
- <v>Character = char()</v>
- <v>Count = integer()</v>
- </type>
<desc>
- <p>Returns the number of words in <c>String</c>, separated by
- blanks or <c>Character</c>.</p>
+ <p>Returns the number of words in <c><anno>String</anno></c>, separated by
+ blanks or <c><anno>Character</anno></c>.</p>
<p>For example:</p>
<code type="none">
> words(" Hello old boy!", $o).
@@ -219,17 +170,12 @@
</desc>
</func>
<func>
- <name>sub_word(String, Number) -> Word</name>
- <name>sub_word(String, Number, Character) -> Word</name>
+ <name name="sub_word" arity="2"/>
+ <name name="sub_word" arity="3"/>
<fsummary>Extract subword</fsummary>
- <type>
- <v>String = Word = string()</v>
- <v>Character = char()</v>
- <v>Number = integer()</v>
- </type>
<desc>
- <p>Returns the word in position <c>Number</c> of <c>String</c>.
- Words are separated by blanks or <c>Character</c>s.</p>
+ <p>Returns the word in position <c><anno>Number</anno></c> of <c><anno>String</anno></c>.
+ Words are separated by blanks or <c><anno>Character</anno></c>s.</p>
<p>For example:</p>
<code type="none">
> string:sub_word(" Hello old boy !",3,$o).
@@ -237,19 +183,14 @@
</desc>
</func>
<func>
- <name>strip(String) -> Stripped</name>
- <name>strip(String, Direction) -> Stripped</name>
- <name>strip(String, Direction, Character) -> Stripped</name>
+ <name name="strip" arity="1"/>
+ <name name="strip" arity="2"/>
+ <name name="strip" arity="3"/>
<fsummary>Strip leading or trailing characters</fsummary>
- <type>
- <v>String = Stripped = string()</v>
- <v>Direction = left | right | both</v>
- <v>Character = char()</v>
- </type>
<desc>
<p>Returns a string, where leading and/or trailing blanks or a
- number of <c>Character</c> have been removed.
- <c>Direction</c> can be <c>left</c>, <c>right</c>, or
+ number of <c><anno>Character</anno></c> have been removed.
+ <c><anno>Direction</anno></c> can be <c>left</c>, <c>right</c>, or
<c>both</c> and indicates from which direction blanks are to be
removed. The function <c>strip/1</c> is equivalent to
<c>strip(String, both)</c>.</p>
@@ -260,19 +201,14 @@
</desc>
</func>
<func>
- <name>left(String, Number) -> Left</name>
- <name>left(String, Number, Character) -> Left</name>
+ <name name="left" arity="2"/>
+ <name name="left" arity="3"/>
<fsummary>Adjust left end of string</fsummary>
- <type>
- <v>String = Left = string()</v>
- <v>Character = char</v>
- <v>Number = integer()</v>
- </type>
<desc>
- <p>Returns the <c>String</c> with the length adjusted in
- accordance with <c>Number</c>. The left margin is
- fixed. If the <c>length(String)</c> &lt; <c>Number</c>,
- <c>String</c> is padded with blanks or <c>Character</c>s.</p>
+ <p>Returns the <c><anno>String</anno></c> with the length adjusted in
+ accordance with <c><anno>Number</anno></c>. The left margin is
+ fixed. If the <c>length(<anno>String</anno>)</c> &lt; <c><anno>Number</anno></c>,
+ <c><anno>String</anno></c> is padded with blanks or <c><anno>Character</anno></c>s.</p>
<p>For example:</p>
<code type="none">
> string:left("Hello",10,$.).
@@ -280,19 +216,14 @@
</desc>
</func>
<func>
- <name>right(String, Number) -> Right</name>
- <name>right(String, Number, Character) -> Right</name>
+ <name name="right" arity="2"/>
+ <name name="right" arity="3"/>
<fsummary>Adjust right end of string</fsummary>
- <type>
- <v>String = Right = string()</v>
- <v>Character = char</v>
- <v>Number = integer()</v>
- </type>
<desc>
- <p>Returns the <c>String</c> with the length adjusted in
- accordance with <c>Number</c>. The right margin is
- fixed. If the length of <c>(String)</c> &lt; <c>Number</c>,
- <c>String</c> is padded with blanks or <c>Character</c>s.</p>
+ <p>Returns the <c><anno>String</anno></c> with the length adjusted in
+ accordance with <c><anno>Number</anno></c>. The right margin is
+ fixed. If the length of <c>(<anno>String</anno>)</c> &lt; <c><anno>Number</anno></c>,
+ <c><anno>String</anno></c> is padded with blanks or <c><anno>Character</anno></c>s.</p>
<p>For example:</p>
<code type="none">
> string:right("Hello", 10, $.).
@@ -300,32 +231,23 @@
</desc>
</func>
<func>
- <name>centre(String, Number) -> Centered</name>
- <name>centre(String, Number, Character) -> Centered</name>
+ <name name="centre" arity="2"/>
+ <name name="centre" arity="3"/>
<fsummary>Center a string</fsummary>
- <type>
- <v>String = Centered = string()</v>
- <v>Character = char</v>
- <v>Number = integer()</v>
- </type>
<desc>
- <p>Returns a string, where <c>String</c> is centred in the
+ <p>Returns a string, where <c><anno>String</anno></c> is centred in the
string and surrounded by blanks or characters. The resulting
- string will have the length <c>Number</c>.</p>
+ string will have the length <c><anno>Number</anno></c>.</p>
</desc>
</func>
<func>
- <name>sub_string(String, Start) -> SubString</name>
- <name>sub_string(String, Start, Stop) -> SubString</name>
+ <name name="sub_string" arity="2"/>
+ <name name="sub_string" arity="3"/>
<fsummary>Extract a substring</fsummary>
- <type>
- <v>String = SubString = string()</v>
- <v>Start = Stop = integer()</v>
- </type>
<desc>
- <p>Returns a substring of <c>String</c>, starting at the
- position <c>Start</c> to the end of the string, or to and
- including the <c>Stop</c> position.</p>
+ <p>Returns a substring of <c><anno>String</anno></c>, starting at the
+ position <c><anno>Start</anno></c> to the end of the string, or to and
+ including the <c><anno>Stop</anno></c> position.</p>
<p>For example:</p>
<code type="none">
sub_string("Hello World", 4, 8).
@@ -383,15 +305,15 @@ sub_string("Hello World", 4, 8).
</desc>
</func>
<func>
- <name>to_lower(String) -> Result</name>
- <name>to_lower(Char) -> CharResult</name>
- <name>to_upper(String) -> Result</name>
- <name>to_upper(Char) -> CharResult</name>
+ <name name="to_lower" arity="1" clause_i="1"/>
+ <name name="to_lower" arity="1" clause_i="2"/>
+ <name name="to_upper" arity="1" clause_i="1"/>
+ <name name="to_upper" arity="1" clause_i="2"/>
<fsummary>Convert case of string (ISO/IEC 8859-1)</fsummary>
- <type>
- <v>String = Result = string()</v>
- <v>Char = CharResult = integer()</v>
- </type>
+ <type variable="String" name_i="1"/>
+ <type variable="Result" name_i="1"/>
+ <type variable="Char"/>
+ <type variable="CharResult"/>
<desc>
<p>The given string or character is case-converted. Note that
the supported character set is ISO/IEC 8859-1 (a.k.a. Latin 1),
diff --git a/lib/stdlib/doc/src/supervisor.xml b/lib/stdlib/doc/src/supervisor.xml
index d6203bdaa0..009aa60faa 100644
--- a/lib/stdlib/doc/src/supervisor.xml
+++ b/lib/stdlib/doc/src/supervisor.xml
@@ -199,51 +199,81 @@ child_spec() = {Id,StartFunc,Restart,Shutdown,Type,Modules}
</item>
</list>
</section>
+ <datatypes>
+ <datatype>
+ <name name="child"/>
+ </datatype>
+ <datatype>
+ <name name="child_id"/>
+ <desc><p>Not a <c>pid()</c>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="child_spec"/>
+ </datatype>
+ <datatype>
+ <name name="mfargs"/>
+ <desc><p><c>A</c> (the argument list) has the value
+ <c>undefined</c> if <c>Restart</c> is <c>temporary</c>.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="modules"/>
+ </datatype>
+ <datatype>
+ <name name="restart"/>
+ </datatype>
+ <datatype>
+ <name name="shutdown"/>
+ </datatype>
+ <datatype>
+ <name name="strategy"/>
+ </datatype>
+ <datatype>
+ <name name="sup_ref"/>
+ </datatype>
+ <datatype>
+ <name name="worker"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>start_link(Module, Args) -> Result</name>
- <name>start_link(SupName, Module, Args) -> Result</name>
+ <name name="start_link" arity="2"/>
+ <name name="start_link" arity="3"/>
<fsummary>Create a supervisor process.</fsummary>
- <type>
- <v>SupName = {local,Name} | {global,Name}</v>
- <v>&nbsp;Name = atom()</v>
- <v>Module = atom()</v>
- <v>Args = term()</v>
- <v>Result = {ok,Pid} | ignore | {error,Error}</v>
- <v>&nbsp;Pid = pid()</v>
- <v>&nbsp;Error = {already_started,Pid}} | shutdown | term()</v>
- </type>
+ <type name="startlink_ret"/>
+ <type name="startlink_err"/>
+ <type name="sup_name"/>
<desc>
<p>Creates a supervisor process as part of a supervision tree.
The function will, among other things, ensure that
the supervisor is linked to the calling process (its
supervisor).</p>
- <p>The created supervisor process calls <c>Module:init/1</c> to
+ <p>The created supervisor process calls <c><anno>Module</anno>:init/1</c> to
find out about restart strategy, maximum restart frequency
and child processes. To ensure a synchronized start-up
procedure, <c>start_link/2,3</c> does not return until
- <c>Module:init/1</c> has returned and all child processes
+ <c><anno>Module</anno>:init/1</c> has returned and all child processes
have been started.</p>
- <p>If <c>SupName={local,Name}</c> the supervisor is registered
+ <p>If <c><anno>SupName</anno>={local,Name}</c> the supervisor is registered
locally as <c>Name</c> using <c>register/2</c>. If
- <c>SupName={global,Name}</c> the supervisor is registered
+ <c><anno>SupName</anno>={global,Name}</c> the supervisor is registered
globally as <c>Name</c> using <c>global:register_name/2</c>.
If no name is provided, the supervisor is not registered.</p>
- <p><c>Module</c> is the name of the callback module.</p>
- <p><c>Args</c> is an arbitrary term which is passed as
- the argument to <c>Module:init/1</c>.</p>
+ <p><c><anno>Module</anno></c> is the name of the callback module.</p>
+ <p><c><anno>Args</anno></c> is an arbitrary term which is passed as
+ the argument to <c><anno>Module</anno>:init/1</c>.</p>
<p>If the supervisor and its child processes are successfully
created (i.e. if all child process start functions return
<c>{ok,Child}</c>, <c>{ok,Child,Info}</c>, or <c>ignore</c>)
the function returns <c>{ok,Pid}</c>, where <c>Pid</c> is
the pid of the supervisor. If there already exists a process
- with the specified <c>SupName</c> the function returns
+ with the specified <c><anno>SupName</anno></c> the function returns
<c>{error,{already_started,Pid}}</c>, where <c>Pid</c> is
the pid of that process.</p>
- <p>If <c>Module:init/1</c> returns <c>ignore</c>, this function
+ <p>If <c><anno>Module</anno>:init/1</c> returns <c>ignore</c>, this function
returns <c>ignore</c> as well and the supervisor terminates
with reason <c>normal</c>.
- If <c>Module:init/1</c> fails or returns an incorrect value,
+ If <c><anno>Module</anno>:init/1</c> fails or returns an incorrect value,
this function returns <c>{error,Term}</c> where <c>Term</c>
is a term with information about the error, and the supervisor
terminates with reason <c>Term</c>.</p>
@@ -255,21 +285,15 @@ child_spec() = {Id,StartFunc,Restart,Shutdown,Type,Modules}
</desc>
</func>
<func>
- <name>start_child(SupRef, ChildSpec) -> Result</name>
+ <name name="start_child" arity="2"/>
<fsummary>Dynamically add a child process to a supervisor.</fsummary>
- <type>
- <v>SupRef = Name | {Name,Node} | {global,Name} | pid()</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>ChildSpec = child_spec() | [term()]</v>
- <v>Result = {ok,Child} | {ok,Child,Info} | {error,Error}</v>
- <v>&nbsp;Child = pid() | undefined</v>
- <v>&nbsp;Info = term()</v>
- <v>&nbsp;Error = already_present | {already_started,Child} | term()</v>
- </type>
+ <type name="child_spec"/>
+ <type name="startchild_ret"/>
+ <type name="startchild_err"/>
<desc>
<p>Dynamically adds a child specification to the supervisor
- <c>SupRef</c> which starts the corresponding child process.</p>
- <p><c>SupRef</c> can be:</p>
+ <c><anno>SupRef</anno></c> which starts the corresponding child process.</p>
+ <p><marker id="SupRef"><c><anno>SupRef</anno></c></marker> can be:</p>
<list type="bulleted">
<item>the pid,</item>
<item><c>Name</c>, if the supervisor is locally registered,</item>
@@ -278,26 +302,26 @@ child_spec() = {Id,StartFunc,Restart,Shutdown,Type,Modules}
<item><c>{global,Name}</c>, if the supervisor is globally
registered.</item>
</list>
- <p><c>ChildSpec</c> should be a valid child specification
+ <p><c><anno>ChildSpec</anno></c> should be a valid child specification
(unless the supervisor is a <c>simple_one_for_one</c>
supervisor, see below). The child process will be started by
using the start function as defined in the child
specification.</p>
<p>If the case of a <c>simple_one_for_one</c> supervisor,
the child specification defined in <c>Module:init/1</c> will
- be used and <c>ChildSpec</c> should instead be an arbitrary
- list of terms <c>List</c>. The child process will then be
- started by appending <c>List</c> to the existing start
+ be used and <c><anno>ChildSpec</anno></c> should instead be an arbitrary
+ list of terms <c><anno>List</anno></c>. The child process will then be
+ started by appending <c><anno>List</anno></c> to the existing start
function arguments, i.e. by calling
- <c>apply(M, F, A++List)</c> where <c>{M,F,A}</c> is the start
+ <c>apply(M, F, A++<anno>List</anno>)</c> where <c>{M,F,A}</c> is the start
function defined in the child specification.</p>
<p>If there already exists a child specification with
- the specified <c>Id</c>, <c>ChildSpec</c> is discarded and
+ the specified <c><anno>Id</anno></c>, <c><anno>ChildSpec</anno></c> is discarded and
the function returns <c>{error,already_present}</c> or
- <c>{error,{already_started,Child}}</c>, depending on if
+ <c>{error,{already_started,<anno>Child</anno>}}</c>, depending on if
the corresponding child process is running or not.</p>
- <p>If the child process start function returns <c>{ok,Child}</c>
- or <c>{ok,Child,Info}</c>, the child specification and pid is
+ <p>If the child process start function returns <c>{ok,<anno>Child</anno>}</c>
+ or <c>{ok,<anno>Child</anno>,<anno>Info</anno>}</c>, the child specification and pid is
added to the supervisor and the function returns the same
value.</p>
<p>If the child process start function returns <c>ignore</c>,
@@ -312,27 +336,20 @@ child_spec() = {Id,StartFunc,Restart,Shutdown,Type,Modules}
</desc>
</func>
<func>
- <name>terminate_child(SupRef, Id) -> Result</name>
+ <name name="terminate_child" arity="2"/>
<fsummary>Terminate a child process belonging to a supervisor.</fsummary>
- <type>
- <v>SupRef = Name | {Name,Node} | {global,Name} | pid()</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>Id = pid() | term()</v>
- <v>Result = ok | {error,Error}</v>
- <v>&nbsp;Error = not_found | simple_one_for_one</v>
- </type>
<desc>
- <p>Tells the supervisor <c>SupRef</c> to terminate the given
+ <p>Tells the supervisor <c><anno>SupRef</anno></c> to terminate the given
child.</p>
<p>If the supervisor is not <c>simple_one_for_one</c>,
- <c>Id</c> must be the child specification identifier. The
+ <c><anno>Id</anno></c> must be the child specification identifier. The
process, if there is one, is terminated but the child
specification is kept by the supervisor. The child process
may later be restarted by the supervisor. The child process
can also be restarted explicitly by calling
<c>restart_child/2</c>. Use <c>delete_child/2</c> to remove
the child specification.</p>
- <p>If the supervisor is <c>simple_one_for_one</c>, <c>Id</c>
+ <p>If the supervisor is <c>simple_one_for_one</c>, <c><anno>Id</anno></c>
must be the child process' <c>pid()</c>. I the specified
process is alive, but is not a child of the given
supervisor, the function will return
@@ -340,119 +357,93 @@ child_spec() = {Id,StartFunc,Restart,Shutdown,Type,Modules}
identifier is given instead instead of a <c>pid()</c>, the
function will return <c>{error,simple_one_for_one}</c>.</p>
<p>If successful, the function returns <c>ok</c>. If there is
- no child specification with the specified <c>Id</c>, the
+ no child specification with the specified <c><anno>Id</anno></c>, the
function returns <c>{error,not_found}</c>.</p>
<p>See <c>start_child/2</c> for a description of
- <c>SupRef</c>.</p>
+ <c><anno>SupRef</anno></c>.</p>
</desc>
</func>
<func>
- <name>delete_child(SupRef, Id) -> Result</name>
+ <name name="delete_child" arity="2"/>
<fsummary>Delete a child specification from a supervisor.</fsummary>
- <type>
- <v>SupRef = Name | {Name,Node} | {global,Name} | pid()</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>Id = term()</v>
- <v>Result = ok | {error,Error}</v>
- <v>&nbsp;Error = running | not_found | simple_one_for_one</v>
- </type>
<desc>
- <p>Tells the supervisor <c>SupRef</c> to delete the child
- specification identified by <c>Id</c>. The corresponding child
+ <p>Tells the supervisor <c><anno>SupRef</anno></c> to delete the child
+ specification identified by <c><anno>Id</anno></c>. The corresponding child
process must not be running, use <c>terminate_child/2</c> to
terminate it.</p>
- <p>See <c>start_child/2</c> for a description of <c>SupRef</c>.</p>
+ <p>See <seealso marker="#SupRef"><c>start_child/2</c></seealso> for a description of
+ <c>SupRef</c>.</p>
<p>If successful, the function returns <c>ok</c>. If the child
- specification identified by <c>Id</c> exists but
+ specification identified by <c><anno>Id</anno></c> exists but
the corresponding child process is running, the function
returns <c>{error,running}</c>. If the child specification
- identified by <c>Id</c> does not exist, the function returns
+ identified by <c><anno>Id</anno></c> does not exist, the function returns
<c>{error,not_found}</c>.</p>
</desc>
</func>
<func>
- <name>restart_child(SupRef, Id) -> Result</name>
+ <name name="restart_child" arity="2"/>
<fsummary>Restart a terminated child process belonging to a supervisor.</fsummary>
- <type>
- <v>SupRef = Name | {Name,Node} | {global,Name} | pid()</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>Id = term()</v>
- <v>Result = {ok,Child} | {ok,Child,Info} | {error,Error}</v>
- <v>&nbsp;Child = pid() | undefined</v>
- <v>&nbsp;Error = running | not_found | simple_one_for_one | term()</v>
- </type>
<desc>
- <p>Tells the supervisor <c>SupRef</c> to restart a child process
+ <p>Tells the supervisor <c><anno>SupRef</anno></c> to restart a child process
corresponding to the child specification identified by
- <c>Id</c>. The child specification must exist and
+ <c><anno>Id</anno></c>. The child specification must exist and
the corresponding child process must not be running.</p>
- <p>See <c>start_child/2</c> for a description of <c>SupRef</c>.</p>
- <p>If the child specification identified by <c>Id</c> does not
+ <p>See <seealso marker="#SupRef"><c>start_child/2</c></seealso> for a description of
+ <c>SupRef</c>.</p>
+ <p>If the child specification identified by <c><anno>Id</anno></c> does not
exist, the function returns <c>{error,not_found}</c>. If
the child specification exists but the corresponding process
is already running, the function returns
<c>{error,running}</c>.</p>
- <p>If the child process start function returns <c>{ok,Child}</c>
- or <c>{ok,Child,Info}</c>, the pid is added to the supervisor
+ <p>If the child process start function returns <c>{ok,<anno>Child</anno>}</c>
+ or <c>{ok,<anno>Child</anno>,<anno>Info</anno>}</c>, the pid is added to the supervisor
and the function returns the same value.</p>
<p>If the child process start function returns <c>ignore</c>,
the pid remains set to <c>undefined</c> and the function
returns <c>{ok,undefined}</c>.</p>
<p>If the child process start function returns an error tuple or
an erroneous value, or if it fails, the function returns
- <c>{error,Error}</c> where <c>Error</c> is a term containing
+ <c>{error,<anno>Error</anno>}</c> where <c><anno>Error</anno></c> is a term containing
information about the error.</p>
</desc>
</func>
<func>
- <name>which_children(SupRef) -> [{Id,Child,Type,Modules}]</name>
+ <name name="which_children" arity="1"/>
<fsummary>Return information about all children specifications and child processes belonging to a supervisor.</fsummary>
- <type>
- <v>SupRef = Name | {Name,Node} | {global,Name} | pid()</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>Id = term() | undefined</v>
- <v>Child = pid() | undefined</v>
- <v>Type = worker | supervisor</v>
- <v>Modules = [Module] | dynamic</v>
- <v>&nbsp;Module = atom()</v>
- </type>
<desc>
<p>Returns a newly created list with information about all child
specifications and child processes belonging to
- the supervisor <c>SupRef</c>.</p>
+ the supervisor <c><anno>SupRef</anno></c>.</p>
<p>Note that calling this function when supervising a large
number of children under low memory conditions can cause an
out of memory exception.</p>
- <p>See <c>start_child/2</c> for a description of <c>SupRef</c>.</p>
+ <p>See <seealso marker="#SupRef"><c>start_child/2</c></seealso> for a description of
+ <c>SupRef</c>.</p>
<p>The information given for each child specification/process
is:</p>
<list type="bulleted">
<item>
- <p><c>Id</c> - as defined in the child specification or
+ <p><c><anno>Id</anno></c> - as defined in the child specification or
<c>undefined</c> in the case of a
<c>simple_one_for_one</c> supervisor.</p>
</item>
<item>
- <p><c>Child</c> - the pid of the corresponding child
+ <p><c><anno>Child</anno></c> - the pid of the corresponding child
process, or <c>undefined</c> if there is no such process.</p>
</item>
<item>
- <p><c>Type</c> - as defined in the child specification.</p>
+ <p><c><anno>Type</anno></c> - as defined in the child specification.</p>
</item>
<item>
- <p><c>Modules</c> - as defined in the child specification.</p>
+ <p><c><anno>Modules</anno></c> - as defined in the child specification.</p>
</item>
</list>
</desc>
</func>
<func>
- <name>count_children(SupRef) -> PropListOfCounts</name>
+ <name name="count_children" arity="1"/>
<fsummary>Return counts for the number of childspecs, active children, supervisors and workers.</fsummary>
- <type>
- <v>SupRef = Name | {Name,Node} | {global,Name} | pid()</v>
- <v>&nbsp;Name = Node = atom()</v>
- <v>PropListOfCounts = [{specs, ChildSpecCount}, {active, ActiveProcessCount}, {supervisors, ChildSupervisorCount}, {workers, ChildWorkerCount}]</v>
- </type>
<desc>
<p>Returns a property list (see <c>proplists</c>) containing the
counts for each of the following elements of the supervisor's
@@ -479,17 +470,12 @@ child_spec() = {Id,StartFunc,Restart,Shutdown,Type,Modules}
</desc>
</func>
<func>
- <name>check_childspecs([ChildSpec]) -> Result</name>
+ <name name="check_childspecs" arity="1"/>
<fsummary>Check if children specifications are syntactically correct.</fsummary>
- <type>
- <v>ChildSpec = child_spec()</v>
- <v>Result = ok | {error,Error}</v>
- <v>&nbsp;Error = term()</v>
- </type>
<desc>
<p>This function takes a list of child specification as argument
and returns <c>ok</c> if all of them are syntactically
- correct, or <c>{error,Error}</c> otherwise.</p>
+ correct, or <c>{error,<anno>Error</anno>}</c> otherwise.</p>
</desc>
</func>
</funcs>
@@ -506,9 +492,9 @@ child_spec() = {Id,StartFunc,Restart,Shutdown,Type,Modules}
<type>
<v>Args = term()</v>
<v>Result = {ok,{{RestartStrategy,MaxR,MaxT},[ChildSpec]}} | ignore</v>
- <v>&nbsp;RestartStrategy = one_for_all | one_for_one | rest_for_one | simple_one_for_one</v>
- <v>&nbsp;MaxR = MaxT = int()>=0</v>
- <v>&nbsp;ChildSpec = child_spec()</v>
+ <v>&nbsp;RestartStrategy = <seealso marker="#type-strategy">strategy()</seealso></v>
+ <v>&nbsp;MaxR = MaxT = integer()>=0</v>
+ <v>&nbsp;ChildSpec = <seealso marker="#type-child_spec">child_spec()</seealso></v>
</type>
<desc>
<p>Whenever a supervisor is started using
diff --git a/lib/stdlib/doc/src/supervisor_bridge.xml b/lib/stdlib/doc/src/supervisor_bridge.xml
index cbd0d9230b..c1a5e7947f 100644
--- a/lib/stdlib/doc/src/supervisor_bridge.xml
+++ b/lib/stdlib/doc/src/supervisor_bridge.xml
@@ -50,46 +50,37 @@
</description>
<funcs>
<func>
- <name>start_link(Module, Args) -> Result</name>
- <name>start_link(SupBridgeName, Module, Args) -> Result</name>
+ <name name="start_link" arity="2"/>
+ <name name="start_link" arity="3"/>
<fsummary>Create a supervisor bridge process.</fsummary>
- <type>
- <v>SupBridgeName = {local,Name} | {global,Name}</v>
- <v>&nbsp;Name = atom()</v>
- <v>Module = atom()</v>
- <v>Args = term()</v>
- <v>Result = {ok,Pid} | ignore | {error,Error}</v>
- <v>&nbsp;Pid = pid()</v>
- <v>&nbsp;Error = {already_started,Pid} | term()</v>
- </type>
<desc>
<p>Creates a supervisor_bridge process, linked to the calling
- process, which calls <c>Module:init/1</c> to start the subsystem.
+ process, which calls <c><anno>Module</anno>:init/1</c> to start the subsystem.
To ensure a synchronized start-up procedure, this function does
- not return until <c>Module:init/1</c> has returned.</p>
- <p>If <c>SupBridgeName={local,Name}</c> the supervisor_bridge is
- registered locally as <c>Name</c> using <c>register/2</c>.
- If <c>SupBridgeName={global,Name}</c> the supervisor_bridge is
- registered globally as <c>Name</c> using
+ not return until <c><anno>Module</anno>:init/1</c> has returned.</p>
+ <p>If <c><anno>SupBridgeName</anno>={local,<anno>Name</anno>}</c> the supervisor_bridge is
+ registered locally as <c><anno>Name</anno></c> using <c>register/2</c>.
+ If <c><anno>SupBridgeName</anno>={global,<anno>Name</anno>}</c> the supervisor_bridge is
+ registered globally as <c><anno>Name</anno></c> using
<c>global:register_name/2</c>.
If no name is provided, the supervisor_bridge is not registered.
If there already exists a process with the specified
- <c>SupBridgeName</c> the function returns
- <c>{error,{already_started,Pid}}</c>, where <c>Pid</c> is the pid
+ <c><anno>SupBridgeName</anno></c> the function returns
+ <c>{error,{already_started,<anno>Pid</anno>}}</c>, where <c><anno>Pid</anno></c> is the pid
of that process.</p>
- <p><c>Module</c> is the name of the callback module.</p>
- <p><c>Args</c> is an arbitrary term which is passed as the argument
- to <c>Module:init/1</c>.</p>
+ <p><c><anno>Module</anno></c> is the name of the callback module.</p>
+ <p><c><anno>Args</anno></c> is an arbitrary term which is passed as the argument
+ to <c><anno>Module</anno>:init/1</c>.</p>
<p>If the supervisor_bridge and the subsystem are successfully
- started the function returns <c>{ok,Pid}</c>, where <c>Pid</c> is
+ started the function returns <c>{ok,<anno>Pid</anno>}</c>, where <c><anno>Pid</anno></c> is
is the pid of the supervisor_bridge.</p>
- <p>If <c>Module:init/1</c> returns <c>ignore</c>, this function
+ <p>If <c><anno>Module</anno>:init/1</c> returns <c>ignore</c>, this function
returns <c>ignore</c> as well and the supervisor_bridge terminates
with reason <c>normal</c>.
- If <c>Module:init/1</c> fails or returns an error tuple or an
- incorrect value, this function returns <c>{error,Term}</c> where
- <c>Term</c> is a term with information about the error, and
- the supervisor_bridge terminates with reason <c>Term</c>.</p>
+ If <c><anno>Module</anno>:init/1</c> fails or returns an error tuple or an
+ incorrect value, this function returns <c>{error,<anno>Error</anno>r}</c> where
+ <c><anno>Error</anno></c> is a term with information about the error, and
+ the supervisor_bridge terminates with reason <c><anno>Error</anno></c>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/sys.xml b/lib/stdlib/doc/src/sys.xml
index efa8922a9d..073faf2df2 100644
--- a/lib/stdlib/doc/src/sys.xml
+++ b/lib/stdlib/doc/src/sys.xml
@@ -39,24 +39,12 @@
<p>Functions used for implementation of processes
should also understand system messages such as debugging
messages and code change. These functions must be used to implement the use of system messages for a process; either directly, or through standard behaviours, such as <c>gen_server</c>.</p>
- <p>The following types are used in the functions defined below:</p>
- <list type="bulleted">
- <item>
- <p><c>Name = pid() | atom() | {global, atom()}</c></p>
- </item>
- <item>
- <p><c>Timeout = int() >= 0 | infinity</c></p>
- </item>
- <item>
- <p><c>system_event() = {in, Msg} | {in, Msg, From} | {out, Msg, To} | term()</c></p>
- </item>
- </list>
<p>The default timeout is 5000 ms, unless otherwise specified. The
<c>timeout</c> defines the time period to wait for the process to
respond to a request. If the process does not respond, the
function evaluates <c>exit({timeout, {M, F, A}})</c>.
</p>
- <p>The functions make reference to a debug structure.
+ <p><marker id="dbg_opt"/>The functions make reference to a debug structure.
The debug structure is a list of <c>dbg_opt()</c>.
<c>dbg_opt()</c> is an internal data type used by the
<c>handle_system_msg/6</c> function. No debugging is performed if it is an empty list.
@@ -113,20 +101,31 @@
own system events. It is always up to the process itself
to format these events.</p>
</section>
+ <datatypes>
+ <datatype>
+ <name name="name"/>
+ </datatype>
+ <datatype>
+ <name name="system_event"/>
+ </datatype>
+ <datatype>
+ <name name="dbg_opt"/>
+ <desc><p>See <seealso marker="#dbg_opt">above</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="dbg_fun"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>log(Name,Flag)</name>
- <name>log(Name,Flag,Timeout) -> ok | {ok, [system_event()]}</name>
+ <name name="log" arity="2"/>
+ <name name="log" arity="3"/>
<fsummary>Log system events in memory</fsummary>
- <type>
- <v>Flag = true | {true, N} | false | get | print</v>
- <v>N = integer() > 0</v>
- </type>
<desc>
<p>Turns the logging of system events On or Off. If On, a
- maximum of <c>N</c> events are kept in the
- debug structure (the default is 10). If <c>Flag</c> is <c>get</c>, a list of all
- logged events is returned. If <c>Flag</c> is <c>print</c>, the
+ maximum of <c><anno>N</anno></c> events are kept in the
+ debug structure (the default is 10). If <c><anno>Flag</anno></c> is <c>get</c>, a list of all
+ logged events is returned. If <c><anno>Flag</anno></c> is <c>print</c>, the
logged events are printed to <c>standard_io</c>. The events are
formatted with a function that is defined by the process that
generated the event (with a call to
@@ -134,13 +133,9 @@
</desc>
</func>
<func>
- <name>log_to_file(Name,Flag)</name>
- <name>log_to_file(Name,Flag,Timeout) -> ok | {error, open_file}</name>
+ <name name="log_to_file" arity="2"/>
+ <name name="log_to_file" arity="3"/>
<fsummary>Log system events to the specified file</fsummary>
- <type>
- <v>Flag = FileName | false</v>
- <v>FileName = string()</v>
- </type>
<desc>
<p>Enables or disables the logging of all system events in textual
format to the file. The events are formatted with a function that is
@@ -149,27 +144,18 @@
</desc>
</func>
<func>
- <name>statistics(Name,Flag)</name>
- <name>statistics(Name,Flag,Timeout) -> ok | {ok, Statistics} </name>
+ <name name="statistics" arity="2"/>
+ <name name="statistics" arity="3"/>
<fsummary>Enable or disable the collections of statistics</fsummary>
- <type>
- <v>Flag = true | false | get</v>
- <v>Statistics = [{start_time, {Date1, Time1}}, {current_time, {Date, Time2}}, {reductions, integer()}, {messages_in, integer()}, {messages_out, integer()}]</v>
- <v>Date1 = Date2 = {Year, Month, Day}</v>
- <v>Time1 = Time2 = {Hour, Min, Sec}</v>
- </type>
<desc>
- <p>Enables or disables the collection of statistics. If <c>Flag</c> is
+ <p>Enables or disables the collection of statistics. If <c><anno>Flag</anno></c> is
<c>get</c>, the statistical collection is returned.</p>
</desc>
</func>
<func>
- <name>trace(Name,Flag)</name>
- <name>trace(Name,Flag,Timeout) -> void()</name>
+ <name name="trace" arity="2"/>
+ <name name="trace" arity="3"/>
<fsummary>Print all system events on <c>standard_io</c></fsummary>
- <type>
- <v>Flag = boolean()</v>
- </type>
<desc>
<p>Prints all system events on <c>standard_io</c>. The events are
formatted with a function that is defined by the process that
@@ -178,8 +164,8 @@
</desc>
</func>
<func>
- <name>no_debug(Name)</name>
- <name>no_debug(Name,Timeout) -> void()</name>
+ <name name="no_debug" arity="1"/>
+ <name name="no_debug" arity="2"/>
<fsummary>Turn off debugging</fsummary>
<desc>
<p>Turns off all debugging for the process. This includes
@@ -188,8 +174,8 @@
</desc>
</func>
<func>
- <name>suspend(Name)</name>
- <name>suspend(Name,Timeout) -> void()</name>
+ <name name="suspend" arity="1"/>
+ <name name="suspend" arity="2"/>
<fsummary>Suspend the process</fsummary>
<desc>
<p>Suspends the process. When the process is suspended, it
@@ -198,49 +184,37 @@
</desc>
</func>
<func>
- <name>resume(Name)</name>
- <name>resume(Name,Timeout) -> void()</name>
+ <name name="resume" arity="1"/>
+ <name name="resume" arity="2"/>
<fsummary>Resume a suspended process</fsummary>
<desc>
<p>Resumes a suspended process.</p>
</desc>
</func>
<func>
- <name>change_code(Name, Module, OldVsn, Extra)</name>
- <name>change_code(Name, Module, OldVsn, Extra, Timeout) -> ok | {error, Reason}</name>
+ <name name="change_code" arity="4"/>
+ <name name="change_code" arity="5"/>
<fsummary>Send the code change system message to the process</fsummary>
- <type>
- <v>OldVsn = undefined | term()</v>
- <v>Module = atom()</v>
- <v>Extra = term()</v>
- </type>
<desc>
<p>Tells the process to change code. The process must be
- suspended to handle this message. The <c>Extra</c> argument is
+ suspended to handle this message. The <c><anno>Extra</anno></c> argument is
reserved for each process to use as its own. The function
- <c>Mod:system_code_change/4</c> is called. <c>OldVsn</c> is
- the old version of the <c>Module</c>.</p>
+ <c><anno>Module</anno>:system_code_change/4</c> is called. <c><anno>OldVsn</anno></c> is
+ the old version of the <c><anno>Module</anno></c>.</p>
</desc>
</func>
<func>
- <name>get_status(Name)</name>
- <name>get_status(Name,Timeout) -> {status, Pid, {module, Mod}, [PDict, SysState, Parent, Dbg, Misc]}</name>
+ <name name="get_status" arity="1"/>
+ <name name="get_status" arity="2"/>
<fsummary>Get the status of the process</fsummary>
- <type>
- <v>PDict = [{Key, Value}]</v>
- <v>SysState = running | suspended</v>
- <v>Parent = pid()</v>
- <v>Dbg = [dbg_opt()]</v>
- <v>Misc = term()</v>
- </type>
<desc>
<p>Gets the status of the process.</p>
- <p>The value of <c>Misc</c> varies for different types of
+ <p>The value of <c><anno>Misc</anno></c> varies for different types of
processes. For example, a <c>gen_server</c> process returns
the callback module's state, and a <c>gen_fsm</c> process
returns information such as its current state name. Callback
modules for <c>gen_server</c> and <c>gen_fsm</c> can also
- customise the value of <c>Misc</c> by exporting
+ customise the value of <c><anno>Misc</anno></c> by exporting
a <c>format_status/2</c> function that contributes
module-specific information;
see <seealso marker="gen_server#Module:format_status/2">gen_server:format_status/2</seealso>
@@ -249,17 +223,9 @@
</desc>
</func>
<func>
- <name>install(Name,{Func,FuncState})</name>
- <name>install(Name,{Func,FuncState},Timeout)</name>
+ <name name="install" arity="2"/>
+ <name name="install" arity="3"/>
<fsummary>Install a debug function in the process</fsummary>
- <type>
- <v>Func = dbg_fun()</v>
- <v>dbg_fun() = fun(FuncState, Event, ProcState) -> done | NewFuncState</v>
- <v>FuncState = term()</v>
- <v>Event = system_event()</v>
- <v>ProcState = term()</v>
- <v>NewFuncState = term()</v>
- </type>
<desc>
<p>This function makes it possible to install other debug
functions than the ones defined above. An example of such a
@@ -267,22 +233,19 @@
special event and performs some action when the event is
generated. This could, for example, be turning on low level tracing.
</p>
- <p><c>Func</c> is called whenever a system event is
+ <p><c><anno>Func</anno></c> is called whenever a system event is
generated. This function should return <c>done</c>, or a new
func state. In the first case, the function is removed. It is removed
if the function fails.</p>
</desc>
</func>
<func>
- <name>remove(Name,Func)</name>
- <name>remove(Name,Func,Timeout) -> void()</name>
+ <name name="remove" arity="2"/>
+ <name name="remove" arity="3"/>
<fsummary>Remove a debug function from the process</fsummary>
- <type>
- <v>Func = dbg_fun()</v>
- </type>
<desc>
<p>Removes a previously installed debug function from the
- process. <c>Func</c> must be the same as previously
+ process. <c><anno>Func</anno></c> must be the same as previously
installed.</p>
</desc>
</func>
@@ -296,86 +259,65 @@
</section>
<funcs>
<func>
- <name>debug_options(Options) -> [dbg_opt()]</name>
+ <name name="debug_options" arity="1"/>
<fsummary>Convert a list of options to a debug structure</fsummary>
- <type>
- <v>Options = [Opt]</v>
- <v>Opt = trace | log | statistics | {log_to_file, FileName} | {install, {Func, FuncState}}</v>
- <v>Func = dbg_fun()</v>
- <v>FuncState = term()</v>
- </type>
<desc>
<p>This function can be used by a process that initiates a debug
structure from a list of options. The values of the
- <c>Opt</c> argument are the same as the corresponding
+ <c><anno>Opt</anno></c> argument are the same as the corresponding
functions.</p>
</desc>
</func>
<func>
- <name>get_debug(Item,Debug,Default) -> term()</name>
+ <name name="get_debug" arity="3"/>
<fsummary>Get the data associated with a debug option</fsummary>
- <type>
- <v>Item = log | statistics</v>
- <v>Debug = [dbg_opt()]</v>
- <v>Default = term()</v>
- </type>
<desc>
- <p>This function gets the data associated with a debug option. <c>Default</c> is returned if the
- <c>Item</c> is not found. Can be
+ <p>This function gets the data associated with a debug option. <c><anno>Default</anno></c> is returned if the
+ <c><anno>Item</anno></c> is not found. Can be
used by the process to retrieve debug data for printing
before it terminates.</p>
</desc>
</func>
<func>
- <name>handle_debug([dbg_opt()],FormFunc,Extra,Event) -> [dbg_opt()]</name>
+ <name name="handle_debug" arity="4"/>
<fsummary>Generate a system event</fsummary>
- <type>
- <v>FormFunc = dbg_fun()</v>
- <v>Extra = term()</v>
- <v>Event = system_event()</v>
- </type>
<desc>
- <p>This function is called by a process when it generates a system event. <c>FormFunc</c> is a formatting function which is called as <c>FormFunc(Device, Event, Extra)</c> in order to print the events, which is necessary if tracing is activated. <c>Extra</c> is any
- extra information which the process needs in the format function, for example the name of the process.</p>
+ <p>This function is called by a process when it generates a
+ system event. <c><anno>FormFunc</anno></c> is a formatting
+ function which is called as <c><anno>FormFunc</anno>(Device,
+ <anno>Event</anno>, <anno>Extra</anno>)</c> in order to print
+ the events, which is necessary if tracing is activated.
+ <c><anno>Extra</anno></c> is any extra information which the
+ process needs in the format function, for example the name
+ of the process.</p>
</desc>
</func>
<func>
- <name>handle_system_msg(Msg,From,Parent,Module,Debug,Misc)</name>
+ <name name="handle_system_msg" arity="6"/>
<fsummary>Take care of system messages</fsummary>
- <type>
- <v>Msg = term()</v>
- <v>From = pid()</v>
- <v>Parent = pid()</v>
- <v>Module = atom()</v>
- <v>Debug = [dbg_opt()]</v>
- <v>Misc = term()</v>
- </type>
<desc>
<p>This function is used by a process module that wishes to take care of system
- messages. The process receives a <c>{system, From, Msg}</c>
- message and passes the <c>Msg</c> and <c>From</c> to this
+ messages. The process receives a <c>{system, <anno>From</anno>, <anno>Msg</anno>}</c>
+ message and passes the <c><anno>Msg</anno></c> and <c><anno>From</anno></c> to this
function.
</p>
<p>This function <em>never</em> returns. It calls the function
- <c>Module:system_continue(Parent, NDebug, Misc)</c> where the
+ <c><anno>Module</anno>:system_continue(<anno>Parent</anno>, NDebug, <anno>Misc</anno>)</c> where the
process continues the execution, or
- <c>Module:system_terminate(Reason, Parent, Debug, Misc)</c> if
- the process should terminate. The <c>Module</c> must export
+ <c><anno>Module</anno>:system_terminate(Reason, <anno>Parent</anno>, <anno>Debug</anno>, <anno>Misc</anno>)</c> if
+ the process should terminate. The <c><anno>Module</anno></c> must export
<c>system_continue/3</c>, <c>system_terminate/4</c>, and
<c>system_code_change/4</c> (see below).
</p>
- <p>The <c>Misc</c> argument can be used to save internal data
+ <p>The <c><anno>Misc</anno></c> argument can be used to save internal data
in a process, for example its state. It is sent to
- <c>Module:system_continue/3</c> or
- <c>Module:system_terminate/4</c></p>
+ <c><anno>Module</anno>:system_continue/3</c> or
+ <c><anno>Module</anno>:system_terminate/4</c></p>
</desc>
</func>
<func>
- <name>print_log(Debug) -> void()</name>
+ <name name="print_log" arity="1"/>
<fsummary>Print the logged events in the debug structure</fsummary>
- <type>
- <v>Debug = [dbg_opt()]</v>
- </type>
<desc>
<p>Prints the logged system events in the debug structure
using <c>FormFunc</c> as defined when the event was
@@ -383,11 +325,11 @@
</desc>
</func>
<func>
- <name>Mod:system_continue(Parent, Debug, Misc)</name>
+ <name>Mod:system_continue(Parent, Debug, Misc) -> none()</name>
<fsummary>Called when the process should continue its execution</fsummary>
<type>
<v>Parent = pid()</v>
- <v>Debug = [dbg_opt()]</v>
+ <v>Debug = [<seealso marker="#type-dbg_opt">dbg_opt()</seealso>]</v>
<v>Misc = term()</v>
</type>
<desc>
@@ -397,12 +339,12 @@
</desc>
</func>
<func>
- <name>Mod:system_terminate(Reason, Parent, Debug, Misc)</name>
+ <name>Mod:system_terminate(Reason, Parent, Debug, Misc) -> none()</name>
<fsummary>Called when the process should terminate</fsummary>
<type>
<v>Reason = term()</v>
<v>Parent = pid()</v>
- <v>Debug = [dbg_opt()]</v>
+ <v>Debug = [<seealso marker="#type-dbg_opt">dbg_opt()</seealso>]</v>
<v>Misc = term()</v>
</type>
<desc>
diff --git a/lib/stdlib/doc/src/timer.xml b/lib/stdlib/doc/src/timer.xml
index 0baeff1db3..b741ab7db1 100644
--- a/lib/stdlib/doc/src/timer.xml
+++ b/lib/stdlib/doc/src/timer.xml
@@ -49,9 +49,19 @@
as requested.
</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="time"/>
+ <desc><p>Time in milliseconds.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="tref"/>
+ <desc><p>A timer reference.</p></desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>start() -> ok</name>
+ <name name="start" arity="0"/>
<fsummary>Start a global timer server (named <c>timer_server</c>).</fsummary>
<desc>
<p>Starts the timer server. Normally, the server does not need
@@ -62,220 +72,181 @@
</desc>
</func>
<func>
- <name>apply_after(Time, Module, Function, Arguments) -> {ok, Tref} | {error, Reason}</name>
+ <name name="apply_after" arity="4"/>
<fsummary>Apply <c>Module:Function(Arguments)</c>after a specified <c>Time</c>.</fsummary>
- <type>
- <v>Time = integer() in Milliseconds</v>
- <v>Module = Function = atom()</v>
- <v>Arguments = [term()]</v>
- </type>
<desc>
- <p>Evaluates <c>apply(M, F, A)</c> after <c>Time</c> amount of time
- has elapsed. Returns <c>{ok, TRef}</c>, or <c>{error, Reason}</c>.</p>
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Arguments</anno>)</c> after <c><anno>Time</anno></c> amount of time
+ has elapsed. Returns <c>{ok, <anno>TRef</anno>}</c>, or <c>{error, <anno>Reason</anno>}</c>.</p>
</desc>
</func>
<func>
- <name>send_after(Time, Pid, Message) -> {ok, TRef} | {error,Reason}</name>
- <name>send_after(Time, Message) -> {ok, TRef} | {error,Reason}</name>
+ <name name="send_after" arity="2"/>
+ <name name="send_after" arity="3"/>
<fsummary>Send <c>Message</c>to <c>Pid</c>after a specified <c>Time</c>.</fsummary>
- <type>
- <v>Time = integer() in Milliseconds</v>
- <v>Pid = pid() | atom()</v>
- <v>Message = term()</v>
- <v>Result = {ok, TRef} | {error, Reason}</v>
- </type>
<desc>
<p></p>
<taglist>
<tag><c>send_after/3</c></tag>
<item>
- <p>Evaluates <c>Pid ! Message</c> after <c>Time</c> amount
- of time has elapsed. (<c>Pid</c> can also be an atom of a
- registered name.) Returns <c>{ok, TRef}</c>, or
- <c>{error, Reason}</c>.</p>
+ <p>Evaluates <c><anno>Pid</anno> ! <anno>Message</anno></c> after <c><anno>Time</anno></c> amount
+ of time has elapsed. (<c><anno>Pid</anno></c> can also be an atom of a
+ registered name.) Returns <c>{ok, <anno>TRef</anno>}</c>, or
+ <c>{error, <anno>Reason</anno>}</c>.</p>
</item>
<tag><c>send_after/2</c></tag>
<item>
- <p>Same as <c>send_after(Time, self(), Message)</c>.</p>
+ <p>Same as <c>send_after(<anno>Time</anno>, self(), <anno>Message</anno>)</c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>exit_after(Time, Pid, Reason1) -> {ok, TRef} | {error,Reason2}</name>
- <name>exit_after(Time, Reason1) -> {ok, TRef} | {error,Reason2}</name>
- <name>kill_after(Time, Pid)-> {ok, TRef} | {error,Reason2}</name>
- <name>kill_after(Time) -> {ok, TRef} | {error,Reason2}</name>
+ <name name="kill_after" arity="1"/>
+ <name name="kill_after" arity="2"/>
+ <name name="exit_after" arity="2"/>
+ <name name="exit_after" arity="3"/>
<fsummary>Send an exit signal with <c>Reason</c>after a specified <c>Time</c>.</fsummary>
- <type>
- <v>Time = integer() in milliseconds</v>
- <v>Pid = pid() | atom()</v>
- <v>Reason1 = Reason2 = term()</v>
- </type>
<desc>
<p></p>
<taglist>
<tag><c>exit_after/3</c></tag>
<item>
- <p>Send an exit signal with reason <c>Reason1</c> to Pid
- <c>Pid</c>. Returns <c>{ok, TRef}</c>, or
- <c>{error, Reason2}</c>.</p>
+ <p>Send an exit signal with reason <c><anno>Reason1</anno></c> to Pid
+ <c><anno>Pid</anno></c>. Returns <c>{ok, <anno>TRef</anno>}</c>, or
+ <c>{error, <anno>Reason2</anno>}</c>.</p>
</item>
<tag><c>exit_after/2</c></tag>
<item>
- <p>Same as <c>exit_after(Time, self(), Reason1)</c>. </p>
+ <p>Same as <c>exit_after(<anno>Time</anno>, self(), <anno>Reason1</anno>)</c>. </p>
</item>
<tag><c>kill_after/2</c></tag>
<item>
- <p>Same as <c>exit_after(Time, Pid, kill)</c>. </p>
+ <p>Same as <c>exit_after(<anno>Time</anno>, <anno>Pid</anno>, kill)</c>. </p>
</item>
<tag><c>kill_after/1</c></tag>
<item>
- <p>Same as <c>exit_after(Time, self(), kill)</c>. </p>
+ <p>Same as <c>exit_after(<anno>Time</anno>, self(), kill)</c>. </p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>apply_interval(Time, Module, Function, Arguments) -> {ok, TRef} | {error, Reason}</name>
+ <name name="apply_interval" arity="4"/>
<fsummary>Evaluate <c>Module:Function(Arguments)</c>repeatedly at intervals of <c>Time</c>.</fsummary>
- <type>
- <v>Time = integer() in milliseconds</v>
- <v>Module = Function = atom()</v>
- <v>Arguments = [term()]</v>
- </type>
<desc>
- <p>Evaluates <c>apply(Module, Function, Arguments)</c> repeatedly at
- intervals of <c>Time</c>. Returns <c>{ok, TRef}</c>, or
- <c>{error, Reason}</c>.</p>
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Arguments</anno>)</c> repeatedly at
+ intervals of <c><anno>Time</anno></c>. Returns <c>{ok, <anno>TRef</anno>}</c>, or
+ <c>{error, <anno>Reason</anno>}</c>.</p>
</desc>
</func>
<func>
- <name>send_interval(Time, Pid, Message) -> {ok, TRef} | {error, Reason}</name>
- <name>send_interval(Time, Message) -> {ok, TRef} | {error, Reason}</name>
+ <name name="send_interval" arity="2"/>
+ <name name="send_interval" arity="3"/>
<fsummary>Send <c>Message</c>repeatedly at intervals of <c>Time</c>.</fsummary>
- <type>
- <v>Time = integer() in milliseconds</v>
- <v>Pid = pid() | atom()</v>
- <v>Message = term()</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p></p>
<taglist>
<tag><c>send_interval/3</c></tag>
<item>
- <p>Evaluates <c>Pid ! Message</c> repeatedly after <c>Time</c>
- amount of time has elapsed. (<c>Pid</c> can also be an atom of
- a registered name.) Returns <c>{ok, TRef}</c> or
- <c>{error, Reason}</c>.</p>
+ <p>Evaluates <c><anno>Pid</anno> ! <anno>Message</anno></c> repeatedly after <c><anno>Time</anno></c>
+ amount of time has elapsed. (<c><anno>Pid</anno></c> can also be an atom of
+ a registered name.) Returns <c>{ok, <anno>TRef</anno>}</c> or
+ <c>{error, <anno>Reason</anno>}</c>.</p>
</item>
<tag><c>send_interval/2</c></tag>
<item>
- <p>Same as <c>send_interval(Time, self(), Message)</c>.</p>
+ <p>Same as <c>send_interval(<anno>Time</anno>, self(), <anno>Message</anno>)</c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>cancel(TRef) -> {ok, cancel} | {error, Reason}</name>
+ <name name="cancel" arity="1"/>
<fsummary>Cancel a previously requested timeout identified by <c>TRef</c>.</fsummary>
<desc>
- <p>Cancels a previously requested timeout. <c>TRef</c> is a unique
+ <p>Cancels a previously requested timeout. <c><anno>TRef</anno></c> is a unique
timer reference returned by the timer function in question. Returns
- <c>{ok, cancel}</c>, or <c>{error, Reason}</c> when <c>TRef</c>
+ <c>{ok, cancel}</c>, or <c>{error, <anno>Reason</anno>}</c> when <c><anno>TRef</anno></c>
is not a timer reference.</p>
</desc>
</func>
<func>
- <name>sleep(Time) -> ok</name>
+ <name name="sleep" arity="1"/>
<fsummary>Suspend the calling process for <c>Time</c>amount of milliseconds.</fsummary>
- <type>
- <v>Time = integer() in milliseconds or the atom infinity</v>
- </type>
<desc>
- <p>Suspends the process calling this function for <c>Time</c> amount
+ <p>Suspends the process calling this function for <c><anno>Time</anno></c> amount
of milliseconds and then returns <c>ok</c>, or suspend the process
- forever if <c>Time</c> is the atom <c>infinity</c>. Naturally, this
+ forever if <c><anno>Time</anno></c> is the atom <c>infinity</c>. Naturally, this
function does <em>not</em> return immediately.</p>
</desc>
</func>
<func>
- <name>tc(Module, Function, Arguments) -> {Time, Value}</name>
- <name>tc(Fun, Arguments) -> {Time, Value}</name>
- <name>tc(Fun) -> {Time, Value}</name>
+ <name name="tc" arity="1"/>
+ <name name="tc" arity="2"/>
+ <name name="tc" arity="3"/>
<fsummary>Measure the real time it takes to evaluate <c>apply(Module,
Function, Arguments)</c> or <c>apply(Fun, Arguments)</c></fsummary>
- <type>
- <v>Module = Function = atom()</v>
- <v>Fun = fun()</v>
- <v>Arguments = [term()]</v>
- <v>Time = integer() in microseconds</v>
- <v>Value = term()</v>
- </type>
+ <type_desc variable="Time">In microseconds</type_desc>
<desc>
<p></p>
<taglist>
<tag><c>tc/3</c></tag>
<item>
- <p>Evaluates <c>apply(Module, Function, Arguments)</c> and measures
+ <p>Evaluates <c>apply(<anno>Module</anno>, <anno>Function</anno>, <anno>Arguments</anno>)</c> and measures
the elapsed real time as reported by <c>os:timestamp/0</c>.
- Returns <c>{Time, Value}</c>, where
- <c>Time</c> is the elapsed real time in <em>microseconds</em>,
- and <c>Value</c> is what is returned from the apply.</p>
+ Returns <c>{<anno>Time</anno>, <anno>Value</anno>}</c>, where
+ <c><anno>Time</anno></c> is the elapsed real time in <em>microseconds</em>,
+ and <c><anno>Value</anno></c> is what is returned from the apply.</p>
</item>
<tag><c>tc/2</c></tag>
<item>
- <p>Evaluates <c>apply(Fun, Arguments)</c>. Otherwise works
+ <p>Evaluates <c>apply(<anno>Fun</anno>, <anno>Arguments</anno>)</c>. Otherwise works
like <c>tc/3</c>.</p>
</item>
<tag><c>tc/1</c></tag>
<item>
- <p>Evaluates <c>Fun()</c>. Otherwise works like <c>tc/2</c>.</p>
+ <p>Evaluates <c><anno>Fun</anno>()</c>. Otherwise works like <c>tc/2</c>.</p>
</item>
</taglist>
</desc>
</func>
<func>
- <name>now_diff(T2, T1) -> Tdiff</name>
+ <name name="now_diff" arity="2"/>
<fsummary>Calculate time difference between <c>now/0</c>timestamps</fsummary>
- <type>
- <v>T1 = T2 = {MegaSecs, Secs, MicroSecs}</v>
- <v>Tdiff = MegaSecs = Secs = MicroSecs = integer()</v>
- </type>
+ <type_desc variable="Tdiff">In microseconds</type_desc>
<desc>
- <p>Calculates the time difference <c>Tdiff = T2 - T1</c> in
- <em>microseconds</em>, where <c>T1</c> and <c>T2</c> probably
+ <p>Calculates the time difference <c><anno>Tdiff</anno> = <anno>T2</anno> - <anno>T1</anno></c> in
+ <em>microseconds</em>, where <c><anno>T1</anno></c> and <c><anno>T2</anno></c> probably
are timestamp tuples returned from <c>erlang:now/0</c>.</p>
</desc>
</func>
<func>
- <name>seconds(Seconds) -> Milliseconds</name>
+ <name name="seconds" arity="1"/>
<fsummary>Convert <c>Seconds</c>to <c>Milliseconds</c>.</fsummary>
<desc>
- <p>Returns the number of milliseconds in <c>Seconds</c>.</p>
+ <p>Returns the number of milliseconds in <c><anno>Seconds</anno></c>.</p>
</desc>
</func>
<func>
- <name>minutes(Minutes) -> Milliseconds</name>
+ <name name="minutes" arity="1"/>
<fsummary>Converts <c>Minutes</c>to <c>Milliseconds</c>.</fsummary>
<desc>
- <p>Return the number of milliseconds in <c>Minutes</c>.</p>
+ <p>Return the number of milliseconds in <c><anno>Minutes</anno></c>.</p>
</desc>
</func>
<func>
- <name>hours(Hours) -> Milliseconds</name>
+ <name name="hours" arity="1"/>
<fsummary>Convert <c>Hours</c>to <c>Milliseconds</c>.</fsummary>
<desc>
- <p>Returns the number of milliseconds in <c>Hours</c>.</p>
+ <p>Returns the number of milliseconds in <c><anno>Hours</anno></c>.</p>
</desc>
</func>
<func>
- <name>hms(Hours, Minutes, Seconds) -> Milliseconds</name>
+ <name name="hms" arity="3"/>
<fsummary>Convert <c>Hours</c>+<c>Minutes</c>+<c>Seconds</c>to <c>Milliseconds</c>.</fsummary>
<desc>
- <p>Returns the number of milliseconds in <c>Hours + Minutes + Seconds</c>.</p>
+ <p>Returns the number of milliseconds in <c><anno>Hours</anno> + <anno>Minutes</anno> + <anno>Seconds</anno></c>.</p>
</desc>
</func>
</funcs>
diff --git a/lib/stdlib/doc/src/unicode.xml b/lib/stdlib/doc/src/unicode.xml
index cb1cfa8ed0..d02763f75c 100644
--- a/lib/stdlib/doc/src/unicode.xml
+++ b/lib/stdlib/doc/src/unicode.xml
@@ -38,50 +38,83 @@
<p>It is recommended to only use external encodings for communication with external entities where this is required. When working inside the Erlang/OTP environment, it is recommended to keep binaries in UTF-8 when representing Unicode characters. Latin1 encoding is supported both for backward compatibility and for communication with external entities not supporting Unicode character sets.</p>
</description>
- <section>
- <title>DATA TYPES</title>
- <marker id="type-charlist"></marker>
- <code type="none">
-unicode_binary() = binary() with characters encoded in UTF-8 coding standard
-unicode_char() = integer() representing valid unicode codepoint
-
-chardata() = charlist() | unicode_binary()
-
-charlist() = [unicode_char() | unicode_binary() | charlist()]
- a unicode_binary is allowed as the tail of the list</code>
-
- <code type="none">
-external_unicode_binary() = binary()
- with characters coded in a user specified Unicode encoding other
- than UTF-8 (UTF-16 or UTF-32)
-
-external_chardata() = external_charlist() | external_unicode_binary()
-
-external_charlist() = [unicode_char() | external_unicode_binary() | external_charlist()]
- an external_unicode_binary is allowed as the tail of the list</code>
-
- <code type="none">
-latin1_binary() = binary() with characters coded in iso-latin-1
-latin1_char() = integer() representing valid latin1 character (0-255)
-
-latin1_chardata() = latin1_charlist() | latin1_binary()
+ <datatypes>
+ <datatype>
+ <name name="encoding"/>
+ </datatype>
+ <datatype>
+ <name name="endian"/>
+ </datatype>
+ <datatype>
+ <name name="unicode_binary"/>
+ <desc>
+ <p>A binary() with characters encoded in the UTF-8 coding standard.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="unicode_char"/>
+ <desc>
+ <p>An integer() representing a valid unicode codepoint.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="chardata"/>
+ </datatype>
+ <datatype>
+ <name name="charlist"/>
+ <desc>
+ <p>A unicode_binary is allowed as the tail of the list.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="external_unicode_binary"/>
+ <desc>
+ <p>A <c>binary()</c> with characters coded in a user specified Unicode
+ encoding other than UTF-8 (UTF-16 or UTF-32).</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="external_chardata"/>
+ </datatype>
+ <datatype>
+ <name name="external_charlist"/>
+ <desc>
+ <p>An <c>external_unicode_binary()</c> is allowed as the tail
+ of the list.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="latin1_binary"/>
+ <desc><p>A <c>binary()</c> with characters coded in iso-latin-1.</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="latin1_char"/>
+ <desc><p>An <c>integer()</c> representing valid latin1
+ character (0-255).</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="latin1_chardata"/>
+ </datatype>
+ <datatype>
+ <name name="latin1_charlist"/>
+ <desc><p>A <c>latin1_binary()</c> is allowed as the tail of
+ the list.</p>
+ </desc>
+ </datatype>
+ </datatypes>
-latin1_charlist() = [latin1_char() | latin1_binary() | latin1_charlist()]
- a latin1_binary is allowed as the tail of the list</code>
- </section>
<funcs>
<func>
- <name>bom_to_encoding(Bin) -> {Encoding,Length}</name>
+ <name name="bom_to_encoding" arity="1"/>
<fsummary>Identify UTF byte order marks in a binary.</fsummary>
- <type>
- <v>Bin = binary() of byte_size 4 or more</v>
- <v>Encoding = latin1 | utf8 | {utf16,little} | {utf16,big} | {utf32,little} | {utf32,big}</v>
- <v>Length = int()</v>
- </type>
+ <type name="endian"/>
+ <type_desc variable="Bin">A binary() of byte_size 4 or more.</type_desc>
<desc>
<p>Check for a UTF byte order mark (BOM) in the beginning of a
- binary. If the supplied binary <c>Bin</c> begins with a valid
+ binary. If the supplied binary <c><anno>Bin</anno></c> begins with a valid
byte order mark for either UTF-8, UTF-16 or UTF-32, the function
returns the encoding identified along with the length of the BOM
in bytes.</p>
@@ -90,23 +123,24 @@ latin1_charlist() = [latin1_char() | latin1_binary() | latin1_charlist()]
</desc>
</func>
<func>
- <name>characters_to_list(Data) -> list() | {error, list(), RestData} | {incomplete, list(), binary()} </name>
+ <name name="characters_to_list" arity="1"/>
<fsummary>Convert a collection of characters to list of Unicode characters</fsummary>
- <type>
- <v>Data = latin1_chardata() | chardata() | external_chardata()</v>
- <v>RestData = latin1_chardata() | chardata() | external_chardata()</v>
- </type>
<desc>
- <p>Same as characters_to_list(Data,unicode).</p>
+ <p>Same as characters_to_list(<anno>Data</anno>,unicode).</p>
</desc>
</func>
<func>
- <name>characters_to_list(Data, InEncoding) -> list() | {error, list(), RestData} | {incomplete, list(), binary()} </name>
+ <name>characters_to_list(Data, InEncoding) -> Result</name>
<fsummary>Convert a collection of characters to list of Unicode characters</fsummary>
<type>
- <v>Data = latin1_chardata() | chardata() | external_chardata()</v>
- <v>RestData = latin1_chardata() | chardata() | external_chardata()</v>
- <v>InEncoding = latin1 | unicode | utf8 | utf16 | utf32 | {utf16,little} | {utf16,big} | {utf32,little} | {utf32,big}</v>
+ <v>Data = <seealso marker="#type-latin1_chardata">latin1_chardata()</seealso>
+ | <seealso marker="#type-chardata">chardata()</seealso>
+ | <seealso marker="#type-external_chardata">external_chardata()</seealso></v>
+ <v>Result = list() | {error, list(), RestData} | {incomplete, list(), binary()}</v>
+ <v>RestData = <seealso marker="#type-latin1_chardata">latin1_chardata()</seealso>
+ | <seealso marker="#type-chardata">chardata()</seealso>
+ | <seealso marker="#type-external_chardata">external_chardata()</seealso></v>
+ <v>InEncoding = <seealso marker="#type-encoding">encoding()</seealso></v>
</type>
<desc>
@@ -234,44 +268,42 @@ latin1_charlist() = [latin1_char() | latin1_binary() | latin1_charlist()]
</desc>
</func>
<func>
- <name>characters_to_binary(Data) -> binary() | {error, binary(), RestData} | {incomplete, binary(), binary()} </name>
- <fsummary>Convert a collection of characters to an UTF-8 binary</fsummary> <type>
- <v>Data = latin1_chardata() | chardata() | external_chardata()</v>
- <v>RestData = latin1_chardata() | chardata() | external_chardata()</v>
- </type>
+ <name name="characters_to_binary" arity="1"/>
+ <fsummary>Convert a collection of characters to an UTF-8 binary</fsummary>
<desc>
<p>Same as characters_to_binary(Data, unicode, unicode).</p>
</desc>
</func>
<func>
- <name>characters_to_binary(Data,InEncoding) -> binary() | {error, binary(), RestData} | {incomplete, binary(), binary()} </name>
- <fsummary>Convert a collection of characters to an UTF-8 binary</fsummary> <type>
- <v>Data = latin1_chardata() | chardata() | external_chardata()</v>
- <v>RestData = latin1_chardata() | chardata() | external_chardata()</v>
- <v>InEncoding = latin1 | unicode | utf8 | utf16 | utf32 | {utf16,little} | {utf16,big} | {utf32,little} | {utf32,big}</v>
+ <name>characters_to_binary(Data,InEncoding) -> Result</name>
+ <fsummary>Convert a collection of characters to an UTF-8 binary</fsummary>
+
+ <type>
+ <v>Data = <seealso marker="#type-latin1_chardata">latin1_chardata()</seealso>
+ | <seealso marker="#type-chardata">chardata()</seealso>
+ | <seealso marker="#type-external_chardata">external_chardata()</seealso></v>
+ <v>Result = binary() | {error, binary(), RestData} | {incomplete, binary(), binary()}</v>
+ <v>RestData = <seealso marker="#type-latin1_chardata">latin1_chardata()</seealso>
+ | <seealso marker="#type-chardata">chardata()</seealso>
+ | <seealso marker="#type-external_chardata">external_chardata()</seealso></v>
+ <v>InEncoding = <seealso marker="#type-encoding">encoding()</seealso></v>
</type>
<desc>
<p>Same as characters_to_binary(Data, InEncoding, unicode).</p>
</desc>
</func>
<func>
- <name>characters_to_binary(Data, InEncoding, OutEncoding) -> binary() | {error, binary(), RestData} | {incomplete, binary(), binary()} </name>
+ <name name="characters_to_binary" arity="3"/>
<fsummary>Convert a collection of characters to an UTF-8 binary</fsummary>
- <type>
- <v>Data = latin1_chardata() | chardata() | external_chardata()</v>
- <v>RestData = latin1_chardata() | chardata() | external_chardata()</v>
- <v>InEncoding = latin1 | unicode | utf8 | utf16 | utf32 | {utf16,little} | {utf16,big} | {utf32,little} | {utf32,big}</v>
- <v>OutEncoding = latin1 | unicode | utf8 | utf16 | utf32| {utf16,little} | {utf16,big} | {utf32,little} | {utf32,big}</v>
- </type>
<desc>
<p>This function behaves as <seealso
marker="#characters_to_list/2">
characters_to_list/2</seealso>, but produces an binary
instead of a unicode list. The
- <c>InEncoding</c> defines how input is to be interpreted if
+ <c><anno>InEncoding</anno></c> defines how input is to be interpreted if
binaries are present in the <c>Data</c>, while
- <c>OutEncoding</c> defines in what format output is to be
+ <c><anno>OutEncoding</anno></c> defines in what format output is to be
generated.</p>
<p>The option <c>unicode</c> is an alias for <c>utf8</c>, as this is the
@@ -291,17 +323,13 @@ latin1_charlist() = [latin1_char() | latin1_binary() | latin1_charlist()]
</desc>
</func>
<func>
- <name>encoding_to_bom(InEncoding) -> Bin</name>
+ <name name="encoding_to_bom" arity="1"/>
<fsummary>Create a binary UTF byte order mark from encoding.</fsummary>
- <type>
- <v>Bin = binary() of byte_size 4 or less</v>
- <v>InEncoding = latin1 | unicode | utf8 | utf16 | utf32 | {utf16,little} | {utf16,big} | {utf32,little} | {utf32,big}</v>
- <v>Length = int()</v>
- </type>
+ <type_desc variable="Bin">A binary() of byte_size 4 or more.</type_desc>
<desc>
<p>Create an UTF byte order mark (BOM) as a binary from the
- supplied <c>InEncoding</c>. The BOM is, if supported at all,
+ supplied <c><anno>InEncoding</anno></c>. The BOM is, if supported at all,
expected to be placed first in UTF encoded files or
messages.</p>
diff --git a/lib/stdlib/doc/src/win32reg.xml b/lib/stdlib/doc/src/win32reg.xml
index 28960cd098..99fd7fdeb6 100644
--- a/lib/stdlib/doc/src/win32reg.xml
+++ b/lib/stdlib/doc/src/win32reg.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2000</year><year>2009</year>
+ <year>2000</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -85,14 +85,22 @@ hkdd HKEY_DYN_DATA</pre>
<p>For additional information on the Windows registry consult the Win32
Programmer's Reference.</p>
</description>
+ <datatypes>
+ <datatype>
+ <name name="reg_handle"/>
+ <desc><p>As returned by <seealso marker="#open/1">open/1</seealso>.</p></desc>
+ </datatype>
+ <datatype>
+ <name name="name"/>
+ </datatype>
+ <datatype>
+ <name name="value"/>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>change_key(RegHandle, Key) -> ReturnValue</name>
+ <name name="change_key" arity="2"/>
<fsummary>Move to a key in the registry</fsummary>
- <type>
- <v>RegHandle = term()</v>
- <v>Key = string()</v>
- </type>
<desc>
<p>Changes the current key to another key. Works like cd.
The key can be specified as a relative path or as an
@@ -100,12 +108,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>change_key_create(RegHandle, Key) -> ReturnValue</name>
+ <name name="change_key_create" arity="2"/>
<fsummary>Move to a key, create it if it is not there</fsummary>
- <type>
- <v>RegHandle = term()</v>
- <v>Key = string()</v>
- </type>
<desc>
<p>Creates a key, or just changes to it, if it is already there. Works
like a combination of <c>mkdir</c> and <c>cd</c>. Calls the Win32 API function
@@ -114,23 +118,16 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>close(RegHandle)-> ReturnValue</name>
+ <name name="close" arity="1"/>
<fsummary>Close the registry.</fsummary>
- <type>
- <v>RegHandle = term()</v>
- </type>
<desc>
- <p>Closes the registry. After that, the <c>RegHandle</c> cannot
+ <p>Closes the registry. After that, the <c><anno>RegHandle</anno></c> cannot
be used.</p>
</desc>
</func>
<func>
- <name>current_key(RegHandle) -> ReturnValue</name>
+ <name name="current_key" arity="1"/>
<fsummary>Return the path to the current key.</fsummary>
- <type>
- <v>RegHandle = term()</v>
- <v>ReturnValue = {ok, string()}</v>
- </type>
<desc>
<p>Returns the path to the current key. This is the equivalent of <c>pwd</c>.</p>
<p>Note that the current key is stored in the driver, and might be
@@ -138,12 +135,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>delete_key(RegHandle) -> ReturnValue</name>
+ <name name="delete_key" arity="1"/>
<fsummary>Delete the current key</fsummary>
- <type>
- <v>RegHandle = term()</v>
- <v>ReturnValue = ok | {error, ErrorId}</v>
- </type>
<desc>
<p>Deletes the current key, if it is valid. Calls the Win32 API
function <c>RegDeleteKey()</c>. Note that this call does not change the current key,
@@ -152,12 +145,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>delete_value(RegHandle, Name) -> ReturnValue</name>
+ <name name="delete_value" arity="2"/>
<fsummary>Delete the named value on the current key.</fsummary>
- <type>
- <v>RegHandle = term()</v>
- <v>ReturnValue = ok | {error, ErrorId}</v>
- </type>
<desc>
<p>Deletes a named value on the current key. The atom <c>default</c> is
used for the the default value.</p>
@@ -165,12 +154,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>expand(String) -> ExpandedString</name>
+ <name name="expand" arity="1"/>
<fsummary>Expand a string with environment variables</fsummary>
- <type>
- <v>String = string()</v>
- <v>ExpandedString = string()</v>
- </type>
<desc>
<p>Expands a string containing environment variables between percent
characters. Anything between two % is taken for a environment
@@ -180,23 +165,15 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>format_error(ErrorId) -> ErrorString</name>
+ <name name="format_error" arity="1"/>
<fsummary>Convert an POSIX errorcode to a string</fsummary>
- <type>
- <v>ErrorId = atom()</v>
- <v>ErrorString = string()</v>
- </type>
<desc>
<p>Convert an POSIX errorcode to a string (by calling <c>erl_posix_msg:message</c>).</p>
</desc>
</func>
<func>
- <name>open(OpenModeList)-> ReturnValue</name>
+ <name name="open" arity="1"/>
<fsummary>Open the registry for reading or writing</fsummary>
- <type>
- <v>OpenModeList = [OpenMode]</v>
- <v>OpenMode = read | write</v>
- </type>
<desc>
<p>Opens the registry for reading or writing. The current key will be the root
(<c>HKEY_CLASSES_ROOT</c>). The <c>read</c> flag in the mode list can be omitted.</p>
@@ -204,12 +181,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>set_value(RegHandle, Name, Value) -> ReturnValue</name>
+ <name name="set_value" arity="3"/>
<fsummary>Set value at the current registry key with specified name.</fsummary>
- <type>
- <v>Name = string() | default</v>
- <v>Value = string() | integer() | binary()</v>
- </type>
<desc>
<p>Sets the named (or default) value to value. Calls the Win32
API function <c>RegSetValueEx()</c>. The value can be of three types, and
@@ -221,13 +194,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>sub_keys(RegHandle) -> ReturnValue</name>
+ <name name="sub_keys" arity="1"/>
<fsummary>Get subkeys to the current key.</fsummary>
- <type>
- <v>ReturnValue = {ok, SubKeys} | {error, ErrorId}</v>
- <v>SubKeys = [SubKey]</v>
- <v>SubKey = string()</v>
- </type>
<desc>
<p>Returns a list of subkeys to the current key. Calls the Win32
API function <c>EnumRegKeysEx()</c>.</p>
@@ -235,13 +203,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>value(RegHandle, Name) -> ReturnValue</name>
+ <name name="value" arity="2"/>
<fsummary>Get the named value on the current key.</fsummary>
- <type>
- <v>Name = string() | default</v>
- <v>ReturnValue = {ok, Value}</v>
- <v>Value = string() | integer() | binary()</v>
- </type>
<desc>
<p>Retrieves the named value (or default) on the current key.
Registry values of type <c>REG_SZ</c>, are returned as strings. Type <c>REG_DWORD</c>
@@ -249,15 +212,8 @@ hkdd HKEY_DYN_DATA</pre>
</desc>
</func>
<func>
- <name>values(RegHandle) -> ReturnValue</name>
+ <name name="values" arity="1"/>
<fsummary>Get all values on the current key.</fsummary>
- <type>
- <v>ReturnValue = {ok, ValuePairs} | {ok, ErrorId}</v>
- <v>ValuePairs = [ValuePair]</v>
- <v>ValuePair = {Name, Value}</v>
- <v>Name = string | default</v>
- <v>Value = string() | integer() | binary()</v>
- </type>
<desc>
<p>Retrieves a list of all values on the current key. The values
have types corresponding to the registry types, see <c>value</c>.
diff --git a/lib/stdlib/doc/src/zip.xml b/lib/stdlib/doc/src/zip.xml
index 529a70a23d..b03fc7f4e2 100644
--- a/lib/stdlib/doc/src/zip.xml
+++ b/lib/stdlib/doc/src/zip.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2006</year><year>2010</year>
+ <year>2006</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -85,67 +85,55 @@
recreated.</p>
</section>
- <section>
- <title>DATA TYPES</title>
- <code type="none">
-zip_file() </code>
- <p>The record <c>zip_file</c> contains the following fields.</p>
- <taglist>
- <tag><c>name = string()</c></tag>
- <item>
- <p>the name of the file</p>
- </item>
- <tag><c>info = file_info()</c></tag>
- <item>
- <p>file info as in
- <seealso marker="erts:file#read_file_info/1">file:read_file_info/1</seealso></p>
- </item>
- <tag><c>comment = string()</c></tag>
- <item>
- <p>the comment for the file in the zip archive</p>
- </item>
- <tag><c>offset = integer()</c></tag>
- <item>
- <p>the offset of the file in the zip archive (used internally)</p>
- </item>
- <tag><c>comp_size = integer()</c></tag>
- <item>
- <p>the compressed size of the file (the uncompressed size is found
- in <c>info</c>)</p>
- </item>
- </taglist>
- <code type="none">zip_comment</code>
- <p>The record <c>zip_comment</c> just contains the archive comment for
- a zip archive</p>
- <taglist>
- <tag><c>comment = string()</c></tag>
- <item>
- <p>the comment for the zip archive</p>
- </item>
- </taglist>
- </section>
+ <datatypes>
+ <datatype>
+ <name name="zip_comment"/>
+ <desc>
+ <p>The record <c>zip_comment</c> just contains the archive comment for
+ a zip archive</p>
+ </desc>
+ </datatype>
+ <datatype>
+ <name name="zip_file"/>
+ <desc>
+ <p>The record <c>zip_file</c> contains the following fields.</p>
+ <taglist>
+ <tag><c>name</c></tag>
+ <item>
+ <p>the name of the file</p>
+ </item>
+ <tag><c>info</c></tag>
+ <item>
+ <p>file info as in
+ <seealso marker="kernel:file#read_file_info/1">file:read_file_info/1</seealso></p>
+ </item>
+ <tag><c>comment</c></tag>
+ <item>
+ <p>the comment for the file in the zip archive</p>
+ </item>
+ <tag><c>offset</c></tag>
+ <item>
+ <p>the offset of the file in the zip archive (used internally)</p>
+ </item>
+ <tag><c>comp_size</c></tag>
+ <item>
+ <p>the compressed size of the file (the uncompressed size is found
+ in <c>info</c>)</p>
+ </item>
+ </taglist>
+ </desc>
+ </datatype>
+ </datatypes>
<funcs>
<func>
- <name>zip(Name, FileList) -> RetValue</name>
- <name>zip(Name, FileList, Options) -> RetValue</name>
- <name>create(Name, FileList) -> RetValue</name>
- <name>create(Name, FileList, Options) -> RetValue</name>
+ <name name="zip" arity="2"/>
+ <name name="zip" arity="3"/>
+ <name name="create" arity="2"/>
+ <name name="create" arity="3"/>
<fsummary>Create a zip archive with options</fsummary>
- <type>
- <v>Name = filename()</v>
- <v>FileList = [FileSpec]</v>
- <v>FileSpec = filename() | {filename(), binary()} | {filename(), binary(), #file_info{}}</v>
- <v>Options = [Option]</v>
- <v>Option = memory | cooked | verbose | {comment, Comment} | {cwd, CWD} | {compress, What} | {uncompress, What}</v>
- <v>What = all | [Extension] | {add, [Extension]} | {del, [Extension]}</v>
- <v>Extension = string()</v>
- <v>Comment = CWD = string()</v>
- <v>RetValue = {ok, Name} | {ok, {Name, binary()}} | {error, Reason}</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>The <marker id="zip_2"></marker><c>zip</c> function creates a
- zip archive containing the files specified in <c>FileList</c>.</p>
+ zip archive containing the files specified in <c><anno>FileList</anno></c>.</p>
<p>As synonyms, the functions <c>create/2</c> and <c>create/3</c>
are provided, to make it resemble the <c>erl_tar</c> module.</p>
<p>The file-list is a list of files, with paths relative to the
@@ -161,9 +149,9 @@ zip_file() </code>
<c>.Z</c>, <c>.zip</c>, <c>.zoo</c>, <c>.arc</c>, <c>.lzh</c>,
<c>.arj</c>.</p>
<p>It is possible to override the default behavior and
- explicitly control what types of files should be
- compressed by using the <c>{compress, What}</c> and
- <c>{uncompress, What}</c> options. It is possible to have
+ explicitly control what types of files that should be
+ compressed by using the <c>{compress, <anno>What</anno>}</c> and
+ <c>{uncompress, <anno>What</anno>}</c> options. It is possible to have
several <c>compress</c> and <c>uncompress</c> options. In
order to trigger compression of a file, its extension must
match with the
@@ -191,22 +179,22 @@ zip_file() </code>
<tag><c>memory</c></tag>
<item>
<p>The output will not be to a file, but instead as a tuple
- <c>{FileName, binary()}</c>. The binary will be a full zip
+ <c>{<anno>FileName</anno>, binary()}</c>. The binary will be a full zip
archive with header, and can be extracted with for instance
<c>unzip/2</c>.</p>
</item>
- <tag><c>{comment, Comment}</c></tag>
+ <tag><c>{comment, <anno>Comment</anno>}</c></tag>
<item>
<p>Add a comment to the zip-archive.</p>
</item>
- <tag><c>{cwd, CWD}</c></tag>
+ <tag><c>{cwd, <anno>CWD</anno>}</c></tag>
<item>
<p>Use the given directory as current directory, it will be
prepended to file names when adding them, although it will not
be in the zip-archive. (Acting like a file:set_cwd/1, but
without changing the global cwd property.)</p>
</item>
- <tag><c>{compress, What}</c></tag>
+ <tag><c>{compress, <anno>What</anno>}</c></tag>
<item>
<p>Controls what types of files will be
compressed. It is by default set to <c>all</c>. The
@@ -215,18 +203,18 @@ zip_file() </code>
<tag><c>all</c></tag>
<item><p> means that all files will be compressed (as long
as they pass the <c>uncompress</c> condition).</p></item>
- <tag><c>[Extension]</c></tag>
+ <tag><c>[<anno>Extension</anno>]</c></tag>
<item><p>means that only files with exactly these extensions
will be compressed.</p></item>
- <tag><c>{add,[Extension]}</c></tag>
+ <tag><c>{add,[<anno>Extension</anno>]}</c></tag>
<item><p>adds these extensions to the list of compress
extensions.</p></item>
- <tag><c>{del,[Extension]}</c></tag>
+ <tag><c>{del,[<anno>Extension</anno>]}</c></tag>
<item><p>deletes these extensions from the list of compress
extensions.</p></item>
</taglist>
</item>
- <tag><c>{uncompress, What}</c></tag>
+ <tag><c>{uncompress, <anno>What</anno>}</c></tag>
<item>
<p>Controls what types of files will be uncompressed. It is by
default set to <c>[".Z",".zip",".zoo",".arc",".lzh",".arj"]</c>.
@@ -234,13 +222,13 @@ zip_file() </code>
<taglist>
<tag><c>all</c></tag>
<item><p> means that no files will be compressed.</p></item>
- <tag><c>[Extension]</c></tag>
+ <tag><c>[<anno>Extension</anno>]</c></tag>
<item><p>means that files with these extensions will be
uncompressed.</p></item>
- <tag><c>{add,[Extension]}</c></tag>
+ <tag><c>{add,[<anno>Extension</anno>]}</c></tag>
<item><p>adds these extensions to the list of uncompress
extensions.</p></item>
- <tag><c>{del,[Extension]}</c></tag>
+ <tag><c>{del,[<anno>Extension</anno>]}</c></tag>
<item><p>deletes these extensions from the list of uncompress
extensions.</p></item>
</taglist>
@@ -249,23 +237,11 @@ zip_file() </code>
</desc>
</func>
<func>
- <name>unzip(Archive) -> RetValue</name>
- <name>unzip(Archive, Options) -> RetValue</name>
- <name>extract(Archive) -> RetValue</name>
- <name>extract(Archive, Options) -> RetValue</name>
+ <name name="unzip" arity="1"/>
+ <name name="unzip" arity="2"/>
+ <name name="extract" arity="1"/>
+ <name name="extract" arity="2"/>
<fsummary>Extract files from a zip archive</fsummary>
- <type>
- <v>Archive = filename() | binary()</v>
- <v>Options = [Option]</v>
- <v>Option = {file_list, FileList} | keep_old_files | verbose | memory | {file_filter, FileFilter} | {cwd, CWD}</v>
- <v>FileList = [filename()]</v>
- <v>FileBinList = [{filename(),binary()}]</v>
- <v>FileFilter = fun(ZipFile) -> true | false</v>
- <v>CWD = string()</v>
- <v>ZipFile = zip_file()</v>
- <v>RetValue = {ok,FileList} | {ok,FileBinList} | {error, Reason} | {error, {Name, Reason}}</v>
- <v>Reason = term()</v>
- </type>
<desc>
<p>The <marker id="unzip_1"></marker>
<c>unzip/1</c> function extracts
@@ -273,17 +249,17 @@ zip_file() </code>
<marker id="unzip_2"></marker>
<c>unzip/2</c> function provides options
to extract some files, and more.</p>
- <p>If the <c>Archive</c> argument is given as a binary,
+ <p>If the <c><anno>Archive</anno></c> argument is given as a binary,
the contents of the binary is assumed to be a zip archive,
otherwise it should be a filename.</p>
<p>The following options are available:</p>
<taglist>
- <tag><c>{file_list, FileList}</c></tag>
+ <tag><c>{file_list, <anno>FileList</anno>}</c></tag>
<item>
<p>By default, all files will be extracted from the zip
- archive. With the <c>{file_list,FileList}</c> option,
+ archive. With the <c>{file_list, <anno>FileList</anno>}</c> option,
the <c>unzip/2</c> function will only extract the files
- whose names are included in <c>FileList</c>. The full
+ whose names are included in <c><anno>FileList</anno></c>. The full
paths, including the names of all sub directories within
the zip archive, must be specified.</p>
</item>
@@ -329,29 +305,29 @@ zip_file() </code>
</desc>
</func>
<func>
- <name>foldl(Fun, Acc0, Archive) -> {ok, Acc1} | {error, Reason}</name>
+ <name name="foldl" arity="3"/>
<fsummary>Fold a function over all files in a zip archive</fsummary>
- <type>
- <v>Fun = fun(FileInArchive, GetInfo, GetBin, AccIn) -> AccOut</v>
- <v>FileInArchive = filename()</v>
- <v>GetInfo = fun() -> #file_info{}</v>
- <v>GetBin = fun() -> binary()</v>
- <v>Acc0 = Acc1 = AccIn = AccOut = term()</v>
- <v>Archive = filename() | {filename(), binary()}</v>
- </type>
<desc>
<p>The <marker id="foldl_3"></marker> <c>foldl/3</c> function
- calls <c>Fun(FileInArchive, GetInfo, GetBin, AccIn)</c> on
- successive files in the <c>Archive</c>, starting with <c>AccIn
- == Acc0</c>. <c>FileInArchive</c> is the name that the file
- has in the archive. <c>GetInfo</c> is a fun that returns info
- about the the file. <c>GetBin</c> returns the contents of the
- file. Both <c>GetInfo</c> and <c>GetBin</c> must be called
- within the <c>Fun</c>. Their behavior is undefined if they are
- called outside the context of the <c>Fun</c>. The <c>Fun</c>
+ calls <c><anno>Fun</anno>(<anno>FileInArchive</anno>, <anno>GetInfo
+ </anno>, <anno>GetBin</anno>, <anno>AccIn</anno>)</c> on
+ successive files in the <c>Archive</c>, starting with
+ <c><anno>AccIn</anno>
+ == <anno>Acc0</anno></c>. <c><anno>FileInArchive</anno></c> is
+ the name that the file
+ has in the archive. <c><anno>GetInfo</anno></c> is a fun that
+ returns info
+ about the the file. <c><anno>GetBin</anno></c> returns the contents
+ of the
+ file. Both <c><anno>GetInfo</anno></c> and <c><anno>GetBin</anno></c>
+ must be called
+ within the <c><anno>Fun</anno></c>. Their behavior is undefined if
+ they are
+ called outside the context of the <c><anno>Fun</anno></c>.
+ The <c><anno>Fun</anno></c>
must return a new accumulator which is passed to the next
call. <c>foldl/3</c> returns the final value of the
- accumulator. <c>Acc0</c> is returned if the archive is
+ accumulator. <c><anno>Acc0</anno></c> is returned if the archive is
empty. It is not necessary to iterate over all files in the
archive. The iteration may be ended prematurely in a
controlled manner by throwing an exception.</p>
@@ -387,26 +363,16 @@ zip_file() </code>
</desc>
</func>
<func>
- <name>list_dir(Archive) -> RetValue</name>
- <name>list_dir(Archive, Options)</name>
- <name>table(Archive) -> RetValue</name>
- <name>table(Archive, Options)</name>
+ <name name="list_dir" arity="1"/>
+ <name name="list_dir" arity="2"/>
+ <name name="table" arity="1" />
+ <name name="table" arity="2"/>
<fsummary>Retrieve the name of all files in a zip archive</fsummary>
- <type>
- <v>Archive = filename() | binary()</v>
- <v>RetValue = {ok, [Comment, Files]} | {error, Reason}</v>
- <v>Comment = zip_comment()</v>
- <v>Files = [zip_file()]</v>
- <v>Options = [Option]</v>
- <v>Option = cooked</v>
- <v>Reason = term()</v>
- </type>
<desc>
- <p>The <marker id="list_dir_1"></marker>
-<c>list_dir/1</c> function retrieves
- the names of all files in the zip archive <c>Archive</c>. The
- <marker id="list_dir_2"></marker>
-<c>list_dir/2</c> function provides options.</p>
+ <p>The <marker id="list_dir_1"></marker><c>list_dir/1</c>
+ function retrieves the names of all files in the zip archive
+ <c><anno>Archive</anno></c>. The <marker id="list_dir_2"></marker>
+ <c>list_dir/2</c> function provides options.</p>
<p>As synonyms, the functions <c>table/2</c> and <c>table/3</c>
are provided, to make it resemble the <c>erl_tar</c> module.</p>
<p>The result value is the tuple <c>{ok, List}</c>, where <c>List</c>
@@ -425,43 +391,27 @@ zip_file() </code>
</desc>
</func>
<func>
- <name>t(Archive)</name>
+ <name name="t" arity="1"/>
<fsummary>Print the name of each file in a zip archive</fsummary>
- <type>
- <v>Archive = filename() | binary() | ZipHandle</v>
- <v>ZipHandle = pid()</v>
- </type>
<desc>
- <p>The <marker id="t_1"></marker>
-<c>t/1</c> function prints the names
- of all files in the zip archive <c>Archive</c> to the Erlang shell.
+ <p>The <marker id="t_1"></marker><c>t/1</c> function prints the names
+ of all files in the zip archive <c><anno>Archive</anno></c> to the Erlang shell.
(Similar to "<c>tar&nbsp;t</c>".)</p>
</desc>
</func>
<func>
- <name>tt(Archive)</name>
+ <name name="tt" arity="1"/>
<fsummary>Print name and information for each file in a zip archive</fsummary>
- <type>
- <v>Archive = filename() | binary()</v>
- </type>
<desc>
- <p>The <marker id="tt_1"></marker>
-<c>tt/1</c> function prints names and
- information about all files in the zip archive <c>Archive</c> to
+ <p>The <marker id="tt_1"></marker><c>tt/1</c> function prints names and
+ information about all files in the zip archive <c><anno>Archive</anno></c> to
the Erlang shell. (Similar to "<c>tar tv</c>".)</p>
</desc>
</func>
<func>
- <name>zip_open(Archive) -> {ok, ZipHandle} | {error, Reason}</name>
- <name>zip_open(Archive, Options) -> {ok, ZipHandle} | {error, Reason}</name>
+ <name name="zip_open" arity="1"/>
+ <name name="zip_open" arity="2"/>
<fsummary>Open an archive and return a handle to it</fsummary>
- <type>
- <v>Archive = filename() | binary()</v>
- <v>Options = [Option]</v>
- <v>Options = cooked | memory | {cwd, CWD}</v>
- <v>CWD = string()</v>
- <v>ZipHandle = pid()</v>
- </type>
<desc>
<p>The <marker id="zip_open"></marker>
<c>zip_open</c> function opens a
@@ -472,29 +422,19 @@ zip_file() </code>
</desc>
</func>
<func>
- <name>zip_list_dir(ZipHandle) -> Result | {error, Reason}</name>
+ <name name="zip_list_dir" arity="1"/>
<fsummary>Return a table of files in open zip archive</fsummary>
- <type>
- <v>Result = [ZipComment, ZipFile...]</v>
- <v>ZipComment = #zip_comment{}</v>
- <v>ZipFile = #zip_file{}</v>
- <v>ZipHandle = pid()</v>
- </type>
<desc>
- <p>The <marker id="zip_list_dir"></marker>
-<c>zip_list_dir/1</c> function
- returns the file list of an open zip archive.</p>
+ <p>The <marker id="zip_list_dir"></marker>
+ <c>zip_list_dir/1</c> function
+ returns the file list of an open zip archive. The first returned
+ element is the zip archive comment.</p>
</desc>
</func>
<func>
- <name>zip_get(ZipHandle) -> {ok, [Result]} | {error, Reason}</name>
- <name>zip_get(FileName, ZipHandle) -> {ok, Result} | {error, Reason}</name>
+ <name name="zip_get" arity="1"/>
+ <name name="zip_get" arity="2"/>
<fsummary>Extract files from an open archive</fsummary>
- <type>
- <v>FileName = filename()</v>
- <v>ZipHandle = pid()</v>
- <v>Result = filename() | {filename(), binary()}</v>
- </type>
<desc>
<p>The <marker id="zip_get"></marker>
<c>zip_get</c> function extracts
@@ -505,11 +445,8 @@ zip_file() </code>
</desc>
</func>
<func>
- <name>zip_close(ZipHandle) -> ok | {error, einval}</name>
+ <name name="zip_close" arity="1"/>
<fsummary>Close an open archive</fsummary>
- <type>
- <v>ZipHandle = pid()</v>
- </type>
<desc>
<p>The <marker id="zip_close"></marker>
<c>zip_close/1</c> function closes
diff --git a/lib/stdlib/include/zip.hrl b/lib/stdlib/include/zip.hrl
index 2b5ddc1dfe..6e3ed9c78a 100644
--- a/lib/stdlib/include/zip.hrl
+++ b/lib/stdlib/include/zip.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2006-2009. All Rights Reserved.
+%% 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
@@ -19,7 +19,7 @@
-record(zip_file, {
name :: string(), % file name
- info :: #file_info{},
+ info :: file:file_info(),
comment :: string(), % zip file comment
offset :: non_neg_integer(), % offset of file's local header in archive
comp_size :: non_neg_integer() % compressed size
diff --git a/lib/stdlib/src/array.erl b/lib/stdlib/src/array.erl
index 83576c9fd3..2f69e2b0a4 100644
--- a/lib/stdlib/src/array.erl
+++ b/lib/stdlib/src/array.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2007-2009. All Rights Reserved.
+%% Copyright Ericsson AB 2007-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
@@ -163,17 +163,17 @@
-type array_indx() :: non_neg_integer().
--type array_opt() :: 'fixed' | non_neg_integer()
- | {'default', term()} | {'fixed', boolean()}
- | {'size', non_neg_integer()}.
+-type array_opt() :: {'fixed', boolean()} | 'fixed'
+ | {'default', Value :: term()}
+ | {'size', N :: non_neg_integer()}
+ | (N :: non_neg_integer()).
-type array_opts() :: array_opt() | [array_opt()].
--type indx_pair() :: {array_indx(), term()}.
+-type indx_pair() :: {Index :: array_indx(), Value :: term()}.
-type indx_pairs() :: [indx_pair()].
%%--------------------------------------------------------------------------
-%% @spec () -> array()
%% @doc Create a new, extendible array with initial size zero.
%% @equiv new([])
%%
@@ -185,7 +185,6 @@
new() ->
new([]).
-%% @spec (Options::term()) -> array()
%% @doc Create a new array according to the given options. By default,
%% the array is extendible and has initial size zero. Array indices
%% start at 0.
@@ -224,12 +223,11 @@ new() ->
%% @see from_list/2
%% @see fix/1
--spec new(array_opts()) -> array().
+-spec new(Options :: array_opts()) -> array().
new(Options) ->
new_0(Options, 0, false).
-%% @spec (Size::integer(), Options::term()) -> array()
%% @doc Create a new array according to the given size and options. If
%% `Size' is not a nonnegative integer, the call fails with reason
%% `badarg'. By default, the array has fixed size. Note that any size
@@ -245,7 +243,7 @@ new(Options) ->
%%
%% @see new/1
--spec new(non_neg_integer(), array_opts()) -> array().
+-spec new(Size :: non_neg_integer(), Options :: array_opts()) -> array().
new(Size, Options) when is_integer(Size), Size >= 0 ->
new_0(Options, Size, true);
@@ -293,13 +291,12 @@ find_max(_I, M) ->
M.
-%% @spec (X::term()) -> boolean()
%% @doc Returns `true' if `X' appears to be an array, otherwise `false'.
%% Note that the check is only shallow; there is no guarantee that `X'
%% is a well-formed array representation even if this function returns
%% `true'.
--spec is_array(term()) -> boolean().
+-spec is_array(X :: term()) -> boolean().
is_array(#array{size = Size, max = Max})
when is_integer(Size), is_integer(Max) ->
@@ -308,25 +305,23 @@ is_array(_) ->
false.
-%% @spec (array()) -> integer()
%% @doc Get the number of entries in the array. Entries are numbered
%% from 0 to `size(Array)-1'; hence, this is also the index of the first
%% entry that is guaranteed to not have been previously set.
%% @see set/3
%% @see sparse_size/1
--spec size(array()) -> non_neg_integer().
+-spec size(Array :: array()) -> non_neg_integer().
size(#array{size = N}) -> N;
size(_) -> erlang:error(badarg).
-%% @spec (array()) -> term()
%% @doc Get the value used for uninitialized entries.
%%
%% @see new/2
--spec default(array()) -> term().
+-spec default(Array :: array()) -> term().
default(#array{default = D}) -> D;
default(_) -> erlang:error(badarg).
@@ -405,23 +400,21 @@ new_test_() ->
-endif.
-%% @spec (array()) -> array()
%% @doc Fix the size of the array. This prevents it from growing
%% automatically upon insertion; see also {@link set/3}.
%% @see relax/1
--spec fix(array()) -> array().
+-spec fix(Array :: array()) -> array().
fix(#array{}=A) ->
A#array{max = 0}.
-%% @spec (array()) -> boolean()
%% @doc Check if the array has fixed size.
%% Returns `true' if the array is fixed, otherwise `false'.
%% @see fix/1
--spec is_fix(array()) -> boolean().
+-spec is_fix(Array :: array()) -> boolean().
is_fix(#array{max = 0}) -> true;
is_fix(#array{}) -> false.
@@ -455,12 +448,11 @@ fix_test_() ->
-endif.
-%% @spec (array()) -> array()
%% @doc Make the array resizable. (Reverses the effects of {@link
%% fix/1}.)
%% @see fix/1
--spec relax(array()) -> array().
+-spec relax(Array :: array()) -> array().
relax(#array{size = N}=A) ->
A#array{max = find_max(N-1, ?LEAFSIZE)}.
@@ -481,12 +473,11 @@ relax_test_() ->
-endif.
-%% @spec (integer(), array()) -> array()
%% @doc Change the size of the array. If `Size' is not a nonnegative
%% integer, the call fails with reason `badarg'. If the given array has
%% fixed size, the resulting array will also have fixed size.
--spec resize(non_neg_integer(), array()) -> array().
+-spec resize(Size :: non_neg_integer(), Array :: array()) -> array().
resize(Size, #array{size = N, max = M, elements = E}=A)
when is_integer(Size), Size >= 0 ->
@@ -510,8 +501,6 @@ resize(_Size, _) ->
erlang:error(badarg).
-%% @spec (array()) -> array()
-
%% @doc Change the size of the array to that reported by {@link
%% sparse_size/1}. If the given array has fixed size, the resulting
%% array will also have fixed size.
@@ -519,7 +508,7 @@ resize(_Size, _) ->
%% @see resize/2
%% @see sparse_size/1
--spec resize(array()) -> array().
+-spec resize(Array :: array()) -> array().
resize(Array) ->
resize(sparse_size(Array), Array).
@@ -559,7 +548,6 @@ resize_test_() ->
-endif.
-%% @spec (integer(), term(), array()) -> array()
%% @doc Set entry `I' of the array to `Value'. If `I' is not a
%% nonnegative integer, or if the array has fixed size and `I' is larger
%% than the maximum index, the call fails with reason `badarg'.
@@ -570,7 +558,7 @@ resize_test_() ->
%% @see get/2
%% @see reset/2
--spec set(array_indx(), term(), array()) -> array().
+-spec set(I :: array_indx(), Value :: term(), Array :: array()) -> array().
set(I, Value, #array{size = N, max = M, default = D, elements = E}=A)
when is_integer(I), I >= 0 ->
@@ -624,7 +612,6 @@ expand(I, _S, X, D) ->
setelement(I+1, ?NEW_LEAF(D), X).
-%% @spec (integer(), array()) -> term()
%% @doc Get the value of entry `I'. If `I' is not a nonnegative
%% integer, or if the array has fixed size and `I' is larger than the
%% maximum index, the call fails with reason `badarg'.
@@ -634,7 +621,7 @@ expand(I, _S, X, D) ->
%% @see set/3
--spec get(array_indx(), array()) -> term().
+-spec get(I :: array_indx(), Array :: array()) -> term().
get(I, #array{size = N, max = M, elements = E, default = D})
when is_integer(I), I >= 0 ->
@@ -660,7 +647,6 @@ get_1(I, E, _D) ->
element(I+1, E).
-%% @spec (integer(), array()) -> array()
%% @doc Reset entry `I' to the default value for the array.
%% If the value of entry `I' is the default value the array will be
%% returned unchanged. Reset will never change size of the array.
@@ -675,7 +661,7 @@ get_1(I, E, _D) ->
%% TODO: a reset_range function
--spec reset(array_indx(), array()) -> array().
+-spec reset(I :: array_indx(), Array :: array()) -> array().
reset(I, #array{size = N, max = M, default = D, elements = E}=A)
when is_integer(I), I >= 0 ->
@@ -756,13 +742,12 @@ set_get_test_() ->
-endif.
-%% @spec (array()) -> list()
%% @doc Converts the array to a list.
%%
%% @see from_list/2
%% @see sparse_to_list/1
--spec to_list(array()) -> list().
+-spec to_list(Array :: array()) -> list().
to_list(#array{size = 0}) ->
[];
@@ -831,12 +816,11 @@ to_list_test_() ->
-endif.
-%% @spec (array()) -> list()
%% @doc Converts the array to a list, skipping default-valued entries.
%%
%% @see to_list/1
--spec sparse_to_list(array()) -> list().
+-spec sparse_to_list(Array :: array()) -> list().
sparse_to_list(#array{size = 0}) ->
[];
@@ -901,15 +885,13 @@ sparse_to_list_test_() ->
-endif.
-%% @spec (list()) -> array()
%% @equiv from_list(List, undefined)
--spec from_list(list()) -> array().
+-spec from_list(List :: list()) -> array().
from_list(List) ->
from_list(List, undefined).
-%% @spec (list(), term()) -> array()
%% @doc Convert a list to an extendible array. `Default' is used as the value
%% for uninitialized entries of the array. If `List' is not a proper list,
%% the call fails with reason `badarg'.
@@ -917,7 +899,7 @@ from_list(List) ->
%% @see new/2
%% @see to_list/1
--spec from_list(list(), term()) -> array().
+-spec from_list(List :: list(), Default :: term()) -> array().
from_list([], Default) ->
new({default,Default});
@@ -1011,13 +993,12 @@ from_list_test_() ->
-endif.
-%% @spec (array()) -> [{Index::integer(), Value::term()}]
%% @doc Convert the array to an ordered list of pairs `{Index, Value}'.
%%
%% @see from_orddict/2
%% @see sparse_to_orddict/1
--spec to_orddict(array()) -> indx_pairs().
+-spec to_orddict(Array :: array()) -> indx_pairs().
to_orddict(#array{size = 0}) ->
[];
@@ -1104,13 +1085,12 @@ to_orddict_test_() ->
-endif.
-%% @spec (array()) -> [{Index::integer(), Value::term()}]
%% @doc Convert the array to an ordered list of pairs `{Index, Value}',
%% skipping default-valued entries.
%%
%% @see to_orddict/1
--spec sparse_to_orddict(array()) -> indx_pairs().
+-spec sparse_to_orddict(Array :: array()) -> indx_pairs().
sparse_to_orddict(#array{size = 0}) ->
[];
@@ -1188,15 +1168,13 @@ sparse_to_orddict_test_() ->
-endif.
-%% @spec (list()) -> array()
%% @equiv from_orddict(Orddict, undefined)
--spec from_orddict(indx_pairs()) -> array().
+-spec from_orddict(Orddict :: indx_pairs()) -> array().
from_orddict(Orddict) ->
from_orddict(Orddict, undefined).
-%% @spec (list(), term()) -> array()
%% @doc Convert an ordered list of pairs `{Index, Value}' to a
%% corresponding extendible array. `Default' is used as the value for
%% uninitialized entries of the array. If `List' is not a proper,
@@ -1206,7 +1184,7 @@ from_orddict(Orddict) ->
%% @see new/2
%% @see to_orddict/1
--spec from_orddict(indx_pairs(), term()) -> array().
+-spec from_orddict(Orddict :: indx_pairs(), Default :: term()) -> array().
from_orddict([], Default) ->
new({default,Default});
@@ -1392,7 +1370,6 @@ from_orddict_test_() ->
-endif.
-%% @spec (Function, array()) -> array()
%% Function = (Index::integer(), Value::term()) -> term()
%% @doc Map the given function onto each element of the array. The
%% elements are visited in order from the lowest index to the highest.
@@ -1402,7 +1379,8 @@ from_orddict_test_() ->
%% @see foldr/3
%% @see sparse_map/2
--spec map(fun((array_indx(), _) -> _), array()) -> array().
+-spec map(Function, Array :: array()) -> array() when
+ Function :: fun((Index :: array_indx(), Value :: _) -> _).
map(Function, Array=#array{size = N, elements = E, default = D})
when is_function(Function, 2) ->
@@ -1485,7 +1463,6 @@ map_test_() ->
-endif.
-%% @spec (Function, array()) -> array()
%% Function = (Index::integer(), Value::term()) -> term()
%% @doc Map the given function onto each element of the array, skipping
%% default-valued entries. The elements are visited in order from the
@@ -1494,7 +1471,8 @@ map_test_() ->
%%
%% @see map/2
--spec sparse_map(fun((array_indx(), _) -> _), array()) -> array().
+-spec sparse_map(Function, Array :: array()) -> array() when
+ Function :: fun((Index :: array_indx(), Value :: _) -> _).
sparse_map(Function, Array=#array{size = N, elements = E, default = D})
when is_function(Function, 2) ->
@@ -1580,9 +1558,6 @@ sparse_map_test_() ->
-endif.
-%% @spec (Function, InitialAcc::term(), array()) -> term()
-%% Function = (Index::integer(), Value::term(), Acc::term()) ->
-%% term()
%% @doc Fold the elements of the array using the given function and
%% initial accumulator value. The elements are visited in order from the
%% lowest index to the highest. If `Function' is not a function, the
@@ -1592,7 +1567,8 @@ sparse_map_test_() ->
%% @see map/2
%% @see sparse_foldl/3
--spec foldl(fun((array_indx(), _, A) -> B), A, array()) -> B.
+-spec foldl(Function, InitialAcc :: A, Array :: array()) -> B when
+ Function :: fun((Index :: array_indx(), Value :: _, Acc :: A) -> B).
foldl(Function, A, #array{size = N, elements = E, default = D})
when is_function(Function, 3) ->
@@ -1656,9 +1632,6 @@ foldl_test_() ->
-endif.
-%% @spec (Function, InitialAcc::term(), array()) -> term()
-%% Function = (Index::integer(), Value::term(), Acc::term()) ->
-%% term()
%% @doc Fold the elements of the array using the given function and
%% initial accumulator value, skipping default-valued entries. The
%% elements are visited in order from the lowest index to the highest.
@@ -1667,7 +1640,8 @@ foldl_test_() ->
%% @see foldl/3
%% @see sparse_foldr/3
--spec sparse_foldl(fun((array_indx(), _, A) -> B), A, array()) -> B.
+-spec sparse_foldl(Function, InitialAcc :: A, Array :: array()) -> B when
+ Function :: fun((Index :: array_indx(), Value :: _, Acc :: A) -> B).
sparse_foldl(Function, A, #array{size = N, elements = E, default = D})
when is_function(Function, 3) ->
@@ -1735,9 +1709,6 @@ sparse_foldl_test_() ->
-endif.
-%% @spec (Function, InitialAcc::term(), array()) -> term()
-%% Function = (Index::integer(), Value::term(), Acc::term()) ->
-%% term()
%% @doc Fold the elements of the array right-to-left using the given
%% function and initial accumulator value. The elements are visited in
%% order from the highest index to the lowest. If `Function' is not a
@@ -1746,7 +1717,8 @@ sparse_foldl_test_() ->
%% @see foldl/3
%% @see map/2
--spec foldr(fun((array_indx(), _, A) -> B), A, array()) -> B.
+-spec foldr(Function, InitialAcc :: A, Array :: array()) -> B when
+ Function :: fun((Index :: array_indx(), Value :: _, Acc :: A) -> B).
foldr(Function, A, #array{size = N, elements = E, default = D})
when is_function(Function, 3) ->
@@ -1815,9 +1787,6 @@ foldr_test_() ->
-endif.
-%% @spec (Function, InitialAcc::term(), array()) -> term()
-%% Function = (Index::integer(), Value::term(), Acc::term()) ->
-%% term()
%% @doc Fold the elements of the array right-to-left using the given
%% function and initial accumulator value, skipping default-valued
%% entries. The elements are visited in order from the highest index to
@@ -1827,7 +1796,8 @@ foldr_test_() ->
%% @see foldr/3
%% @see sparse_foldl/3
--spec sparse_foldr(fun((array_indx(), _, A) -> B), A, array()) -> B.
+-spec sparse_foldr(Function, InitialAcc :: A, Array :: array()) -> B when
+ Function :: fun((Index :: array_indx(), Value :: _, Acc :: A) -> B).
sparse_foldr(Function, A, #array{size = N, elements = E, default = D})
when is_function(Function, 3) ->
@@ -1870,7 +1840,6 @@ sparse_foldr_3(I, T, Ix, A, F, D) ->
end.
-%% @spec (array()) -> integer()
%% @doc Get the number of entries in the array up until the last
%% non-default valued entry. In other words, returns `I+1' if `I' is the
%% last non-default valued entry in the array, or zero if no such entry
@@ -1878,7 +1847,7 @@ sparse_foldr_3(I, T, Ix, A, F, D) ->
%% @see size/1
%% @see resize/1
--spec sparse_size(array()) -> non_neg_integer().
+-spec sparse_size(Array :: array()) -> non_neg_integer().
sparse_size(A) ->
F = fun (I, _V, _A) -> throw({value, I}) end,
diff --git a/lib/stdlib/src/base64.erl b/lib/stdlib/src/base64.erl
index a14a72ac6d..5d800e87b8 100644
--- a/lib/stdlib/src/base64.erl
+++ b/lib/stdlib/src/base64.erl
@@ -38,7 +38,9 @@
%% Description: Encodes a plain ASCII string (or binary) into base64.
%%-------------------------------------------------------------------------
--spec encode_to_string(string() | binary()) -> ascii_string().
+-spec encode_to_string(Data) -> Base64String when
+ Data :: string() | binary(),
+ Base64String :: ascii_string().
encode_to_string(Bin) when is_binary(Bin) ->
encode_to_string(binary_to_list(Bin));
@@ -53,7 +55,9 @@ encode_to_string(List) when is_list(List) ->
%% Description: Encodes a plain ASCII string (or binary) into base64.
%%-------------------------------------------------------------------------
--spec encode(string() | binary()) -> binary().
+-spec encode(Data) -> Base64 when
+ Data :: string() | binary(),
+ Base64 :: binary().
encode(Bin) when is_binary(Bin) ->
encode_binary(Bin);
@@ -102,14 +106,18 @@ encode_binary(Bin) ->
%% whereas decode crashes if an illegal character is found
%%-------------------------------------------------------------------------
--spec decode(string() | binary()) -> binary().
+-spec decode(Base64) -> Data when
+ Base64 :: string() | binary(),
+ Data :: binary().
decode(Bin) when is_binary(Bin) ->
decode_binary(<<>>, Bin);
decode(List) when is_list(List) ->
list_to_binary(decode_l(List)).
--spec mime_decode(string() | binary()) -> binary().
+-spec mime_decode(Base64) -> Data when
+ Base64 :: string() | binary(),
+ Data :: binary().
mime_decode(Bin) when is_binary(Bin) ->
mime_decode_binary(<<>>, Bin);
@@ -139,14 +147,18 @@ mime_decode_l(List) ->
%% whereas decode crashes if an illegal character is found
%%-------------------------------------------------------------------------
--spec decode_to_string(string() | binary()) -> string().
+-spec decode_to_string(Base64) -> DataString when
+ Base64 :: string() | binary(),
+ DataString :: string().
decode_to_string(Bin) when is_binary(Bin) ->
decode_to_string(binary_to_list(Bin));
decode_to_string(List) when is_list(List) ->
decode_l(List).
--spec mime_decode_to_string(string() | binary()) -> string().
+-spec mime_decode_to_string(Base64) -> DataString when
+ Base64 :: string() | binary(),
+ DataString :: string().
mime_decode_to_string(Bin) when is_binary(Bin) ->
mime_decode_to_string(binary_to_list(Bin));
diff --git a/lib/stdlib/src/beam_lib.erl b/lib/stdlib/src/beam_lib.erl
index 74d4ad3da7..d9c645d787 100644
--- a/lib/stdlib/src/beam_lib.erl
+++ b/lib/stdlib/src/beam_lib.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2000-2010. All Rights Reserved.
+%% 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
@@ -54,13 +54,9 @@
-type beam() :: module() | file:filename() | binary().
-%% XXX: THE FOLLOWING SHOULD BE IMPORTED FROM SOMEWHERE ELSE
--type forms() :: term().
+-type forms() :: [erl_parse:abstract_form()].
--type abst_vsn() :: atom().
--type abst_code() :: {abst_vsn(), forms()} | 'no_abstract_code'.
--type attribute() :: atom().
--type attrvalue() :: term().
+-type abst_code() :: {AbstVersion :: atom(), forms()} | 'no_abstract_code'.
-type dataB() :: binary().
-type index() :: non_neg_integer().
-type label() :: integer().
@@ -74,9 +70,9 @@
| 'atoms'.
-type chunkref() :: chunkname() | chunkid().
--type attrib_entry() :: {attribute(), [attrvalue()]}.
--type compinfo_entry() :: {atom(), term()}.
--type labeled_entry() :: {atom(), arity(), label()}.
+-type attrib_entry() :: {Attribute :: atom(), [AttributeValue :: term()]}.
+-type compinfo_entry() :: {InfoKey :: atom(), term()}.
+-type labeled_entry() :: {Function :: atom(), arity(), label()}.
-type chunkdata() :: {chunkid(), dataB()}
| {'abstract_code', abst_code()}
@@ -85,20 +81,17 @@
| {'exports', [{atom(), arity()}]}
| {'labeled_exports', [labeled_entry()]}
| {'imports', [mfa()]}
- | {'indexed_imports', [{index(), module(), atom(), arity()}]}
+ | {'indexed_imports', [{index(), module(), Function :: atom(), arity()}]}
| {'locals', [{atom(), arity()}]}
| {'labeled_locals', [labeled_entry()]}
| {'atoms', [{integer(), atom()}]}.
--type info_pair() :: {'file', file:filename()}
- | {'binary', binary()}
- | {'module', module()}
- | {'chunks', [{chunkid(), integer(), integer()}]}.
-
%% Error reasons
-type info_rsn() :: {'chunk_too_big', file:filename(),
- chunkid(), integer(), integer()}
- | {'invalid_beam_file', file:filename(), integer()}
+ chunkid(), ChunkSize :: non_neg_integer(),
+ FileSize :: non_neg_integer()}
+ | {'invalid_beam_file', file:filename(),
+ Position :: non_neg_integer()}
| {'invalid_chunk', file:filename(), chunkid()}
| {'missing_chunk', file:filename(), chunkid()}
| {'not_a_beam_file', file:filename()}
@@ -118,20 +111,34 @@
%% Exported functions
%%
--spec info(beam()) -> [info_pair()] | {'error', 'beam_lib', info_rsn()}.
+-spec info(Beam) -> [InfoPair] | {'error', 'beam_lib', info_rsn()} when
+ Beam :: beam(),
+ InfoPair :: {'file', Filename :: file:filename()}
+ | {'binary', Binary :: binary()}
+ | {'module', Module :: module()}
+ | {'chunks', [{ChunkId :: chunkid(),
+ Pos :: non_neg_integer(),
+ Size :: non_neg_integer()}]}.
info(File) ->
read_info(beam_filename(File)).
--spec chunks(beam(), [chunkref()]) ->
- {'ok', {module(), [chunkdata()]}} | {'error', 'beam_lib', chnk_rsn()}.
+-spec chunks(Beam, ChunkRefs) ->
+ {'ok', {module(), [chunkdata()]}} |
+ {'error', 'beam_lib', chnk_rsn()} when
+ Beam :: beam(),
+ ChunkRefs :: [chunkref()].
chunks(File, Chunks) ->
read_chunk_data(File, Chunks).
--spec chunks(beam(), [chunkref()], ['allow_missing_chunks']) ->
- {'ok', {module(), [{chunkref(), chunkdata() | 'missing_chunk'}]}}
- | {'error', 'beam_lib', chnk_rsn()}.
+-spec chunks(Beam, ChunkRefs, Options) ->
+ {'ok', {module(), [ChunkResult]}} |
+ {'error', 'beam_lib', chnk_rsn()} when
+ Beam :: beam(),
+ ChunkRefs :: [chunkref()],
+ Options :: ['allow_missing_chunks'],
+ ChunkResult :: chunkdata() | {ChunkRef :: chunkref(), 'missing_chunk'}.
chunks(File, Chunks, Options) ->
try read_chunk_data(File, Chunks, Options)
@@ -142,49 +149,65 @@ chunks(File, Chunks, Options) ->
all_chunks(File) ->
read_all_chunks(File).
--spec cmp(beam(), beam()) -> 'ok' | {'error', 'beam_lib', cmp_rsn()}.
+-spec cmp(Beam1, Beam2) -> 'ok' | {'error', 'beam_lib', cmp_rsn()} when
+ Beam1 :: beam(),
+ Beam2 :: beam().
cmp(File1, File2) ->
try cmp_files(File1, File2)
catch Error -> Error end.
--spec cmp_dirs(atom() | file:filename(), atom() | file:filename()) ->
- {[file:filename()], [file:filename()],
- [{file:filename(), file:filename()}]}
- | {'error', 'beam_lib', {'not_a_directory', term()} | info_rsn()}.
+-spec cmp_dirs(Dir1, Dir2) ->
+ {Only1, Only2, Different} | {'error', 'beam_lib', Reason} when
+ Dir1 :: atom() | file:filename(),
+ Dir2 :: atom() | file:filename(),
+ Only1 :: [file:filename()],
+ Only2 :: [file:filename()],
+ Different :: [{Filename1 :: file:filename(), Filename2 :: file:filename()}],
+ Reason :: {'not_a_directory', term()} | info_rsn().
cmp_dirs(Dir1, Dir2) ->
catch compare_dirs(Dir1, Dir2).
--spec diff_dirs(atom() | file:filename(), atom() | file:filename()) ->
- 'ok' | {'error', 'beam_lib', {'not_a_directory', term()} | info_rsn()}.
+-spec diff_dirs(Dir1, Dir2) -> 'ok' | {'error', 'beam_lib', Reason} when
+ Dir1 :: atom() | file:filename(),
+ Dir2 :: atom() | file:filename(),
+ Reason :: {'not_a_directory', term()} | info_rsn().
diff_dirs(Dir1, Dir2) ->
catch diff_directories(Dir1, Dir2).
--spec strip(beam()) ->
- {'ok', {module(), beam()}} | {'error', 'beam_lib', info_rsn()}.
+-spec strip(Beam1) ->
+ {'ok', {module(), Beam2}} | {'error', 'beam_lib', info_rsn()} when
+ Beam1 :: beam(),
+ Beam2 :: beam().
strip(FileName) ->
try strip_file(FileName)
catch Error -> Error end.
--spec strip_files([beam()]) ->
- {'ok', [{module(), beam()}]} | {'error', 'beam_lib', info_rsn()}.
+-spec strip_files(Files) ->
+ {'ok', [{module(), Beam}]} | {'error', 'beam_lib', info_rsn()} when
+ Files :: [beam()],
+ Beam :: beam().
strip_files(Files) when is_list(Files) ->
try strip_fils(Files)
catch Error -> Error end.
--spec strip_release(atom() | file:filename()) ->
+-spec strip_release(Dir) ->
{'ok', [{module(), file:filename()}]}
- | {'error', 'beam_lib', {'not_a_directory', term()} | info_rsn()}.
+ | {'error', 'beam_lib', Reason} when
+ Dir :: atom() | file:filename(),
+ Reason :: {'not_a_directory', term()} | info_rsn().
strip_release(Root) ->
catch strip_rel(Root).
--spec version(beam()) ->
- {'ok', {module(), [term()]}} | {'error', 'beam_lib', chnk_rsn()}.
+-spec version(Beam) ->
+ {'ok', {module(), [Version :: term()]}} |
+ {'error', 'beam_lib', chnk_rsn()} when
+ Beam :: beam().
version(File) ->
case catch read_chunk_data(File, [attributes]) of
@@ -195,8 +218,10 @@ version(File) ->
Error
end.
--spec md5(beam()) ->
- {'ok', {module(), binary()}} | {'error', 'beam_lib', chnk_rsn()}.
+-spec md5(Beam) ->
+ {'ok', {module(), MD5}} | {'error', 'beam_lib', chnk_rsn()} when
+ Beam :: beam(),
+ MD5 :: binary().
md5(File) ->
case catch read_significant_chunks(File) of
@@ -207,7 +232,8 @@ md5(File) ->
Error
end.
--spec format_error(term()) -> [char() | string()].
+-spec format_error(Reason) -> io_lib:chars() when
+ Reason :: term().
format_error({error, Error}) ->
format_error(Error);
@@ -260,12 +286,15 @@ format_error(E) ->
| {'debug_info', mode(), module(), file:filename()}.
-type crypto_fun() :: fun((crypto_fun_arg()) -> term()).
--spec crypto_key_fun(crypto_fun()) -> 'ok' | {'error', term()}.
+-spec crypto_key_fun(CryptoKeyFun) -> 'ok' | {'error', Reason} when
+ CryptoKeyFun :: crypto_fun(),
+ Reason :: badfun | exists | term().
crypto_key_fun(F) ->
call_crypto_server({crypto_key_fun, F}).
--spec clear_crypto_key_fun() -> 'undefined' | {'ok', term()}.
+-spec clear_crypto_key_fun() -> 'undefined' | {'ok', Result} when
+ Result :: 'undefined' | term().
clear_crypto_key_fun() ->
call_crypto_server(clear_crypto_key_fun).
diff --git a/lib/stdlib/src/binary.erl b/lib/stdlib/src/binary.erl
index f6489788b2..cb1e12ae46 100644
--- a/lib/stdlib/src/binary.erl
+++ b/lib/stdlib/src/binary.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010. All Rights Reserved.
+%% 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
@@ -38,11 +38,28 @@
%% Implemented in this module:
-export([split/2,split/3,replace/3,replace/4]).
+-opaque cp() :: tuple().
+-type part() :: {Start :: non_neg_integer(), Length :: integer()}.
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% split
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+-spec split(Subject, Pattern) -> Parts when
+ Subject :: binary(),
+ Pattern :: binary() | [binary()] | cp(),
+ Parts :: [binary()].
+
split(H,N) ->
split(H,N,[]).
+
+-spec split(Subject, Pattern, Options) -> Parts when
+ Subject :: binary(),
+ Pattern :: binary() | [binary()] | cp(),
+ Options :: [Option],
+ Option :: {scope, part()} | trim | global,
+ Parts :: [binary()].
+
split(Haystack,Needles,Options) ->
try
{Part,Global,Trim} = get_opts_split(Options,{no,false,false}),
@@ -89,8 +106,26 @@ do_split(H,[{A,B}|T],N,Trim) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% replace
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+-spec replace(Subject, Pattern, Replacement) -> Result when
+ Subject :: binary(),
+ Pattern :: binary() | [ binary() ] | cp(),
+ Replacement :: binary(),
+ Result :: binary().
+
replace(H,N,R) ->
replace(H,N,R,[]).
+
+-spec replace(Subject, Pattern, Replacement, Options) -> Result when
+ Subject :: binary(),
+ Pattern :: binary() | [ binary() ] | cp(),
+ Replacement :: binary(),
+ Options :: [Option],
+ Option :: global | {scope, part()} | {insert_replaced, InsPos},
+ InsPos :: OnePos | [ OnePos ],
+ OnePos :: non_neg_integer(),
+ Result :: binary().
+
replace(Haystack,Needles,Replacement,Options) ->
try
true = is_binary(Replacement), % Make badarg instead of function clause
diff --git a/lib/stdlib/src/c.erl b/lib/stdlib/src/c.erl
index 235ea939a8..febfdd6285 100644
--- a/lib/stdlib/src/c.erl
+++ b/lib/stdlib/src/c.erl
@@ -71,11 +71,16 @@ help() ->
%% c(FileName)
%% Compile a file/module.
--spec c(file:name()) -> {'ok', module()} | 'error'.
+-spec c(File) -> {'ok', Module} | 'error' when
+ File :: file:name(),
+ Module :: module().
c(File) -> c(File, []).
--spec c(file:name(), [compile:option()]) -> {'ok', module()} | 'error'.
+-spec c(File, Options) -> {'ok', Module} | 'error' when
+ File :: file:name(),
+ Options :: [compile:option()],
+ Module :: module().
c(File, Opts0) when is_list(Opts0) ->
Opts = [report_errors,report_warnings|Opts0],
@@ -140,7 +145,8 @@ check_load(_, Mod) -> {ok, Mod}.
%% with constant c2 defined, c1=v1 (v1 must be a term!), include dir
%% IDir, outdir ODir.
--spec lc([erl_compile:cmd_line_arg()]) -> 'ok' | 'error'.
+-spec lc(Files) -> 'ok' | 'error' when
+ Files :: [File :: erl_compile:cmd_line_arg()].
lc(Args) ->
case catch split(Args, [], []) of
@@ -205,12 +211,17 @@ make_term(Str) ->
throw(error)
end.
--spec nc(file:name()) -> {'ok', module()} | 'error'.
+-spec nc(File) -> {'ok', Module} | 'error' when
+ File :: file:name(),
+ Module :: module().
nc(File) -> nc(File, []).
--spec nc(file:name(), [compile:option()] | compile:option()) ->
- {'ok', module} | 'error'.
+-spec nc(File, Options) -> {'ok', Module} | 'error' when
+ File :: file:name(),
+ Options :: [Option] | Option,
+ Option:: compile:option(),
+ Module :: module().
nc(File, Opts0) when is_list(Opts0) ->
Opts = Opts0 ++ [report_errors, report_warnings],
@@ -234,14 +245,17 @@ nc(File, Opt) when is_atom(Opt) ->
%% l(Mod)
%% Reload module Mod from file of same name
--spec l(module()) -> code:load_ret().
+-spec l(Module) -> code:load_ret() when
+ Module :: module().
l(Mod) ->
code:purge(Mod),
code:load_file(Mod).
%% Network version of l/1
-%%-spec nl(module()) ->
+-spec nl(Module) -> abcast | error when
+ Module :: module().
+
nl(Mod) ->
case code:get_object_code(Mod) of
{_Module, Bin, Fname} ->
@@ -396,15 +410,20 @@ fetch(Key, Info) ->
false -> 0
end.
--spec pid(non_neg_integer(), non_neg_integer(), non_neg_integer()) -> pid().
+-spec pid(X, Y, Z) -> pid() when
+ X :: non_neg_integer(),
+ Y :: non_neg_integer(),
+ Z :: non_neg_integer().
pid(X, Y, Z) ->
list_to_pid("<" ++ integer_to_list(X) ++ "." ++
integer_to_list(Y) ++ "." ++
integer_to_list(Z) ++ ">").
--spec i(non_neg_integer(), non_neg_integer(), non_neg_integer()) ->
- [{atom(), term()}].
+-spec i(X, Y, Z) -> [{atom(), term()}] when
+ X :: non_neg_integer(),
+ Y :: non_neg_integer(),
+ Z :: non_neg_integer().
i(X, Y, Z) -> pinfo(pid(X, Y, Z)).
@@ -413,7 +432,8 @@ i(X, Y, Z) -> pinfo(pid(X, Y, Z)).
q() ->
init:stop().
--spec bt(pid()) -> 'ok' | 'undefined'.
+-spec bt(Pid) -> 'ok' | 'undefined' when
+ Pid :: pid().
bt(Pid) ->
case catch erlang:process_display(Pid, backtrace) of
@@ -476,7 +496,8 @@ bi(I) ->
%%
%% Short and nice form of module info
%%
--spec m(module()) -> 'ok'.
+-spec m(Module) -> 'ok' when
+ Module :: module().
m(M) ->
L = M:module_info(),
@@ -664,7 +685,8 @@ pwd() ->
ok = io:format("Cannot determine current directory\n")
end.
--spec cd(file:name()) -> 'ok'.
+-spec cd(Dir) -> 'ok' when
+ Dir :: file:name().
cd(Dir) ->
file:set_cwd(Dir),
@@ -679,7 +701,8 @@ cd(Dir) ->
ls() ->
ls(".").
--spec ls(file:name()) -> 'ok'.
+-spec ls(Dir) -> 'ok' when
+ Dir :: file:name().
ls(Dir) ->
case file:list_dir(Dir) of
@@ -729,12 +752,19 @@ w(X) ->
%% memory/[0,1]
%%
--spec memory() -> [{atom(), non_neg_integer()}].
+-spec memory() -> [{Type, Size}] when
+ Type :: atom(),
+ Size :: non_neg_integer().
memory() -> erlang:memory().
--spec memory(atom()) -> non_neg_integer()
- ; ([atom()]) -> [{atom(), non_neg_integer()}].
+-spec memory(Type) -> Size when
+ Type :: atom(),
+ Size :: non_neg_integer()
+ ; (Types) -> [{Type, Size}] when
+ Types :: [Type],
+ Type :: atom(),
+ Size :: non_neg_integer().
memory(TypeSpec) -> erlang:memory(TypeSpec).
diff --git a/lib/stdlib/src/calendar.erl b/lib/stdlib/src/calendar.erl
index 33725d999c..8d1071209e 100644
--- a/lib/stdlib/src/calendar.erl
+++ b/lib/stdlib/src/calendar.erl
@@ -63,6 +63,8 @@
%% Types
%%----------------------------------------------------------------------
+-export_type([t_now/0]).
+
-type year() :: non_neg_integer().
-type year1970() :: 1970..10000. % should probably be 1970..
-type month() :: 1..12.
@@ -74,7 +76,9 @@
-type ldom() :: 28 | 29 | 30 | 31. % last day of month
-type weeknum() :: 1..53.
--type t_now() :: {non_neg_integer(),non_neg_integer(),non_neg_integer()}.
+-type t_now() :: {MegaSecs :: non_neg_integer(),
+ Secs :: non_neg_integer(),
+ MicroSecs :: non_neg_integer()}.
-type t_date() :: {year(),month(),day()}.
-type t_time() :: {hour(),minute(),second()}.
@@ -106,7 +110,11 @@
%% January 1st.
%%
%% df/2 catches the case Year<0
--spec date_to_gregorian_days(year(),month(),day()) -> non_neg_integer().
+-spec date_to_gregorian_days(Year, Month, Day) -> Days when
+ Year :: year(),
+ Month :: month(),
+ Day :: day(),
+ Days :: non_neg_integer().
date_to_gregorian_days(Year, Month, Day) when is_integer(Day), Day > 0 ->
Last = last_day_of_the_month(Year, Month),
if
@@ -114,7 +122,9 @@ date_to_gregorian_days(Year, Month, Day) when is_integer(Day), Day > 0 ->
dy(Year) + dm(Month) + df(Year, Month) + Day - 1
end.
--spec date_to_gregorian_days(t_date()) -> non_neg_integer().
+-spec date_to_gregorian_days(Date) -> Days when
+ Date :: t_date(),
+ Days :: non_neg_integer().
date_to_gregorian_days({Year, Month, Day}) ->
date_to_gregorian_days(Year, Month, Day).
@@ -124,7 +134,9 @@ date_to_gregorian_days({Year, Month, Day}) ->
%% Computes the total number of seconds starting from year 0,
%% January 1st.
%%
--spec datetime_to_gregorian_seconds(t_datetime()) -> non_neg_integer().
+-spec datetime_to_gregorian_seconds(DateTime) -> Seconds when
+ DateTime :: t_datetime(),
+ Seconds :: non_neg_integer().
datetime_to_gregorian_seconds({Date, Time}) ->
?SECONDS_PER_DAY*date_to_gregorian_days(Date) +
time_to_seconds(Time).
@@ -135,18 +147,23 @@ datetime_to_gregorian_seconds({Date, Time}) ->
%%
%% Returns: 1 | .. | 7. Monday = 1, Tuesday = 2, ..., Sunday = 7.
%%
--spec day_of_the_week(year(), month(), day()) -> daynum().
+-spec day_of_the_week(Year, Month, Day) -> daynum() when
+ Year :: year(),
+ Month :: month(),
+ Day :: day().
day_of_the_week(Year, Month, Day) ->
(date_to_gregorian_days(Year, Month, Day) + 5) rem 7 + 1.
--spec day_of_the_week(t_date()) -> daynum().
+-spec day_of_the_week(Date) -> daynum() when
+ Date:: t_date().
day_of_the_week({Year, Month, Day}) ->
day_of_the_week(Year, Month, Day).
%% gregorian_days_to_date(Days) = {Year, Month, Day}
%%
--spec gregorian_days_to_date(non_neg_integer()) -> t_date().
+-spec gregorian_days_to_date(Days) -> t_date() when
+ Days :: non_neg_integer().
gregorian_days_to_date(Days) ->
{Year, DayOfYear} = day_to_year(Days),
{Month, DayOfMonth} = year_day_to_date(Year, DayOfYear),
@@ -155,7 +172,8 @@ gregorian_days_to_date(Days) ->
%% gregorian_seconds_to_datetime(Secs)
%%
--spec gregorian_seconds_to_datetime(non_neg_integer()) -> t_datetime().
+-spec gregorian_seconds_to_datetime(Seconds) -> t_datetime() when
+ Seconds :: non_neg_integer().
gregorian_seconds_to_datetime(Secs) when Secs >= 0 ->
Days = Secs div ?SECONDS_PER_DAY,
Rest = Secs rem ?SECONDS_PER_DAY,
@@ -164,7 +182,8 @@ gregorian_seconds_to_datetime(Secs) when Secs >= 0 ->
%% is_leap_year(Year) = true | false
%%
--spec is_leap_year(year()) -> boolean().
+-spec is_leap_year(Year) -> boolean() when
+ Year :: year().
is_leap_year(Y) when is_integer(Y), Y >= 0 ->
is_leap_year1(Y).
@@ -188,7 +207,8 @@ iso_week_number() ->
%%
%% Calculates the iso week number for the given date.
%%
--spec iso_week_number(t_date()) -> t_yearweeknum().
+-spec iso_week_number(Date) -> t_yearweeknum() when
+ Date :: t_date().
iso_week_number({Year, Month, Day}) ->
D = date_to_gregorian_days({Year, Month, Day}),
W01_1_Year = gregorian_days_of_iso_w01_1(Year),
@@ -216,7 +236,10 @@ iso_week_number({Year, Month, Day}) ->
%%
%% Returns the number of days in a month.
%%
--spec last_day_of_the_month(year(), month()) -> ldom().
+-spec last_day_of_the_month(Year, Month) -> LastDay when
+ Year :: year(),
+ Month :: month(),
+ LastDay :: ldom().
last_day_of_the_month(Y, M) when is_integer(Y), Y >= 0 ->
last_day_of_the_month1(Y, M).
@@ -244,7 +267,9 @@ local_time() ->
%% local_time_to_universal_time(DateTime)
%%
--spec local_time_to_universal_time(t_datetime1970()) -> t_datetime1970().
+-spec local_time_to_universal_time(DateTime1) -> DateTime2 when
+ DateTime1 :: t_datetime1970(),
+ DateTime2 :: t_datetime1970().
local_time_to_universal_time(DateTime) ->
erlang:localtime_to_universaltime(DateTime).
@@ -254,7 +279,9 @@ local_time_to_universal_time(DateTime) ->
local_time_to_universal_time(DateTime, IsDst) ->
erlang:localtime_to_universaltime(DateTime, IsDst).
--spec local_time_to_universal_time_dst(t_datetime1970()) -> [t_datetime1970()].
+-spec local_time_to_universal_time_dst(DateTime1) -> [DateTime] when
+ DateTime1 :: t_datetime1970(),
+ DateTime :: t_datetime1970().
local_time_to_universal_time_dst(DateTime) ->
UtDst = erlang:localtime_to_universaltime(DateTime, true),
Ut = erlang:localtime_to_universaltime(DateTime, false),
@@ -282,12 +309,14 @@ local_time_to_universal_time_dst(DateTime) ->
%% = MilliSec = integer()
%% Returns: {date(), time()}, date() = {Y, M, D}, time() = {H, M, S}.
%%
--spec now_to_datetime(t_now()) -> t_datetime1970().
+-spec now_to_datetime(Now) -> t_datetime1970() when
+ Now :: t_now().
now_to_datetime({MSec, Sec, _uSec}) ->
Sec0 = MSec*1000000 + Sec + ?DAYS_FROM_0_TO_1970*?SECONDS_PER_DAY,
gregorian_seconds_to_datetime(Sec0).
--spec now_to_universal_time(t_now()) -> t_datetime1970().
+-spec now_to_universal_time(Now) -> t_datetime1970() when
+ Now :: t_now().
now_to_universal_time(Now) ->
now_to_datetime(Now).
@@ -296,7 +325,8 @@ now_to_universal_time(Now) ->
%%
%% Args: Now = now()
%%
--spec now_to_local_time(t_now()) -> t_datetime1970().
+-spec now_to_local_time(Now) -> t_datetime1970() when
+ Now :: t_now().
now_to_local_time({MSec, Sec, _uSec}) ->
erlang:universaltime_to_localtime(
now_to_universal_time({MSec, Sec, _uSec})).
@@ -305,7 +335,10 @@ now_to_local_time({MSec, Sec, _uSec}) ->
%% seconds_to_daystime(Secs) = {Days, {Hour, Minute, Second}}
%%
--spec seconds_to_daystime(integer()) -> {integer(), t_time()}.
+-spec seconds_to_daystime(Seconds) -> {Days, Time} when
+ Seconds :: integer(),
+ Days :: integer(),
+ Time :: t_time().
seconds_to_daystime(Secs) ->
Days0 = Secs div ?SECONDS_PER_DAY,
Secs0 = Secs rem ?SECONDS_PER_DAY,
@@ -323,7 +356,8 @@ seconds_to_daystime(Secs) ->
%% Wraps.
%%
-type secs_per_day() :: 0..?SECONDS_PER_DAY.
--spec seconds_to_time(secs_per_day()) -> t_time().
+-spec seconds_to_time(Seconds) -> t_time() when
+ Seconds :: secs_per_day().
seconds_to_time(Secs) when Secs >= 0, Secs < ?SECONDS_PER_DAY ->
Secs0 = Secs rem ?SECONDS_PER_DAY,
Hour = Secs0 div ?SECONDS_PER_HOUR,
@@ -340,8 +374,11 @@ seconds_to_time(Secs) when Secs >= 0, Secs < ?SECONDS_PER_DAY ->
%% Date = {Year, Month, Day}, Time = {Hour, Minute, Sec},
%% Year = Month = Day = Hour = Minute = Sec = integer()
%%
--type timediff() :: {integer(), t_time()}.
--spec time_difference(t_datetime(), t_datetime()) -> timediff().
+-spec time_difference(T1, T2) -> {Days, Time} when
+ T1 :: t_datetime(),
+ T2 :: t_datetime(),
+ Days :: integer(),
+ Time :: t_time().
time_difference({{Y1, Mo1, D1}, {H1, Mi1, S1}},
{{Y2, Mo2, D2}, {H2, Mi2, S2}}) ->
Secs = datetime_to_gregorian_seconds({{Y2, Mo2, D2}, {H2, Mi2, S2}}) -
@@ -352,7 +389,8 @@ time_difference({{Y1, Mo1, D1}, {H1, Mi1, S1}},
%%
%% time_to_seconds(Time)
%%
--spec time_to_seconds(t_time()) -> secs_per_day().
+-spec time_to_seconds(Time) -> secs_per_day() when
+ Time :: t_time().
time_to_seconds({H, M, S}) when is_integer(H), is_integer(M), is_integer(S) ->
H * ?SECONDS_PER_HOUR +
M * ?SECONDS_PER_MINUTE + S.
@@ -368,7 +406,8 @@ universal_time() ->
%% universal_time_to_local_time(DateTime)
%%
--spec universal_time_to_local_time(t_datetime()) -> t_datetime().
+-spec universal_time_to_local_time(DateTime) -> t_datetime() when
+ DateTime :: t_datetime1970().
universal_time_to_local_time(DateTime) ->
erlang:universaltime_to_localtime(DateTime).
@@ -376,7 +415,10 @@ universal_time_to_local_time(DateTime) ->
%% valid_date(Year, Month, Day) = true | false
%% valid_date({Year, Month, Day}) = true | false
%%
--spec valid_date(integer(), integer(), integer()) -> boolean().
+-spec valid_date(Year, Month, Day) -> boolean() when
+ Year :: integer(),
+ Month :: integer(),
+ Day :: integer().
valid_date(Y, M, D) when is_integer(Y), is_integer(M), is_integer(D) ->
valid_date1(Y, M, D).
@@ -386,7 +428,8 @@ valid_date1(Y, M, D) when Y >= 0, M > 0, M < 13, D > 0 ->
valid_date1(_, _, _) ->
false.
--spec valid_date({integer(),integer(),integer()}) -> boolean().
+-spec valid_date(Date) -> boolean() when
+ Date :: t_date().
valid_date({Y, M, D}) ->
valid_date(Y, M, D).
diff --git a/lib/stdlib/src/dets.erl b/lib/stdlib/src/dets.erl
index 6c91f1efb7..671b5a9dd4 100644
--- a/lib/stdlib/src/dets.erl
+++ b/lib/stdlib/src/dets.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -97,10 +97,6 @@
-include("dets.hrl").
--type object() :: tuple().
--type pattern() :: atom() | tuple().
--type tab_name() :: atom() | reference().
-
%%% This is the implementation of the mnesia file storage. Each (non
%%% ram-copy) table is maintained in a corresponding .DAT file. The
%%% dat file is organized as a segmented linear hashlist. The head of
@@ -179,6 +175,21 @@
%%-define(PROFILE(C), C).
-define(PROFILE(C), void).
+-type access() :: 'read' | 'read_write'.
+-type auto_save() :: 'infinity' | non_neg_integer().
+-opaque bindings_cont() :: #dets_cont{}.
+-opaque cont() :: #dets_cont{}.
+-type keypos() :: pos_integer().
+-type match_spec() :: ets:match_spec().
+-type object() :: tuple().
+-type no_slots() :: non_neg_integer() | 'default'.
+-opaque object_cont() :: #dets_cont{}.
+-type pattern() :: atom() | tuple().
+-opaque select_cont() :: #dets_cont{}.
+-type tab_name() :: term().
+-type type() :: 'bag' | 'duplicate_bag' | 'set'.
+-type version() :: 8 | 9 | 'default'.
+
%%% Some further debug code was added in R12B-1 (stdlib-1.15.1):
%%% - there is a new open_file() option 'debug';
%%% - there is a new OS environment variable 'DETS_DEBUG';
@@ -203,9 +214,13 @@ add_user(Pid, Tab, Args) ->
all() ->
dets_server:all().
--type cont() :: #dets_cont{}.
--spec bchunk(tab_name(), 'start' | cont()) ->
- {cont(), binary() | tuple()} | '$end_of_table' | {'error', term()}.
+-spec bchunk(Name, Continuation) ->
+ {Continuation2, Data} | '$end_of_table' | {'error', Reason} when
+ Name :: tab_name(),
+ Continuation :: 'start' | cont(),
+ Continuation2 :: cont(),
+ Data :: binary() | tuple(),
+ Reason :: term().
bchunk(Tab, start) ->
badarg(treq(Tab, {bchunk_init, Tab}), [Tab, start]);
@@ -214,7 +229,9 @@ bchunk(Tab, #dets_cont{what = bchunk, tab = Tab} = State) ->
bchunk(Tab, Term) ->
erlang:error(badarg, [Tab, Term]).
--spec close(tab_name()) -> 'ok' | {'error', term()}.
+-spec close(Name) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ Reason :: term().
close(Tab) ->
case dets_server:close(Tab) of
@@ -224,12 +241,17 @@ close(Tab) ->
Reply
end.
--spec delete(tab_name(), term()) -> 'ok' | {'error', term()}.
+-spec delete(Name, Key) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ Key :: term(),
+ Reason :: term().
delete(Tab, Key) ->
badarg(treq(Tab, {delete_key, [Key]}), [Tab, Key]).
--spec delete_all_objects(tab_name()) -> 'ok' | {'error', term()}.
+-spec delete_all_objects(Name) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ Reason :: term().
delete_all_objects(Tab) ->
case treq(Tab, delete_all_objects) of
@@ -241,7 +263,10 @@ delete_all_objects(Tab) ->
Reply
end.
--spec delete_object(tab_name(), object()) -> 'ok' | {'error', term()}.
+-spec delete_object(Name, Object) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ Object :: object(),
+ Reason :: term().
delete_object(Tab, O) ->
badarg(treq(Tab, {delete_object, [O]}), [Tab, O]).
@@ -264,23 +289,42 @@ fsck(Fname, Version) ->
end
end.
--spec first(tab_name()) -> term() | '$end_of_table'.
+-spec first(Name) -> Key | '$end_of_table' when
+ Name :: tab_name(),
+ Key :: term().
first(Tab) ->
badarg_exit(treq(Tab, first), [Tab]).
--spec foldr(fun((object(), Acc) -> Acc), Acc, tab_name()) -> Acc | {'error', term()}.
+-spec foldr(Function, Acc0, Name) -> Acc | {'error', Reason} when
+ Name :: tab_name(),
+ Function :: fun((Object :: object(), AccIn) -> AccOut),
+ Acc0 :: term(),
+ Acc :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ Reason :: term().
foldr(Fun, Acc, Tab) ->
foldl(Fun, Acc, Tab).
--spec foldl(fun((object(), Acc) -> Acc), Acc, tab_name()) -> Acc | {'error', term()}.
+-spec foldl(Function, Acc0, Name) -> Acc | {'error', Reason} when
+ Name :: tab_name(),
+ Function :: fun((Object :: object(), AccIn) -> AccOut),
+ Acc0 :: term(),
+ Acc :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ Reason :: term().
foldl(Fun, Acc, Tab) ->
Ref = make_ref(),
do_traverse(Fun, Acc, Tab, Ref).
--spec from_ets(tab_name(), ets:tab()) -> 'ok' | {'error', term()}.
+-spec from_ets(Name, EtsTab) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ EtsTab :: ets:tab(),
+ Reason :: term().
from_ets(DTab, ETab) ->
ets:safe_fixtable(ETab, true),
@@ -304,6 +348,15 @@ from_ets_fun(LC, ETab) ->
{L, from_ets_fun(ets:select(C), ETab)}
end.
+-spec info(Name) -> InfoList | 'undefined' when
+ Name :: tab_name(),
+ InfoList :: [InfoTuple],
+ InfoTuple :: {'file_size', non_neg_integer()}
+ | {'filename', file:name()}
+ | {'keypos', keypos()}
+ | {'size', non_neg_integer()}
+ | {'type', type()}.
+
info(Tab) ->
case catch dets_server:get_pid(Tab) of
{'EXIT', _Reason} ->
@@ -312,6 +365,14 @@ info(Tab) ->
undefined(req(Pid, info))
end.
+-spec info(Name, Item) -> Value | 'undefined' when
+ Name :: tab_name(),
+ Item :: 'access' | 'auto_save' | 'bchunk_format'
+ | 'hash' | 'file_size' | 'filename' | 'keypos' | 'memory'
+ | 'no_keys' | 'no_objects' | 'no_slots' | 'owner' | 'ram_file'
+ | 'safe_fixed' | 'size' | 'type' | 'version',
+ Value :: term().
+
info(Tab, owner) ->
case catch dets_server:get_pid(Tab) of
Pid when is_pid(Pid) ->
@@ -334,9 +395,26 @@ info(Tab, Tag) ->
undefined(req(Pid, {info, Tag}))
end.
+-spec init_table(Name, InitFun) -> ok | {'error', Reason} when
+ Name :: tab_name(),
+ InitFun :: fun((Arg) -> Res),
+ Arg :: read | close,
+ Res :: end_of_input | {[object()], InitFun} | {Data, InitFun} | term(),
+ Reason :: term(),
+ Data :: binary() | tuple().
+
init_table(Tab, InitFun) ->
init_table(Tab, InitFun, []).
+-spec init_table(Name, InitFun, Options) -> ok | {'error', Reason} when
+ Name :: tab_name(),
+ InitFun :: fun((Arg) -> Res),
+ Arg :: read | close,
+ Res :: end_of_input | {[object()], InitFun} | {Data, InitFun} | term(),
+ Options :: [{min_no_slots,no_slots()} | {format,term | bchunk}],
+ Reason :: term(),
+ Data :: binary() | tuple().
+
init_table(Tab, InitFun, Options) when is_function(InitFun) ->
case options(Options, [format, min_no_slots]) of
{badarg,_} ->
@@ -350,11 +428,20 @@ init_table(Tab, InitFun, Options) when is_function(InitFun) ->
init_table(Tab, InitFun, Options) ->
erlang:error(badarg, [Tab, InitFun, Options]).
+-spec insert(Name, Objects) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ Objects :: object() | [object()],
+ Reason :: term().
+
insert(Tab, Objs) when is_list(Objs) ->
badarg(treq(Tab, {insert, Objs}), [Tab, Objs]);
insert(Tab, Obj) ->
badarg(treq(Tab, {insert, [Obj]}), [Tab, Obj]).
+-spec insert_new(Name, Objects) -> boolean() when
+ Name :: tab_name(),
+ Objects :: object() | [object()].
+
insert_new(Tab, Objs) when is_list(Objs) ->
badarg(treq(Tab, {insert_new, Objs}), [Tab, Objs]);
insert_new(Tab, Obj) ->
@@ -366,9 +453,17 @@ internal_close(Pid) ->
internal_open(Pid, Ref, Args) ->
req(Pid, {internal_open, Ref, Args}).
+-spec is_compatible_bchunk_format(Name, BchunkFormat) -> boolean() when
+ Name :: tab_name(),
+ BchunkFormat :: binary().
+
is_compatible_bchunk_format(Tab, Term) ->
badarg(treq(Tab, {is_compatible_bchunk_format, Term}), [Tab, Term]).
+-spec is_dets_file(Filename) -> boolean() | {'error', Reason} when
+ Filename :: file:name(),
+ Reason :: term().
+
is_dets_file(FileName) ->
case catch read_file_header(FileName, read, false) of
{ok, Fd, FH} ->
@@ -382,6 +477,12 @@ is_dets_file(FileName) ->
Other
end.
+-spec lookup(Name, Key) -> Objects | {'error', Reason} when
+ Name :: tab_name(),
+ Key :: term(),
+ Objects :: [object()],
+ Reason :: term().
+
lookup(Tab, Key) ->
badarg(treq(Tab, {lookup_keys, [Key]}), [Tab, Key]).
@@ -394,19 +495,43 @@ lookup_keys(Tab, Keys) ->
erlang:error(badarg, [Tab, Keys])
end.
+-spec match(Name, Pattern) -> [Match] | {'error', Reason} when
+ Name :: tab_name(),
+ Pattern :: pattern(),
+ Match :: [term()],
+ Reason :: term().
+
match(Tab, Pat) ->
badarg(safe_match(Tab, Pat, bindings), [Tab, Pat]).
+-spec match(Name, Pattern, N) ->
+ {[Match], Continuation} | '$end_of_table' | {'error', Reason} when
+ Name :: tab_name(),
+ Pattern :: pattern(),
+ N :: 'default' | non_neg_integer(),
+ Continuation :: bindings_cont(),
+ Match :: [term()],
+ Reason :: term().
+
match(Tab, Pat, N) ->
badarg(init_chunk_match(Tab, Pat, bindings, N), [Tab, Pat, N]).
+-spec match(Continuation) ->
+ {[Match], Continuation2} | '$end_of_table' | {'error', Reason} when
+ Continuation :: bindings_cont(),
+ Continuation2 :: bindings_cont(),
+ Match :: [term()],
+ Reason :: term().
+
match(State) when State#dets_cont.what =:= bindings ->
badarg(chunk_match(State), [State]);
match(Term) ->
erlang:error(badarg, [Term]).
--spec match_delete(tab_name(), pattern()) ->
- non_neg_integer() | 'ok' | {'error', term()}.
+-spec match_delete(Name, Pattern) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ Pattern :: pattern(),
+ Reason :: term().
match_delete(Tab, Pat) ->
badarg(match_delete(Tab, Pat, delete), [Tab, Pat]).
@@ -434,23 +559,60 @@ do_match_delete(Tab, _Proc, Error, _What, _N) ->
safe_fixtable(Tab, false),
Error.
+-spec match_object(Name, Pattern) -> Objects | {'error', Reason} when
+ Name :: tab_name(),
+ Pattern :: pattern(),
+ Objects :: [object()],
+ Reason :: term().
+
match_object(Tab, Pat) ->
badarg(safe_match(Tab, Pat, object), [Tab, Pat]).
+-spec match_object(Name, Pattern, N) ->
+ {Objects, Continuation} | '$end_of_table' | {'error', Reason} when
+ Name :: tab_name(),
+ Pattern :: pattern(),
+ N :: 'default' | non_neg_integer(),
+ Continuation :: object_cont(),
+ Objects :: [object()],
+ Reason :: term().
+
match_object(Tab, Pat, N) ->
badarg(init_chunk_match(Tab, Pat, object, N), [Tab, Pat, N]).
+-spec match_object(Continuation) ->
+ {Objects, Continuation2} | '$end_of_table' | {'error', Reason} when
+ Continuation :: object_cont(),
+ Continuation2 :: object_cont(),
+ Objects :: [object()],
+ Reason :: term().
+
match_object(State) when State#dets_cont.what =:= object ->
badarg(chunk_match(State), [State]);
match_object(Term) ->
erlang:error(badarg, [Term]).
+-spec member(Name, Key) -> boolean() | {'error', Reason} when
+ Name :: tab_name(),
+ Key :: term(),
+ Reason :: term().
+
member(Tab, Key) ->
badarg(treq(Tab, {member, Key}), [Tab, Key]).
+-spec next(Name, Key1) -> Key2 | '$end_of_table' when
+ Name :: tab_name(),
+ Key1 :: term(),
+ Key2 :: term().
+
next(Tab, Key) ->
badarg_exit(treq(Tab, {next, Key}), [Tab, Key]).
+-spec open_file(Filename) -> {'ok', Reference} | {'error', Reason} when
+ Filename :: file:name(),
+ Reference :: reference(),
+ Reason :: term().
+
%% Assuming that a file already exists, open it with the
%% parameters as already specified in the file itself.
%% Return a ref leading to the file.
@@ -462,6 +624,22 @@ open_file(File) ->
einval(Reply, [File])
end.
+-spec open_file(Name, Args) -> {'ok', Name} | {'error', Reason} when
+ Name :: tab_name(),
+ Args :: [OpenArg],
+ OpenArg :: {'access', access()}
+ | {'auto_save', auto_save()}
+ | {'estimated_no_objects', non_neg_integer()}
+ | {'file', file:name()}
+ | {'max_no_slots', no_slots()}
+ | {'min_no_slots', no_slots()}
+ | {'keypos', keypos()}
+ | {'ram_file', boolean()}
+ | {'repair', boolean() | 'force'}
+ | {'type', type()}
+ | {'version', version()},
+ Reason :: term().
+
open_file(Tab, Args) when is_list(Args) ->
case catch defaults(Tab, Args) of
OpenArgs when is_record(OpenArgs, open_args) ->
@@ -477,12 +655,21 @@ open_file(Tab, Args) when is_list(Args) ->
open_file(Tab, Arg) ->
open_file(Tab, [Arg]).
+-spec pid2name(Pid) -> {'ok', Name} | 'undefined' when
+ Pid :: pid(),
+ Name :: tab_name().
+
pid2name(Pid) ->
dets_server:pid2name(Pid).
remove_user(Pid, From) ->
req(Pid, {close, From}).
+-spec repair_continuation(Continuation, MatchSpec) -> Continuation2 when
+ Continuation :: select_cont(),
+ Continuation2 :: select_cont(),
+ MatchSpec :: match_spec().
+
repair_continuation(#dets_cont{match_program = B}=Cont, MS)
when is_binary(B) ->
case ets:is_compiled_ms(B) of
@@ -496,25 +683,63 @@ repair_continuation(#dets_cont{}=Cont, _MS) ->
repair_continuation(T, MS) ->
erlang:error(badarg, [T, MS]).
+-spec safe_fixtable(Name, Fix) -> 'ok' when
+ Name :: tab_name(),
+ Fix :: boolean().
+
safe_fixtable(Tab, Bool) when Bool; not Bool ->
badarg(treq(Tab, {safe_fixtable, Bool}), [Tab, Bool]);
safe_fixtable(Tab, Term) ->
erlang:error(badarg, [Tab, Term]).
+-spec select(Name, MatchSpec) -> Selection | {'error', Reason} when
+ Name :: tab_name(),
+ MatchSpec :: match_spec(),
+ Selection :: [term()],
+ Reason :: term().
+
select(Tab, Pat) ->
badarg(safe_match(Tab, Pat, select), [Tab, Pat]).
+-spec select(Name, MatchSpec, N) ->
+ {Selection, Continuation} | '$end_of_table' | {'error', Reason} when
+ Name :: tab_name(),
+ MatchSpec :: match_spec(),
+ N :: 'default' | non_neg_integer(),
+ Continuation :: select_cont(),
+ Selection :: [term()],
+ Reason :: term().
+
select(Tab, Pat, N) ->
badarg(init_chunk_match(Tab, Pat, select, N), [Tab, Pat, N]).
+-spec select(Continuation) ->
+ {Selection, Continuation2} | '$end_of_table' | {'error', Reason} when
+ Continuation :: select_cont(),
+ Continuation2 :: select_cont(),
+ Selection :: [term()],
+ Reason :: term().
+
select(State) when State#dets_cont.what =:= select ->
badarg(chunk_match(State), [State]);
select(Term) ->
erlang:error(badarg, [Term]).
+-spec select_delete(Name, MatchSpec) -> N | {'error', Reason} when
+ Name :: tab_name(),
+ MatchSpec :: match_spec(),
+ N :: non_neg_integer(),
+ Reason :: term().
+
select_delete(Tab, Pat) ->
badarg(match_delete(Tab, Pat, select), [Tab, Pat]).
+-spec slot(Name, I) -> '$end_of_table' | Objects | {'error', Reason} when
+ Name :: tab_name(),
+ I :: non_neg_integer(),
+ Objects :: [object()],
+ Reason :: term().
+
slot(Tab, Slot) when is_integer(Slot), Slot >= 0 ->
badarg(treq(Tab, {slot, Slot}), [Tab, Slot]);
slot(Tab, Term) ->
@@ -529,12 +754,29 @@ stop() ->
istart_link(Server) ->
{ok, proc_lib:spawn_link(dets, init, [self(), Server])}.
+-spec sync(Name) -> 'ok' | {'error', Reason} when
+ Name :: tab_name(),
+ Reason :: term().
+
sync(Tab) ->
badarg(treq(Tab, sync), [Tab]).
+-spec table(Name) -> QueryHandle when
+ Name :: tab_name(),
+ QueryHandle :: qlc:query_handle().
+
table(Tab) ->
table(Tab, []).
+-spec table(Name, Options) -> QueryHandle when
+ Name :: tab_name(),
+ Options :: Option | [Option],
+ Option :: {'n_objects', Limit}
+ | {'traverse', TraverseMethod},
+ Limit :: 'default' | pos_integer(),
+ TraverseMethod :: 'first_next' | 'select' | {'select', match_spec()},
+ QueryHandle :: qlc:query_handle().
+
table(Tab, Opts) ->
case options(Opts, [traverse, n_objects]) of
{badarg,_} ->
@@ -612,6 +854,11 @@ table_info(_Tab, _) ->
%% End of table/2.
+-spec to_ets(Name, EtsTab) -> EtsTab | {'error', Reason} when
+ Name :: tab_name(),
+ EtsTab :: ets:tab(),
+ Reason :: term().
+
to_ets(DTab, ETab) ->
case ets:info(ETab, protection) of
undefined ->
@@ -621,6 +868,16 @@ to_ets(DTab, ETab) ->
foldl(Fun, ETab, DTab)
end.
+-spec traverse(Name, Fun) -> Return | {'error', Reason} when
+ Name :: tab_name(),
+ Fun :: fun((Object) -> FunReturn),
+ FunReturn :: 'continue' | {'continue', Val} | {'done', Value},
+ Val :: term(),
+ Value :: term(),
+ Object :: object(),
+ Return :: [term()],
+ Reason :: term().
+
traverse(Tab, Fun) ->
Ref = make_ref(),
TFun =
@@ -638,6 +895,14 @@ traverse(Tab, Fun) ->
end,
do_traverse(TFun, [], Tab, Ref).
+-spec update_counter(Name, Key, Increment) -> Result when
+ Name :: tab_name(),
+ Key :: term(),
+ Increment :: {Pos, Incr} | Incr,
+ Pos :: integer(),
+ Incr :: integer(),
+ Result :: integer().
+
update_counter(Tab, Key, C) ->
badarg(treq(Tab, {update_counter, Key, C}), [Tab, Key, C]).
diff --git a/lib/stdlib/src/dict.erl b/lib/stdlib/src/dict.erl
index 7e51141098..2e9eba4bfa 100644
--- a/lib/stdlib/src/dict.erl
+++ b/lib/stdlib/src/dict.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2000-2009. All Rights Reserved.
+%% 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
@@ -80,7 +80,9 @@ new() ->
Empty = mk_seg(?seg_size),
#dict{empty=Empty,segs={Empty}}.
--spec is_key(term(), dict()) -> boolean().
+-spec is_key(Key, Dict) -> boolean() when
+ Key :: term(),
+ Dict :: dict().
is_key(Key, D) ->
Slot = get_slot(D, Key),
@@ -91,21 +93,29 @@ find_key(K, [?kv(K,_Val)|_]) -> true;
find_key(K, [_|Bkt]) -> find_key(K, Bkt);
find_key(_, []) -> false.
--spec to_list(dict()) -> [{term(), term()}].
+-spec to_list(Dict) -> List when
+ Dict :: dict(),
+ List :: [{Key :: term(), Value :: term()}].
to_list(D) ->
fold(fun (Key, Val, List) -> [{Key,Val}|List] end, [], D).
--spec from_list([{term(), term()}]) -> dict().
+-spec from_list(List) -> Dict when
+ List :: [{Key :: term(), Value :: term()}],
+ Dict :: dict().
from_list(L) ->
lists:foldl(fun ({K,V}, D) -> store(K, V, D) end, new(), L).
--spec size(dict()) -> non_neg_integer().
+-spec size(Dict) -> non_neg_integer() when
+ Dict :: dict().
size(#dict{size=N}) when is_integer(N), N >= 0 -> N.
--spec fetch(term(), dict()) -> term().
+-spec fetch(Key, Dict) -> Value when
+ Key :: term(),
+ Dict :: dict(),
+ Value :: term().
fetch(Key, D) ->
Slot = get_slot(D, Key),
@@ -119,7 +129,10 @@ fetch_val(K, [?kv(K,Val)|_]) -> Val;
fetch_val(K, [_|Bkt]) -> fetch_val(K, Bkt);
fetch_val(_, []) -> throw(badarg).
--spec find(term(), dict()) -> {'ok', term()} | 'error'.
+-spec find(Key, Dict) -> {'ok', Value} | 'error' when
+ Key :: term(),
+ Dict :: dict(),
+ Value :: term().
find(Key, D) ->
Slot = get_slot(D, Key),
@@ -130,12 +143,17 @@ find_val(K, [?kv(K,Val)|_]) -> {ok,Val};
find_val(K, [_|Bkt]) -> find_val(K, Bkt);
find_val(_, []) -> error.
--spec fetch_keys(dict()) -> [term()].
+-spec fetch_keys(Dict) -> Keys when
+ Dict :: dict(),
+ Keys :: [term()].
fetch_keys(D) ->
fold(fun (Key, _Val, Keys) -> [Key|Keys] end, [], D).
--spec erase(term(), dict()) -> dict().
+-spec erase(Key, Dict1) -> Dict2 when
+ Key :: term(),
+ Dict1 :: dict(),
+ Dict2 :: dict().
%% Erase all elements with key Key.
erase(Key, D0) ->
@@ -150,7 +168,11 @@ erase_key(Key, [E|Bkt0]) ->
{[E|Bkt1],Dc};
erase_key(_, []) -> {[],0}.
--spec store(term(), term(), dict()) -> dict().
+-spec store(Key, Value, Dict1) -> Dict2 when
+ Key :: term(),
+ Value :: term(),
+ Dict1 :: dict(),
+ Dict2 :: dict().
store(Key, Val, D0) ->
Slot = get_slot(D0, Key),
@@ -166,7 +188,11 @@ store_bkt_val(Key, New, [Other|Bkt0]) ->
{[Other|Bkt1],Ic};
store_bkt_val(Key, New, []) -> {[?kv(Key,New)],1}.
--spec append(term(), term(), dict()) -> dict().
+-spec append(Key, Value, Dict1) -> Dict2 when
+ Key :: term(),
+ Value :: term(),
+ Dict1 :: dict(),
+ Dict2 :: dict().
append(Key, Val, D0) ->
Slot = get_slot(D0, Key),
@@ -182,7 +208,11 @@ append_bkt(Key, Val, [Other|Bkt0]) ->
{[Other|Bkt1],Ic};
append_bkt(Key, Val, []) -> {[?kv(Key,[Val])],1}.
--spec append_list(term(), [term()], dict()) -> dict().
+-spec append_list(Key, ValList, Dict1) -> Dict2 when
+ Key :: term(),
+ ValList :: [Value :: term()],
+ Dict1 :: dict(),
+ Dict2 :: dict().
append_list(Key, L, D0) ->
Slot = get_slot(D0, Key),
@@ -252,7 +282,11 @@ app_list_bkt(Key, L, []) -> {[?kv(Key,L)],1}.
%% {Bkt1,Dc} = on_key_bkt(Key, F, Bkt0),
%% {[Other|Bkt1],Dc}.
--spec update(term(), fun((term()) -> term()), dict()) -> dict().
+-spec update(Key, Fun, Dict1) -> Dict2 when
+ Key :: term(),
+ Fun :: fun((Value1 :: term()) -> Value2 :: term()),
+ Dict1 :: dict(),
+ Dict2 :: dict().
update(Key, F, D0) ->
Slot = get_slot(D0, Key),
@@ -271,7 +305,12 @@ update_bkt(Key, F, [Other|Bkt0]) ->
update_bkt(_Key, _F, []) ->
throw(badarg).
--spec update(term(), fun((term()) -> term()), term(), dict()) -> dict().
+-spec update(Key, Fun, Initial, Dict1) -> Dict2 when
+ Key :: term(),
+ Initial :: term(),
+ Fun :: fun((Value1 :: term()) -> Value2 :: term()),
+ Dict1 :: dict(),
+ Dict2 :: dict().
update(Key, F, Init, D0) ->
Slot = get_slot(D0, Key),
@@ -286,7 +325,11 @@ update_bkt(Key, F, I, [Other|Bkt0]) ->
{[Other|Bkt1],Ic};
update_bkt(Key, F, I, []) when is_function(F, 1) -> {[?kv(Key,I)],1}.
--spec update_counter(term(), number(), dict()) -> dict().
+-spec update_counter(Key, Increment, Dict1) -> Dict2 when
+ Key :: term(),
+ Increment :: number(),
+ Dict1 :: dict(),
+ Dict2 :: dict().
update_counter(Key, Incr, D0) when is_number(Incr) ->
Slot = get_slot(D0, Key),
@@ -301,20 +344,38 @@ counter_bkt(Key, I, [Other|Bkt0]) ->
{[Other|Bkt1],Ic};
counter_bkt(Key, I, []) -> {[?kv(Key,I)],1}.
--spec fold(fun((term(), term(), term()) -> term()), term(), dict()) -> term().
+-spec fold(Fun, Acc0, Dict) -> Acc1 when
+ Fun :: fun((Key, Value, AccIn) -> AccOut),
+ Key :: term(),
+ Value :: term(),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ Dict :: dict().
%% Fold function Fun over all "bags" in Table and return Accumulator.
fold(F, Acc, D) -> fold_dict(F, Acc, D).
--spec map(fun((term(), term()) -> term()), dict()) -> dict().
+-spec map(Fun, Dict1) -> Dict2 when
+ Fun :: fun((Key :: term(), Value1 :: term()) -> Value2 :: term()),
+ Dict1 :: dict(),
+ Dict2 :: dict().
map(F, D) -> map_dict(F, D).
--spec filter(fun((term(), term()) -> boolean()), dict()) -> dict().
+-spec filter(Pred, Dict1) -> Dict2 when
+ Pred :: fun((Key :: term(), Value :: term()) -> boolean()),
+ Dict1 :: dict(),
+ Dict2 :: dict().
filter(F, D) -> filter_dict(F, D).
--spec merge(fun((term(), term(), term()) -> term()), dict(), dict()) -> dict().
+-spec merge(Fun, Dict1, Dict2) -> Dict3 when
+ Fun :: fun((Key :: term(), Value1 :: term(), Value2 :: term()) -> Value :: term()),
+ Dict1 :: dict(),
+ Dict2 :: dict(),
+ Dict3 :: dict().
merge(F, D1, D2) when D1#dict.size < D2#dict.size ->
fold_dict(fun (K, V1, D) ->
diff --git a/lib/stdlib/src/digraph.erl b/lib/stdlib/src/digraph.erl
index 5edc868a94..e3f87d2c57 100644
--- a/lib/stdlib/src/digraph.erl
+++ b/lib/stdlib/src/digraph.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -53,7 +53,8 @@
-type label() :: term().
-type vertex() :: term().
--type add_edge_err_rsn() :: {'bad_edge', [vertex()]} | {'bad_vertex', vertex()}.
+-type add_edge_err_rsn() :: {'bad_edge', Path :: [vertex()]}
+ | {'bad_vertex', V :: vertex()}.
%%
%% Type is a list of
@@ -70,7 +71,8 @@
new() -> new([]).
--spec new([d_type()]) -> digraph().
+-spec new(Type) -> digraph() when
+ Type :: [d_type()].
new(Type) ->
case check_type(Type, protected, []) of
@@ -113,16 +115,20 @@ set_type([], G) -> G.
%% Data access functions
--spec delete(digraph()) -> 'true'.
+-spec delete(G) -> 'true' when
+ G :: digraph().
delete(G) ->
ets:delete(G#digraph.vtab),
ets:delete(G#digraph.etab),
ets:delete(G#digraph.ntab).
--spec info(digraph()) -> [{'cyclicity', d_cyclicity()} |
- {'memory', non_neg_integer()} |
- {'protection', d_protection()}].
+-spec info(G) -> InfoList when
+ G :: digraph(),
+ InfoList :: [{'cyclicity', Cyclicity :: d_cyclicity()} |
+ {'memory', NoWords :: non_neg_integer()} |
+ {'protection', Protection :: d_protection()}].
+
info(G) ->
VT = G#digraph.vtab,
ET = G#digraph.etab,
@@ -135,32 +141,45 @@ info(G) ->
Memory = ets:info(VT, memory) + ets:info(ET, memory) + ets:info(NT, memory),
[{cyclicity, Cyclicity}, {memory, Memory}, {protection, Protection}].
--spec add_vertex(digraph()) -> vertex().
+-spec add_vertex(G) -> vertex() when
+ G :: digraph().
add_vertex(G) ->
do_add_vertex({new_vertex_id(G), []}, G).
--spec add_vertex(digraph(), vertex()) -> vertex().
+-spec add_vertex(G, V) -> vertex() when
+ G :: digraph(),
+ V :: vertex().
add_vertex(G, V) ->
do_add_vertex({V, []}, G).
--spec add_vertex(digraph(), vertex(), label()) -> vertex().
+-spec add_vertex(G, V, Label) -> vertex() when
+ G :: digraph(),
+ V :: vertex(),
+ Label :: label().
add_vertex(G, V, D) ->
do_add_vertex({V, D}, G).
--spec del_vertex(digraph(), vertex()) -> 'true'.
+-spec del_vertex(G, V) -> 'true' when
+ G :: digraph(),
+ V :: vertex().
del_vertex(G, V) ->
do_del_vertex(V, G).
--spec del_vertices(digraph(), [vertex()]) -> 'true'.
+-spec del_vertices(G, Vertices) -> 'true' when
+ G :: digraph(),
+ Vertices :: [vertex()].
del_vertices(G, Vs) ->
do_del_vertices(Vs, G).
--spec vertex(digraph(), vertex()) -> {vertex(), label()} | 'false'.
+-spec vertex(G, V) -> {V, Label} | 'false' when
+ G :: digraph(),
+ V :: vertex(),
+ Label :: label().
vertex(G, V) ->
case ets:lookup(G#digraph.vtab, V) of
@@ -168,12 +187,15 @@ vertex(G, V) ->
[Vertex] -> Vertex
end.
--spec no_vertices(digraph()) -> non_neg_integer().
+-spec no_vertices(G) -> non_neg_integer() when
+ G :: digraph().
no_vertices(G) ->
ets:info(G#digraph.vtab, size).
--spec vertices(digraph()) -> [vertex()].
+-spec vertices(G) -> Vertices when
+ G :: digraph(),
+ Vertices :: [vertex()].
vertices(G) ->
ets:select(G#digraph.vtab, [{{'$1', '_'}, [], ['$1']}]).
@@ -188,85 +210,125 @@ source_vertices(G) ->
sink_vertices(G) ->
collect_vertices(G, out).
--spec in_degree(digraph(), vertex()) -> non_neg_integer().
+-spec in_degree(G, V) -> non_neg_integer() when
+ G :: digraph(),
+ V :: vertex().
in_degree(G, V) ->
length(ets:lookup(G#digraph.ntab, {in, V})).
--spec in_neighbours(digraph(), vertex()) -> [vertex()].
+-spec in_neighbours(G, V) -> Vertex when
+ G :: digraph(),
+ V :: vertex(),
+ Vertex :: [vertex()].
in_neighbours(G, V) ->
ET = G#digraph.etab,
NT = G#digraph.ntab,
collect_elems(ets:lookup(NT, {in, V}), ET, 2).
--spec in_edges(digraph(), vertex()) -> [edge()].
+-spec in_edges(G, V) -> Edges when
+ G :: digraph(),
+ V :: vertex(),
+ Edges :: [edge()].
in_edges(G, V) ->
ets:select(G#digraph.ntab, [{{{in, V}, '$1'}, [], ['$1']}]).
--spec out_degree(digraph(), vertex()) -> non_neg_integer().
+-spec out_degree(G, V) -> non_neg_integer() when
+ G :: digraph(),
+ V :: vertex().
out_degree(G, V) ->
length(ets:lookup(G#digraph.ntab, {out, V})).
--spec out_neighbours(digraph(), vertex()) -> [vertex()].
+-spec out_neighbours(G, V) -> Vertices when
+ G :: digraph(),
+ V :: vertex(),
+ Vertices :: [vertex()].
out_neighbours(G, V) ->
ET = G#digraph.etab,
NT = G#digraph.ntab,
collect_elems(ets:lookup(NT, {out, V}), ET, 3).
--spec out_edges(digraph(), vertex()) -> [edge()].
+-spec out_edges(G, V) -> Edges when
+ G :: digraph(),
+ V :: vertex(),
+ Edges :: [edge()].
out_edges(G, V) ->
ets:select(G#digraph.ntab, [{{{out, V}, '$1'}, [], ['$1']}]).
--spec add_edge(digraph(), vertex(), vertex()) ->
- edge() | {'error', add_edge_err_rsn()}.
+-spec add_edge(G, V1, V2) -> edge() | {'error', add_edge_err_rsn()} when
+ G :: digraph(),
+ V1 :: vertex(),
+ V2 :: vertex().
add_edge(G, V1, V2) ->
do_add_edge({new_edge_id(G), V1, V2, []}, G).
--spec add_edge(digraph(), vertex(), vertex(), label()) ->
- edge() | {'error', add_edge_err_rsn()}.
+-spec add_edge(G, V1, V2, Label) -> edge() | {'error', add_edge_err_rsn()} when
+ G :: digraph(),
+ V1 :: vertex(),
+ V2 :: vertex(),
+ Label :: label().
add_edge(G, V1, V2, D) ->
do_add_edge({new_edge_id(G), V1, V2, D}, G).
--spec add_edge(digraph(), edge(), vertex(), vertex(), label()) ->
- edge() | {'error', add_edge_err_rsn()}.
+-spec add_edge(G, E, V1, V2, Label) -> edge() | {'error', add_edge_err_rsn()} when
+ G :: digraph(),
+ E :: edge(),
+ V1 :: vertex(),
+ V2 :: vertex(),
+ Label :: label().
add_edge(G, E, V1, V2, D) ->
do_add_edge({E, V1, V2, D}, G).
--spec del_edge(digraph(), edge()) -> 'true'.
+-spec del_edge(G, E) -> 'true' when
+ G :: digraph(),
+ E :: edge().
del_edge(G, E) ->
do_del_edges([E], G).
--spec del_edges(digraph(), [edge()]) -> 'true'.
+-spec del_edges(G, Edges) -> 'true' when
+ G :: digraph(),
+ Edges :: [edge()].
del_edges(G, Es) ->
do_del_edges(Es, G).
--spec no_edges(digraph()) -> non_neg_integer().
+-spec no_edges(G) -> non_neg_integer() when
+ G :: digraph().
no_edges(G) ->
ets:info(G#digraph.etab, size).
--spec edges(digraph()) -> [edge()].
+-spec edges(G) -> Edges when
+ G :: digraph(),
+ Edges :: [edge()].
edges(G) ->
ets:select(G#digraph.etab, [{{'$1', '_', '_', '_'}, [], ['$1']}]).
--spec edges(digraph(), vertex()) -> [edge()].
+-spec edges(G, V) -> Edges when
+ G :: digraph(),
+ V :: vertex(),
+ Edges :: [edge()].
edges(G, V) ->
ets:select(G#digraph.ntab, [{{{out, V},'$1'}, [], ['$1']},
{{{in, V}, '$1'}, [], ['$1']}]).
--spec edge(digraph(), edge()) -> {edge(),vertex(),vertex(),label()} | 'false'.
+-spec edge(G, E) -> {E, V1, V2, Label} | 'false' when
+ G :: digraph(),
+ E :: edge(),
+ V1 :: vertex(),
+ V2 :: vertex(),
+ Label :: label().
edge(G, E) ->
case ets:lookup(G#digraph.etab,E) of
@@ -277,7 +339,7 @@ edge(G, E) ->
%%
%% Generate a "unique" edge identifier (relative to this graph)
%%
--spec new_edge_id(digraph()) -> nonempty_improper_list('$e', non_neg_integer()).
+-spec new_edge_id(digraph()) -> edge().
new_edge_id(G) ->
NT = G#digraph.ntab,
@@ -289,7 +351,7 @@ new_edge_id(G) ->
%%
%% Generate a "unique" vertex identifier (relative to this graph)
%%
--spec new_vertex_id(digraph()) -> nonempty_improper_list('$v', non_neg_integer()).
+-spec new_vertex_id(digraph()) -> vertex().
new_vertex_id(G) ->
NT = G#digraph.ntab,
@@ -444,7 +506,10 @@ acyclic_add_edge(E, V1, V2, Label, G) ->
%% Delete all paths from vertex V1 to vertex V2
%%
--spec del_path(digraph(), vertex(), vertex()) -> 'true'.
+-spec del_path(G, V1, V2) -> 'true' when
+ G :: digraph(),
+ V1 :: vertex(),
+ V2 :: vertex().
del_path(G, V1, V2) ->
case get_path(G, V1, V2) of
@@ -463,7 +528,10 @@ del_path(G, V1, V2) ->
%% been searched.
%%
--spec get_cycle(digraph(), vertex()) -> [vertex(),...] | 'false'.
+-spec get_cycle(G, V) -> Vertices | 'false' when
+ G :: digraph(),
+ V :: vertex(),
+ Vertices :: [vertex(),...].
get_cycle(G, V) ->
case one_path(out_neighbours(G, V), V, [], [V], [V], 2, G, 1) of
@@ -481,7 +549,11 @@ get_cycle(G, V) ->
%% if no path exists false is returned
%%
--spec get_path(digraph(), vertex(), vertex()) -> [vertex(),...] | 'false'.
+-spec get_path(G, V1, V2) -> Vertices | 'false' when
+ G :: digraph(),
+ V1 :: vertex(),
+ V2 :: vertex(),
+ Vertices :: [vertex(),...].
get_path(G, V1, V2) ->
one_path(out_neighbours(G, V1), V2, [], [V1], [V1], 1, G, 1).
@@ -516,7 +588,10 @@ one_path([], _, [], _, _, _, _, _Counter) -> false.
%% Like get_cycle/2, but a cycle of length one is preferred.
%%
--spec get_short_cycle(digraph(), vertex()) -> [vertex(),...] | 'false'.
+-spec get_short_cycle(G, V) -> Vertices | 'false' when
+ G :: digraph(),
+ V :: vertex(),
+ Vertices :: [vertex(),...].
get_short_cycle(G, V) ->
get_short_path(G, V, V).
@@ -526,7 +601,11 @@ get_short_cycle(G, V) ->
%% to find a short path.
%%
--spec get_short_path(digraph(), vertex(), vertex()) -> [vertex(),...] | 'false'.
+-spec get_short_path(G, V1, V2) -> Vertices | 'false' when
+ G :: digraph(),
+ V1 :: vertex(),
+ V2 :: vertex(),
+ Vertices :: [vertex(),...].
get_short_path(G, V1, V2) ->
T = new(),
diff --git a/lib/stdlib/src/digraph_utils.erl b/lib/stdlib/src/digraph_utils.erl
index 080cae4742..e221be15a1 100644
--- a/lib/stdlib/src/digraph_utils.erl
+++ b/lib/stdlib/src/digraph_utils.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1999-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1999-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
@@ -38,48 +38,66 @@
%% A convenient type alias
%%
--type vertices() :: [digraph:vertex()].
-
%%
%% Exported functions
%%
--spec components(digraph()) -> vertices().
+-spec components(Digraph) -> [Component] when
+ Digraph :: digraph(),
+ Component :: [digraph:vertex()].
components(G) ->
forest(G, fun inout/3).
--spec strong_components(digraph()) -> vertices().
+-spec strong_components(Digraph) -> [StrongComponent] when
+ Digraph :: digraph(),
+ StrongComponent :: [digraph:vertex()].
strong_components(G) ->
forest(G, fun in/3, revpostorder(G)).
--spec cyclic_strong_components(digraph()) -> vertices().
+-spec cyclic_strong_components(Digraph) -> [StrongComponent] when
+ Digraph :: digraph(),
+ StrongComponent :: [digraph:vertex()].
cyclic_strong_components(G) ->
remove_singletons(strong_components(G), G, []).
--spec reachable(vertices(), digraph()) -> vertices().
+-spec reachable(Vertices, Digraph) -> Reachable when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()],
+ Reachable :: [digraph:vertex()].
reachable(Vs, G) when is_list(Vs) ->
lists:append(forest(G, fun out/3, Vs, first)).
--spec reachable_neighbours(vertices(), digraph()) -> vertices().
+-spec reachable_neighbours(Vertices, Digraph) -> Reachable when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()],
+ Reachable :: [digraph:vertex()].
reachable_neighbours(Vs, G) when is_list(Vs) ->
lists:append(forest(G, fun out/3, Vs, not_first)).
--spec reaching(vertices(), digraph()) -> vertices().
+-spec reaching(Vertices, Digraph) -> Reaching when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()],
+ Reaching :: [digraph:vertex()].
reaching(Vs, G) when is_list(Vs) ->
lists:append(forest(G, fun in/3, Vs, first)).
--spec reaching_neighbours(vertices(), digraph()) -> vertices().
+-spec reaching_neighbours(Vertices, Digraph) -> Reaching when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()],
+ Reaching :: [digraph:vertex()].
reaching_neighbours(Vs, G) when is_list(Vs) ->
lists:append(forest(G, fun in/3, Vs, not_first)).
--spec topsort(digraph()) -> vertices() | 'false'.
+-spec topsort(Digraph) -> Vertices | 'false' when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()].
topsort(G) ->
L = revpostorder(G),
@@ -88,12 +106,15 @@ topsort(G) ->
false -> false
end.
--spec is_acyclic(digraph()) -> boolean().
+-spec is_acyclic(Digraph) -> boolean() when
+ Digraph :: digraph().
is_acyclic(G) ->
loop_vertices(G) =:= [] andalso topsort(G) =/= false.
--spec arborescence_root(digraph()) -> 'no' | {'yes', digraph:vertex()}.
+-spec arborescence_root(Digraph) -> 'no' | {'yes', Root} when
+ Digraph :: digraph(),
+ Root :: digraph:vertex().
arborescence_root(G) ->
case digraph:no_edges(G) =:= digraph:no_vertices(G) - 1 of
@@ -114,23 +135,30 @@ arborescence_root(G) ->
no
end.
--spec is_arborescence(digraph()) -> boolean().
+-spec is_arborescence(Digraph) -> boolean() when
+ Digraph :: digraph().
is_arborescence(G) ->
arborescence_root(G) =/= no.
--spec is_tree(digraph()) -> boolean().
+-spec is_tree(Digraph) -> boolean() when
+ Digraph :: digraph().
is_tree(G) ->
(digraph:no_edges(G) =:= digraph:no_vertices(G) - 1)
andalso (length(components(G)) =:= 1).
--spec loop_vertices(digraph()) -> vertices().
+-spec loop_vertices(Digraph) -> Vertices when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()].
loop_vertices(G) ->
[V || V <- digraph:vertices(G), is_reflexive_vertex(V, G)].
--spec subgraph(digraph(), vertices()) -> digraph().
+-spec subgraph(Digraph, Vertices) -> SubGraph when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()],
+ SubGraph :: digraph().
subgraph(G, Vs) ->
try
@@ -140,10 +168,12 @@ subgraph(G, Vs) ->
erlang:error(badarg)
end.
--type option() :: {'type', 'inherit' | [digraph:d_type()]}
- | {'keep_labels', boolean()}.
-
--spec subgraph(digraph(), vertices(), [option()]) -> digraph().
+-spec subgraph(Digraph, Vertices, Options) -> SubGraph when
+ Digraph :: digraph(),
+ SubGraph :: digraph(),
+ Vertices :: [digraph:vertex()],
+ Options :: [{'type', SubgraphType} | {'keep_labels', boolean()}],
+ SubgraphType :: 'inherit' | [digraph:d_type()].
subgraph(G, Vs, Opts) ->
try
@@ -153,7 +183,9 @@ subgraph(G, Vs, Opts) ->
erlang:error(badarg)
end.
--spec condensation(digraph()) -> digraph().
+-spec condensation(Digraph) -> CondensedDigraph when
+ Digraph :: digraph(),
+ CondensedDigraph :: digraph().
condensation(G) ->
SCs = strong_components(G),
@@ -176,12 +208,16 @@ condensation(G) ->
ets:delete(I2C),
SCG.
--spec preorder(digraph()) -> vertices().
+-spec preorder(Digraph) -> Vertices when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()].
preorder(G) ->
lists:reverse(revpreorder(G)).
--spec postorder(digraph()) -> vertices().
+-spec postorder(Digraph) -> Vertices when
+ Digraph :: digraph(),
+ Vertices :: [digraph:vertex()].
postorder(G) ->
lists:reverse(revpostorder(G)).
diff --git a/lib/stdlib/src/epp.erl b/lib/stdlib/src/epp.erl
index e5ccaddbb4..d804c1dee5 100644
--- a/lib/stdlib/src/epp.erl
+++ b/lib/stdlib/src/epp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -29,6 +29,7 @@
%%------------------------------------------------------------------------
-type macros() :: [{atom(), term()}].
+-type epp_handle() :: pid().
%% Epp state record.
-record(epp, {file, %Current file
@@ -61,14 +62,23 @@
%% parse_file(FileName, IncludePath, PreDefMacros)
%% macro_defs(Epp)
--spec open(file:name(), [file:name()]) ->
- {'ok', pid()} | {'error', term()}.
+-spec open(FileName, IncludePath) ->
+ {'ok', Epp} | {'error', ErrorDescriptor} when
+ FileName :: file:name(),
+ IncludePath :: [DirectoryName :: file:name()],
+ Epp :: epp_handle(),
+ ErrorDescriptor :: term().
open(Name, Path) ->
open(Name, Path, []).
--spec open(file:name(), [file:name()], macros()) ->
- {'ok', pid()} | {'error', term()}.
+-spec open(FileName, IncludePath, PredefMacros) ->
+ {'ok', Epp} | {'error', ErrorDescriptor} when
+ FileName :: file:name(),
+ IncludePath :: [DirectoryName :: file:name()],
+ PredefMacros :: macros(),
+ Epp :: epp_handle(),
+ ErrorDescriptor :: term().
open(Name, Path, Pdm) ->
Self = self(),
@@ -80,7 +90,8 @@ open(Name, File, StartLocation, Path, Pdm) ->
Epp = spawn(fun() -> server(Self, Name, File, StartLocation,Path,Pdm) end),
epp_request(Epp).
--spec close(pid()) -> 'ok'.
+-spec close(Epp) -> 'ok' when
+ Epp :: epp_handle().
close(Epp) ->
%% Make sure that close is synchronous as a courtesy to test
@@ -93,6 +104,13 @@ close(Epp) ->
scan_erl_form(Epp) ->
epp_request(Epp, scan_erl_form).
+-spec parse_erl_form(Epp) ->
+ {'ok', AbsForm} | {'eof', Line} | {error, ErrorInfo} when
+ Epp :: epp_handle(),
+ AbsForm :: erl_parse:abstract_form(),
+ Line :: erl_scan:line(),
+ ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
+
parse_erl_form(Epp) ->
case epp_request(Epp, scan_erl_form) of
{ok,Toks} ->
@@ -107,6 +125,9 @@ macro_defs(Epp) ->
%% format_error(ErrorDescriptor) -> String
%% Return a string describing the error.
+-spec format_error(ErrorDescriptor) -> io_lib:chars() when
+ ErrorDescriptor :: term().
+
format_error(cannot_parse) ->
io_lib:format("cannot parse file, giving up", []);
format_error({bad,W}) ->
@@ -146,6 +167,16 @@ format_error(E) -> file:format_error(E).
%% parse_file(FileName, IncludePath, [PreDefMacro]) ->
%% {ok,[Form]} | {error,OpenError}
+-spec parse_file(FileName, IncludePath, PredefMacros) ->
+ {'ok', [Form]} | {error, OpenError} when
+ FileName :: file:name(),
+ IncludePath :: [DirectoryName :: file:name()],
+ Form :: erl_parse:abstract_form() | {'error', ErrorInfo} | {'eof',Line},
+ PredefMacros :: macros(),
+ Line :: erl_scan:line(),
+ ErrorInfo :: erl_scan:error_info() | erl_parse:error_info(),
+ OpenError :: file:posix() | badarg | system_limit.
+
parse_file(Ifile, Path, Predefs) ->
case open(Ifile, Path, Predefs) of
{ok,Epp} ->
diff --git a/lib/stdlib/src/erl_eval.erl b/lib/stdlib/src/erl_eval.erl
index ea1b179ee5..46288cf467 100644
--- a/lib/stdlib/src/erl_eval.erl
+++ b/lib/stdlib/src/erl_eval.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -34,6 +34,37 @@
-import(lists, [reverse/1,foldl/3,member/2]).
+-export_type([binding_struct/0]).
+
+-type(expression() :: erl_parse:abstract_expr()).
+-type(expressions() :: [erl_parse:abstract_expr()]).
+-type(expression_list() :: [expression()]).
+-type(clauses() :: [erl_parse:abstract_clause()]).
+-type(name() :: term()).
+-type(value() :: term()).
+-type(bindings() :: [{name(), value()}]).
+-opaque(binding_struct() :: orddict:orddict()).
+
+-type(lfun_value_handler() :: fun((Name :: atom(),
+ Arguments :: [term()]) ->
+ Value :: value())).
+-type(lfun_eval_handler() :: fun((Name :: atom(),
+ Arguments :: expression_list(),
+ Bindings :: binding_struct()) ->
+ {value,
+ Value :: value(),
+ NewBindings :: binding_struct()})).
+-type(local_function_handler() :: {value, lfun_value_handler()}
+ | {eval, lfun_eval_handler()}
+ | none).
+
+-type(func_spec() :: {Module :: module(), Function :: atom()} | function()).
+-type(nlfun_handler() :: fun((FuncSpec :: func_spec(),
+ Arguments :: [term()]) ->
+ term())).
+-type(non_local_function_handler() :: {value, nlfun_handler()}
+ | none).
+
%% exprs(ExpressionSeq, Bindings)
%% exprs(ExpressionSeq, Bindings, LocalFuncHandler)
%% exprs(ExpressionSeq, Bindings, LocalFuncHandler, ExternalFuncHandler)
@@ -45,6 +76,11 @@
%% that there are valid constructs in Expression to be taken care of
%% by a function handler but considerad errors by erl_lint.
+-spec(exprs(Expressions, Bindings) -> {value, Value, NewBindings} when
+ Expressions :: expressions(),
+ Bindings :: binding_struct(),
+ Value :: value(),
+ NewBindings :: binding_struct()).
exprs(Exprs, Bs) ->
case check_command(Exprs, Bs) of
ok ->
@@ -53,9 +89,25 @@ exprs(Exprs, Bs) ->
erlang:raise(error, Error, [{?MODULE,exprs,2}])
end.
+-spec(exprs(Expressions, Bindings, LocalFunctionHandler) ->
+ {value, Value, NewBindings} when
+ Expressions :: expressions(),
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ Value :: value(),
+ NewBindings :: binding_struct()).
exprs(Exprs, Bs, Lf) ->
exprs(Exprs, Bs, Lf, none, none).
+-spec(exprs(Expressions, Bindings, LocalFunctionHandler,
+ NonLocalFunctionHandler) ->
+ {value, Value, NewBindings} when
+ Expressions :: expressions(),
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ NonLocalFunctionHandler :: non_local_function_handler(),
+ Value :: value(),
+ NewBindings :: binding_struct()).
exprs(Exprs, Bs, Lf, Ef) ->
exprs(Exprs, Bs, Lf, Ef, none).
@@ -75,6 +127,11 @@ exprs([E|Es], Bs0, Lf, Ef, RBs) ->
%%
%% Only expr/2 checks the command by calling erl_lint. See exprs/2.
+-spec(expr(Expression, Bindings) -> {value, Value, NewBindings} when
+ Expression :: expression(),
+ Bindings :: binding_struct(),
+ Value :: value(),
+ NewBindings :: binding_struct()).
expr(E, Bs) ->
case check_command([E], Bs) of
ok ->
@@ -83,9 +140,25 @@ expr(E, Bs) ->
erlang:raise(error, Error, [{?MODULE,expr,2}])
end.
+-spec(expr(Expression, Bindings, LocalFunctionHandler) ->
+ {value, Value, NewBindings} when
+ Expression :: expression(),
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ Value :: value(),
+ NewBindings :: binding_struct()).
expr(E, Bs, Lf) ->
expr(E, Bs, Lf, none, none).
+-spec(expr(Expression, Bindings, LocalFunctionHandler,
+ NonLocalFunctionHandler) ->
+ {value, Value, NewBindings} when
+ Expression :: expression(),
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ NonLocalFunctionHandler :: non_local_function_handler(),
+ Value :: value(),
+ NewBindings :: binding_struct()).
expr(E, Bs, Lf, Ef) ->
expr(E, Bs, Lf, Ef, none).
@@ -114,6 +187,16 @@ fun_data(F) when is_function(F) ->
fun_data(_T) ->
false.
+-spec(expr(Expression, Bindings, LocalFunctionHandler,
+ NonLocalFunctionHandler, ReturnFormat) ->
+ {value, Value, NewBindings} | Value when
+ Expression :: expression(),
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ NonLocalFunctionHandler :: non_local_function_handler(),
+ ReturnFormat :: none | value,
+ Value :: value(),
+ NewBindings :: binding_struct()).
expr({var,_,V}, Bs, _Lf, _Ef, RBs) ->
case binding(V, Bs) of
{value,Val} ->
@@ -384,12 +467,9 @@ local_func(Func, As0, Bs0, {value,F}, value) ->
local_func(Func, As0, Bs0, {value,F}, RBs) ->
{As1,Bs1} = expr_list(As0, Bs0, {value,F}),
ret_expr(F(Func, As1), Bs1, RBs);
-local_func(Func, As0, Bs0, {value,F,Eas}, value) ->
- {As1,_Bs1} = expr_list(As0, Bs0, {value,F,Eas}),
- apply(F, [Func,As1|Eas]);
local_func(Func, As0, Bs0, {value,F,Eas}, RBs) ->
- {As1,Bs1} = expr_list(As0, Bs0, {value,F,Eas}),
- ret_expr(apply(F, [Func,As1|Eas]), Bs1, RBs);
+ Fun = fun(Name, Args) -> apply(F, [Name,Args|Eas]) end,
+ local_func(Func, As0, Bs0, {value, Fun}, RBs);
local_func(Func, As, Bs, {eval,F}, RBs) ->
local_func2(F(Func, As, Bs), RBs);
local_func(Func, As, Bs, {eval,F,Eas}, RBs) ->
@@ -613,12 +693,33 @@ eval_fun([], As, _Bs, _Lf, _Ef, _RBs) ->
%% expr_list(ExpressionList, Bindings, LocalFuncHandler, ExternalFuncHandler)
%% Evaluate a list of expressions "in parallel" at the same level.
+-spec(expr_list(ExpressionList, Bindings) -> {ValueList, NewBindings} when
+ ExpressionList :: expression_list(),
+ Bindings :: binding_struct(),
+ ValueList :: [value()],
+ NewBindings :: binding_struct()).
expr_list(Es, Bs) ->
expr_list(Es, Bs, none, none).
+-spec(expr_list(ExpressionList, Bindings, LocalFunctionHandler) ->
+ {ValueList, NewBindings} when
+ ExpressionList :: expression_list(),
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ ValueList :: [value()],
+ NewBindings :: binding_struct()).
expr_list(Es, Bs, Lf) ->
expr_list(Es, Bs, Lf, none).
+-spec(expr_list(ExpressionList, Bindings, LocalFunctionHandler,
+ NonLocalFunctionHandler) ->
+ {ValueList, NewBindings} when
+ ExpressionList :: expression_list(),
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ NonLocalFunctionHandler :: non_local_function_handler(),
+ ValueList :: [value()],
+ NewBindings :: binding_struct()).
expr_list(Es, Bs, Lf, Ef) ->
expr_list(Es, [], Bs, Bs, Lf, Ef).
@@ -757,6 +858,15 @@ send_all([], _) -> true.
%% match_clause -> {Body, Bindings} or nomatch
+-spec(match_clause(Clauses, ValueList, Bindings, LocalFunctionHandler) ->
+ {Body, NewBindings} | nomatch when
+ Clauses :: clauses(),
+ ValueList :: [value()],
+ Bindings :: binding_struct(),
+ LocalFunctionHandler :: local_function_handler(),
+ Body :: expression_list(),
+ NewBindings :: binding_struct()).
+
match_clause(Cs, Vs, Bs, Lf) ->
match_clause(Cs, Vs, Bs, Lf, none).
@@ -973,18 +1083,30 @@ match_list(_, _, _Bs, _BBs) ->
%% add_binding(Name, Value, Bindings)
%% del_binding(Name, Bindings)
+-spec(new_bindings() -> binding_struct()).
new_bindings() -> orddict:new().
+-spec(bindings(BindingStruct :: binding_struct()) -> bindings()).
bindings(Bs) -> orddict:to_list(Bs).
+-spec(binding(Name, BindingStruct) -> {value, value()} | unbound when
+ Name :: name(),
+ BindingStruct :: binding_struct()).
binding(Name, Bs) ->
case orddict:find(Name, Bs) of
{ok,Val} -> {value,Val};
error -> unbound
end.
+-spec(add_binding(Name, Value, BindingStruct) -> binding_struct() when
+ Name :: name(),
+ Value :: value(),
+ BindingStruct :: binding_struct()).
add_binding(Name, Val, Bs) -> orddict:store(Name, Val, Bs).
+-spec(del_binding(Name, BindingStruct) -> binding_struct() when
+ Name :: name(),
+ BindingStruct :: binding_struct()).
del_binding(Name, Bs) -> orddict:erase(Name, Bs).
add_bindings(Bs1, Bs2) ->
diff --git a/lib/stdlib/src/erl_expand_records.erl b/lib/stdlib/src/erl_expand_records.erl
index 61ce41f714..eada563914 100644
--- a/lib/stdlib/src/erl_expand_records.erl
+++ b/lib/stdlib/src/erl_expand_records.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2005-2010. All Rights Reserved.
+%% 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
@@ -38,6 +38,10 @@
checked_ra=[] % succesfully accessed records
}).
+-spec(module(AbsForms, CompileOptions) -> AbsForms when
+ AbsForms :: [erl_parse:abstract_form()],
+ CompileOptions :: [compile:option()]).
+
%% Is is assumed that Fs is a valid list of forms. It should pass
%% erl_lint without errors.
module(Fs0, Opts0) ->
diff --git a/lib/stdlib/src/erl_internal.erl b/lib/stdlib/src/erl_internal.erl
index b30b02a96f..478f05e792 100644
--- a/lib/stdlib/src/erl_internal.erl
+++ b/lib/stdlib/src/erl_internal.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1998-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1998-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
@@ -54,7 +54,9 @@
%%---------------------------------------------------------------------------
%% Erlang builtin functions allowed in guards.
--spec guard_bif(Name::atom(), Arity::arity()) -> boolean().
+-spec guard_bif(Name, Arity) -> boolean() when
+ Name :: atom(),
+ Arity :: arity().
guard_bif(abs, 1) -> true;
guard_bif(float, 1) -> true;
@@ -92,7 +94,9 @@ guard_bif(binary_part, 3) -> true;
guard_bif(Name, A) when is_atom(Name), is_integer(A) -> false.
%% Erlang type tests.
--spec type_test(Name::atom(), Arity::arity()) -> boolean().
+-spec type_test(Name, Arity) -> boolean() when
+ Name :: atom(),
+ Arity :: arity().
type_test(Name, Arity) ->
new_type_test(Name, Arity) orelse old_type_test(Name, Arity).
@@ -135,7 +139,9 @@ old_type_test(record, 2) -> true;
old_type_test(function, 1) -> true;
old_type_test(Name, A) when is_atom(Name), is_integer(A) -> false.
--spec arith_op(Op::atom(), Arity::arity()) -> boolean().
+-spec arith_op(OpName, Arity) -> boolean() when
+ OpName :: atom(),
+ Arity :: arity().
arith_op('+', 1) -> true;
arith_op('-', 1) -> true;
@@ -153,7 +159,9 @@ arith_op('bsl', 2) -> true;
arith_op('bsr', 2) -> true;
arith_op(Op, A) when is_atom(Op), is_integer(A) -> false.
--spec bool_op(Op::atom(), Arity::arity()) -> boolean().
+-spec bool_op(OpName, Arity) -> boolean() when
+ OpName :: atom(),
+ Arity :: arity().
bool_op('not', 1) -> true;
bool_op('and', 2) -> true;
@@ -161,7 +169,9 @@ bool_op('or', 2) -> true;
bool_op('xor', 2) -> true;
bool_op(Op, A) when is_atom(Op), is_integer(A) -> false.
--spec comp_op(Op::atom(), Arity::arity()) -> boolean().
+-spec comp_op(OpName, Arity) -> boolean() when
+ OpName :: atom(),
+ Arity :: arity().
comp_op('==', 2) -> true;
comp_op('/=', 2) -> true;
@@ -173,18 +183,25 @@ comp_op('=:=', 2) -> true;
comp_op('=/=', 2) -> true;
comp_op(Op, A) when is_atom(Op), is_integer(A) -> false.
--spec list_op(Op::atom(), Arity::arity()) -> boolean().
+-spec list_op(OpName, Arity) -> boolean() when
+ OpName :: atom(),
+ Arity :: arity().
list_op('++', 2) -> true;
list_op('--', 2) -> true;
list_op(Op, A) when is_atom(Op), is_integer(A) -> false.
--spec send_op(Op::atom(), Arity::arity()) -> boolean().
+-spec send_op(OpName, Arity) -> boolean() when
+ OpName :: atom(),
+ Arity :: arity().
send_op('!', 2) -> true;
send_op(Op, A) when is_atom(Op), is_integer(A) -> false.
--spec op_type(atom(), arity()) -> 'arith' | 'bool' | 'comp' | 'list' | 'send'.
+-spec op_type(OpName, Arity) -> Type when
+ OpName :: atom(),
+ Arity :: arity(),
+ Type :: 'arith' | 'bool' | 'comp' | 'list' | 'send'.
op_type('+', 1) -> arith;
op_type('-', 1) -> arith;
@@ -221,7 +238,9 @@ op_type('!', 2) -> send.
bif(erlang, Name, Arity) -> bif(Name, Arity);
bif(M, F, A) when is_atom(M), is_atom(F), is_integer(A) -> false.
--spec bif(Name::atom(), Arity::arity()) -> boolean().
+-spec bif(Name, Arity) -> boolean() when
+ Name :: atom(),
+ Arity::arity().
%% Returns true if erlang:Name/Arity is an auto-imported BIF, false otherwise.
%% Use erlang:is_bultin(Mod, Name, Arity) to find whether a function is a BIF
%% (meaning implemented in C) or not.
diff --git a/lib/stdlib/src/erl_lint.erl b/lib/stdlib/src/erl_lint.erl
index cfb9f0ca98..dd0b9bc2ab 100644
--- a/lib/stdlib/src/erl_lint.erl
+++ b/lib/stdlib/src/erl_lint.erl
@@ -128,10 +128,15 @@ value_option(Flag, Default, On, OnVal, Off, OffVal, Opts) ->
}).
-type lint_state() :: #lint{}.
+-type error_description() :: term().
+-type error_info() :: {erl_scan:line(), module(), error_description()}.
%% format_error(Error)
%% Return a string describing the error.
+-spec format_error(ErrorDescriptor) -> io_lib:chars() when
+ ErrorDescriptor :: error_description().
+
format_error(undefined_module) ->
"no module definition";
format_error({bad_module_name, M}) ->
@@ -419,16 +424,39 @@ used_vars(Exprs, BindingsList) ->
%% apply_lambda/2 has been called to shut lint up. N.B. these lists are
%% really all ordsets!
+-spec(module(AbsForms) -> {ok, Warnings} | {error, Errors, Warnings} when
+ AbsForms :: [erl_parse:abstract_form()],
+ Warnings :: [{file:filename(),[ErrorInfo]}],
+ Errors :: [{FileName2 :: file:filename(),[ErrorInfo]}],
+ ErrorInfo :: error_info()).
+
module(Forms) ->
Opts = compiler_options(Forms),
St = forms(Forms, start("nofile", Opts)),
return_status(St).
+-spec(module(AbsForms, FileName) ->
+ {ok, Warnings} | {error, Errors, Warnings} when
+ AbsForms :: [erl_parse:abstract_form()],
+ FileName :: atom() | string(),
+ Warnings :: [{file:filename(),[ErrorInfo]}],
+ Errors :: [{FileName2 :: file:filename(),[ErrorInfo]}],
+ ErrorInfo :: error_info()).
+
module(Forms, FileName) ->
Opts = compiler_options(Forms),
St = forms(Forms, start(FileName, Opts)),
return_status(St).
+-spec(module(AbsForms, FileName, CompileOptions) ->
+ {ok, Warnings} | {error, Errors, Warnings} when
+ AbsForms :: [erl_parse:abstract_form()],
+ FileName :: atom() | string(),
+ CompileOptions :: [compile:option()],
+ Warnings :: [{file:filename(),[ErrorInfo]}],
+ Errors :: [{FileName2 :: file:filename(),[ErrorInfo]}],
+ ErrorInfo :: error_info()).
+
module(Forms, FileName, Opts0) ->
%% We want the options given on the command line to take
%% precedence over options in the module.
@@ -1877,6 +1905,9 @@ gexpr_list(Es, Vt, St) ->
%% is_guard_test(Expression) -> boolean().
%% Test if a general expression is a guard test.
+-spec is_guard_test(Expr) -> boolean() when
+ Expr :: erl_parse:abstract_expr().
+
is_guard_test(E) ->
is_guard_test2(E, dict:new()).
diff --git a/lib/stdlib/src/erl_parse.yrl b/lib/stdlib/src/erl_parse.yrl
index 15b45d72f4..bd5d65a1e1 100644
--- a/lib/stdlib/src/erl_parse.yrl
+++ b/lib/stdlib/src/erl_parse.yrl
@@ -511,6 +511,15 @@ Erlang code.
%% of the generated .erl file by the HiPE compiler. Please do not remove.
-compile([{hipe,[{regalloc,linear_scan}]}]).
+-export_type([abstract_clause/0, abstract_expr/0, abstract_form/0,
+ error_info/0]).
+
+-type abstract_clause() :: term().
+-type abstract_expr() :: term().
+-type abstract_form() :: term().
+-type error_description() :: term().
+-type error_info() :: {erl_scan:line(), module(), error_description()}.
+-type token() :: {Tag :: atom(), Line :: erl_scan:line()}.
%% mkop(Op, Arg) -> {op,Line,Op,Arg}.
%% mkop(Left, Op, Right) -> {op,Line,Op,Left,Right}.
@@ -534,11 +543,19 @@ Erlang code.
%% These really suck and are only here until Calle gets multiple
%% entry points working.
+-spec parse_form(Tokens) -> {ok, AbsForm} | {error, ErrorInfo} when
+ Tokens :: [token()],
+ AbsForm :: abstract_form(),
+ ErrorInfo :: error_info().
parse_form([{'-',L1},{atom,L2,spec}|Tokens]) ->
parse([{'-',L1},{'spec',L2}|Tokens]);
parse_form(Tokens) ->
parse(Tokens).
+-spec parse_exprs(Tokens) -> {ok, ExprList} | {error, ErrorInfo} when
+ Tokens :: [token()],
+ ExprList :: [abstract_expr()],
+ ErrorInfo :: error_info().
parse_exprs(Tokens) ->
case parse([{atom,0,f},{'(',0},{')',0},{'->',0}|Tokens]) of
{ok,{function,_Lf,f,0,[{clause,_Lc,[],[],Exprs}]}} ->
@@ -546,6 +563,10 @@ parse_exprs(Tokens) ->
{error,_} = Err -> Err
end.
+-spec parse_term(Tokens) -> {ok, Term} | {error, ErrorInfo} when
+ Tokens :: [token()],
+ Term :: term(),
+ ErrorInfo :: error_info().
parse_term(Tokens) ->
case parse([{atom,0,f},{'(',0},{')',0},{'->',0}|Tokens]) of
{ok,{function,_Lf,f,0,[{clause,_Lc,[],[],[Expr]}]}} ->
@@ -830,6 +851,7 @@ check_clauses(Cs, Name, Arity) ->
build_try(L,Es,Scs,{Ccs,As}) ->
{'try',L,Es,Scs,Ccs,As}.
+-spec ret_err(_, _) -> no_return().
ret_err(L, S) ->
{location,Location} = get_attribute(L, location),
return_error(Location, S).
@@ -846,10 +868,11 @@ mapl(F, [H|T]) ->
mapl(_, []) ->
[].
-%% normalise(AbsTerm)
-%% abstract(Term)
%% Convert between the abstract form of a term and a term.
+-spec normalise(AbsTerm) -> Data when
+ AbsTerm :: abstract_expr(),
+ Data :: term().
normalise({char,_,C}) -> C;
normalise({integer,_,I}) -> I;
normalise({float,_,F}) -> F;
@@ -887,6 +910,9 @@ normalise_list([H|T]) ->
normalise_list([]) ->
[].
+-spec abstract(Data) -> AbsTerm when
+ Data :: term(),
+ AbsTerm :: abstract_expr().
abstract(T) when is_integer(T) -> {integer,0,T};
abstract(T) when is_float(T) -> {float,0,T};
abstract(T) when is_atom(T) -> {atom,0,T};
@@ -955,13 +981,18 @@ abstract_list([H|T], Line) ->
abstract_list([], _Line) ->
[].
-%% tokens(AbsTerm) -> [Token]
-%% tokens(AbsTerm, More) -> [Token]
%% Generate a list of tokens representing the abstract term.
+-spec tokens(AbsTerm) -> Tokens when
+ AbsTerm :: abstract_expr(),
+ Tokens :: [token()].
tokens(Abs) ->
tokens(Abs, []).
+-spec tokens(AbsTerm, MoreTokens) -> Tokens when
+ AbsTerm :: abstract_expr(),
+ MoreTokens :: [token()],
+ Tokens :: [token()].
tokens({char,L,C}, More) -> [{char,L,C}|More];
tokens({integer,L,N}, More) -> [{integer,L,N}|More];
tokens({float,L,F}, More) -> [{float,L,F}|More];
diff --git a/lib/stdlib/src/erl_pp.erl b/lib/stdlib/src/erl_pp.erl
index 66c80a45cb..7dc19f2e9b 100644
--- a/lib/stdlib/src/erl_pp.erl
+++ b/lib/stdlib/src/erl_pp.erl
@@ -31,25 +31,53 @@
-define(MAXLINE, 72).
+-type(hook_function() :: none
+ | fun((Expr :: erl_parse:abstract_expr(),
+ CurrentIndentation :: integer(),
+ CurrentPrecedence :: non_neg_integer(),
+ HookFunction :: hook_function()) ->
+ io_lib:chars())).
+
%%%
%%% Exported functions
%%%
+-spec(form(Form) -> io_lib:chars() when
+ Form :: erl_parse:abstract_form()).
+
form(Thing) ->
form(Thing, none).
+-spec(form(Form, HookFunction) -> io_lib:chars() when
+ Form :: erl_parse:abstract_form(),
+ HookFunction :: hook_function()).
+
form(Thing, Hook) ->
frmt(lform(Thing, Hook)).
+-spec(attribute(Attribute) -> io_lib:chars() when
+ Attribute :: erl_parse:abstract_form()).
+
attribute(Thing) ->
attribute(Thing, none).
+-spec(attribute(Attribute, HookFunction) -> io_lib:chars() when
+ Attribute :: erl_parse:abstract_form(),
+ HookFunction :: hook_function()).
+
attribute(Thing, Hook) ->
frmt(lattribute(Thing, Hook)).
+-spec(function(Function) -> io_lib:chars() when
+ Function :: erl_parse:abstract_form()).
+
function(F) ->
function(F, none).
+-spec(function(Function, HookFunction) -> io_lib:chars() when
+ Function :: erl_parse:abstract_form(),
+ HookFunction :: hook_function()).
+
function(F, Hook) ->
frmt(lfunction(F, Hook)).
@@ -59,30 +87,67 @@ rule(R) ->
rule(R, Hook) ->
frmt(lrule(R, Hook)).
+-spec(guard(Guard) -> io_lib:chars() when
+ Guard :: [erl_parse:abstract_expr()]).
+
guard(Gs) ->
guard(Gs, none).
+-spec(guard(Guard, HookFunction) -> io_lib:chars() when
+ Guard :: [erl_parse:abstract_expr()],
+ HookFunction :: hook_function()).
+
guard(Gs, Hook) ->
frmt(lguard(Gs, Hook)).
+-spec(exprs(Expressions) -> io_lib:chars() when
+ Expressions :: [erl_parse:abstract_expr()]).
+
exprs(Es) ->
exprs(Es, 0, none).
+-spec(exprs(Expressions, HookFunction) -> io_lib:chars() when
+ Expressions :: [erl_parse:abstract_expr()],
+ HookFunction :: hook_function()).
+
exprs(Es, Hook) ->
exprs(Es, 0, Hook).
+-spec(exprs(Expressions, Indent, HookFunction) -> io_lib:chars() when
+ Expressions :: [erl_parse:abstract_expr()],
+ Indent :: integer(),
+ HookFunction :: hook_function()).
+
exprs(Es, I, Hook) ->
frmt({seq,[],[],[$,],lexprs(Es, Hook)}, I).
+-spec(expr(Expression) -> io_lib:chars() when
+ Expression :: erl_parse:abstract_expr()).
+
expr(E) ->
frmt(lexpr(E, 0, none)).
+-spec(expr(Expression, HookFunction) -> io_lib:chars() when
+ Expression :: erl_parse:abstract_expr(),
+ HookFunction :: hook_function()).
+
expr(E, Hook) ->
frmt(lexpr(E, 0, Hook)).
+-spec(expr(Expression, Indent, HookFunction) -> io_lib:chars() when
+ Expression :: erl_parse:abstract_expr(),
+ Indent :: integer(),
+ HookFunction :: hook_function()).
+
expr(E, I, Hook) ->
frmt(lexpr(E, 0, Hook), I).
+-spec(expr(Expression, Indent, Precedence, HookFunction) -> io_lib:chars() when
+ Expression :: erl_parse:abstract_expr(),
+ Indent :: integer(),
+ Precedence :: non_neg_integer(),
+ HookFunction :: hook_function()).
+
expr(E, I, P, Hook) ->
frmt(lexpr(E, P, Hook), I).
diff --git a/lib/stdlib/src/erl_scan.erl b/lib/stdlib/src/erl_scan.erl
index 18f64c46d0..718ca2e91a 100644
--- a/lib/stdlib/src/erl_scan.erl
+++ b/lib/stdlib/src/erl_scan.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -99,7 +99,8 @@
%%----------------------------------------------------------------------------
--spec format_error(Error :: term()) -> string().
+-spec format_error(ErrorDescriptor) -> string() when
+ ErrorDescriptor :: error_description().
format_error({string,Quote,Head}) ->
lists:flatten(["unterminated " ++ string_thing(Quote) ++
" starting with " ++
@@ -112,20 +113,33 @@ format_error({base,Base}) ->
format_error(Other) ->
lists:flatten(io_lib:write(Other)).
--type string_return() :: {'ok', tokens(), location()}
- | {'error', error_info(), location()}.
-
--spec string(String :: string()) -> string_return().
+-spec string(String) -> Return when
+ String :: string(),
+ Return :: {'ok', Tokens :: tokens(), EndLocation}
+ | {'error', ErrorInfo :: error_info(), ErrorLocation},
+ EndLocation :: location(),
+ ErrorLocation :: location().
string(String) ->
string(String, 1, []).
--spec string(String :: string(), StartLocation :: location()) ->
- string_return().
+-spec string(String, StartLocation) -> Return when
+ String :: string(),
+ Return :: {'ok', Tokens :: tokens(), EndLocation}
+ | {'error', ErrorInfo :: error_info(), ErrorLocation},
+ StartLocation :: location(),
+ EndLocation :: location(),
+ ErrorLocation :: location().
string(String, StartLocation) ->
string(String, StartLocation, []).
--spec string(String :: string(), StartLocation :: location(),
- Options :: options()) -> string_return().
+-spec string(String, StartLocation, Options) -> Return when
+ String :: string(),
+ Options :: options(),
+ Return :: {'ok', Tokens :: tokens(), EndLocation}
+ | {'error', ErrorInfo :: error_info(), ErrorLocation},
+ StartLocation :: location(),
+ EndLocation :: location(),
+ ErrorLocation :: location().
string(String, Line, Options) when ?STRING(String), ?ALINE(Line) ->
string1(String, options(Options), Line, no_col, []);
string(String, {Line,Column}, Options) when ?STRING(String),
@@ -136,29 +150,37 @@ string(String, {Line,Column}, Options) when ?STRING(String),
-type char_spec() :: string() | 'eof'.
-type cont_fun() :: fun((char_spec(), #erl_scan{}, line(), column(),
tokens(), any()) -> any()).
--opaque return_cont() :: {string(), column(), tokens(), line(),
- #erl_scan{}, cont_fun(), any()}.
--type cont() :: return_cont() | [].
--type tokens_result() :: {'ok', tokens(), location()}
- | {'eof', location()}
- | {'error', error_info(), location()}.
--type tokens_return() :: {'done', tokens_result(), char_spec()}
- | {'more', return_cont()}.
-
--spec tokens(Cont :: cont(), CharSpec :: char_spec(),
- StartLocation :: location()) -> tokens_return().
+-opaque return_cont() :: {erl_scan_continuation,
+ string(), column(), tokens(), line(),
+ #erl_scan{}, any(), cont_fun()}.
+-type tokens_result() :: {'ok', Tokens :: tokens(), EndLocation :: location()}
+ | {'eof', EndLocation :: location()}
+ | {'error', ErrorInfo :: error_info(),
+ EndLocation :: location()}.
+
+-spec tokens(Continuation, CharSpec, StartLocation) -> Return when
+ Continuation :: return_cont() | [],
+ CharSpec :: char_spec(),
+ StartLocation :: location(),
+ Return :: {'done',Result :: tokens_result(),LeftOverChars :: char_spec()}
+ | {'more', Continuation1 :: return_cont()}.
tokens(Cont, CharSpec, StartLocation) ->
tokens(Cont, CharSpec, StartLocation, []).
--spec tokens(Cont :: cont(), CharSpec :: char_spec(),
- StartLocation :: location(), Options :: options()) ->
- tokens_return().
+-spec tokens(Continuation, CharSpec, StartLocation, Options) -> Return when
+ Continuation :: return_cont() | [],
+ CharSpec :: char_spec(),
+ StartLocation :: location(),
+ Options :: options(),
+ Return :: {'done',Result :: tokens_result(),LeftOverChars :: char_spec()}
+ | {'more', Continuation1 :: return_cont()}.
tokens([], CharSpec, Line, Options) when ?ALINE(Line) ->
tokens1(CharSpec, options(Options), Line, no_col, [], fun scan/6, []);
tokens([], CharSpec, {Line,Column}, Options) when ?ALINE(Line),
?COLUMN(Column) ->
tokens1(CharSpec, options(Options), Line, Column, [], fun scan/6, []);
-tokens({Cs,Col,Toks,Line,St,Any,Fun}, CharSpec, _Loc, _Opts) ->
+tokens({erl_scan_continuation,Cs,Col,Toks,Line,St,Any,Fun},
+ CharSpec, _Loc, _Opts) ->
tokens1(Cs++CharSpec, St, Line, Col, Toks, Fun, Any).
-type attribute_item() :: 'column' | 'length' | 'line'
@@ -172,13 +194,22 @@ tokens({Cs,Col,Toks,Line,St,Any,Fun}, CharSpec, _Loc, _Opts) ->
-type token_info() :: {'category', category()} | {'symbol', symbol()}
| attribute_info().
--spec token_info(token()) -> [token_info()].
+-spec token_info(Token) -> TokenInfo when
+ Token :: token(),
+ TokenInfo :: [TokenInfoTuple :: token_info()].
token_info(Token) ->
Items = [category,column,length,line,symbol,text], % undefined order
token_info(Token, Items).
--spec token_info(token(), token_item()) -> token_info() | 'undefined';
- (token(), [token_item()]) -> [token_info()].
+-spec token_info(Token, TokenItem) -> TokenInfo | 'undefined' when
+ Token :: token(),
+ TokenItem :: token_item(),
+ TokenInfo :: TokenInfoTuple :: token_info();
+ (Token, TokenItems) -> [TokenInfo] when
+ Token :: token(),
+ TokenItems :: [TokenItem],
+ TokenItem :: token_item(),
+ TokenInfo :: [TokenInfoTuple :: token_info()].
token_info(_Token, []) ->
[];
token_info(Token, [Item|Items]) when is_atom(Item) ->
@@ -201,14 +232,23 @@ token_info({_Category,Attrs}, Item) ->
token_info({_Category,Attrs,_Symbol}, Item) ->
attributes_info(Attrs, Item).
--spec attributes_info(attributes()) -> [attribute_info()].
+-spec attributes_info(Attributes) -> AttributesInfo when
+ Attributes :: attributes(),
+ AttributesInfo :: [AttributeInfoTuple :: attribute_info()].
attributes_info(Attributes) ->
Items = [column,length,line,text], % undefined order
attributes_info(Attributes, Items).
--spec attributes_info(attributes(), attribute_item()) ->
- attribute_info() | 'undefined';
- (attributes(), [attribute_item()]) -> [attribute_info()].
+-spec attributes_info(Attributes, AttributeItem) ->
+ AttributeInfo | 'undefined' when
+ Attributes :: attributes(),
+ AttributeItem :: attribute_item(),
+ AttributeInfo :: AttributeInfoTuple :: attribute_info();
+ (Attributes, AttributeItems) -> [AttributeInfo] when
+ Attributes :: attributes(),
+ AttributeItems :: [AttributeItem],
+ AttributeItem :: attribute_item(),
+ AttributeInfo :: [AttributeInfoTuple :: attribute_info()].
attributes_info(_Attrs, []) ->
[];
attributes_info(Attrs, [A|As]) when is_atom(A) ->
@@ -265,9 +305,10 @@ attributes_info(Attrs, text=Item) ->
attributes_info(T1, T2) ->
erlang:error(badarg, [T1,T2]).
--type setlineattr_fun() :: fun((info_line()) -> info_line()).
-
--spec set_attribute('line', attributes(), setlineattr_fun()) -> attributes().
+-spec set_attribute(AttributeItem, Attributes, SetAttributeFun) -> Attributes when
+ AttributeItem :: 'line',
+ Attributes :: attributes(),
+ SetAttributeFun :: fun((info_line()) -> info_line()).
set_attribute(Tag, Attributes, Fun) when ?SETATTRFUN(Fun) ->
set_attr(Tag, Attributes, Fun).
@@ -374,7 +415,7 @@ set_attr(T1, T2, T3) ->
tokens1(Cs, St, Line, Col, Toks, Fun, Any) when ?STRING(Cs); Cs =:= eof ->
case Fun(Cs, St, Line, Col, Toks, Any) of
{more,{Cs0,Ncol,Ntoks,Nline,Nany,Nfun}} ->
- {more,{Cs0,Ncol,Ntoks,Nline,St,Nany,Nfun}};
+ {more,{erl_scan_continuation,Cs0,Ncol,Ntoks,Nline,St,Nany,Nfun}};
{ok,Toks0,eof,Nline,Ncol} ->
Res = case Toks0 of
[] ->
@@ -1285,7 +1326,7 @@ tabs(8) -> "\t\t\t\t\t\t\t\t";
tabs(9) -> "\t\t\t\t\t\t\t\t\t";
tabs(10) -> "\t\t\t\t\t\t\t\t\t\t".
--spec reserved_word(atom()) -> boolean().
+-spec reserved_word(Atom :: atom()) -> boolean().
reserved_word('after') -> true;
reserved_word('begin') -> true;
reserved_word('case') -> true;
diff --git a/lib/stdlib/src/ets.erl b/lib/stdlib/src/ets.erl
index 6e6e949e2c..afa914a456 100644
--- a/lib/stdlib/src/ets.erl
+++ b/lib/stdlib/src/ets.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -42,7 +42,7 @@
-export([i/0, i/1, i/2, i/3]).
--export_type([tab/0, tid/0]).
+-export_type([tab/0, tid/0, match_spec/0]).
%%-----------------------------------------------------------------------------
@@ -51,22 +51,9 @@
%% a similar definition is also in erl_types
-opaque tid() :: integer().
--type ext_info() :: 'md5sum' | 'object_count'.
--type protection() :: 'private' | 'protected' | 'public'.
--type type() :: 'bag' | 'duplicate_bag' | 'ordered_set' | 'set'.
-
--type table_info() :: {'name', atom()}
- | {'type', type()}
- | {'protection', protection()}
- | {'named_table', boolean()}
- | {'keypos', non_neg_integer()}
- | {'size', non_neg_integer()}
- | {'extended_info', [ext_info()]}
- | {'version', {non_neg_integer(), non_neg_integer()}}.
-
%% these ones are also defined in erl_bif_types
-type match_pattern() :: atom() | tuple().
--type match_specs() :: [{match_pattern(), [_], [_]}].
+-type match_spec() :: [{match_pattern(), [_], [_]}].
%%-----------------------------------------------------------------------------
@@ -86,6 +73,7 @@
%% insert/2
%% is_compiled_ms/1
%% last/1
+%% member/2
%% next/2
%% prev/2
%% rename/2
@@ -101,11 +89,14 @@
%% select/1
%% select/2
%% select/3
+%% select_count/2
%% select_reverse/1
%% select_reverse/2
%% select_reverse/3
%% select_delete/2
+%% setopts/2
%% update_counter/3
+%% update_element/3
%%
-opaque comp_match_spec() :: any(). %% this one is REALLY opaque
@@ -119,7 +110,9 @@ match_spec_run(List, CompiledMS) ->
| {tab(),integer(),integer(),binary(),list(),integer()}
| {tab(),_,_,integer(),binary(),list(),integer(),integer()}.
--spec repair_continuation(continuation(), match_specs()) -> continuation().
+-spec repair_continuation(Continuation, MatchSpec) -> Continuation when
+ Continuation :: continuation(),
+ MatchSpec :: match_spec().
%% $end_of_table is an allowed continuation in ets...
repair_continuation('$end_of_table', _) ->
@@ -153,7 +146,9 @@ repair_continuation(Untouched = {Table,N1,N2,Bin,L,N3}, MS)
{Table,N1,N2,ets:match_spec_compile(MS),L,N3}
end.
--spec fun2ms(function()) -> match_specs().
+-spec fun2ms(LiteralFun) -> MatchSpec when
+ LiteralFun :: function(),
+ MatchSpec :: match_spec().
fun2ms(ShellFun) when is_function(ShellFun) ->
%% Check that this is really a shell fun...
@@ -177,7 +172,13 @@ fun2ms(ShellFun) when is_function(ShellFun) ->
shell]}})
end.
--spec foldl(fun((_, term()) -> term()), term(), tab()) -> term().
+-spec foldl(Function, Acc0, Tab) -> Acc1 when
+ Function :: fun((Element :: term(), AccIn) -> AccOut),
+ Tab :: tab(),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term().
foldl(F, Accu, T) ->
ets:safe_fixtable(T, true),
@@ -198,7 +199,13 @@ do_foldl(F, Accu0, Key, T) ->
ets:next(T, Key), T)
end.
--spec foldr(fun((_, term()) -> term()), term(), tab()) -> term().
+-spec foldr(Function, Acc0, Tab) -> Acc1 when
+ Function :: fun((Element :: term(), AccIn) -> AccOut),
+ Tab :: tab(),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term().
foldr(F, Accu, T) ->
ets:safe_fixtable(T, true),
@@ -219,7 +226,9 @@ do_foldr(F, Accu0, Key, T) ->
ets:prev(T, Key), T)
end.
--spec from_dets(tab(), dets:tab_name()) -> 'true'.
+-spec from_dets(Tab, DetsTab) -> 'true' when
+ Tab :: tab(),
+ DetsTab :: dets:tab_name().
from_dets(EtsTable, DetsTable) ->
case (catch dets:to_ets(DetsTable, EtsTable)) of
@@ -235,7 +244,9 @@ from_dets(EtsTable, DetsTable) ->
erlang:error(Unexpected,[EtsTable,DetsTable])
end.
--spec to_dets(tab(), dets:tab_name()) -> dets:tab_name().
+-spec to_dets(Tab, DetsTab) -> DetsTab when
+ Tab :: tab(),
+ DetsTab :: dets:tab_name().
to_dets(EtsTable, DetsTable) ->
case (catch dets:from_ets(DetsTable, EtsTable)) of
@@ -251,8 +262,11 @@ to_dets(EtsTable, DetsTable) ->
erlang:error(Unexpected,[EtsTable,DetsTable])
end.
--spec test_ms(tuple(), match_specs()) ->
- {'ok', term()} | {'error', [{'warning'|'error', string()}]}.
+-spec test_ms(Tuple, MatchSpec) -> {'ok', Result} | {'error', Errors} when
+ Tuple :: tuple(),
+ MatchSpec :: match_spec(),
+ Result :: term(),
+ Errors :: [{'warning'|'error', string()}].
test_ms(Term, MS) ->
case erlang:match_spec_test(Term, MS, table) of
@@ -262,7 +276,11 @@ test_ms(Term, MS) ->
Error
end.
--spec init_table(tab(), fun(('read' | 'close') -> term())) -> 'true'.
+-spec init_table(Tab, InitFun) -> 'true' when
+ Tab :: tab(),
+ InitFun :: fun((Arg) -> Res),
+ Arg :: 'read' | 'close',
+ Res :: 'end_of_input' | {Objects :: [term()], InitFun} | term().
init_table(Table, Fun) ->
ets:delete_all_objects(Table),
@@ -287,7 +305,9 @@ init_table_sub(Table, [H|T]) ->
ets:insert(Table, H),
init_table_sub(Table, T).
--spec match_delete(tab(), match_pattern()) -> 'true'.
+-spec match_delete(Tab, Pattern) -> 'true' when
+ Tab :: tab(),
+ Pattern :: match_pattern().
match_delete(Table, Pattern) ->
ets:select_delete(Table, [{Pattern,[],[true]}]),
@@ -295,7 +315,9 @@ match_delete(Table, Pattern) ->
%% Produce a list of tuples from a table
--spec tab2list(tab()) -> [tuple()].
+-spec tab2list(Tab) -> [Object] when
+ Tab :: tab(),
+ Object :: tuple().
tab2list(T) ->
ets:match_object(T, '_').
@@ -334,15 +356,21 @@ do_filter(Tab, Key, F, A, Ack) ->
md5sum = false :: boolean()
}).
--type fname() :: string() | atom().
--type t2f_option() :: {'extended_info', [ext_info()]}.
-
--spec tab2file(tab(), fname()) -> 'ok' | {'error', term()}.
+-spec tab2file(Tab, Filename) -> 'ok' | {'error', Reason} when
+ Tab :: tab(),
+ Filename :: file:name(),
+ Reason :: term().
tab2file(Tab, File) ->
tab2file(Tab, File, []).
--spec tab2file(tab(), fname(), [t2f_option()]) -> 'ok' | {'error', term()}.
+-spec tab2file(Tab, Filename, Options) -> 'ok' | {'error', Reason} when
+ Tab :: tab(),
+ Filename :: file:name(),
+ Options :: [Option],
+ Option :: {'extended_info', [ExtInfo]},
+ ExtInfo :: 'md5sum' | 'object_count',
+ Reason :: term().
tab2file(Tab, File, Options) ->
try
@@ -501,14 +529,20 @@ parse_ft_info_options(_,Malformed) ->
%% Opt := {verify,boolean()}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--type f2t_option() :: {'verify', boolean()}.
-
--spec file2tab(fname()) -> {'ok', tab()} | {'error', term()}.
+-spec file2tab(Filename) -> {'ok', Tab} | {'error', Reason} when
+ Filename :: file:name(),
+ Tab :: tab(),
+ Reason :: term().
file2tab(File) ->
file2tab(File, []).
--spec file2tab(fname(), [f2t_option()]) -> {'ok', tab()} | {'error', term()}.
+-spec file2tab(Filename, Options) -> {'ok', Tab} | {'error', Reason} when
+ Filename :: file:name(),
+ Tab :: tab(),
+ Options :: [Option],
+ Option :: {'verify', boolean()},
+ Reason :: term().
file2tab(File, Opts) ->
try
@@ -895,7 +929,22 @@ named_table(false) -> [].
%% information
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec tabfile_info(fname()) -> {'ok', [table_info()]} | {'error', term()}.
+-spec tabfile_info(Filename) -> {'ok', TableInfo} | {'error', Reason} when
+ Filename :: file:name(),
+ TableInfo :: [InfoItem],
+ InfoItem :: {'name', atom()}
+ | {'type', Type}
+ | {'protection', Protection}
+ | {'named_table', boolean()}
+ | {'keypos', non_neg_integer()}
+ | {'size', non_neg_integer()}
+ | {'extended_info', [ExtInfo]}
+ | {'version', {Major :: non_neg_integer(),
+ Minor :: non_neg_integer()}},
+ ExtInfo :: 'md5sum' | 'object_count',
+ Type :: 'bag' | 'duplicate_bag' | 'ordered_set' | 'set',
+ Protection :: 'private' | 'protected' | 'public',
+ Reason :: term().
tabfile_info(File) when is_list(File) ; is_atom(File) ->
try
@@ -932,20 +981,22 @@ tabfile_info(File) when is_list(File) ; is_atom(File) ->
{error,ExReason}
end.
--type qlc__query_handle() :: term(). %% XXX: belongs in 'qlc'
-
--type num_objects() :: 'default' | pos_integer().
--type trav_method() :: 'first_next' | 'last_prev'
- | 'select' | {'select', match_specs()}.
--type table_option() :: {'n_objects', num_objects()}
- | {'traverse', trav_method()}.
-
--spec table(tab()) -> qlc__query_handle().
+-spec table(Tab) -> QueryHandle when
+ Tab :: tab(),
+ QueryHandle :: qlc:query_handle().
table(Tab) ->
table(Tab, []).
--spec table(tab(), table_option() | [table_option()]) -> qlc__query_handle().
+-spec table(Tab, Options) -> QueryHandle when
+ Tab :: tab(),
+ QueryHandle :: qlc:query_handle(),
+ Options :: [Option] | Option,
+ Option :: {'n_objects', NObjects}
+ | {'traverse', TraverseMethod},
+ NObjects :: 'default' | pos_integer(),
+ TraverseMethod :: 'first_next' | 'last_prev'
+ | 'select' | {'select', MatchSpec :: match_spec()}.
table(Tab, Opts) ->
case options(Opts, [traverse, n_objects]) of
@@ -1135,7 +1186,8 @@ to_string(X) ->
lists:flatten(io_lib:format("~p", [X])).
%% view a specific table
--spec i(tab()) -> 'ok'.
+-spec i(Tab) -> 'ok' when
+ Tab :: tab().
i(Tab) ->
i(Tab, 40).
diff --git a/lib/stdlib/src/file_sorter.erl b/lib/stdlib/src/file_sorter.erl
index 2a5b08b581..3f31852afc 100644
--- a/lib/stdlib/src/file_sorter.erl
+++ b/lib/stdlib/src/file_sorter.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2001-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2001-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
@@ -50,12 +50,68 @@
%%% Exported functions
%%%
+-export_type([reason/0]).
+
+-type(file_name() :: file:name()).
+-type(file_names() :: [file:name()]).
+-type(i_command() :: read | close).
+-type(i_reply() :: end_of_input | {end_of_input, value()}
+ | {[object()], infun()} | input_reply()).
+-type(infun() :: fun((i_command()) -> i_reply())).
+-type(input() :: file_names() | infun()).
+-type(input_reply() :: term()).
+-type(o_command() :: {value, value()} | [object()] | close).
+-type(o_reply() :: outfun() | output_reply()).
+-type(object() :: term() | binary()).
+-type(outfun() :: fun((o_command()) -> o_reply())).
+-type(output() :: file_name() | outfun()).
+-type(output_reply() :: term()).
+-type(value() :: term()).
+
+-type(options() :: [option()] | option()).
+-type(option() :: {compressed, boolean()}
+ | {header, header_length()}
+ | {format, format()}
+ | {no_files, no_files()}
+ | {order, order()}
+ | {size, size()}
+ | {tmpdir, tmp_directory()}
+ | {unique, boolean()}).
+-type(format() :: binary_term | term | binary | format_fun()).
+-type(format_fun() :: fun((binary()) -> term())).
+-type(header_length() :: pos_integer()).
+-type(key_pos() :: pos_integer() | [pos_integer()]).
+-type(no_files() :: pos_integer()). % > 1
+-type(order() :: ascending | descending | order_fun()).
+-type(order_fun() :: fun((term(), term()) -> boolean())).
+-type(size() :: non_neg_integer()).
+-type(tmp_directory() :: [] | file:name()).
+
+-type(reason() :: bad_object
+ | {bad_object, file_name()}
+ | {bad_term, file_name()}
+ | {file_error, file_name(),
+ file:posix() | badarg | system_limit}
+ | {premature_eof, file_name()}).
+
+-spec(sort(FileName) -> Reply when
+ FileName :: file_name(),
+ Reply :: ok | {error, reason()} | input_reply() | output_reply()).
sort(FileName) ->
sort([FileName], FileName).
+-spec(sort(Input, Output) -> Reply when
+ Input :: input(),
+ Output :: output(),
+ Reply :: ok | {error, reason()} | input_reply() | output_reply()).
sort(Input, Output) ->
sort(Input, Output, []).
+-spec(sort(Input, Output, Options) -> Reply when
+ Input :: input(),
+ Output :: output(),
+ Options :: options(),
+ Reply :: ok | {error, reason()} | input_reply() | output_reply()).
sort(Input0, Output0, Options) ->
case {is_input(Input0), maybe_output(Output0), options(Options)} of
{{true,Input}, {true,Output}, #opts{}=Opts} ->
@@ -64,12 +120,27 @@ sort(Input0, Output0, Options) ->
badarg(culprit(tuple_to_list(T)), [Input0, Output0, Options])
end.
+-spec(keysort(KeyPos, FileName) -> Reply when
+ KeyPos :: key_pos(),
+ FileName :: file_name(),
+ Reply :: ok | {error, reason()} | input_reply() | output_reply()).
keysort(KeyPos, FileName) ->
keysort(KeyPos, [FileName], FileName).
+-spec(keysort(KeyPos, Input, Output) -> Reply when
+ KeyPos :: key_pos(),
+ Input :: input(),
+ Output :: output(),
+ Reply :: ok | {error, reason()} | input_reply() | output_reply()).
keysort(KeyPos, Input, Output) ->
keysort(KeyPos, Input, Output, []).
+-spec(keysort(KeyPos, Input, Output, Options) -> Reply when
+ KeyPos :: key_pos(),
+ Input :: input(),
+ Output :: output(),
+ Options :: options(),
+ Reply :: ok | {error, reason()} | input_reply() | output_reply()).
keysort(KeyPos, Input0, Output0, Options) ->
R = case {is_keypos(KeyPos), is_input(Input0),
maybe_output(Output0), options(Options)} of
@@ -89,9 +160,18 @@ keysort(KeyPos, Input0, Output0, Options) ->
badarg(culprit(O), [KeyPos, Input0, Output0, Options])
end.
+-spec(merge(FileNames, Output) -> Reply when
+ FileNames :: file_names(),
+ Output :: output(),
+ Reply :: ok | {error, reason()} | output_reply()).
merge(Files, Output) ->
merge(Files, Output, []).
+-spec(merge(FileNames, Output, Options) -> Reply when
+ FileNames :: file_names(),
+ Output :: output(),
+ Options :: options(),
+ Reply :: ok | {error, reason()} | output_reply()).
merge(Files0, Output0, Options) ->
case {is_files(Files0), maybe_output(Output0), options(Options)} of
%% size not used
@@ -101,9 +181,20 @@ merge(Files0, Output0, Options) ->
badarg(culprit(tuple_to_list(T)), [Files0, Output0, Options])
end.
+-spec(keymerge(KeyPos, FileNames, Output) -> Reply when
+ KeyPos :: key_pos(),
+ FileNames :: file_names(),
+ Output :: output(),
+ Reply :: ok | {error, reason()} | output_reply()).
keymerge(KeyPos, Files, Output) ->
keymerge(KeyPos, Files, Output, []).
+-spec(keymerge(KeyPos, FileNames, Output, Options) -> Reply when
+ KeyPos :: key_pos(),
+ FileNames :: file_names(),
+ Output :: output(),
+ Options :: options(),
+ Reply :: ok | {error, reason()} | output_reply()).
keymerge(KeyPos, Files0, Output0, Options) ->
R = case {is_keypos(KeyPos), is_files(Files0),
maybe_output(Output0), options(Options)} of
@@ -123,9 +214,21 @@ keymerge(KeyPos, Files0, Output0, Options) ->
badarg(culprit(O), [KeyPos, Files0, Output0, Options])
end.
+-spec(check(FileName) -> Reply when
+ FileName :: file_name(),
+ Reply :: {ok, [Result]} | {error, reason()},
+ Result :: {FileName, TermPosition, term()},
+ TermPosition :: pos_integer()).
check(FileName) ->
check([FileName], []).
+-spec(check(FileNames, Options) -> Reply when
+ FileNames :: file_names(),
+ Options :: options(),
+ Reply :: {ok, [Result]} | {error, reason()},
+ Result :: {FileName, TermPosition, term()},
+ FileName :: file_name(),
+ TermPosition :: pos_integer()).
check(Files0, Options) ->
case {is_files(Files0), options(Options)} of
{{true,Files}, #opts{}=Opts} ->
@@ -134,9 +237,23 @@ check(Files0, Options) ->
badarg(culprit(tuple_to_list(T)), [Files0, Options])
end.
+-spec(keycheck(KeyPos, FileName) -> Reply when
+ KeyPos :: key_pos(),
+ FileName :: file_name(),
+ Reply :: {ok, [Result]} | {error, reason()},
+ Result :: {FileName, TermPosition, term()},
+ TermPosition :: pos_integer()).
keycheck(KeyPos, FileName) ->
keycheck(KeyPos, [FileName], []).
+-spec(keycheck(KeyPos, FileNames, Options) -> Reply when
+ KeyPos :: key_pos(),
+ FileNames :: file_names(),
+ Options :: options(),
+ Reply :: {ok, [Result]} | {error, reason()},
+ Result :: {FileName, TermPosition, term()},
+ FileName :: file_name(),
+ TermPosition :: pos_integer()).
keycheck(KeyPos, Files0, Options) ->
R = case {is_keypos(KeyPos), is_files(Files0), options(Options)} of
{_, _, #opts{format = binary}} ->
diff --git a/lib/stdlib/src/filelib.erl b/lib/stdlib/src/filelib.erl
index c845b61204..d532cea187 100644
--- a/lib/stdlib/src/filelib.erl
+++ b/lib/stdlib/src/filelib.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -40,13 +40,19 @@
erlang:error(UnUsUalVaRiAbLeNaMe)
end).
+-type filename() :: file:name().
+-type dirname() :: filename().
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec wildcard(file:name()) -> [file:filename()].
+-spec wildcard(Wildcard) -> [file:filename()] when
+ Wildcard :: filename() | dirname().
wildcard(Pattern) when is_list(Pattern) ->
?HANDLE_ERROR(do_wildcard(Pattern, file)).
--spec wildcard(file:name(), file:name() | atom()) -> [file:filename()].
+-spec wildcard(Wildcard, Cwd) -> [file:filename()] when
+ Wildcard :: filename() | dirname(),
+ Cwd :: dirname().
wildcard(Pattern, Cwd) when is_list(Pattern), (is_list(Cwd) or is_binary(Cwd)) ->
?HANDLE_ERROR(do_wildcard(Pattern, Cwd, file));
wildcard(Pattern, Mod) when is_list(Pattern), is_atom(Mod) ->
@@ -57,7 +63,8 @@ wildcard(Pattern, Cwd, Mod)
when is_list(Pattern), (is_list(Cwd) or is_binary(Cwd)), is_atom(Mod) ->
?HANDLE_ERROR(do_wildcard(Pattern, Cwd, Mod)).
--spec is_dir(file:name()) -> boolean().
+-spec is_dir(Name) -> boolean() when
+ Name :: filename() | dirname().
is_dir(Dir) ->
do_is_dir(Dir, file).
@@ -65,7 +72,8 @@ is_dir(Dir) ->
is_dir(Dir, Mod) when is_atom(Mod) ->
do_is_dir(Dir, Mod).
--spec is_file(file:name()) -> boolean().
+-spec is_file(Name) -> boolean() when
+ Name :: filename() | dirname().
is_file(File) ->
do_is_file(File, file).
@@ -73,7 +81,8 @@ is_file(File) ->
is_file(File, Mod) when is_atom(Mod) ->
do_is_file(File, Mod).
--spec is_regular(file:name()) -> boolean().
+-spec is_regular(Name) -> boolean() when
+ Name :: filename().
is_regular(File) ->
do_is_regular(File, file).
@@ -81,7 +90,13 @@ is_regular(File) ->
is_regular(File, Mod) when is_atom(Mod) ->
do_is_regular(File, Mod).
--spec fold_files(file:name(), string(), boolean(), fun((_,_) -> _), _) -> _.
+-spec fold_files(Dir, RegExp, Recursive, Fun, AccIn) -> AccOut when
+ Dir :: dirname(),
+ RegExp :: string(),
+ Recursive :: boolean(),
+ Fun :: fun((F :: file:filename(), AccIn) -> AccOut),
+ AccIn :: term(),
+ AccOut :: term().
fold_files(Dir, RegExp, Recursive, Fun, Acc) ->
do_fold_files(Dir, RegExp, Recursive, Fun, Acc, file).
@@ -89,7 +104,8 @@ fold_files(Dir, RegExp, Recursive, Fun, Acc) ->
fold_files(Dir, RegExp, Recursive, Fun, Acc, Mod) when is_atom(Mod) ->
do_fold_files(Dir, RegExp, Recursive, Fun, Acc, Mod).
--spec last_modified(file:name()) -> file:date_time() | 0.
+-spec last_modified(Name) -> file:date_time() | 0 when
+ Name :: filename() | dirname().
last_modified(File) ->
do_last_modified(File, file).
@@ -97,7 +113,8 @@ last_modified(File) ->
last_modified(File, Mod) when is_atom(Mod) ->
do_last_modified(File, Mod).
--spec file_size(file:name()) -> non_neg_integer().
+-spec file_size(Filename) -> non_neg_integer() when
+ Filename :: filename().
file_size(File) ->
do_file_size(File, file).
@@ -237,7 +254,9 @@ do_file_size(File, Mod) ->
%% +type X = filename() | dirname()
%% ensures that the directory name required to create D exists
--spec ensure_dir(file:name()) -> 'ok' | {'error', file:posix()}.
+-spec ensure_dir(Name) -> 'ok' | {'error', Reason} when
+ Name :: filename() | dirname(),
+ Reason :: file:posix().
ensure_dir("/") ->
ok;
ensure_dir(F) ->
diff --git a/lib/stdlib/src/filename.erl b/lib/stdlib/src/filename.erl
index 24abf1e977..1cb9e4a25e 100644
--- a/lib/stdlib/src/filename.erl
+++ b/lib/stdlib/src/filename.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
+%% 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
@@ -61,12 +61,15 @@
%% (for WIN32): absname("/") -> "D:/"
--spec absname(file:name()) -> file:filename().
+-spec absname(Filename) -> file:filename() when
+ Filename :: file:name().
absname(Name) ->
{ok, Cwd} = file:get_cwd(),
absname(Name, Cwd).
--spec absname(file:name(), file:filename()) -> file:filename().
+-spec absname(Filename, Dir) -> file:filename() when
+ Filename :: file:name(),
+ Dir :: file:filename().
absname(Name, AbsBase) when is_binary(Name), is_list(AbsBase) ->
absname(Name,filename_string_to_binary(AbsBase));
absname(Name, AbsBase) when is_list(Name), is_binary(AbsBase) ->
@@ -119,7 +122,9 @@ absname_vr([[X, $:]|Name], _, _AbsBase) ->
%% This is just a join/2, but assumes that
%% AbsBase must be absolute and Name must be relative.
--spec absname_join(file:filename(), file:name()) -> file:filename().
+-spec absname_join(Dir, Filename) -> file:filename() when
+ Dir :: file:filename(),
+ Filename :: file:name().
absname_join(AbsBase, Name) ->
join(AbsBase, flatten(Name)).
@@ -131,7 +136,8 @@ absname_join(AbsBase, Name) ->
%% basename("/usr/foo/") -> "foo" (trailing slashes ignored)
%% basename("/") -> []
--spec basename(file:name()) -> file:filename().
+-spec basename(Filename) -> file:filename() when
+ Filename :: file:name().
basename(Name) when is_binary(Name) ->
case os:type() of
{win32,_} ->
@@ -192,7 +198,9 @@ skip_prefix(Name, _) ->
%% rootname(basename("xxx.jam")) -> "xxx"
%% rootname(basename("xxx.erl")) -> "xxx"
--spec basename(file:name(), file:name()) -> file:filename().
+-spec basename(Filename, Ext) -> file:filename() when
+ Filename :: file:name(),
+ Ext :: file:name().
basename(Name, Ext) when is_binary(Name), is_list(Ext) ->
basename(Name,filename_string_to_binary(Ext));
basename(Name, Ext) when is_list(Name), is_binary(Ext) ->
@@ -240,7 +248,8 @@ basename([], _Ext, Tail, _DrvSep2) ->
%% Example: dirname("/usr/src/kalle.erl") -> "/usr/src",
%% dirname("kalle.erl") -> "."
--spec dirname(file:name()) -> file:filename().
+-spec dirname(Filename) -> file:filename() when
+ Filename :: file:name().
dirname(Name) when is_binary(Name) ->
{Dsep,Drivesep} = separators(),
SList = case Dsep of
@@ -332,7 +341,8 @@ dirjoin1([H|T],Acc,Sep) ->
%%
%% On Windows: fn:dirname("\\usr\\src/kalle.erl") -> "/usr/src"
--spec extension(file:name()) -> file:filename().
+-spec extension(Filename) -> file:filename() when
+ Filename :: file:name().
extension(Name) when is_binary(Name) ->
{Dsep,_} = separators(),
SList = case Dsep of
@@ -374,7 +384,8 @@ extension([], Result, _OsType) ->
%% Joins a list of filenames with directory separators.
--spec join([file:filename()]) -> file:filename().
+-spec join(Components) -> file:filename() when
+ Components :: [file:filename()].
join([Name1, Name2|Rest]) ->
join([join(Name1, Name2)|Rest]);
join([Name]) when is_list(Name) ->
@@ -386,7 +397,9 @@ join([Name]) when is_atom(Name) ->
%% Joins two filenames with directory separators.
--spec join(file:filename(), file:filename()) -> file:filename().
+-spec join(Name1, Name2) -> file:filename() when
+ Name1 :: file:filename(),
+ Name2 :: file:filename().
join(Name1, Name2) when is_list(Name1), is_list(Name2) ->
OsType = major_os_type(),
case pathtype(Name2) of
@@ -494,7 +507,8 @@ append(Dir, Name) ->
%% current working volume. (Windows only)
%% Example: a:bar.erl, /temp/foo.erl
--spec pathtype(file:name()) -> 'absolute' | 'relative' | 'volumerelative'.
+-spec pathtype(Path) -> 'absolute' | 'relative' | 'volumerelative' when
+ Path :: file:name().
pathtype(Atom) when is_atom(Atom) ->
pathtype(atom_to_list(Atom));
pathtype(Name) when is_list(Name) or is_binary(Name) ->
@@ -547,7 +561,8 @@ win32_pathtype(_) -> relative.
%% Examples: rootname("/jam.src/kalle") -> "/jam.src/kalle"
%% rootname("/jam.src/foo.erl") -> "/jam.src/foo"
--spec rootname(file:name()) -> file:filename().
+-spec rootname(Filename) -> file:filename() when
+ Filename :: file:name().
rootname(Name) when is_binary(Name) ->
list_to_binary(rootname(binary_to_list(Name))); % No need to handle unicode, . is < 128
rootname(Name0) ->
@@ -576,7 +591,9 @@ rootname([], Root, _Ext, _OsType) ->
%% Examples: rootname("/jam.src/kalle.jam", ".erl") -> "/jam.src/kalle.jam"
%% rootname("/jam.src/foo.erl", ".erl") -> "/jam.src/foo"
--spec rootname(file:name(), file:name()) -> file:filename().
+-spec rootname(Filename, Ext) -> file:filename() when
+ Filename :: file:name(),
+ Ext :: file:name().
rootname(Name, Ext) when is_binary(Name), is_binary(Ext) ->
list_to_binary(rootname(binary_to_list(Name),binary_to_list(Ext)));
rootname(Name, Ext) when is_binary(Name) ->
@@ -602,7 +619,9 @@ rootname2([Char|Rest], Ext, Result) when is_integer(Char) ->
%% split("foo/bar") -> ["foo", "bar"]
%% split("a:\\msdev\\include") -> ["a:/", "msdev", "include"]
--spec split(file:name()) -> [file:filename()].
+-spec split(Filename) -> Components when
+ Filename :: file:name(),
+ Components :: [file:filename()].
split(Name) when is_binary(Name) ->
case os:type() of
{win32, _} -> win32_splitb(Name);
@@ -695,7 +714,8 @@ split([], Comp, Components, OsType) ->
%% will be converted to backslashes. On all platforms, the
%% name will be normalized as done by join/1.
--spec nativename(file:filename()) -> file:filename().
+-spec nativename(Path) -> file:filename() when
+ Path :: file:filename().
nativename(Name0) ->
Name = join([Name0]), %Normalize.
case os:type() of
@@ -747,12 +767,17 @@ separators() ->
%% The paths in the {outdir, Path} and {i, Path} options are guaranteed
%% to be absolute.
--type rule() :: {string(), string()}.
--type ecode() :: 'non_existing' | 'preloaded' | 'interpreted'.
--type option() :: {'i', string()} | {'outdir', string()} | {'d', atom()}.
-
--spec find_src(atom() | string()) ->
- {string(), [option()]} | {'error', {ecode(), atom()}}.
+-spec find_src(Beam) -> {SourceFile, Options}
+ | {error, {ErrorReason, Module}} when
+ Beam :: Module | Filename,
+ Filename :: atom() | string(),
+ Module :: module(),
+ SourceFile :: string(),
+ Options :: [Option],
+ Option :: {'i', Path :: string()}
+ | {'outdir', Path :: string()}
+ | {'d', atom()},
+ ErrorReason :: 'non_existing' | 'preloaded' | 'interpreted'.
find_src(Mod) ->
Default = [{"", ""}, {"ebin", "src"}, {"ebin", "esrc"}],
Rules =
@@ -763,8 +788,18 @@ find_src(Mod) ->
end,
find_src(Mod, Rules).
--spec find_src(atom() | string(), [rule()]) ->
- {string(), [option()]} | {'error', {ecode(), atom()}}.
+-spec find_src(Beam, Rules) -> {SourceFile, Options}
+ | {error, {ErrorReason, Module}} when
+ Beam :: Module | Filename,
+ Filename :: atom() | string(),
+ Rules :: [{BinSuffix :: string(), SourceSuffix :: string()}],
+ Module :: module(),
+ SourceFile :: string(),
+ Options :: [Option],
+ Option :: {'i', Path :: string()}
+ | {'outdir', Path :: string()}
+ | {'d', atom()},
+ ErrorReason :: 'non_existing' | 'preloaded' | 'interpreted'.
find_src(Mod, Rules) when is_atom(Mod) ->
find_src(atom_to_list(Mod), Rules);
find_src(File0, Rules) when is_list(File0) ->
@@ -890,7 +925,8 @@ major_os_type() ->
%% flatten(List)
%% Flatten a list, also accepting atoms.
--spec flatten(file:name()) -> file:filename().
+-spec flatten(Filename) -> file:filename() when
+ Filename :: file:name().
flatten(Bin) when is_binary(Bin) ->
Bin;
flatten(List) ->
diff --git a/lib/stdlib/src/gb_sets.erl b/lib/stdlib/src/gb_sets.erl
index fc5beb28b0..91d21d869c 100644
--- a/lib/stdlib/src/gb_sets.erl
+++ b/lib/stdlib/src/gb_sets.erl
@@ -197,6 +197,7 @@
%% Some types.
-type gb_set_node() :: 'nil' | {term(), _, _}.
+-opaque iter() :: [gb_set_node()].
%% A declaration equivalent to the following is currently hard-coded
%% in erl_types.erl
@@ -205,38 +206,47 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec empty() -> gb_set().
+-spec empty() -> Set when
+ Set :: gb_set().
empty() ->
{0, nil}.
--spec new() -> gb_set().
+-spec new() -> Set when
+ Set :: gb_set().
new() -> empty().
--spec is_empty(gb_set()) -> boolean().
+-spec is_empty(Set) -> boolean() when
+ Set :: gb_set().
is_empty({0, nil}) ->
true;
is_empty(_) ->
false.
--spec size(gb_set()) -> non_neg_integer().
+-spec size(Set) -> non_neg_integer() when
+ Set :: gb_set().
size({Size, _}) ->
Size.
--spec singleton(term()) -> gb_set().
+-spec singleton(Element) -> gb_set() when
+ Element :: term().
singleton(Key) ->
{1, {Key, nil, nil}}.
--spec is_element(term(), gb_set()) -> boolean().
+-spec is_element(Element, Set) -> boolean() when
+ Element :: term(),
+ Set :: gb_set().
is_element(Key, S) ->
is_member(Key, S).
--spec is_member(term(), gb_set()) -> boolean().
+-spec is_member(Element, Set) -> boolean() when
+ Element :: term(),
+ Set :: gb_set().
is_member(Key, {_, T}) ->
is_member_1(Key, T).
@@ -250,7 +260,10 @@ is_member_1(_, {_, _, _}) ->
is_member_1(_, nil) ->
false.
--spec insert(term(), gb_set()) -> gb_set().
+-spec insert(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
insert(Key, {S, T}) ->
S1 = S + 1,
@@ -306,7 +319,9 @@ count({_, Sm, Bi}) ->
count(nil) ->
{1, 0}.
--spec balance(gb_set()) -> gb_set().
+-spec balance(Set1) -> Set2 when
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
balance({S, T}) ->
{S, balance(T, S)}.
@@ -331,12 +346,18 @@ balance_list_1([Key | L], 1) ->
balance_list_1(L, 0) ->
{nil, L}.
--spec add_element(term(), gb_set()) -> gb_set().
+-spec add_element(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
add_element(X, S) ->
add(X, S).
--spec add(term(), gb_set()) -> gb_set().
+-spec add(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
add(X, S) ->
case is_member(X, S) of
@@ -346,23 +367,33 @@ add(X, S) ->
insert(X, S)
end.
--spec from_list([term()]) -> gb_set().
+-spec from_list(List) -> Set when
+ List :: [term()],
+ Set :: gb_set().
from_list(L) ->
from_ordset(ordsets:from_list(L)).
--spec from_ordset([term()]) -> gb_set().
+-spec from_ordset(List) -> Set when
+ List :: [term()],
+ Set :: gb_set().
from_ordset(L) ->
S = length(L),
{S, balance_list(L, S)}.
--spec del_element(term(), gb_set()) -> gb_set().
+-spec del_element(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
del_element(Key, S) ->
delete_any(Key, S).
--spec delete_any(term(), gb_set()) -> gb_set().
+-spec delete_any(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
delete_any(Key, S) ->
case is_member(Key, S) of
@@ -372,7 +403,10 @@ delete_any(Key, S) ->
S
end.
--spec delete(term(), gb_set()) -> gb_set().
+-spec delete(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
delete(Key, {S, T}) ->
{S - 1, delete_1(Key, T)}.
@@ -394,7 +428,10 @@ merge(Smaller, Larger) ->
{Key, Larger1} = take_smallest1(Larger),
{Key, Smaller, Larger1}.
--spec take_smallest(gb_set()) -> {term(), gb_set()}.
+-spec take_smallest(Set1) -> {Element, Set2} when
+ Set1 :: gb_set(),
+ Set2 :: gb_set(),
+ Element :: term().
take_smallest({S, T}) ->
{Key, Larger} = take_smallest1(T),
@@ -406,7 +443,8 @@ take_smallest1({Key, Smaller, Larger}) ->
{Key1, Smaller1} = take_smallest1(Smaller),
{Key1, {Key, Smaller1, Larger}}.
--spec smallest(gb_set()) -> term().
+-spec smallest(Set) -> term() when
+ Set :: gb_set().
smallest({_, T}) ->
smallest_1(T).
@@ -416,7 +454,10 @@ smallest_1({Key, nil, _Larger}) ->
smallest_1({_Key, Smaller, _Larger}) ->
smallest_1(Smaller).
--spec take_largest(gb_set()) -> {term(), gb_set()}.
+-spec take_largest(Set1) -> {Element, Set2} when
+ Set1 :: gb_set(),
+ Set2 :: gb_set(),
+ Element :: term().
take_largest({S, T}) ->
{Key, Smaller} = take_largest1(T),
@@ -428,7 +469,8 @@ take_largest1({Key, Smaller, Larger}) ->
{Key1, Larger1} = take_largest1(Larger),
{Key1, {Key, Smaller, Larger1}}.
--spec largest(gb_set()) -> term().
+-spec largest(Set) -> term() when
+ Set :: gb_set().
largest({_, T}) ->
largest_1(T).
@@ -438,7 +480,9 @@ largest_1({Key, _Smaller, nil}) ->
largest_1({_Key, _Smaller, Larger}) ->
largest_1(Larger).
--spec to_list(gb_set()) -> [term()].
+-spec to_list(Set) -> List when
+ Set :: gb_set(),
+ List :: [term()].
to_list({_, T}) ->
to_list(T, []).
@@ -449,7 +493,9 @@ to_list({Key, Small, Big}, L) ->
to_list(Small, [Key | to_list(Big, L)]);
to_list(nil, L) -> L.
--spec iterator(gb_set()) -> [term()].
+-spec iterator(Set) -> Iter when
+ Set :: gb_set(),
+ Iter :: iter().
iterator({_, T}) ->
iterator(T, []).
@@ -464,7 +510,10 @@ iterator({_, L, _} = T, As) ->
iterator(nil, As) ->
As.
--spec next([term()]) -> {term(), [term()]} | 'none'.
+-spec next(Iter1) -> {Element, Iter2} | 'none' when
+ Iter1 :: iter(),
+ Iter2 :: iter(),
+ Element :: term().
next([{X, _, T} | As]) ->
{X, iterator(T, As)};
@@ -494,7 +543,10 @@ next([]) ->
%% traversing the elements can be devised, but they all have higher
%% overhead.
--spec union(gb_set(), gb_set()) -> gb_set().
+-spec union(Set1, Set2) -> Set3 when
+ Set1 :: gb_set(),
+ Set2 :: gb_set(),
+ Set3 :: gb_set().
union({N1, T1}, {N2, T2}) when N2 < N1 ->
union(to_list_1(T2), N2, T1, N1);
@@ -596,7 +648,9 @@ balance_revlist_1([Key | L], 1) ->
balance_revlist_1(L, 0) ->
{nil, L}.
--spec union([gb_set()]) -> gb_set().
+-spec union(SetList) -> Set when
+ SetList :: [gb_set(),...],
+ Set :: gb_set().
union([S | Ss]) ->
union_list(S, Ss);
@@ -609,7 +663,10 @@ union_list(S, []) -> S.
%% The rest is modelled on the above.
--spec intersection(gb_set(), gb_set()) -> gb_set().
+-spec intersection(Set1, Set2) -> Set3 when
+ Set1 :: gb_set(),
+ Set2 :: gb_set(),
+ Set3 :: gb_set().
intersection({N1, T1}, {N2, T2}) when N2 < N1 ->
intersection(to_list_1(T2), N2, T1, N1);
@@ -657,7 +714,9 @@ intersection_2([], _, As, S) ->
intersection_2(_, [], As, S) ->
{S, balance_revlist(As, S)}.
--spec intersection([gb_set(),...]) -> gb_set().
+-spec intersection(SetList) -> Set when
+ SetList :: [gb_set(),...],
+ Set :: gb_set().
intersection([S | Ss]) ->
intersection_list(S, Ss).
@@ -666,7 +725,9 @@ intersection_list(S, [S1 | Ss]) ->
intersection_list(intersection(S, S1), Ss);
intersection_list(S, []) -> S.
--spec is_disjoint(gb_set(), gb_set()) -> boolean().
+-spec is_disjoint(Set1, Set2) -> boolean() when
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
is_disjoint({N1, T1}, {N2, T2}) when N1 < N2 ->
is_disjoint_1(T1, T2);
@@ -694,12 +755,18 @@ is_disjoint_1(_, nil) ->
%% the sets. Therefore, we always build a new tree, and thus we need to
%% traverse the whole element list of the left operand.
--spec subtract(gb_set(), gb_set()) -> gb_set().
+-spec subtract(Set1, Set2) -> Set3 when
+ Set1 :: gb_set(),
+ Set2 :: gb_set(),
+ Set3 :: gb_set().
subtract(S1, S2) ->
difference(S1, S2).
--spec difference(gb_set(), gb_set()) -> gb_set().
+-spec difference(Set1, Set2) -> Set3 when
+ Set1 :: gb_set(),
+ Set2 :: gb_set(),
+ Set3 :: gb_set().
difference({N1, T1}, {N2, T2}) ->
difference(to_list_1(T1), N1, T2, N2).
@@ -747,7 +814,9 @@ difference_2(Xs, [], As, S) ->
%% Subset testing is much the same thing as set difference, but
%% without the construction of a new set.
--spec is_subset(gb_set(), gb_set()) -> boolean().
+-spec is_subset(Set1, Set2) -> boolean() when
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
is_subset({N1, T1}, {N2, T2}) ->
is_subset(to_list_1(T1), N1, T2, N2).
@@ -788,18 +857,28 @@ is_subset_2(_, []) ->
%% For compatibility with `sets':
--spec is_set(term()) -> boolean().
+-spec is_set(Term) -> boolean() when
+ Term :: term().
is_set({0, nil}) -> true;
is_set({N, {_, _, _}}) when is_integer(N), N >= 0 -> true;
is_set(_) -> false.
--spec filter(fun((term()) -> boolean()), gb_set()) -> gb_set().
+-spec filter(Pred, Set1) -> Set2 when
+ Pred :: fun((E :: term()) -> boolean()),
+ Set1 :: gb_set(),
+ Set2 :: gb_set().
filter(F, S) ->
from_ordset([X || X <- to_list(S), F(X)]).
--spec fold(fun((term(), term()) -> term()), term(), gb_set()) -> term().
+-spec fold(Function, Acc0, Set) -> Acc1 when
+ Function :: fun((E :: term(), AccIn) -> AccOut),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ Set :: gb_set().
fold(F, A, {_, T}) when is_function(F, 2) ->
fold_1(F, A, T).
diff --git a/lib/stdlib/src/gb_trees.erl b/lib/stdlib/src/gb_trees.erl
index d37786a100..6ad861ff5b 100644
--- a/lib/stdlib/src/gb_trees.erl
+++ b/lib/stdlib/src/gb_trees.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2001-2009. All Rights Reserved.
+%% Copyright Ericsson AB 2001-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
@@ -153,6 +153,7 @@
%% Some types.
-type gb_tree_node() :: 'nil' | {_, _, _, _}.
+-opaque iter() :: [gb_tree_node()].
%% A declaration equivalent to the following is currently hard-coded
%% in erl_types.erl
@@ -166,21 +167,26 @@
empty() ->
{0, nil}.
--spec is_empty(gb_tree()) -> boolean().
+-spec is_empty(Tree) -> boolean() when
+ Tree :: gb_tree().
is_empty({0, nil}) ->
true;
is_empty(_) ->
false.
--spec size(gb_tree()) -> non_neg_integer().
+-spec size(Tree) -> non_neg_integer() when
+ Tree :: gb_tree().
size({Size, _}) when is_integer(Size), Size >= 0 ->
Size.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec lookup(term(), gb_tree()) -> 'none' | {'value', term()}.
+-spec lookup(Key, Tree) -> 'none' | {'value', Val} when
+ Key :: term(),
+ Val :: term(),
+ Tree :: gb_tree().
lookup(Key, {_, T}) ->
lookup_1(Key, T).
@@ -205,7 +211,9 @@ lookup_1(_, nil) ->
%% This is a specialized version of `lookup'.
--spec is_defined(term(), gb_tree()) -> boolean().
+-spec is_defined(Key, Tree) -> boolean() when
+ Key :: term(),
+ Tree :: gb_tree().
is_defined(Key, {_, T}) ->
is_defined_1(Key, T).
@@ -223,7 +231,10 @@ is_defined_1(_, nil) ->
%% This is a specialized version of `lookup'.
--spec get(term(), gb_tree()) -> term().
+-spec get(Key, Tree) -> Val when
+ Key :: term(),
+ Tree :: gb_tree(),
+ Val :: term().
get(Key, {_, T}) ->
get_1(Key, T).
@@ -237,7 +248,11 @@ get_1(_, {_, Value, _, _}) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec update(term(), term(), gb_tree()) -> gb_tree().
+-spec update(Key, Val, Tree1) -> Tree2 when
+ Key :: term(),
+ Val :: term(),
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree().
update(Key, Val, {S, T}) ->
T1 = update_1(Key, Val, T),
@@ -254,7 +269,11 @@ update_1(Key, Value, {_, _, Smaller, Bigger}) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec insert(term(), term(), gb_tree()) -> gb_tree().
+-spec insert(Key, Val, Tree1) -> Tree2 when
+ Key :: term(),
+ Val :: term(),
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree().
insert(Key, Val, {S, T}) when is_integer(S) ->
S1 = S+1,
@@ -303,7 +322,11 @@ insert_1(Key, _, _, _) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec enter(term(), term(), gb_tree()) -> gb_tree().
+-spec enter(Key, Val, Tree1) -> Tree2 when
+ Key :: term(),
+ Val :: term(),
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree().
enter(Key, Val, T) ->
case is_defined(Key, T) of
@@ -326,7 +349,9 @@ count(nil) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec balance(gb_tree()) -> gb_tree().
+-spec balance(Tree1) -> Tree2 when
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree().
balance({S, T}) ->
{S, balance(T, S)}.
@@ -351,7 +376,9 @@ balance_list_1([{Key, Val} | L], 1) ->
balance_list_1(L, 0) ->
{nil, L}.
--spec from_orddict([{_,_}]) -> gb_tree().
+-spec from_orddict(List) -> Tree when
+ List :: [{Key :: term(), Val :: term()}],
+ Tree :: gb_tree().
from_orddict(L) ->
S = length(L),
@@ -359,7 +386,10 @@ from_orddict(L) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec delete_any(term(), gb_tree()) -> gb_tree().
+-spec delete_any(Key, Tree1) -> Tree2 when
+ Key :: term(),
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree().
delete_any(Key, T) ->
case is_defined(Key, T) of
@@ -371,7 +401,10 @@ delete_any(Key, T) ->
%%% delete. Assumes that key is present.
--spec delete(term(), gb_tree()) -> gb_tree().
+-spec delete(Key, Tree1) -> Tree2 when
+ Key :: term(),
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree().
delete(Key, {S, T}) when is_integer(S), S >= 0 ->
{S - 1, delete_1(Key, T)}.
@@ -397,7 +430,11 @@ merge(Smaller, Larger) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec take_smallest(gb_tree()) -> {term(), term(), gb_tree()}.
+-spec take_smallest(Tree1) -> {Key, Val, Tree2} when
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree(),
+ Key :: term(),
+ Val :: term().
take_smallest({Size, Tree}) when is_integer(Size), Size >= 0 ->
{Key, Value, Larger} = take_smallest1(Tree),
@@ -409,7 +446,10 @@ take_smallest1({Key, Value, Smaller, Larger}) ->
{Key1, Value1, Smaller1} = take_smallest1(Smaller),
{Key1, Value1, {Key, Value, Smaller1, Larger}}.
--spec smallest(gb_tree()) -> {term(), term()}.
+-spec smallest(Tree) -> {Key, Val} when
+ Tree :: gb_tree(),
+ Key :: term(),
+ Val :: term().
smallest({_, Tree}) ->
smallest_1(Tree).
@@ -419,7 +459,11 @@ smallest_1({Key, Value, nil, _Larger}) ->
smallest_1({_Key, _Value, Smaller, _Larger}) ->
smallest_1(Smaller).
--spec take_largest(gb_tree()) -> {term(), term(), gb_tree()}.
+-spec take_largest(Tree1) -> {Key, Val, Tree2} when
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree(),
+ Key :: term(),
+ Val :: term().
take_largest({Size, Tree}) when is_integer(Size), Size >= 0 ->
{Key, Value, Smaller} = take_largest1(Tree),
@@ -431,7 +475,10 @@ take_largest1({Key, Value, Smaller, Larger}) ->
{Key1, Value1, Larger1} = take_largest1(Larger),
{Key1, Value1, {Key, Value, Smaller, Larger1}}.
--spec largest(gb_tree()) -> {term(), term()}.
+-spec largest(Tree) -> {Key, Val} when
+ Tree :: gb_tree(),
+ Key :: term(),
+ Val :: term().
largest({_, Tree}) ->
largest_1(Tree).
@@ -443,7 +490,10 @@ largest_1({_Key, _Value, _Smaller, Larger}) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec to_list(gb_tree()) -> [{term(), term()}].
+-spec to_list(Tree) -> [{Key, Val}] when
+ Tree :: gb_tree(),
+ Key :: term(),
+ Val :: term().
to_list({_, T}) ->
to_list(T, []).
@@ -456,7 +506,9 @@ to_list(nil, L) -> L.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec keys(gb_tree()) -> [term()].
+-spec keys(Tree) -> [Key] when
+ Tree :: gb_tree(),
+ Key :: term().
keys({_, T}) ->
keys(T, []).
@@ -467,7 +519,9 @@ keys(nil, L) -> L.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec values(gb_tree()) -> [term()].
+-spec values(Tree) -> [Val] when
+ Tree :: gb_tree(),
+ Val :: term().
values({_, T}) ->
values(T, []).
@@ -478,7 +532,9 @@ values(nil, L) -> L.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec iterator(gb_tree()) -> [gb_tree_node()].
+-spec iterator(Tree) -> Iter when
+ Tree :: gb_tree(),
+ Iter :: iter().
iterator({_, T}) ->
iterator_1(T).
@@ -496,7 +552,11 @@ iterator({_, _, L, _} = T, As) ->
iterator(nil, As) ->
As.
--spec next([gb_tree_node()]) -> 'none' | {term(), term(), [gb_tree_node()]}.
+-spec next(Iter1) -> 'none' | {Key, Val, Iter2} when
+ Iter1 :: iter(),
+ Iter2 :: iter(),
+ Key :: term(),
+ Val :: term().
next([{X, V, _, T} | As]) ->
{X, V, iterator(T, As)};
@@ -505,7 +565,10 @@ next([]) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--spec map(fun((term(), term()) -> term()), gb_tree()) -> gb_tree().
+-spec map(Function, Tree1) -> Tree2 when
+ Function :: fun((K :: term(), V1 :: term()) -> V2 :: term()),
+ Tree1 :: gb_tree(),
+ Tree2 :: gb_tree().
map(F, {Size, Tree}) when is_function(F, 2) ->
{Size, map_1(F, Tree)}.
diff --git a/lib/stdlib/src/gen_event.erl b/lib/stdlib/src/gen_event.erl
index b00910771f..1c4a73680b 100644
--- a/lib/stdlib/src/gen_event.erl
+++ b/lib/stdlib/src/gen_event.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -44,6 +44,9 @@
system_code_change/4,
format_status/2]).
+-export_type([handler/0, handler_args/0, add_handler_ret/0,
+ del_handler_ret/0]).
+
-import(error_logger, [error_msg/2]).
-define(reply(X), From ! {element(2,Tag), X}).
@@ -113,7 +116,11 @@ behaviour_info(_Other) ->
%%---------------------------------------------------------------------------
--type handler() :: atom() | {atom(), term()}.
+-type handler() :: atom() | {atom(), term()}.
+-type handler_args() :: term().
+-type add_handler_ret() :: ok | term() | {'EXIT',term()}.
+-type del_handler_ret() :: ok | term() | {'EXIT',term()}.
+
-type emgr_name() :: {'local', atom()} | {'global', atom()}.
-type emgr_ref() :: atom() | {atom(), atom()} | {'global', atom()} | pid().
-type start_ret() :: {'ok', pid()} | {'error', term()}.
diff --git a/lib/stdlib/src/io.erl b/lib/stdlib/src/io.erl
index 6aeb076a0b..9f65bbfa3a 100644
--- a/lib/stdlib/src/io.erl
+++ b/lib/stdlib/src/io.erl
@@ -41,6 +41,7 @@
-type error_description() :: term(). % Whatever the io-server sends.
-type request_error() :: {'error',error_description()}.
+
%% XXX: Some uses of line() in this file may need to read erl_scan:location()
-type line() :: pos_integer().
@@ -66,12 +67,15 @@ o_request(Io, Request, Func) ->
end.
%% Put chars takes mixed *unicode* list from R13 onwards.
--spec put_chars(iodata()) -> 'ok'.
+-spec put_chars(CharData) -> 'ok' when
+ CharData :: unicode:chardata().
put_chars(Chars) ->
put_chars(default_output(), Chars).
--spec put_chars(device(), iodata()) -> 'ok'.
+-spec put_chars(IoDevice, IoData) -> 'ok' when
+ IoDevice :: device(),
+ IoData :: unicode:chardata().
put_chars(Io, Chars) ->
o_request(Io, {put_chars,unicode,Chars}, put_chars).
@@ -81,7 +85,8 @@ put_chars(Io, Chars) ->
nl() ->
nl(default_output()).
--spec nl(device()) -> 'ok'.
+-spec nl(IoDevice) -> 'ok' when
+ IoDevice :: device().
nl(Io) ->
% o_request(Io, {put_chars,io_lib:nl()}).
@@ -92,7 +97,8 @@ nl(Io) ->
columns() ->
columns(default_output()).
--spec columns(device()) -> {'ok', pos_integer()} | {'error', 'enotsup'}.
+-spec columns(IoDevice) -> {'ok', pos_integer()} | {'error', 'enotsup'} when
+ IoDevice :: device().
columns(Io) ->
case request(Io, {get_geometry,columns}) of
@@ -107,7 +113,8 @@ columns(Io) ->
rows() ->
rows(default_output()).
--spec rows(device()) -> {'ok', pos_integer()} | {'error', 'enotsup'}.
+-spec rows(IoDevice) -> {'ok', pos_integer()} | {'error', 'enotsup'} when
+ IoDevice :: device().
rows(Io) ->
case request(Io,{get_geometry,rows}) of
@@ -117,22 +124,36 @@ rows(Io) ->
{error,enotsup}
end.
--spec get_chars(prompt(), non_neg_integer()) -> iodata() | 'eof'.
+-spec get_chars(Prompt, Count) -> Data | 'eof' when
+ Prompt :: prompt(),
+ Count :: non_neg_integer(),
+ Data :: [unicode:unicode_char()] | unicode:unicode_binary().
get_chars(Prompt, N) ->
get_chars(default_input(), Prompt, N).
--spec get_chars(device(), prompt(), non_neg_integer()) -> iodata() | 'eof'.
+-spec get_chars(IoDevice, Prompt, Count) -> Data | 'eof' | {error, Reason} when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ Count :: non_neg_integer(),
+ Reason :: term(),
+ Data :: [unicode:unicode_char()] | unicode:unicode_binary().
get_chars(Io, Prompt, N) when is_integer(N), N >= 0 ->
request(Io, {get_chars,unicode,Prompt,N}).
--spec get_line(prompt()) -> iodata() | 'eof' | {'error', term()}.
+-spec get_line(Prompt) -> Data | 'eof' | {'error', Reason} when
+ Prompt :: prompt(),
+ Reason :: term(),
+ Data :: [unicode:unicode_char()] | unicode:unicode_binary().
get_line(Prompt) ->
get_line(default_input(), Prompt).
--spec get_line(device(), prompt()) -> iodata() | 'eof' | {'error', term()}.
+-spec get_line(IoDevice, Prompt) -> Data | 'eof' | {'error', term()} when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ Data :: [unicode:unicode_char()] | unicode:unicode_binary().
get_line(Io, Prompt) ->
request(Io, {get_line,unicode,Prompt}).
@@ -156,46 +177,62 @@ get_password(Io) ->
getopts() ->
getopts(default_input()).
--spec getopts(device()) -> [opt_pair()].
+-spec getopts(IoDevice) -> [opt_pair()] when
+ IoDevice :: device().
getopts(Io) ->
request(Io, getopts).
-type setopt() :: 'binary' | 'list' | opt_pair().
--spec setopts([setopt()]) -> 'ok' | {'error', term()}.
+-spec setopts(Opts) -> 'ok' | {'error', Reason} when
+ Opts :: [setopt()],
+ Reason :: term().
setopts(Opts) ->
setopts(default_input(), Opts).
--spec setopts(device(), [setopt()]) -> 'ok' | {'error', term()}.
+-spec setopts(IoDevice, Opts) -> 'ok' | {'error', Reason} when
+ IoDevice :: device(),
+ Opts :: [setopt()],
+ Reason :: term().
setopts(Io, Opts) ->
request(Io, {setopts, Opts}).
%% Writing and reading Erlang terms.
--spec write(term()) -> 'ok'.
+-spec write(Term) -> 'ok' when
+ Term :: term().
write(Term) ->
write(default_output(), Term).
--spec write(device(), term()) -> 'ok'.
+-spec write(IoDevice, Term) -> 'ok' when
+ IoDevice :: device(),
+ Term :: term().
write(Io, Term) ->
o_request(Io, {write,Term}, write).
--spec read(prompt()) ->
- {'ok', term()} | 'eof' | {'error', erl_scan:error_info()}.
+-spec read(Prompt) -> Result when
+ Prompt :: prompt(),
+ Result :: {'ok', Term :: term()}
+ | 'eof'
+ | {'error', ErrorInfo :: erl_scan:error_info()}.
% Read does not use get_until as erl_scan does not work with unicode
% XXX:PaN fixme?
read(Prompt) ->
read(default_input(), Prompt).
--spec read(device(), prompt()) ->
- {'ok', term()} | 'eof' | {'error', erl_scan:error_info()}.
+-spec read(IoDevice, Prompt) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ Result :: {'ok', Term :: term()}
+ | 'eof'
+ | {'error', ErrorInfo :: erl_scan:error_info()}.
read(Io, Prompt) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[1]}) of
@@ -211,9 +248,13 @@ read(Io, Prompt) ->
Other
end.
--spec read(device(), prompt(), line()) ->
- {'ok', term(), line()} | {'eof', line()} |
- {'error', erl_scan:error_info(), line()}.
+-spec read(IoDevice, Prompt, StartLine) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ StartLine :: line(),
+ Result :: {'ok', Term :: term(), EndLine :: line()}
+ | {'eof', EndLine :: line()}
+ | {'error', ErrorInfo :: erl_scan:error_info(), ErrorLine :: line()}.
read(Io, Prompt, StartLine) when is_integer(StartLine) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[StartLine]}) of
@@ -239,28 +280,40 @@ conv_reason(_, _Reason) -> badarg.
-type format() :: atom() | string() | binary().
--spec fwrite(format()) -> 'ok'.
+-spec fwrite(Format) -> 'ok' when
+ Format :: format().
fwrite(Format) ->
format(Format).
--spec fwrite(format(), [term()]) -> 'ok'.
+-spec fwrite(Format, Data) -> 'ok' when
+ Format :: format(),
+ Data :: [term()].
fwrite(Format, Args) ->
format(Format, Args).
--spec fwrite(device(), format(), [term()]) -> 'ok'.
+-spec fwrite(IoDevice, Format, Data) -> 'ok' when
+ IoDevice :: device(),
+ Format :: format(),
+ Data :: [term()].
fwrite(Io, Format, Args) ->
format(Io, Format, Args).
--spec fread(prompt(), format()) -> {'ok', [term()]} | 'eof' | {'error',term()}.
+-spec fread(Prompt, Format) -> Result when
+ Prompt :: prompt(),
+ Format :: format(),
+ Result :: {'ok', Terms :: [term()]} | 'eof' | {'error', What :: term()}.
fread(Prompt, Format) ->
fread(default_input(), Prompt, Format).
--spec fread(device(), prompt(), format()) ->
- {'ok', [term()]} | 'eof' | {'error',term()}.
+-spec fread(IoDevice, Prompt, Format) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ Format :: format(),
+ Result :: {'ok', Terms :: [term()]} | 'eof' | {'error', What :: term()}.
fread(Io, Prompt, Format) ->
case request(Io, {fread,Prompt,Format}) of
@@ -270,73 +323,104 @@ fread(Io, Prompt, Format) ->
Other
end.
--spec format(format()) -> 'ok'.
+-spec format(Format) -> 'ok' when
+ Format :: format().
format(Format) ->
format(Format, []).
--spec format(format(), [term()]) -> 'ok'.
+-spec format(Format, Data) -> 'ok' when
+ Format :: format(),
+ Data :: [term()].
format(Format, Args) ->
format(default_output(), Format, Args).
--spec format(device(), format(), [term()]) -> 'ok'.
+-spec format(IoDevice, Format, Data) -> 'ok' when
+ IoDevice :: device(),
+ Format :: format(),
+ Data :: [term()].
format(Io, Format, Args) ->
o_request(Io, {format,Format,Args}, format).
%% Scanning Erlang code.
--spec scan_erl_exprs(prompt()) -> erl_scan:tokens_result() | request_error().
+-spec scan_erl_exprs(Prompt) -> Result when
+ Prompt :: prompt(),
+ Result :: erl_scan:tokens_result() | request_error().
scan_erl_exprs(Prompt) ->
scan_erl_exprs(default_input(), Prompt, 1).
--spec scan_erl_exprs(device(), prompt()) -> erl_scan:tokens_result() | request_error().
+-spec scan_erl_exprs(Device, Prompt) -> Result when
+ Device :: device(),
+ Prompt :: prompt(),
+ Result :: erl_scan:tokens_result() | request_error().
scan_erl_exprs(Io, Prompt) ->
scan_erl_exprs(Io, Prompt, 1).
--spec scan_erl_exprs(device(), prompt(), line()) -> erl_scan:tokens_result() | request_error().
+-spec scan_erl_exprs(Device, Prompt, StartLine) -> Result when
+ Device :: device(),
+ Prompt :: prompt(),
+ StartLine :: line(),
+ Result :: erl_scan:tokens_result() | request_error().
scan_erl_exprs(Io, Prompt, Pos0) ->
request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0]}).
--spec scan_erl_form(prompt()) -> erl_scan:tokens_result() | request_error().
+-spec scan_erl_form(Prompt) -> Result when
+ Prompt :: prompt(),
+ Result :: erl_scan:tokens_result() | request_error().
scan_erl_form(Prompt) ->
scan_erl_form(default_input(), Prompt, 1).
--spec scan_erl_form(device(), prompt()) -> erl_scan:tokens_result() | request_error().
+-spec scan_erl_form(IoDevice, Prompt) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ Result :: erl_scan:tokens_result() | request_error().
scan_erl_form(Io, Prompt) ->
scan_erl_form(Io, Prompt, 1).
--spec scan_erl_form(device(), prompt(), line()) -> erl_scan:tokens_result() | request_error().
+-spec scan_erl_form(IoDevice, Prompt, StartLine) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ StartLine :: line(),
+ Result :: erl_scan:tokens_result() | request_error().
scan_erl_form(Io, Prompt, Pos0) ->
request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0]}).
%% Parsing Erlang code.
--type erl_parse_expr_list() :: [_]. %% XXX: should be imported from erl_parse
-
--type parse_ret() :: {'ok', erl_parse_expr_list(), line()}
- | {'eof', line()}
- | {'error', erl_scan:error_info(), line()}
+-type parse_ret() :: {'ok', ExprList :: erl_parse:abstract_expr(), EndLine :: line()}
+ | {'eof', EndLine :: line()}
+ | {'error', ErrorInfo :: erl_scan:error_info(), ErrorLine :: line()}
| request_error().
--spec parse_erl_exprs(prompt()) -> parse_ret().
+-spec parse_erl_exprs(Prompt) -> Result when
+ Prompt :: prompt(),
+ Result :: parse_ret().
parse_erl_exprs(Prompt) ->
parse_erl_exprs(default_input(), Prompt, 1).
--spec parse_erl_exprs(device(), prompt()) -> parse_ret().
+-spec parse_erl_exprs(IoDevice, Prompt) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ Result :: parse_ret().
parse_erl_exprs(Io, Prompt) ->
parse_erl_exprs(Io, Prompt, 1).
--spec parse_erl_exprs(device(), prompt(), line()) -> parse_ret().
+-spec parse_erl_exprs(IoDevice, Prompt, StartLine) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ StartLine :: line(),
+ Result :: parse_ret().
parse_erl_exprs(Io, Prompt, Pos0) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0]}) of
@@ -349,24 +433,31 @@ parse_erl_exprs(Io, Prompt, Pos0) ->
Other
end.
--type erl_parse_absform() :: _. %% XXX: should be imported from erl_parse
-
--type parse_form_ret() :: {'ok', erl_parse_absform(), line()}
- | {'eof', line()}
- | {'error', erl_scan:error_info(), line()}
+-type parse_form_ret() :: {'ok', AbsForm :: erl_parse:abstract_form(), EndLine :: line()}
+ | {'eof', EndLine :: line()}
+ | {'error', ErrorInfo :: erl_scan:error_info(), ErrorLine :: line()}
| request_error().
--spec parse_erl_form(prompt()) -> parse_form_ret().
+-spec parse_erl_form(Prompt) -> Result when
+ Prompt :: prompt(),
+ Result :: parse_form_ret().
parse_erl_form(Prompt) ->
parse_erl_form(default_input(), Prompt, 1).
--spec parse_erl_form(device(), prompt()) -> parse_form_ret().
+-spec parse_erl_form(IoDevice, Prompt) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ Result :: parse_form_ret().
parse_erl_form(Io, Prompt) ->
parse_erl_form(Io, Prompt, 1).
--spec parse_erl_form(device(), prompt(), line()) -> parse_form_ret().
+-spec parse_erl_form(IoDevice, Prompt, StartLine) -> Result when
+ IoDevice :: device(),
+ Prompt :: prompt(),
+ StartLine :: line(),
+ Result :: parse_form_ret().
parse_erl_form(Io, Prompt, Pos0) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0]}) of
diff --git a/lib/stdlib/src/io_lib.erl b/lib/stdlib/src/io_lib.erl
index 4ca9d079b7..54c7283abf 100644
--- a/lib/stdlib/src/io_lib.erl
+++ b/lib/stdlib/src/io_lib.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -75,35 +75,57 @@
collect_line/2, collect_line/3, collect_line/4,
get_until/3, get_until/4]).
--export_type([chars/0]).
+-export_type([chars/0, continuation/0]).
%%----------------------------------------------------------------------
- %% XXX: overapproximates a deep list of (unicode) characters
--type chars() :: [_].
+-type chars() :: [char() | chars()].
-type depth() :: -1 | non_neg_integer().
+-opaque continuation() :: {_, _, _, _}. % XXX: refine
+
%%----------------------------------------------------------------------
%% Interface calls to sub-modules.
--spec fwrite(io:format(), [term()]) -> chars().
+-spec fwrite(Format, Data) -> chars() | UnicodeList when
+ Format :: io:format(),
+ Data :: [term()],
+ UnicodeList :: [unicode:unicode_char()],
+ Data :: [term()].
fwrite(Format, Args) ->
format(Format, Args).
--spec fread(string(), string()) -> io_lib_fread:fread_2_ret().
+-spec fread(Format, String) -> Result when
+ Format :: string(),
+ String :: string(),
+ Result :: {'ok', InputList :: chars(), LeftOverChars :: string()}
+ | {'more', RestFormat :: string(),
+ Nchars :: non_neg_integer(),
+ InputStack :: chars()}
+ | {'error', What :: term()}.
fread(Chars, Format) ->
io_lib_fread:fread(Chars, Format).
--spec fread(io_lib_fread:continuation(), string(), string()) ->
- io_lib_fread:fread_3_ret().
+-spec fread(Continuation, String, Format) -> Return when
+ Continuation :: continuation() | [],
+ String :: string(),
+ Format :: string(),
+ Return :: {'more', Continuation1 :: continuation()}
+ | {'done', Result, LeftOverChars :: string()},
+ Result :: {'ok', InputList :: chars()}
+ | 'eof'
+ | {'error', What :: term()}.
fread(Cont, Chars, Format) ->
io_lib_fread:fread(Cont, Chars, Format).
--spec format(io:format(), [term()]) -> chars().
+-spec format(Format, Data) -> chars() | UnicodeList when
+ Format :: io:format(),
+ Data :: [term()],
+ UnicodeList :: [unicode:unicode_char()].
format(Format, Args) ->
case catch io_lib_format:fwrite(Format, Args) of
@@ -113,17 +135,24 @@ format(Format, Args) ->
Other
end.
--spec print(term()) -> chars().
+-spec print(Term) -> chars() when
+ Term :: term().
print(Term) ->
io_lib_pretty:print(Term).
--spec print(term(), non_neg_integer(), non_neg_integer(), depth()) -> chars().
+-spec print(Term, Column, LineLength, Depth) -> chars() when
+ Term :: term(),
+ Column :: non_neg_integer(),
+ LineLength :: non_neg_integer(),
+ Depth :: depth().
print(Term, Column, LineLength, Depth) ->
io_lib_pretty:print(Term, Column, LineLength, Depth).
--spec indentation(string(), integer()) -> integer().
+-spec indentation(String, StartIndent) -> integer() when
+ String :: string(),
+ StartIndent :: integer().
indentation(Chars, Current) ->
io_lib_format:indentation(Chars, Current).
@@ -158,7 +187,8 @@ format_prompt(Format, Args) ->
%% Return a (non-flattened) list of characters giving a printed
%% representation of the term. write/3 is for backward compatibility.
--spec write(term()) -> chars().
+-spec write(Term) -> chars() when
+ Term :: term().
write(Term) -> write(Term, -1).
@@ -169,7 +199,9 @@ write(Term, D, true) ->
write(Term, D, false) ->
write(Term, D).
--spec write(term(), depth()) -> chars().
+-spec write(Term, Depth) -> chars() when
+ Term :: term(),
+ Depth :: depth().
write(_Term, 0) -> "...";
write(Term, _D) when is_integer(Term) -> integer_to_list(Term);
@@ -234,7 +266,8 @@ write_binary_body(B, _D) ->
%% write_atom(Atom) -> [Char]
%% Generate the list of characters needed to print an atom.
--spec write_atom(atom()) -> chars().
+-spec write_atom(Atom) -> chars() when
+ Atom :: atom().
write_atom(Atom) ->
Chars = atom_to_list(Atom),
@@ -283,7 +316,8 @@ name_char(_) -> false.
%% write_string([Char]) -> [Char]
%% Generate the list of characters needed to print a string.
--spec write_string(string()) -> chars().
+-spec write_string(String) -> chars() when
+ String :: string().
write_string(S) ->
write_string(S, $"). %"
@@ -330,7 +364,8 @@ string_char(_,C, _, Tail) when C < $\240-> %Other control characters.
%% Generate the list of characters needed to print a character constant.
%% Must special case SPACE, $\s, here.
--spec write_char(char()) -> chars().
+-spec write_char(Char) -> chars() when
+ Char :: char().
write_char($\s) -> "$\\s"; %Must special case this.
write_char(C) when is_integer(C), C >= $\000, C =< $\377 ->
@@ -346,7 +381,8 @@ write_unicode_char(Uni) ->
%% Return true if CharList is a (possibly deep) list of characters, else
%% false.
--spec char_list(term()) -> boolean().
+-spec char_list(Term) -> boolean() when
+ Term :: term().
char_list([C|Cs]) when is_integer(C), C >= $\000, C =< $\377 ->
char_list(Cs);
@@ -362,7 +398,8 @@ unicode_char_list([C|Cs]) when is_integer(C), C >= 0, C < 16#D800;
unicode_char_list([]) -> true;
unicode_char_list(_) -> false. %Everything else is false
--spec deep_char_list(term()) -> boolean().
+-spec deep_char_list(Term) -> boolean() when
+ Term :: term().
deep_char_list(Cs) ->
deep_char_list(Cs, []).
@@ -399,7 +436,8 @@ deep_unicode_char_list(_, _More) -> %Everything else is false
%% Return true if CharList is a list of printable characters, else
%% false.
--spec printable_list(term()) -> boolean().
+-spec printable_list(Term) -> boolean() when
+ Term :: term().
printable_list([C|Cs]) when is_integer(C), C >= $\040, C =< $\176 ->
printable_list(Cs);
diff --git a/lib/stdlib/src/io_lib_fread.erl b/lib/stdlib/src/io_lib_fread.erl
index 33553692bc..52aa4d073c 100644
--- a/lib/stdlib/src/io_lib_fread.erl
+++ b/lib/stdlib/src/io_lib_fread.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -22,36 +22,24 @@
-export([fread/2,fread/3]).
--export_type([continuation/0, fread_2_ret/0, fread_3_ret/0]).
-
-import(lists, [reverse/1,reverse/2]).
%%-----------------------------------------------------------------------
-%% Local types
-%%-----------------------------------------------------------------------
-
--type done_arg2() :: {'ok', io_lib:chars()} | 'eof' | {'error', term()}.
-
-%%-----------------------------------------------------------------------
-%% Types also used in other files
-%%-----------------------------------------------------------------------
-
--type continuation() :: [] | {_, _, _, _}. % XXX: refine
-
--type fread_2_ret() :: {'ok', io_lib:chars(), string()}
- | {'more', string(), non_neg_integer(), io_lib:chars()}
- | {'error', term()}.
--type fread_3_ret() :: {'more', continuation()}
- | {'done', done_arg2(), string()}.
-
-%%-----------------------------------------------------------------------
%% fread(Continuation, CharList, FormatString)
%% This is the main function into the re-entrant formatted reader. It
%% repeatedly collects lines and calls fread/2 to format the input until
%% all the format string has been used. And it counts the characters.
--spec fread(io_lib_fread:continuation(), string(), string()) -> fread_3_ret().
+-spec fread(Continuation, String, Format) -> Return when
+ Continuation :: io_lib:continuation() | [],
+ String :: string(),
+ Format :: string(),
+ Return :: {'more', Continuation1 :: io_lib:continuation()}
+ | {'done', Result, LeftOverChars :: string()},
+ Result :: {'ok', InputList :: io_lib:chars()}
+ | 'eof'
+ | {'error', What :: term()}.
fread([], Chars, Format) ->
%%io:format("FREAD: ~w `~s'~n", [Format,Chars]),
@@ -106,7 +94,14 @@ fread_line(Format0, Line, N0, Results0, More, Newline) ->
%% WHITE Skip white space
%% X Literal X
--spec fread(string(), string()) -> fread_2_ret().
+-spec fread(Format, String) -> Result when
+ Format :: string(),
+ String :: string(),
+ Result :: {'ok', InputList :: io_lib:chars(), LeftOverChars :: string()}
+ | {'more', RestFormat :: string(),
+ Nchars :: non_neg_integer(),
+ InputStack :: io_lib:chars()}
+ | {'error', What :: term()}.
fread(Format, Line) ->
fread(Format, Line, 0, []).
diff --git a/lib/stdlib/src/lib.erl b/lib/stdlib/src/lib.erl
index b2cfb00de9..c303ae60b5 100644
--- a/lib/stdlib/src/lib.erl
+++ b/lib/stdlib/src/lib.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -38,7 +38,9 @@ flush_receive() ->
%%
%% Functions for doing standard system format i/o.
%%
--spec error_message(atom() | string() | binary(), [term()]) -> 'ok'.
+-spec error_message(Format, Args) -> 'ok' when
+ Format :: io:format(),
+ Args :: [term()].
error_message(Format, Args) ->
io:format(<<"** ~s **\n">>, [io_lib:format(Format, Args)]).
@@ -55,17 +57,23 @@ progname() ->
no_prog_name
end.
--spec nonl(string()) -> string().
+-spec nonl(String1) -> String2 when
+ String1 :: string(),
+ String2 :: string().
nonl([10]) -> [];
nonl([]) -> [];
nonl([H|T]) -> [H|nonl(T)].
--spec send(pid() | atom() | {atom(), node()}, term()) -> term().
+-spec send(To, Msg) -> Msg when
+ To :: pid() | atom() | {atom(), node()},
+ Msg :: term().
send(To, Msg) -> To ! Msg.
--spec sendw(pid() | atom() | {atom(), node()}, term()) -> term().
+-spec sendw(To, Msg) -> Msg when
+ To :: pid() | atom() | {atom(), node()},
+ Msg :: term().
sendw(To, Msg) ->
To ! {self(), Msg},
@@ -89,7 +97,7 @@ eval_str(Str) when is_list(Str) ->
true ->
case erl_parse:parse_exprs(Toks) of
{ok, Exprs} ->
- case catch erl_eval:exprs(Exprs, []) of
+ case catch erl_eval:exprs(Exprs, erl_eval:new_bindings()) of
{value, Val, _} ->
{ok, Val};
Other ->
diff --git a/lib/stdlib/src/lists.erl b/lib/stdlib/src/lists.erl
index c669c1f7c1..bba46e4cb6 100644
--- a/lib/stdlib/src/lists.erl
+++ b/lib/stdlib/src/lists.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -54,13 +54,21 @@
%% append(X, Y) appends lists X and Y
--spec append([T], [T]) -> [T].
+-spec append(List1, List2) -> List3 when
+ List1 :: [T],
+ List2 :: [T],
+ List3 :: [T],
+ T :: term().
append(L1, L2) -> L1 ++ L2.
%% append(L) appends the list of lists L
--spec append([[T]]) -> [T].
+-spec append(ListOfLists) -> List1 when
+ ListOfLists :: [List],
+ List :: [T],
+ List1 :: [T],
+ T :: term().
append([E]) -> E;
append([H|T]) -> H ++ append(T);
@@ -68,13 +76,20 @@ append([]) -> [].
%% subtract(List1, List2) subtract elements in List2 form List1.
--spec subtract([T], [T]) -> [T].
+-spec subtract(List1, List2) -> List3 when
+ List1 :: [T],
+ List2 :: [T],
+ List3 :: [T],
+ T :: term().
subtract(L1, L2) -> L1 -- L2.
%% reverse(L) reverse all elements in the list L. Is now a BIF!
--spec reverse([T]) -> [T].
+-spec reverse(List1) -> List2 when
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
reverse([] = L) ->
L;
@@ -93,13 +108,21 @@ reverse([A, B | L]) ->
%% nth(N, L) returns the N`th element of the list L
%% nthtail(N, L) returns the N`th tail of the list L
--spec nth(pos_integer(), [T,...]) -> T.
+-spec nth(N, List) -> Elem when
+ N :: pos_integer(),
+ List :: [T,...],
+ Elem :: T,
+ T :: term().
nth(1, [H|_]) -> H;
nth(N, [_|T]) when N > 1 ->
nth(N - 1, T).
--spec nthtail(non_neg_integer(), [T,...]) -> [T].
+-spec nthtail(N, List) -> Tail when
+ N :: non_neg_integer(),
+ List :: [T,...],
+ Tail :: [T],
+ T :: term().
nthtail(1, [_|T]) -> T;
nthtail(N, [_|T]) when N > 1 ->
@@ -108,7 +131,10 @@ nthtail(0, L) when is_list(L) -> L.
%% prefix(Prefix, List) -> (true | false)
--spec prefix([T], [T]) -> boolean().
+-spec prefix(List1, List2) -> boolean() when
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
prefix([X|PreTail], [X|Tail]) ->
prefix(PreTail, Tail);
@@ -117,7 +143,10 @@ prefix([_|_], List) when is_list(List) -> false.
%% suffix(Suffix, List) -> (true | false)
--spec suffix([T], [T]) -> boolean().
+-spec suffix(List1, List2) -> boolean() when
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
suffix(Suffix, List) ->
Delta = length(List) - length(Suffix),
@@ -125,7 +154,10 @@ suffix(Suffix, List) ->
%% last(List) returns the last element in a list.
--spec last([T,...]) -> T.
+-spec last(List) -> Last when
+ List :: [T,...],
+ Last :: T,
+ T :: term().
last([E|Es]) -> last(E, Es).
@@ -137,7 +169,10 @@ last(E, []) -> E.
%% returns the sequence Min..Max
%% Min <= Max and Min and Max must be integers
--spec seq(integer(), integer()) -> [integer()].
+-spec seq(From, To) -> Seq when
+ From :: integer(),
+ To :: integer(),
+ Seq :: [integer()].
seq(First, Last)
when is_integer(First), is_integer(Last), First-1 =< Last ->
@@ -152,7 +187,11 @@ seq_loop(1, X, L) ->
seq_loop(0, _, L) ->
L.
--spec seq(integer(), integer(), integer()) -> [integer()].
+-spec seq(From, To, Incr) -> Seq when
+ From :: integer(),
+ To :: integer(),
+ Incr :: integer(),
+ Seq :: [integer()].
seq(First, Last, Inc)
when is_integer(First), is_integer(Last), is_integer(Inc) ->
@@ -178,7 +217,8 @@ seq_loop(0, _, _, L) ->
%% sum(L) returns the sum of the elements in L
--spec sum([number()]) -> number().
+-spec sum(List) -> number() when
+ List :: [number()].
sum(L) -> sum(L, 0).
@@ -188,7 +228,11 @@ sum([], Sum) -> Sum.
%% duplicate(N, X) -> [X,X,X,.....,X] (N times)
%% return N copies of X
--spec duplicate(non_neg_integer(), T) -> [T].
+-spec duplicate(N, Elem) -> List when
+ N :: non_neg_integer(),
+ Elem :: T,
+ List :: [T],
+ T :: term().
duplicate(N, X) when is_integer(N), N >= 0 -> duplicate(N, X, []).
@@ -197,7 +241,10 @@ duplicate(N, X, L) -> duplicate(N-1, X, [X|L]).
%% min(L) -> returns the minimum element of the list L
--spec min([T,...]) -> T.
+-spec min(List) -> Min when
+ List :: [T,...],
+ Min :: T,
+ T :: term().
min([H|T]) -> min(T, H).
@@ -207,7 +254,10 @@ min([], Min) -> Min.
%% max(L) -> returns the maximum element of the list L
--spec max([T,...]) -> T.
+-spec max(List) -> Max when
+ List :: [T,...],
+ Max :: T,
+ T :: term().
max([H|T]) -> max(T, H).
@@ -218,12 +268,21 @@ max([], Max) -> Max.
%% sublist(List, Start, Length)
%% Returns the sub-list starting at Start of length Length.
--spec sublist([T], pos_integer(), non_neg_integer()) -> [T].
+-spec sublist(List1, Start, Len) -> List2 when
+ List1 :: [T],
+ List2 :: [T],
+ Start :: pos_integer(),
+ Len :: non_neg_integer(),
+ T :: term().
sublist(List, S, L) when is_integer(L), L >= 0 ->
sublist(nthtail(S-1, List), L).
--spec sublist([T], non_neg_integer()) -> [T].
+-spec sublist(List1, Len) -> List2 when
+ List1 :: [T],
+ List2 :: [T],
+ Len :: non_neg_integer(),
+ T :: term().
sublist(List, L) when is_integer(L), is_list(List) ->
sublist_2(List, L).
@@ -238,7 +297,11 @@ sublist_2(List, L) when is_list(List), L > 0 ->
%% delete(Item, List) -> List'
%% Delete the first occurrence of Item from the list L.
--spec delete(T, [T]) -> [T].
+-spec delete(Elem, List1) -> List2 when
+ Elem :: T,
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
delete(Item, [Item|Rest]) -> Rest;
delete(Item, [H|Rest]) ->
@@ -248,7 +311,12 @@ delete(_, []) -> [].
%% Return [{X0, Y0}, {X1, Y1}, ..., {Xn, Yn}] for lists [X0, X1, ...,
%% Xn] and [Y0, Y1, ..., Yn].
--spec zip([A], [B]) -> [{A, B}].
+-spec zip(List1, List2) -> List3 when
+ List1 :: [A],
+ List2 :: [B],
+ List3 :: [{A, B}],
+ A :: term(),
+ B :: term().
zip([X | Xs], [Y | Ys]) -> [{X, Y} | zip(Xs, Ys)];
zip([], []) -> [].
@@ -256,7 +324,12 @@ zip([], []) -> [].
%% Return {[X0, X1, ..., Xn], [Y0, Y1, ..., Yn]}, for a list [{X0, Y0},
%% {X1, Y1}, ..., {Xn, Yn}].
--spec unzip([{A, B}]) -> {[A], [B]}.
+-spec unzip(List1) -> {List2, List3} when
+ List1 :: [{A, B}],
+ List2 :: [A],
+ List3 :: [B],
+ A :: term(),
+ B :: term().
unzip(Ts) -> unzip(Ts, [], []).
@@ -266,7 +339,14 @@ unzip([], Xs, Ys) -> {reverse(Xs), reverse(Ys)}.
%% Return [{X0, Y0, Z0}, {X1, Y1, Z1}, ..., {Xn, Yn, Zn}] for lists [X0,
%% X1, ..., Xn], [Y0, Y1, ..., Yn] and [Z0, Z1, ..., Zn].
--spec zip3([A], [B], [C]) -> [{A, B, C}].
+-spec zip3(List1, List2, List3) -> List4 when
+ List1 :: [A],
+ List2 :: [B],
+ List3 :: [C],
+ List4 :: [{A, B, C}],
+ A :: term(),
+ B :: term(),
+ C :: term().
zip3([X | Xs], [Y | Ys], [Z | Zs]) -> [{X, Y, Z} | zip3(Xs, Ys, Zs)];
zip3([], [], []) -> [].
@@ -274,7 +354,14 @@ zip3([], [], []) -> [].
%% Return {[X0, X1, ..., Xn], [Y0, Y1, ..., Yn], [Z0, Z1, ..., Zn]}, for
%% a list [{X0, Y0, Z0}, {X1, Y1, Z1}, ..., {Xn, Yn, Zn}].
--spec unzip3([{A, B, C}]) -> {[A], [B], [C]}.
+-spec unzip3(List1) -> {List2, List3, List4} when
+ List1 :: [{A, B, C}],
+ List2 :: [A],
+ List3 :: [B],
+ List4 :: [C],
+ A :: term(),
+ B :: term(),
+ C :: term().
unzip3(Ts) -> unzip3(Ts, [], [], []).
@@ -286,7 +373,14 @@ unzip3([], Xs, Ys, Zs) ->
%% Return [F(X0, Y0), F(X1, Y1), ..., F(Xn, Yn)] for lists [X0, X1, ...,
%% Xn] and [Y0, Y1, ..., Yn].
--spec zipwith(fun((X, Y) -> R), [X], [Y]) -> [R].
+-spec zipwith(Combine, List1, List2) -> List3 when
+ Combine :: fun((X, Y) -> T),
+ List1 :: [X],
+ List2 :: [Y],
+ List3 :: [T],
+ X :: term(),
+ Y :: term(),
+ T :: term().
zipwith(F, [X | Xs], [Y | Ys]) -> [F(X, Y) | zipwith(F, Xs, Ys)];
zipwith(F, [], []) when is_function(F, 2) -> [].
@@ -294,7 +388,16 @@ zipwith(F, [], []) when is_function(F, 2) -> [].
%% Return [F(X0, Y0, Z0), F(X1, Y1, Z1), ..., F(Xn, Yn, Zn)] for lists
%% [X0, X1, ..., Xn], [Y0, Y1, ..., Yn] and [Z0, Z1, ..., Zn].
--spec zipwith3(fun((X, Y, Z) -> R), [X], [Y], [Z]) -> [R].
+-spec zipwith3(Combine, List1, List2, List3) -> List4 when
+ Combine :: fun((X, Y, Z) -> T),
+ List1 :: [X],
+ List2 :: [Y],
+ List3 :: [Z],
+ List4 :: [T],
+ X :: term(),
+ Y :: term(),
+ Z :: term(),
+ T :: term().
zipwith3(F, [X | Xs], [Y | Ys], [Z | Zs]) ->
[F(X, Y, Z) | zipwith3(F, Xs, Ys, Zs)];
@@ -303,7 +406,10 @@ zipwith3(F, [], [], []) when is_function(F, 3) -> [].
%% sort(List) -> L
%% sorts the list L
--spec sort([T]) -> [T].
+-spec sort(List1) -> List2 when
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
sort([X, Y | L] = L0) when X =< Y ->
case L of
@@ -350,7 +456,11 @@ sort_1(X, [], R) ->
%% merge(List) -> L
%% merges a list of sorted lists
--spec merge([[T]]) -> [T].
+-spec merge(ListOfLists) -> List1 when
+ ListOfLists :: [List],
+ List :: [T],
+ List1 :: [T],
+ T :: term().
merge(L) ->
mergel(L, []).
@@ -358,7 +468,14 @@ merge(L) ->
%% merge3(X, Y, Z) -> L
%% merges three sorted lists X, Y and Z
--spec merge3([X], [Y], [Z]) -> [(X | Y | Z)].
+-spec merge3(List1, List2, List3) -> List4 when
+ List1 :: [X],
+ List2 :: [Y],
+ List3 :: [Z],
+ List4 :: [(X | Y | Z)],
+ X :: term(),
+ Y :: term(),
+ Z :: term().
merge3(L1, [], L3) ->
merge(L1, L3);
@@ -382,7 +499,12 @@ rmerge3(L1, [H2 | T2], [H3 | T3]) ->
%% merge(X, Y) -> L
%% merges two sorted lists X and Y
--spec merge([X], [Y]) -> [(X | Y)].
+-spec merge(List1, List2) -> List3 when
+ List1 :: [X],
+ List2 :: [Y],
+ List3 :: [(X | Y)],
+ X :: term(),
+ Y :: term().
merge(T1, []) ->
T1;
@@ -405,8 +527,9 @@ rmerge(T1, [H2 | T2]) ->
%% in L - the elements in L can be atoms, numbers of strings.
%% Returns a list of characters.
--type concat_thing() :: atom() | integer() | float() | string().
--spec concat([concat_thing()]) -> string().
+-spec concat(Things) -> string() when
+ Things :: [Thing],
+ Thing :: atom() | integer() | float() | string().
concat(List) ->
flatmap(fun thing_to_list/1, List).
@@ -420,12 +543,17 @@ thing_to_list(X) when is_list(X) -> X. %Assumed to be a string
%% flatten(List, Tail)
%% Flatten a list, adding optional tail.
--spec flatten([term()]) -> [term()].
+-spec flatten(DeepList) -> List when
+ DeepList :: [term() | DeepList],
+ List :: [term()].
flatten(List) when is_list(List) ->
do_flatten(List, []).
--spec flatten([term()], [term()]) -> [term()].
+-spec flatten(DeepList, Tail) -> List when
+ DeepList :: [term() | DeepList],
+ Tail :: [term()],
+ List :: [term()].
flatten(List, Tail) when is_list(List), is_list(Tail) ->
do_flatten(List, Tail).
@@ -440,7 +568,8 @@ do_flatten([], Tail) ->
%% flatlength(List)
%% Calculate the length of a list of lists.
--spec flatlength([term()]) -> non_neg_integer().
+-spec flatlength(DeepList) -> non_neg_integer() when
+ DeepList :: [term() | DeepList].
flatlength(List) ->
flatlength(List, 0).
@@ -481,7 +610,12 @@ flatlength([], L) -> L.
% keysearch3(Key, N, T);
%keysearch3(Key, N, []) -> false.
--spec keydelete(term(), pos_integer(), [T]) -> [T] when T :: tuple().
+-spec keydelete(Key, N, TupleList1) -> TupleList2 when
+ Key :: term(),
+ N :: pos_integer(),
+ TupleList1 :: [Tuple],
+ TupleList2 :: [Tuple],
+ Tuple :: tuple().
keydelete(K, N, L) when is_integer(N), N > 0 ->
keydelete3(K, N, L).
@@ -491,7 +625,12 @@ keydelete3(Key, N, [H|T]) ->
[H|keydelete3(Key, N, T)];
keydelete3(_, _, []) -> [].
--spec keyreplace(term(), pos_integer(), [tuple()], tuple()) -> [tuple()].
+-spec keyreplace(Key, N, TupleList1, NewTuple) -> TupleList2 when
+ Key :: term(),
+ N :: pos_integer(),
+ TupleList1 :: [tuple()],
+ TupleList2 :: [tuple()],
+ NewTuple :: tuple().
keyreplace(K, N, L, New) when is_integer(N), N > 0, is_tuple(New) ->
keyreplace3(K, N, L, New).
@@ -502,8 +641,12 @@ keyreplace3(Key, Pos, [H|T], New) ->
[H|keyreplace3(Key, Pos, T, New)];
keyreplace3(_, _, [], _) -> [].
--spec keytake(term(), pos_integer(), [tuple()]) ->
- {'value', tuple(), [tuple()]} | 'false'.
+-spec keytake(Key, N, TupleList1) -> {value, Tuple, TupleList2} | false when
+ Key :: term(),
+ N :: pos_integer(),
+ TupleList1 :: [tuple()],
+ TupleList2 :: [tuple()],
+ Tuple :: tuple().
keytake(Key, N, L) when is_integer(N), N > 0 ->
keytake(Key, N, L, []).
@@ -514,7 +657,12 @@ keytake(Key, N, [H|T], L) ->
keytake(Key, N, T, [H|L]);
keytake(_K, _N, [], _L) -> false.
--spec keystore(term(), pos_integer(), [tuple()], tuple()) -> [tuple(),...].
+-spec keystore(Key, N, TupleList1, NewTuple) -> TupleList2 when
+ Key :: term(),
+ N :: pos_integer(),
+ TupleList1 :: [tuple()],
+ TupleList2 :: [tuple(), ...],
+ NewTuple :: tuple().
keystore(K, N, L, New) when is_integer(N), N > 0, is_tuple(New) ->
keystore2(K, N, L, New).
@@ -526,7 +674,11 @@ keystore2(Key, N, [H|T], New) ->
keystore2(_Key, _N, [], New) ->
[New].
--spec keysort(pos_integer(), [T]) -> [T] when T :: tuple().
+-spec keysort(N, TupleList1) -> TupleList2 when
+ N :: pos_integer(),
+ TupleList1 :: [Tuple],
+ TupleList2 :: [Tuple],
+ Tuple :: tuple().
keysort(I, L) when is_integer(I), I > 0 ->
case L of
@@ -583,8 +735,13 @@ keysort_1(I, X, EX, [Y | L], R) ->
keysort_1(_I, X, _EX, [], R) ->
lists:reverse(R, [X]).
--spec keymerge(pos_integer(), [X], [Y]) ->
- [R] when X :: tuple(), Y :: tuple(), R :: tuple().
+-spec keymerge(N, TupleList1, TupleList2) -> TupleList3 when
+ N :: pos_integer(),
+ TupleList1 :: [T1],
+ TupleList2 :: [T2],
+ TupleList3 :: [(T1 | T2)],
+ T1 :: tuple(),
+ T2 :: tuple().
keymerge(Index, T1, L2) when is_integer(Index), Index > 0 ->
case L2 of
@@ -611,7 +768,11 @@ rkeymerge(Index, T1, L2) when is_integer(Index), Index > 0 ->
lists:reverse(M, [])
end.
--spec ukeysort(pos_integer(), [T]) -> [T] when T :: tuple().
+-spec ukeysort(N, TupleList1) -> TupleList2 when
+ N :: pos_integer(),
+ TupleList1 :: [Tuple],
+ TupleList2 :: [Tuple],
+ Tuple :: tuple().
ukeysort(I, L) when is_integer(I), I > 0 ->
case L of
@@ -676,8 +837,13 @@ ukeysort_1(I, X, EX, [Y | L]) ->
ukeysort_1(_I, X, _EX, []) ->
[X].
--spec ukeymerge(pos_integer(), [X], [Y]) ->
- [(X | Y)] when X :: tuple(), Y :: tuple().
+-spec ukeymerge(N, TupleList1, TupleList2) -> TupleList3 when
+ N :: pos_integer(),
+ TupleList1 :: [T1],
+ TupleList2 :: [T2],
+ TupleList3 :: [(T1 | T2)],
+ T1 :: tuple(),
+ T2 :: tuple().
ukeymerge(Index, L1, T2) when is_integer(Index), Index > 0 ->
case L1 of
@@ -704,7 +870,11 @@ rukeymerge(Index, T1, L2) when is_integer(Index), Index > 0 ->
lists:reverse(M, [])
end.
--spec keymap(fun((term()) -> term()), pos_integer(), [tuple()]) -> [tuple()].
+-spec keymap(Fun, N, TupleList1) -> TupleList2 when
+ Fun :: fun((Term1 :: term()) -> Term2 :: term()),
+ N :: pos_integer(),
+ TupleList1 :: [tuple()],
+ TupleList2 :: [tuple()].
keymap(Fun, Index, [Tup|Tail]) ->
[setelement(Index, Tup, Fun(element(Index, Tup)))|keymap(Fun, Index, Tail)];
@@ -713,7 +883,11 @@ keymap(Fun, Index, []) when is_integer(Index), Index >= 1,
%%% Suggestion from OTP-2948: sort and merge with Fun.
--spec sort(fun((T, T) -> boolean()), [T]) -> [T].
+-spec sort(Fun, List1) -> List2 when
+ Fun :: fun((A :: T, B :: T) -> boolean()),
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
sort(Fun, []) when is_function(Fun, 2) ->
[];
@@ -727,7 +901,13 @@ sort(Fun, [X, Y | T]) ->
fsplit_2(Y, X, Fun, T, [], [])
end.
--spec merge(fun((X, Y) -> boolean()), [X], [Y]) -> [(X | Y)].
+-spec merge(Fun, List1, List2) -> List3 when
+ Fun :: fun((A, B) -> boolean()),
+ List1 :: [A],
+ List2 :: [B],
+ List3 :: [(A | B)],
+ A :: term(),
+ B :: term().
merge(Fun, T1, [H2 | T2]) when is_function(Fun, 2) ->
lists:reverse(fmerge2_1(T1, H2, Fun, T2, []), []);
@@ -743,7 +923,11 @@ rmerge(Fun, T1, [H2 | T2]) when is_function(Fun, 2) ->
rmerge(Fun, T1, []) when is_function(Fun, 2) ->
T1.
--spec usort(fun((T, T) -> boolean()), [T]) -> [T].
+-spec usort(Fun, List1) -> List2 when
+ Fun :: fun((T, T) -> boolean()),
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
usort(Fun, [_] = L) when is_function(Fun, 2) ->
L;
@@ -770,7 +954,13 @@ usort_1(Fun, X, [Y | L]) ->
ufsplit_2(Y, L, Fun, [X])
end.
--spec umerge(fun((X, Y) -> boolean()), [X], [Y]) -> [(X | Y)].
+-spec umerge(Fun, List1, List2) -> List3 when
+ Fun :: fun((A, B) -> boolean()),
+ List1 :: [A],
+ List2 :: [B],
+ List3 :: [(A | B)],
+ A :: term(),
+ B :: term().
umerge(Fun, [], T2) when is_function(Fun, 2) ->
T2;
@@ -789,7 +979,10 @@ rumerge(Fun, T1, [H2 | T2]) when is_function(Fun, 2) ->
%% usort(List) -> L
%% sorts the list L, removes duplicates
--spec usort([T]) -> [T].
+-spec usort(List1) -> List2 when
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
usort([X, Y | L] = L0) when X < Y ->
case L of
@@ -844,7 +1037,11 @@ usort_1(X, []) ->
%% umerge(List) -> L
%% merges a list of sorted lists without duplicates, removes duplicates
--spec umerge([[T]]) -> [T].
+-spec umerge(ListOfLists) -> List1 when
+ ListOfLists :: [List],
+ List :: [T],
+ List1 :: [T],
+ T :: term().
umerge(L) ->
umergel(L).
@@ -853,7 +1050,14 @@ umerge(L) ->
%% merges three sorted lists X, Y and Z without duplicates,
%% removes duplicates
--spec umerge3([X], [Y], [Z]) -> [(X | Y | Z)].
+-spec umerge3(List1, List2, List3) -> List4 when
+ List1 :: [X],
+ List2 :: [Y],
+ List3 :: [Z],
+ List4 :: [(X | Y | Z)],
+ X :: term(),
+ Y :: term(),
+ Z :: term().
umerge3(L1, [], L3) ->
umerge(L1, L3);
@@ -878,7 +1082,12 @@ rumerge3(L1, [H2 | T2], [H3 | T3]) ->
%% umerge(X, Y) -> L
%% merges two sorted lists X and Y without duplicates, removes duplicates
--spec umerge([X], [Y]) -> [(X | Y)].
+-spec umerge(List1, List2) -> List3 when
+ List1 :: [X],
+ List2 :: [Y],
+ List3 :: [(X | Y)],
+ X :: term(),
+ Y :: term().
umerge([], T2) ->
T2;
@@ -924,7 +1133,10 @@ rumerge(T1, [H2 | T2]) ->
%% There are also versions with an extra argument, ExtraArgs, which is a
%% list of extra arguments to each call.
--spec all(fun((T) -> boolean()), [T]) -> boolean().
+-spec all(Pred, List) -> boolean() when
+ Pred :: fun((Elem :: T) -> boolean()),
+ List :: [T],
+ T :: term().
all(Pred, [Hd|Tail]) ->
case Pred(Hd) of
@@ -933,7 +1145,10 @@ all(Pred, [Hd|Tail]) ->
end;
all(Pred, []) when is_function(Pred, 1) -> true.
--spec any(fun((T) -> boolean()), [T]) -> boolean().
+-spec any(Pred, List) -> boolean() when
+ Pred :: fun((Elem :: T) -> boolean()),
+ List :: [T],
+ T :: term().
any(Pred, [Hd|Tail]) ->
case Pred(Hd) of
@@ -942,31 +1157,59 @@ any(Pred, [Hd|Tail]) ->
end;
any(Pred, []) when is_function(Pred, 1) -> false.
--spec map(fun((D) -> R), [D]) -> [R].
+-spec map(Fun, List1) -> List2 when
+ Fun :: fun((A) -> B),
+ List1 :: [A],
+ List2 :: [B],
+ A :: term(),
+ B :: term().
map(F, [H|T]) ->
[F(H)|map(F, T)];
map(F, []) when is_function(F, 1) -> [].
--spec flatmap(fun((D) -> [R]), [D]) -> [R].
+-spec flatmap(Fun, List1) -> List2 when
+ Fun :: fun((A) -> [B]),
+ List1 :: [A],
+ List2 :: [B],
+ A :: term(),
+ B :: term().
flatmap(F, [Hd|Tail]) ->
F(Hd) ++ flatmap(F, Tail);
flatmap(F, []) when is_function(F, 1) -> [].
--spec foldl(fun((T, term()) -> term()), term(), [T]) -> term().
+-spec foldl(Fun, Acc0, List) -> Acc1 when
+ Fun :: fun((Elem :: T, AccIn) -> AccOut),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ List :: [T],
+ T :: term().
foldl(F, Accu, [Hd|Tail]) ->
foldl(F, F(Hd, Accu), Tail);
foldl(F, Accu, []) when is_function(F, 2) -> Accu.
--spec foldr(fun((T, term()) -> term()), term(), [T]) -> term().
+-spec foldr(Fun, Acc0, List) -> Acc1 when
+ Fun :: fun((Elem :: T, AccIn) -> AccOut),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ List :: [T],
+ T :: term().
foldr(F, Accu, [Hd|Tail]) ->
F(Hd, foldr(F, Accu, Tail));
foldr(F, Accu, []) when is_function(F, 2) -> Accu.
--spec filter(Pred :: fun((T) -> boolean()), List :: [T]) -> [T].
+-spec filter(Pred, List1) -> List2 when
+ Pred :: fun((Elem :: T) -> boolean()),
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
filter(Pred, List) when is_function(Pred, 1) ->
[ E || E <- List, Pred(E) ].
@@ -974,7 +1217,12 @@ filter(Pred, List) when is_function(Pred, 1) ->
%% Equivalent to {filter(F, L), filter(NotF, L)}, if NotF = 'fun(X) ->
%% not F(X) end'.
--spec partition(Pred :: fun((T) -> boolean()), List :: [T]) -> {[T], [T]}.
+-spec partition(Pred, List) -> {Satisfying, NotSatisfying} when
+ Pred :: fun((Elem :: T) -> boolean()),
+ List :: [T],
+ Satisfying :: [T],
+ NotSatisfying :: [T],
+ T :: term().
partition(Pred, L) ->
partition(Pred, L, [], []).
@@ -1000,14 +1248,26 @@ zf(F, [Hd|Tail]) ->
end;
zf(F, []) when is_function(F, 1) -> [].
--spec foreach(F :: fun((T) -> term()), List :: [T]) -> 'ok'.
+-spec foreach(Fun, List) -> ok when
+ Fun :: fun((Elem :: T) -> term()),
+ List :: [T],
+ T :: term().
foreach(F, [Hd|Tail]) ->
F(Hd),
foreach(F, Tail);
foreach(F, []) when is_function(F, 1) -> ok.
--spec mapfoldl(fun((A, term()) -> {B, term()}), term(), [A]) -> {[B], term()}.
+-spec mapfoldl(Fun, Acc0, List1) -> {List2, Acc1} when
+ Fun :: fun((A, AccIn) -> {B, AccOut}),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ List1 :: [A],
+ List2 :: [B],
+ A :: term(),
+ B :: term().
mapfoldl(F, Accu0, [Hd|Tail]) ->
{R,Accu1} = F(Hd, Accu0),
@@ -1015,7 +1275,16 @@ mapfoldl(F, Accu0, [Hd|Tail]) ->
{[R|Rs],Accu2};
mapfoldl(F, Accu, []) when is_function(F, 2) -> {[],Accu}.
--spec mapfoldr(fun((A, term()) -> {B, term()}), term(), [A]) -> {[B], term()}.
+-spec mapfoldr(Fun, Acc0, List1) -> {List2, Acc1} when
+ Fun :: fun((A, AccIn) -> {B, AccOut}),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ List1 :: [A],
+ List2 :: [B],
+ A :: term(),
+ B :: term().
mapfoldr(F, Accu0, [Hd|Tail]) ->
{Rs,Accu1} = mapfoldr(F, Accu0, Tail),
@@ -1023,7 +1292,11 @@ mapfoldr(F, Accu0, [Hd|Tail]) ->
{[R|Rs],Accu2};
mapfoldr(F, Accu, []) when is_function(F, 2) -> {[],Accu}.
--spec takewhile(fun((T) -> boolean()), [T]) -> [T].
+-spec takewhile(Pred, List1) -> List2 when
+ Pred :: fun((Elem :: T) -> boolean()),
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
takewhile(Pred, [Hd|Tail]) ->
case Pred(Hd) of
@@ -1032,7 +1305,11 @@ takewhile(Pred, [Hd|Tail]) ->
end;
takewhile(Pred, []) when is_function(Pred, 1) -> [].
--spec dropwhile(fun((T) -> boolean()), [T]) -> [T].
+-spec dropwhile(Pred, List1) -> List2 when
+ Pred :: fun((Elem :: T) -> boolean()),
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
dropwhile(Pred, [Hd|Tail]=Rest) ->
case Pred(Hd) of
@@ -1041,7 +1318,12 @@ dropwhile(Pred, [Hd|Tail]=Rest) ->
end;
dropwhile(Pred, []) when is_function(Pred, 1) -> [].
--spec splitwith(fun((T) -> boolean()), [T]) -> {[T], [T]}.
+-spec splitwith(Pred, List) -> {List1, List2} when
+ Pred :: fun((T) -> boolean()),
+ List :: [T],
+ List1 :: [T],
+ List2 :: [T],
+ T :: term().
splitwith(Pred, List) when is_function(Pred, 1) ->
splitwith(Pred, List, []).
@@ -1054,7 +1336,12 @@ splitwith(Pred, [Hd|Tail], Taken) ->
splitwith(Pred, [], Taken) when is_function(Pred, 1) ->
{reverse(Taken),[]}.
--spec split(non_neg_integer(), [T]) -> {[T], [T]}.
+-spec split(N, List1) -> {List2, List3} when
+ N :: non_neg_integer(),
+ List1 :: [T],
+ List2 :: [T],
+ List3 :: [T],
+ T :: term().
split(N, List) when is_integer(N), N >= 0, is_list(List) ->
case split(N, List, []) of
diff --git a/lib/stdlib/src/log_mf_h.erl b/lib/stdlib/src/log_mf_h.erl
index 5fa5360fa1..f7f128dac7 100644
--- a/lib/stdlib/src/log_mf_h.erl
+++ b/lib/stdlib/src/log_mf_h.erl
@@ -27,14 +27,13 @@
%%-----------------------------------------------------------------
--type dir() :: file:filename().
-type b() :: non_neg_integer().
-type f() :: 1..255.
-type pred() :: fun((term()) -> boolean()).
%%-----------------------------------------------------------------
--record(state, {dir :: dir(),
+-record(state, {dir :: file:filename(),
maxB :: b(),
maxF :: f(),
curB :: b(),
@@ -67,11 +66,23 @@
%% EventMgr = pid() | atom().
%%-----------------------------------------------------------------
--spec init(dir(), b(), f()) -> {dir(), b(), f(), pred()}.
+-opaque args() :: {file:filename(), b(), f(), pred()}.
+
+
+-spec init(Dir, MaxBytes, MaxFiles) -> Args when
+ Dir :: file:filename(),
+ MaxBytes :: non_neg_integer(), % b()
+ MaxFiles :: 1..255, % f()
+ Args :: args().
init(Dir, MaxB, MaxF) -> init(Dir, MaxB, MaxF, fun(_) -> true end).
--spec init(dir(), b(), f(), pred()) -> {dir(), b(), f(), pred()}.
+-spec init(Dir, MaxBytes, MaxFiles, Pred) -> Args when
+ Dir :: file:filename(),
+ MaxBytes :: non_neg_integer(), % b()
+ MaxFiles :: 1..255, % f()
+ Pred :: fun((Event :: term()) -> boolean()), % pred()
+ Args :: args().
init(Dir, MaxB, MaxF, Pred) -> {Dir, MaxB, MaxF, Pred}.
@@ -79,7 +90,7 @@ init(Dir, MaxB, MaxF, Pred) -> {Dir, MaxB, MaxF, Pred}.
%% Call-back functions from gen_event
%%-----------------------------------------------------------------
--spec init({dir(), b(), f(), pred()}) -> {'ok', #state{}} | {'error', term()}.
+-spec init({file:filename(), non_neg_integer(), f(), pred()}) -> {'ok', #state{}} | {'error', term()}.
init({Dir, MaxB, MaxF, Pred}) when is_integer(MaxF), MaxF > 0, MaxF < 256 ->
First =
diff --git a/lib/stdlib/src/ms_transform.erl b/lib/stdlib/src/ms_transform.erl
index b565eb20f4..48e22e53fa 100644
--- a/lib/stdlib/src/ms_transform.erl
+++ b/lib/stdlib/src/ms_transform.erl
@@ -66,6 +66,11 @@
%%
%% Called by compiler or ets/dbg:fun2ms when errors/warnings occur
%%
+
+-spec(format_error(Error) -> Chars when
+ Error :: {error, module(), term()},
+ Chars :: io_lib:chars()).
+
format_error({?WARN_SHADOW_VAR,Name}) ->
lists:flatten(
io_lib:format("variable ~p shadowed in ms_transform fun head",
@@ -186,6 +191,12 @@ format_error(Else) ->
%%
%% Called when translating in shell
%%
+
+-spec transform_from_shell(Dialect, Clauses, BoundEnvironment) -> term() when
+ Dialect :: ets | dbg,
+ Clauses :: [erl_parse:abstract_clause()],
+ BoundEnvironment :: erl_eval:binding_struct().
+
transform_from_shell(Dialect, Clauses, BoundEnvironment) ->
SaveFilename = setup_filename(),
case catch ms_clause_list(1,Clauses,Dialect,gb_sets:new()) of
@@ -211,6 +222,11 @@ transform_from_shell(Dialect, Clauses, BoundEnvironment) ->
%%
%% Called when translating during compiling
%%
+
+-spec parse_transform(Forms, Options) -> Forms when
+ Forms :: [erl_parse:abstract_form()],
+ Options :: term().
+
parse_transform(Forms, _Options) ->
SaveFilename = setup_filename(),
%io:format("Forms: ~p~n",[Forms]),
diff --git a/lib/stdlib/src/orddict.erl b/lib/stdlib/src/orddict.erl
index 4e30c9eefd..45d3c84b3e 100644
--- a/lib/stdlib/src/orddict.erl
+++ b/lib/stdlib/src/orddict.erl
@@ -25,9 +25,11 @@
-export([store/3,append/3,append_list/3,update/3,update/4,update_counter/3]).
-export([fold/3,map/2,filter/2,merge/3]).
+-export_type([orddict/0]).
+
%%---------------------------------------------------------------------------
--type orddict() :: [{term(), term()}].
+-type orddict() :: [{Key :: term(), Value :: term()}].
%%---------------------------------------------------------------------------
@@ -35,45 +37,63 @@
new() -> [].
--spec is_key(Key::term(), Dictionary::orddict()) -> boolean().
+-spec is_key(Key, Orddict) -> boolean() when
+ Key :: term(),
+ Orddict :: orddict().
is_key(Key, [{K,_}|_]) when Key < K -> false;
is_key(Key, [{K,_}|Dict]) when Key > K -> is_key(Key, Dict);
is_key(_Key, [{_K,_Val}|_]) -> true; %Key == K
is_key(_, []) -> false.
--spec to_list(orddict()) -> [{term(), term()}].
+-spec to_list(Orddict) -> List when
+ Orddict :: orddict(),
+ List :: [{Key :: term(), Value :: term()}].
to_list(Dict) -> Dict.
--spec from_list([{term(), term()}]) -> orddict().
+-spec from_list(List) -> Orddict when
+ List :: [{Key :: term(), Value :: term()}],
+ Orddict :: orddict().
from_list(Pairs) ->
lists:foldl(fun ({K,V}, D) -> store(K, V, D) end, [], Pairs).
--spec size(orddict()) -> non_neg_integer().
+-spec size(Orddict) -> non_neg_integer() when
+ Orddict :: orddict().
size(D) -> length(D).
--spec fetch(Key::term(), Dictionary::orddict()) -> term().
+-spec fetch(Key, Orddict) -> Value when
+ Key :: term(),
+ Value :: term(),
+ Orddict :: orddict().
fetch(Key, [{K,_}|D]) when Key > K -> fetch(Key, D);
fetch(Key, [{K,Value}|_]) when Key == K -> Value.
--spec find(Key::term(), Dictionary::orddict()) -> {'ok', term()} | 'error'.
+-spec find(Key, Orddict) -> {'ok', Value} | 'error' when
+ Key :: term(),
+ Orddict :: orddict(),
+ Value :: term().
find(Key, [{K,_}|_]) when Key < K -> error;
find(Key, [{K,_}|D]) when Key > K -> find(Key, D);
find(_Key, [{_K,Value}|_]) -> {ok,Value}; %Key == K
find(_, []) -> error.
--spec fetch_keys(Dictionary::orddict()) -> [term()].
+-spec fetch_keys(Orddict) -> Keys when
+ Orddict :: orddict(),
+ Keys :: [term()].
fetch_keys([{Key,_}|Dict]) ->
[Key|fetch_keys(Dict)];
fetch_keys([]) -> [].
--spec erase(Key::term(), Dictionary::orddict()) -> orddict().
+-spec erase(Key, Orddict1) -> Orddict2 when
+ Key :: term(),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
erase(Key, [{K,_}=E|Dict]) when Key < K -> [E|Dict];
erase(Key, [{K,_}=E|Dict]) when Key > K ->
@@ -81,7 +101,11 @@ erase(Key, [{K,_}=E|Dict]) when Key > K ->
erase(_Key, [{_K,_Val}|Dict]) -> Dict; %Key == K
erase(_, []) -> [].
--spec store(Key::term(), Value::term(), Dictionary::orddict()) -> orddict().
+-spec store(Key, Value, Orddict1) -> Orddict2 when
+ Key :: term(),
+ Value :: term(),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
store(Key, New, [{K,_}=E|Dict]) when Key < K ->
[{Key,New},E|Dict];
@@ -91,7 +115,11 @@ store(Key, New, [{_K,_Old}|Dict]) -> %Key == K
[{Key,New}|Dict];
store(Key, New, []) -> [{Key,New}].
--spec append(Key::term(), Value::term(), Dictionary::orddict()) -> orddict().
+-spec append(Key, Value, Orddict1) -> Orddict2 when
+ Key :: term(),
+ Value :: term(),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
append(Key, New, [{K,_}=E|Dict]) when Key < K ->
[{Key,[New]},E|Dict];
@@ -101,7 +129,11 @@ append(Key, New, [{_K,Old}|Dict]) -> %Key == K
[{Key,Old ++ [New]}|Dict];
append(Key, New, []) -> [{Key,[New]}].
--spec append_list(Key::term(), ValueList::[term()], orddict()) -> orddict().
+-spec append_list(Key, ValList, Orddict1) -> Orddict2 when
+ Key :: term(),
+ ValList :: [Value :: term()],
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
append_list(Key, NewList, [{K,_}=E|Dict]) when Key < K ->
[{Key,NewList},E|Dict];
@@ -112,14 +144,23 @@ append_list(Key, NewList, [{_K,Old}|Dict]) -> %Key == K
append_list(Key, NewList, []) ->
[{Key,NewList}].
--spec update(Key::term(), Fun::fun((term()) -> term()), orddict()) -> orddict().
+-spec update(Key, Fun, Orddict1) -> Orddict2 when
+ Key :: term(),
+ Fun :: fun((Value1 :: term()) -> Value2 :: term()),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
update(Key, Fun, [{K,_}=E|Dict]) when Key > K ->
[E|update(Key, Fun, Dict)];
update(Key, Fun, [{K,Val}|Dict]) when Key == K ->
[{Key,Fun(Val)}|Dict].
--spec update(term(), fun((term()) -> term()), term(), orddict()) -> orddict().
+-spec update(Key, Fun, Initial, Orddict1) -> Orddict2 when
+ Key :: term(),
+ Initial :: term(),
+ Fun :: fun((Value1 :: term()) -> Value2 :: term()),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
update(Key, _, Init, [{K,_}=E|Dict]) when Key < K ->
[{Key,Init},E|Dict];
@@ -129,7 +170,11 @@ update(Key, Fun, _Init, [{_K,Val}|Dict]) -> %Key == K
[{Key,Fun(Val)}|Dict];
update(Key, _, Init, []) -> [{Key,Init}].
--spec update_counter(Key::term(), Incr::number(), orddict()) -> orddict().
+-spec update_counter(Key, Increment, Orddict1) -> Orddict2 when
+ Key :: term(),
+ Increment :: number(),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
update_counter(Key, Incr, [{K,_}=E|Dict]) when Key < K ->
[{Key,Incr},E|Dict];
@@ -139,19 +184,29 @@ update_counter(Key, Incr, [{_K,Val}|Dict]) -> %Key == K
[{Key,Val+Incr}|Dict];
update_counter(Key, Incr, []) -> [{Key,Incr}].
--spec fold(fun((term(),term(),term()) -> term()), term(), orddict()) -> term().
+-spec fold(Fun, Acc0, Orddict) -> Acc1 when
+ Fun :: fun((Key :: term(), Value :: term(), AccIn :: term()) -> AccOut :: term()),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ Orddict :: orddict().
fold(F, Acc, [{Key,Val}|D]) ->
fold(F, F(Key, Val, Acc), D);
fold(F, Acc, []) when is_function(F, 3) -> Acc.
--spec map(fun((term(), term()) -> term()), orddict()) -> orddict().
+-spec map(Fun, Orddict1) -> Orddict2 when
+ Fun :: fun((Key :: term(), Value1 :: term()) -> Value2 :: term()),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
map(F, [{Key,Val}|D]) ->
[{Key,F(Key, Val)}|map(F, D)];
map(F, []) when is_function(F, 2) -> [].
--spec filter(fun((term(), term()) -> boolean()), orddict()) -> orddict().
+-spec filter(Pred, Orddict1) -> Orddict2 when
+ Pred :: fun((Key :: term(), Value :: term()) -> boolean()),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict().
filter(F, [{Key,Val}=E|D]) ->
case F(Key, Val) of
@@ -160,8 +215,11 @@ filter(F, [{Key,Val}=E|D]) ->
end;
filter(F, []) when is_function(F, 2) -> [].
--spec merge(fun((term(), term(), term()) -> term()), orddict(), orddict()) ->
- orddict().
+-spec merge(Fun, Orddict1, Orddict2) -> Orddict3 when
+ Fun :: fun((Key :: term(), Value1 :: term(), Value2 :: term()) -> Value :: term()),
+ Orddict1 :: orddict(),
+ Orddict2 :: orddict(),
+ Orddict3 :: orddict().
merge(F, [{K1,_}=E1|D1], [{K2,_}=E2|D2]) when K1 < K2 ->
[E1|merge(F, D1, [E2|D2])];
diff --git a/lib/stdlib/src/ordsets.erl b/lib/stdlib/src/ordsets.erl
index 5a1c260703..4a8b1275b2 100644
--- a/lib/stdlib/src/ordsets.erl
+++ b/lib/stdlib/src/ordsets.erl
@@ -40,7 +40,8 @@ new() -> [].
%% is_set(Term) -> boolean().
%% Return 'true' if Set is an ordered set of elements, else 'false'.
--spec is_set(term()) -> boolean().
+-spec is_set(Ordset) -> boolean() when
+ Ordset :: term().
is_set([E|Es]) -> is_set(Es, E);
is_set([]) -> true;
@@ -54,21 +55,26 @@ is_set([], _) -> true.
%% size(OrdSet) -> int().
%% Return the number of elements in OrdSet.
--spec size(ordset(_)) -> non_neg_integer().
+-spec size(Ordset) -> non_neg_integer() when
+ Ordset :: ordset(_).
size(S) -> length(S).
%% to_list(OrdSet) -> [Elem].
%% Return the elements in OrdSet as a list.
--spec to_list(ordset(T)) -> [T].
+-spec to_list(Ordset) -> List when
+ Ordset :: ordset(T),
+ List :: [T].
to_list(S) -> S.
%% from_list([Elem]) -> Set.
%% Build an ordered set from the elements in List.
--spec from_list([T]) -> ordset(T).
+-spec from_list(List) -> Ordset when
+ List :: [T],
+ Ordset :: ordset(T).
from_list(L) ->
lists:usort(L).
@@ -76,7 +82,9 @@ from_list(L) ->
%% is_element(Element, OrdSet) -> boolean().
%% Return 'true' if Element is an element of OrdSet, else 'false'.
--spec is_element(term(), ordset(_)) -> boolean().
+-spec is_element(Element, Ordset) -> boolean() when
+ Element :: term(),
+ Ordset :: ordset(_).
is_element(E, [H|Es]) when E > H -> is_element(E, Es);
is_element(E, [H|_]) when E < H -> false;
@@ -86,7 +94,12 @@ is_element(_, []) -> false.
%% add_element(Element, OrdSet) -> OrdSet.
%% Return OrdSet with Element inserted in it.
--spec add_element(E, ordset(T)) -> [T | E,...].
+-spec add_element(Element, Ordset1) -> Ordset2 when
+ Element :: E,
+ Ordset1 :: ordset(T),
+ Ordset2 :: ordset(T | E).
+
+%-spec add_element(E, ordset(T)) -> [T | E,...].
add_element(E, [H|Es]) when E > H -> [H|add_element(E, Es)];
add_element(E, [H|_]=Set) when E < H -> [E|Set];
@@ -96,7 +109,10 @@ add_element(E, []) -> [E].
%% del_element(Element, OrdSet) -> OrdSet.
%% Return OrdSet but with Element removed.
--spec del_element(term(), ordset(T)) -> ordset(T).
+-spec del_element(Element, Ordset1) -> Ordset2 when
+ Element :: term(),
+ Ordset1 :: ordset(T),
+ Ordset2 :: ordset(T).
del_element(E, [H|Es]) when E > H -> [H|del_element(E, Es)];
del_element(E, [H|_]=Set) when E < H -> Set;
@@ -106,7 +122,10 @@ del_element(_, []) -> [].
%% union(OrdSet1, OrdSet2) -> OrdSet
%% Return the union of OrdSet1 and OrdSet2.
--spec union(ordset(T1), ordset(T2)) -> ordset(T1 | T2).
+-spec union(Ordset1, Ordset2) -> Ordset3 when
+ Ordset1 :: ordset(T1),
+ Ordset2 :: ordset(T2),
+ Ordset3 :: ordset(T1 | T2).
union([E1|Es1], [E2|_]=Set2) when E1 < E2 ->
[E1|union(Es1, Set2)];
@@ -120,7 +139,9 @@ union(Es1, []) -> Es1.
%% union([OrdSet]) -> OrdSet
%% Return the union of the list of ordered sets.
--spec union([ordset(T)]) -> ordset(T).
+-spec union(OrdsetList) -> Ordset when
+ OrdsetList :: [ordset(T)],
+ Ordset :: ordset(T).
union([S1,S2|Ss]) ->
union1(union(S1, S2), Ss);
@@ -133,7 +154,10 @@ union1(S1, []) -> S1.
%% intersection(OrdSet1, OrdSet2) -> OrdSet.
%% Return the intersection of OrdSet1 and OrdSet2.
--spec intersection(ordset(_), ordset(_)) -> ordset(_).
+-spec intersection(Ordset1, Ordset2) -> Ordset3 when
+ Ordset1 :: ordset(_),
+ Ordset2 :: ordset(_),
+ Ordset3 :: ordset(_).
intersection([E1|Es1], [E2|_]=Set2) when E1 < E2 ->
intersection(Es1, Set2);
@@ -149,7 +173,9 @@ intersection(_, []) ->
%% intersection([OrdSet]) -> OrdSet.
%% Return the intersection of the list of ordered sets.
--spec intersection([ordset(_),...]) -> ordset(_).
+-spec intersection(OrdsetList) -> Ordset when
+ OrdsetList :: [ordset(_),...],
+ Ordset :: ordset(_).
intersection([S1,S2|Ss]) ->
intersection1(intersection(S1, S2), Ss);
@@ -162,7 +188,9 @@ intersection1(S1, []) -> S1.
%% is_disjoint(OrdSet1, OrdSet2) -> boolean().
%% Check whether OrdSet1 and OrdSet2 are disjoint.
--spec is_disjoint(ordset(_), ordset(_)) -> boolean().
+-spec is_disjoint(Ordset1, Ordset2) -> boolean() when
+ Ordset1 :: ordset(_),
+ Ordset2 :: ordset(_).
is_disjoint([E1|Es1], [E2|_]=Set2) when E1 < E2 ->
is_disjoint(Es1, Set2);
@@ -179,7 +207,10 @@ is_disjoint(_, []) ->
%% Return all and only the elements of OrdSet1 which are not also in
%% OrdSet2.
--spec subtract(ordset(_), ordset(_)) -> ordset(_).
+-spec subtract(Ordset1, Ordset2) -> Ordset3 when
+ Ordset1 :: ordset(_),
+ Ordset2 :: ordset(_),
+ Ordset3 :: ordset(_).
subtract([E1|Es1], [E2|_]=Set2) when E1 < E2 ->
[E1|subtract(Es1, Set2)];
@@ -194,7 +225,9 @@ subtract(Es1, []) -> Es1.
%% Return 'true' when every element of OrdSet1 is also a member of
%% OrdSet2, else 'false'.
--spec is_subset(ordset(_), ordset(_)) -> boolean().
+-spec is_subset(Ordset1, Ordset2) -> boolean() when
+ Ordset1 :: ordset(_),
+ Ordset2 :: ordset(_).
is_subset([E1|_], [E2|_]) when E1 < E2 -> %E1 not in Set2
false;
@@ -208,7 +241,11 @@ is_subset(_, []) -> false.
%% fold(Fun, Accumulator, OrdSet) -> Accumulator.
%% Fold function Fun over all elements in OrdSet and return Accumulator.
--spec fold(fun((T, term()) -> term()), term(), ordset(T)) -> term().
+-spec fold(Function, Acc0, Ordset) -> Acc1 when
+ Function :: fun((Element :: T, AccIn :: term()) -> AccOut :: term()),
+ Ordset :: ordset(T),
+ Acc0 :: term(),
+ Acc1 :: term().
fold(F, Acc, Set) ->
lists:foldl(F, Acc, Set).
@@ -216,7 +253,10 @@ fold(F, Acc, Set) ->
%% filter(Fun, OrdSet) -> OrdSet.
%% Filter OrdSet with Fun.
--spec filter(fun((T) -> boolean()), ordset(T)) -> ordset(T).
+-spec filter(Pred, Ordset1) -> Ordset2 when
+ Pred :: fun((Element :: T) -> boolean()),
+ Ordset1 :: ordset(T),
+ Ordset2 :: ordset(T).
filter(F, Set) ->
lists:filter(F, Set).
diff --git a/lib/stdlib/src/otp_internal.erl b/lib/stdlib/src/otp_internal.erl
index 5c52dfcbf0..39d017d430 100644
--- a/lib/stdlib/src/otp_internal.erl
+++ b/lib/stdlib/src/otp_internal.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1999-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1999-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
@@ -180,6 +180,9 @@ obsolete_1(calendar, local_time_to_universal_time, 1) ->
obsolete_1(rpc, safe_multi_server_call, A) when A =:= 2; A =:= 3 ->
{deprecated, {rpc, multi_server_call, A}};
+
+%% *** SNMP ***
+
obsolete_1(snmp, N, A) ->
case is_snmp_agent_function(N, A) of
false ->
@@ -189,9 +192,100 @@ obsolete_1(snmp, N, A) ->
integer_to_list(A)++" instead"}
end;
+obsolete_1(snmpm, agent_info, 3) ->
+ {deprecated, {snmpm, agent_info, 2}, "R16B"};
+obsolete_1(snmpm, update_agent_info, 5) ->
+ {deprecated, {snmpm, update_agent_info, 4}, "R16B"};
+obsolete_1(snmpm, g, 3) ->
+ {deprecated, {snmpm, sync_get, 3}, "R16B"};
+obsolete_1(snmpm, g, 4) ->
+ {deprecated, {snmpm, sync_get, [3,4]}, "R16B"};
+obsolete_1(snmpm, g, 5) ->
+ {deprecated, {snmpm, sync_get, [4,5]}, "R16B"};
+obsolete_1(snmpm, g, 6) ->
+ {deprecated, {snmpm, sync_get, [5,6]}, "R16B"};
+obsolete_1(snmpm, g, 7) ->
+ {deprecated, {snmpm, sync_get, 6}, "R16B"};
+obsolete_1(snmpm, ag, 3) ->
+ {deprecated, {snmpm, async_get, 3}, "R16B"};
+obsolete_1(snmpm, ag, 4) ->
+ {deprecated, {snmpm, async_get, [3,4]}, "R16B"};
+obsolete_1(snmpm, ag, 5) ->
+ {deprecated, {snmpm, async_get, [4,5]}, "R16B"};
+obsolete_1(snmpm, ag, 6) ->
+ {deprecated, {snmpm, async_get, [5,6]}, "R16B"};
+obsolete_1(snmpm, ag, 7) ->
+ {deprecated, {snmpm, async_get, 6}, "R16B"};
+obsolete_1(snmpm, gn, 3) ->
+ {deprecated, {snmpm, sync_get_next, 3}, "R16B"};
+obsolete_1(snmpm, gn, 4) ->
+ {deprecated, {snmpm, sync_get_next, [3,4]}, "R16B"};
+obsolete_1(snmpm, gn, 5) ->
+ {deprecated, {snmpm, sync_get_next, [4,5]}, "R16B"};
+obsolete_1(snmpm, gn, 6) ->
+ {deprecated, {snmpm, sync_get_next, [5,6]}, "R16B"};
+obsolete_1(snmpm, gn, 7) ->
+ {deprecated, {snmpm, sync_get_next, 6}, "R16B"};
+obsolete_1(snmpm, agn, 3) ->
+ {deprecated, {snmpm, async_get_next, 3}, "R16B"};
+obsolete_1(snmpm, agn, 4) ->
+ {deprecated, {snmpm, async_get_next, [3,4]}, "R16B"};
+obsolete_1(snmpm, agn, 5) ->
+ {deprecated, {snmpm, async_get_next, [4,5]}, "R16B"};
+obsolete_1(snmpm, agn, 6) ->
+ {deprecated, {snmpm, async_get_next, [5,6]}, "R16B"};
+obsolete_1(snmpm, agn, 7) ->
+ {deprecated, {snmpm, async_get_next, 6}, "R16B"};
+obsolete_1(snmpm, s, 3) ->
+ {deprecated, {snmpm, sync_set, 3}, "R16B"};
+obsolete_1(snmpm, s, 4) ->
+ {deprecated, {snmpm, sync_set, [3,4]}, "R16B"};
+obsolete_1(snmpm, s, 5) ->
+ {deprecated, {snmpm, sync_set, [4,5]}, "R16B"};
+obsolete_1(snmpm, s, 6) ->
+ {deprecated, {snmpm, sync_set, [5,6]}, "R16B"};
+obsolete_1(snmpm, s, 7) ->
+ {deprecated, {snmpm, sync_set, 6}, "R16B"};
+obsolete_1(snmpm, as, 3) ->
+ {deprecated, {snmpm, async_set, 3}, "R16B"};
+obsolete_1(snmpm, as, 4) ->
+ {deprecated, {snmpm, async_set, [3,4]}, "R16B"};
+obsolete_1(snmpm, as, 5) ->
+ {deprecated, {snmpm, async_set, [4,5]}, "R16B"};
+obsolete_1(snmpm, as, 6) ->
+ {deprecated, {snmpm, async_set, [5,6]}, "R16B"};
+obsolete_1(snmpm, as, 7) ->
+ {deprecated, {snmpm, async_set, 6}, "R16B"};
+obsolete_1(snmpm, gb, 5) ->
+ {deprecated, {snmpm, sync_get_bulk, 5}, "R16B"};
+obsolete_1(snmpm, gb, 6) ->
+ {deprecated, {snmpm, sync_get_bulk, [5,6]}, "R16B"};
+obsolete_1(snmpm, gb, 7) ->
+ {deprecated, {snmpm, sync_get_bulk, [6,7]}, "R16B"};
+obsolete_1(snmpm, gb, 8) ->
+ {deprecated, {snmpm, sync_get_bulk, [7,8]}, "R16B"};
+obsolete_1(snmpm, gb, 9) ->
+ {deprecated, {snmpm, sync_get_bulk, 8}, "R16B"};
+obsolete_1(snmpm, agb, 5) ->
+ {deprecated, {snmpm, async_get_bulk, 5}, "R16B"};
+obsolete_1(snmpm, agb, 6) ->
+ {deprecated, {snmpm, async_get_bulk, [5,6]}, "R16B"};
+obsolete_1(snmpm, agb, 7) ->
+ {deprecated, {snmpm, async_get_bulk, [6,7]}, "R16B"};
+obsolete_1(snmpm, agb, 8) ->
+ {deprecated, {snmpm, async_get_bulk, [7,8]}, "R16B"};
+obsolete_1(snmpm, agb, 9) ->
+ {deprecated, {snmpm, async_get_bulk, 8}, "R16B"};
+
+
+%% *** MEGACO ***
+
obsolete_1(megaco, format_versions, 1) ->
{deprecated, "Deprecated; use megaco:print_version_info/0,1 instead"};
+
+%% *** OS-MON-MIB ***
+
obsolete_1(os_mon_mib, init, 1) ->
{deprecated, {os_mon_mib, load, 1}};
obsolete_1(os_mon_mib, stop, 1) ->
diff --git a/lib/stdlib/src/pg.erl b/lib/stdlib/src/pg.erl
index 503654e706..ee177e4e0b 100644
--- a/lib/stdlib/src/pg.erl
+++ b/lib/stdlib/src/pg.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -35,7 +35,9 @@
%% Create a brand new empty process group with the master residing
%% at the local node
--spec create(term()) -> 'ok' | {'error', term()}.
+-spec create(PgName) -> 'ok' | {'error', Reason} when
+ PgName :: term(),
+ Reason :: 'already_created' | term().
create(PgName) ->
catch begin check(PgName),
@@ -46,7 +48,10 @@ create(PgName) ->
%% Create a brand new empty process group with the master
%% residing at Node
--spec create(term(), node()) -> 'ok' | {'error', term()}.
+-spec create(PgName, Node) -> 'ok' | {'error', Reason} when
+ PgName :: term(),
+ Node :: node(),
+ Reason :: 'already_created' | term().
create(PgName, Node) ->
catch begin check(PgName),
@@ -66,7 +71,10 @@ standby(_PgName, _Node) ->
%% Tell process group PgName that Pid is a new member of the group
%% synchronously return a list of all old members in the group
--spec join(atom(), pid()) -> [pid()].
+-spec join(PgName, Pid) -> Members when
+ PgName :: term(),
+ Pid :: pid(),
+ Members :: [pid()].
join(PgName, Pid) when is_atom(PgName) ->
global:send(PgName, {join,self(),Pid}),
@@ -77,7 +85,9 @@ join(PgName, Pid) when is_atom(PgName) ->
%% Multi cast Mess to all members in the group
--spec send(atom() | pid(), term()) -> 'ok'.
+-spec send(PgName, Msg) -> 'ok' when
+ PgName :: term(),
+ Msg :: term().
send(PgName, Mess) when is_atom(PgName) ->
global:send(PgName, {send, self(), Mess}),
@@ -89,7 +99,9 @@ send(Pg, Mess) when is_pid(Pg) ->
%% multi cast a message to all members in the group but ourselves
%% If we are a member
--spec esend(atom() | pid(), term()) -> 'ok'.
+-spec esend(PgName, Msg) -> 'ok' when
+ PgName :: term(),
+ Msg :: term().
esend(PgName, Mess) when is_atom(PgName) ->
global:send(PgName, {esend,self(),Mess}),
@@ -100,7 +112,9 @@ esend(Pg, Mess) when is_pid(Pg) ->
%% Return the members of the group
--spec members(atom() | pid()) -> [pid()].
+-spec members(PgName) -> Members when
+ PgName :: term(),
+ Members :: [pid()].
members(PgName) when is_atom(PgName) ->
global:send(PgName, {self() ,members}),
diff --git a/lib/stdlib/src/pool.erl b/lib/stdlib/src/pool.erl
index a3c9927ee9..a5eb191ab2 100644
--- a/lib/stdlib/src/pool.erl
+++ b/lib/stdlib/src/pool.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -52,11 +52,16 @@
%% Start up using the .hosts.erlang file
--spec start(atom()) -> [node()].
+-spec start(Name) -> Nodes when
+ Name :: atom(),
+ Nodes :: [node()].
start(Name) ->
start(Name,[]).
--spec start(atom(), string()) -> [node()].
+-spec start(Name, Args) -> Nodes when
+ Name :: atom(),
+ Args :: string(),
+ Nodes :: [node()].
start(Name, Args) when is_atom(Name) ->
gen_server:start({global, pool_master}, pool, [], []),
Hosts = net_adm:host_file(),
@@ -71,7 +76,8 @@ start(Name, Args) when is_atom(Name) ->
get_nodes() ->
get_elements(2, get_nodes_and_load()).
--spec attach(node()) -> 'already_attached' | 'attached'.
+-spec attach(Node) -> 'already_attached' | 'attached' when
+ Node :: node().
attach(Node) ->
gen_server:call({global, pool_master}, {attach, Node}).
@@ -82,11 +88,17 @@ get_nodes_and_load() ->
get_node() ->
gen_server:call({global, pool_master}, get_node).
--spec pspawn(module(), atom(), [term()]) -> pid().
+-spec pspawn(Mod, Fun, Args) -> pid() when
+ Mod :: module(),
+ Fun :: atom(),
+ Args :: [term()].
pspawn(M, F, A) ->
gen_server:call({global, pool_master}, {spawn, group_leader(), M, F, A}).
--spec pspawn_link(module(), atom(), [term()]) -> pid().
+-spec pspawn_link(Mod, Fun, Args) -> pid() when
+ Mod :: module(),
+ Fun :: atom(),
+ Args :: [term()].
pspawn_link(M, F, A) ->
P = pspawn(M, F, A),
link(P),
diff --git a/lib/stdlib/src/proc_lib.erl b/lib/stdlib/src/proc_lib.erl
index 4fb64a3353..02bcbb5a60 100644
--- a/lib/stdlib/src/proc_lib.erl
+++ b/lib/stdlib/src/proc_lib.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -40,77 +40,108 @@
-type priority_level() :: 'high' | 'low' | 'max' | 'normal'.
-type spawn_option() :: 'link'
+ | 'monitor'
| {'priority', priority_level()}
| {'min_heap_size', non_neg_integer()}
+ | {'min_bin_vheap_size', non_neg_integer()}
| {'fullsweep_after', non_neg_integer()}.
--type dict_or_pid() :: pid() | [_] | {integer(), integer(), integer()}.
+-type dict_or_pid() :: pid()
+ | (ProcInfo :: [_])
+ | {X :: integer(), Y :: integer(), Z :: integer()}.
%%-----------------------------------------------------------------------------
--spec spawn(function()) -> pid().
+-spec spawn(Fun) -> pid() when
+ Fun :: function().
spawn(F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(?MODULE, init_p, [Parent,Ancestors,F]).
--spec spawn(atom(), atom(), [term()]) -> pid().
+-spec spawn(Module, Function, Args) -> pid() when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
spawn(M,F,A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(?MODULE, init_p, [Parent,Ancestors,M,F,A]).
--spec spawn_link(function()) -> pid().
+-spec spawn_link(Fun) -> pid() when
+ Fun :: function().
spawn_link(F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(?MODULE, init_p, [Parent,Ancestors,F]).
--spec spawn_link(atom(), atom(), [term()]) -> pid().
+-spec spawn_link(Module, Function, Args) -> pid() when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
spawn_link(M,F,A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(?MODULE, init_p, [Parent,Ancestors,M,F,A]).
--spec spawn(node(), function()) -> pid().
+-spec spawn(Node, Fun) -> pid() when
+ Node :: node(),
+ Fun :: function().
spawn(Node, F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(Node, ?MODULE, init_p, [Parent,Ancestors,F]).
--spec spawn(node(), atom(), atom(), [term()]) -> pid().
+-spec spawn(Node, Module, Function, Args) -> pid() when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
+
spawn(Node, M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(Node, ?MODULE, init_p, [Parent,Ancestors,M,F,A]).
--spec spawn_link(node(), function()) -> pid().
+-spec spawn_link(Node, Fun) -> pid() when
+ Node :: node(),
+ Fun :: function().
spawn_link(Node, F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(Node, ?MODULE, init_p, [Parent,Ancestors,F]).
--spec spawn_link(node(), atom(), atom(), [term()]) -> pid().
+-spec spawn_link(Node, Module, Function, Args) -> pid() when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
spawn_link(Node, M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(Node, ?MODULE, init_p, [Parent,Ancestors,M,F,A]).
--spec spawn_opt(function(), [spawn_option()]) -> pid().
+-spec spawn_opt(Fun, SpawnOpts) -> pid() when
+ Fun :: function(),
+ SpawnOpts :: [spawn_option()].
+
spawn_opt(F, Opts) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
check_for_monitor(Opts),
erlang:spawn_opt(?MODULE, init_p, [Parent,Ancestors,F],Opts).
--spec spawn_opt(node(), function(), [spawn_option()]) -> pid().
+-spec spawn_opt(Node, Function, SpawnOpts) -> pid() when
+ Node :: node(),
+ Function :: function(),
+ SpawnOpts :: [spawn_option()].
spawn_opt(Node, F, Opts) when is_function(F) ->
Parent = get_my_name(),
@@ -118,7 +149,11 @@ spawn_opt(Node, F, Opts) when is_function(F) ->
check_for_monitor(Opts),
erlang:spawn_opt(Node, ?MODULE, init_p, [Parent,Ancestors,F], Opts).
--spec spawn_opt(atom(), atom(), [term()], [spawn_option()]) -> pid().
+-spec spawn_opt(Module, Function, Args, SpawnOpts) -> pid() when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ SpawnOpts :: [spawn_option()].
spawn_opt(M, F, A, Opts) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
@@ -126,7 +161,12 @@ spawn_opt(M, F, A, Opts) when is_atom(M), is_atom(F), is_list(A) ->
check_for_monitor(Opts),
erlang:spawn_opt(?MODULE, init_p, [Parent,Ancestors,M,F,A], Opts).
--spec spawn_opt(node(), atom(), atom(), [term()], [spawn_option()]) -> pid().
+-spec spawn_opt(Node, Module, Function, Args, SpawnOpts) -> pid() when
+ Node :: node(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ SpawnOpts :: [spawn_option()].
spawn_opt(Node, M, F, A, Opts) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
@@ -144,7 +184,10 @@ check_for_monitor(SpawnOpts) ->
false
end.
--spec hibernate(module(), atom(), [term()]) -> no_return().
+-spec hibernate(Module, Function, Args) -> no_return() when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()].
hibernate(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
erlang:hibernate(?MODULE, wake_up, [M, F, A]).
@@ -210,35 +253,65 @@ exit_p(Class, Reason) ->
exit(Reason)
end.
--spec start(atom(), atom(), [term()]) -> term().
+-spec start(Module, Function, Args) -> Ret when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Ret :: term() | {error, Reason :: term()}.
start(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
start(M, F, A, infinity).
--spec start(atom(), atom(), [term()], timeout()) -> term().
+-spec start(Module, Function, Args, Time) -> Ret when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Time :: timeout(),
+ Ret :: term() | {error, Reason :: term()}.
start(M, F, A, Timeout) when is_atom(M), is_atom(F), is_list(A) ->
Pid = ?MODULE:spawn(M, F, A),
sync_wait(Pid, Timeout).
--spec start(atom(), atom(), [term()], timeout(), [spawn_option()]) -> term().
+-spec start(Module, Function, Args, Time, SpawnOpts) -> Ret when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Time :: timeout(),
+ SpawnOpts :: [spawn_option()],
+ Ret :: term() | {error, Reason :: term()}.
start(M, F, A, Timeout, SpawnOpts) when is_atom(M), is_atom(F), is_list(A) ->
Pid = ?MODULE:spawn_opt(M, F, A, SpawnOpts),
sync_wait(Pid, Timeout).
--spec start_link(atom(), atom(), [term()]) -> term().
+-spec start_link(Module, Function, Args) -> Ret when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Ret :: term() | {error, Reason :: term()}.
start_link(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
start_link(M, F, A, infinity).
--spec start_link(atom(), atom(), [term()], timeout()) -> term().
+-spec start_link(Module, Function, Args, Time) -> Ret when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Time :: timeout(),
+ Ret :: term() | {error, Reason :: term()}.
start_link(M, F, A, Timeout) when is_atom(M), is_atom(F), is_list(A) ->
Pid = ?MODULE:spawn_link(M, F, A),
sync_wait(Pid, Timeout).
--spec start_link(atom(),atom(),[term()],timeout(),[spawn_option()]) -> term().
+-spec start_link(Module, Function, Args, Time, SpawnOpts) -> Ret when
+ Module :: module(),
+ Function :: atom(),
+ Args :: [term()],
+ Time :: timeout(),
+ SpawnOpts :: [spawn_option()],
+ Ret :: term() | {error, Reason :: term()}.
start_link(M,F,A,Timeout,SpawnOpts) when is_atom(M), is_atom(F), is_list(A) ->
Pid = ?MODULE:spawn_opt(M, F, A, ensure_link(SpawnOpts)),
@@ -267,13 +340,17 @@ flush(Pid) ->
true
end.
--spec init_ack(pid(), term()) -> 'ok'.
+-spec init_ack(Parent, Ret) -> 'ok' when
+ Parent :: pid(),
+ Ret :: term().
init_ack(Parent, Return) ->
Parent ! {ack, self(), Return},
ok.
--spec init_ack(term()) -> 'ok'.
+-spec init_ack(Ret) -> 'ok' when
+ Ret :: term().
+
init_ack(Return) ->
[Parent|_] = get('$ancestors'),
init_ack(Parent, Return).
@@ -282,7 +359,11 @@ init_ack(Return) ->
%% Fetch the initial call of a proc_lib spawned process.
%% -----------------------------------------------------
--spec initial_call(dict_or_pid()) -> {atom(), atom(), [atom()]} | 'false'.
+-spec initial_call(Process) -> {Module, Function, Args} | 'false' when
+ Process :: dict_or_pid(),
+ Module :: module(),
+ Function :: atom(),
+ Args :: [atom()].
initial_call(DictOrPid) ->
case raw_initial_call(DictOrPid) of
@@ -305,7 +386,11 @@ make_dummy_args(N, Acc) ->
%% This function is typically called from c:i() and c:regs().
%% -----------------------------------------------------
--spec translate_initial_call(dict_or_pid()) -> mfa().
+-spec translate_initial_call(Process) -> {Module, Function, Arity} when
+ Process :: dict_or_pid(),
+ Module :: module(),
+ Function :: atom(),
+ Arity :: byte().
translate_initial_call(DictOrPid) ->
case raw_initial_call(DictOrPid) of
@@ -577,7 +662,8 @@ check(Res) -> Res.
%%% Format (and write) a generated crash info structure.
%%% -----------------------------------------------------------
--spec format([term()]) -> string().
+-spec format(CrashReport) -> string() when
+ CrashReport :: [term()].
format([OwnReport,LinkReport]) ->
OwnFormat = format_report(OwnReport),
diff --git a/lib/stdlib/src/proplists.erl b/lib/stdlib/src/proplists.erl
index 6a45e0f868..68697d0da2 100644
--- a/lib/stdlib/src/proplists.erl
+++ b/lib/stdlib/src/proplists.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2001-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2001-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
@@ -37,7 +37,7 @@
%% overriding the default settings, object properties, annotations,
%% etc.</p>
%%
-%% @type property() = atom() | tuple()
+%% % @type property() = atom() | tuple()
-module(proplists).
@@ -53,14 +53,8 @@
-type property() :: atom() | tuple().
--type aliases() :: [{any(), any()}].
--type negations() :: [{any(), any()}].
--type expansions() :: [{property(), [any()]}].
-
%% ---------------------------------------------------------------------
-%% @spec property(P::property()) -> property()
-%%
%% @doc Creates a normal form (minimal) representation of a property. If
%% <code>P</code> is <code>{Key, true}</code> where <code>Key</code> is
%% an atom, this returns <code>Key</code>, otherwise the whole term
@@ -68,7 +62,8 @@
%%
%% @see property/2
--spec property(property()) -> property().
+-spec property(Property) -> Property when
+ Property :: property().
property({Key, true}) when is_atom(Key) ->
Key;
@@ -76,8 +71,6 @@ property(Property) ->
Property.
-%% @spec property(Key::term(), Value::term()) -> property()
-%%
%% @doc Creates a normal form (minimal) representation of a simple
%% key/value property. Returns <code>Key</code> if <code>Value</code> is
%% <code>true</code> and <code>Key</code> is an atom, otherwise a tuple
@@ -85,7 +78,10 @@ property(Property) ->
%%
%% @see property/1
--spec property(Key::term(), Value::term()) -> atom() | {term(), term()}.
+-spec property(Key, Value) -> Property when
+ Key :: term(),
+ Value :: term(),
+ Property :: atom() | {term(), term()}.
property(Key, true) when is_atom(Key) ->
Key;
@@ -95,14 +91,13 @@ property(Key, Value) ->
%% ---------------------------------------------------------------------
-%% @spec unfold(List::[term()]) -> [term()]
-%%
%% @doc Unfolds all occurences of atoms in <code>List</code> to tuples
%% <code>{Atom, true}</code>.
%%
%% @see compact/1
--spec unfold(List::[term()]) -> [term()].
+-spec unfold(List) -> List when
+ List :: [term()].
unfold([P | Ps]) ->
if is_atom(P) ->
@@ -113,15 +108,14 @@ unfold([P | Ps]) ->
unfold([]) ->
[].
-%% @spec compact(List::[term()]) -> [term()]
-%%
%% @doc Minimizes the representation of all entries in the list. This is
%% equivalent to <code>[property(P) || P &lt;- List]</code>.
%%
%% @see unfold/1
%% @see property/1
--spec compact(List::[property()]) -> [property()].
+-spec compact(List) -> List when
+ List :: [property()].
compact(List) ->
[property(P) || P <- List].
@@ -129,8 +123,6 @@ compact(List) ->
%% ---------------------------------------------------------------------
-%% @spec lookup(Key::term(), List::[term()]) -> none | tuple()
-%%
%% @doc Returns the first entry associated with <code>Key</code> in
%% <code>List</code>, if one exists, otherwise returns
%% <code>none</code>. For an atom <code>A</code> in the list, the tuple
@@ -140,7 +132,9 @@ compact(List) ->
%% @see get_value/2
%% @see get_bool/2
--spec lookup(Key::term(), List::[term()]) -> 'none' | tuple().
+-spec lookup(Key, List) -> 'none' | tuple() when
+ Key :: term(),
+ List :: [term()].
lookup(Key, [P | Ps]) ->
if is_atom(P), P =:= Key ->
@@ -154,15 +148,15 @@ lookup(Key, [P | Ps]) ->
lookup(_Key, []) ->
none.
-%% @spec lookup_all(Key::term(), List::[term()]) -> [tuple()]
-%%
%% @doc Returns the list of all entries associated with <code>Key</code>
%% in <code>List</code>. If no such entry exists, the result is the
%% empty list.
%%
%% @see lookup/2
--spec lookup_all(Key::term(), List::[term()]) -> [tuple()].
+-spec lookup_all(Key, List) -> [tuple()] when
+ Key :: term(),
+ List :: [term()].
lookup_all(Key, [P | Ps]) ->
if is_atom(P), P =:= Key ->
@@ -178,13 +172,13 @@ lookup_all(_Key, []) ->
%% ---------------------------------------------------------------------
-%% @spec is_defined(Key::term(), List::[term()]) -> boolean()
-%%
%% @doc Returns <code>true</code> if <code>List</code> contains at least
%% one entry associated with <code>Key</code>, otherwise
%% <code>false</code> is returned.
--spec is_defined(Key::term(), List::[term()]) -> boolean().
+-spec is_defined(Key, List) -> boolean() when
+ Key :: term(),
+ List :: [term()].
is_defined(Key, [P | Ps]) ->
if is_atom(P), P =:= Key ->
@@ -200,17 +194,15 @@ is_defined(_Key, []) ->
%% ---------------------------------------------------------------------
-%% @spec get_value(Key::term(), List::[term()]) -> term()
%% @equiv get_value(Key, List, undefined)
--spec get_value(Key::term(), List::[term()]) -> term().
+-spec get_value(Key, List) -> term() when
+ Key :: term(),
+ List :: List::[term()].
get_value(Key, List) ->
get_value(Key, List, undefined).
-%% @spec get_value(Key::term(), List::[term()], Default::term()) ->
-%% term()
-%%
%% @doc Returns the value of a simple key/value property in
%% <code>List</code>. If <code>lookup(Key, List)</code> would yield
%% <code>{Key, Value}</code>, this function returns the corresponding
@@ -221,7 +213,10 @@ get_value(Key, List) ->
%% @see get_all_values/2
%% @see get_bool/2
--spec get_value(Key::term(), List::[term()], Default::term()) -> term().
+-spec get_value(Key, List, Default) -> term() when
+ Key :: term(),
+ List :: [term()],
+ Default :: term().
get_value(Key, [P | Ps], Default) ->
if is_atom(P), P =:= Key ->
@@ -240,8 +235,6 @@ get_value(Key, [P | Ps], Default) ->
get_value(_Key, [], Default) ->
Default.
-%% @spec get_all_values(Key, List) -> [term()]
-%%
%% @doc Similar to <code>get_value/2</code>, but returns the list of
%% values for <em>all</em> entries <code>{Key, Value}</code> in
%% <code>List</code>. If no such entry exists, the result is the empty
@@ -249,7 +242,9 @@ get_value(_Key, [], Default) ->
%%
%% @see get_value/2
--spec get_all_values(Key::term(), List::[term()]) -> [term()].
+-spec get_all_values(Key, List) -> [term()] when
+ Key :: term(),
+ List :: [term()].
get_all_values(Key, [P | Ps]) ->
if is_atom(P), P =:= Key ->
@@ -267,8 +262,6 @@ get_all_values(Key, [P | Ps]) ->
get_all_values(_Key, []) ->
[].
-%% @spec append_values(Key::term(), List::[term()]) -> [term()]
-%%
%% @doc Similar to <code>get_all_values/2</code>, but each value is
%% wrapped in a list unless it is already itself a list, and the
%% resulting list of lists is concatenated. This is often useful for
@@ -278,7 +271,9 @@ get_all_values(_Key, []) ->
%%
%% @see get_all_values/2
--spec append_values(Key::term(), List::[term()]) -> [term()].
+-spec append_values(Key, List) -> List when
+ Key :: term(),
+ List :: [term()].
append_values(Key, [P | Ps]) ->
if is_atom(P), P =:= Key ->
@@ -301,8 +296,6 @@ append_values(_Key, []) ->
%% ---------------------------------------------------------------------
-%% @spec get_bool(Key::term(), List::[term()]) -> boolean()
-%%
%% @doc Returns the value of a boolean key/value option. If
%% <code>lookup(Key, List)</code> would yield <code>{Key, true}</code>,
%% this function returns <code>true</code>; otherwise <code>false</code>
@@ -311,7 +304,9 @@ append_values(_Key, []) ->
%% @see lookup/2
%% @see get_value/2
--spec get_bool(Key::term(), List::[term()]) -> boolean().
+-spec get_bool(Key, List) -> boolean() when
+ Key :: term(),
+ List :: [term()].
get_bool(Key, [P | Ps]) ->
if is_atom(P), P =:= Key ->
@@ -333,12 +328,11 @@ get_bool(_Key, []) ->
%% ---------------------------------------------------------------------
-%% @spec get_keys(List::[term()]) -> [term()]
-%%
%% @doc Returns an unordered list of the keys used in <code>List</code>,
%% not containing duplicates.
--spec get_keys(List::[term()]) -> [term()].
+-spec get_keys(List) -> [term()] when
+ List :: [term()].
get_keys(Ps) ->
sets:to_list(get_keys(Ps, sets:new())).
@@ -357,12 +351,12 @@ get_keys([], Keys) ->
%% ---------------------------------------------------------------------
-%% @spec delete(Key::term(), List::[term()]) -> [term()]
-%%
%% @doc Deletes all entries associated with <code>Key</code> from
%% <code>List</code>.
--spec delete(Key::term(), List::[term()]) -> [term()].
+-spec delete(Key, List) -> List when
+ Key :: term(),
+ List::[term()].
delete(Key, [P | Ps]) ->
if is_atom(P), P =:= Key ->
@@ -378,11 +372,6 @@ delete(_, []) ->
%% ---------------------------------------------------------------------
-%% @spec substitute_aliases(Aliases, List::[term()]) -> [term()]
-%%
-%% Aliases = [{Key, Key}]
-%% Key = term()
-%%
%% @doc Substitutes keys of properties. For each entry in
%% <code>List</code>, if it is associated with some key <code>K1</code>
%% such that <code>{K1, K2}</code> occurs in <code>Aliases</code>, the
@@ -398,7 +387,10 @@ delete(_, []) ->
%% @see substitute_negations/2
%% @see normalize/2
--spec substitute_aliases(aliases(), List::[term()]) -> [term()].
+-spec substitute_aliases(Aliases, List) -> List when
+ Aliases :: [{Key, Key}],
+ Key :: term(),
+ List::[term()].
substitute_aliases(As, Props) ->
[substitute_aliases_1(As, P) || P <- Props].
@@ -417,11 +409,6 @@ substitute_aliases_1([], P) ->
%% ---------------------------------------------------------------------
-%% @spec substitute_negations(Negations, List::[term()]) -> [term()]
-%%
-%% Negations = [{Key, Key}]
-%% Key = term()
-%%
%% @doc Substitutes keys of boolean-valued properties and simultaneously
%% negates their values. For each entry in <code>List</code>, if it is
%% associated with some key <code>K1</code> such that <code>{K1,
@@ -443,7 +430,10 @@ substitute_aliases_1([], P) ->
%% @see substitute_aliases/2
%% @see normalize/2
--spec substitute_negations(negations(), List::[term()]) -> [term()].
+-spec substitute_negations(Negations, List) -> List when
+ Negations :: [{Key, Key}],
+ Key :: term(),
+ List :: [term()].
substitute_negations(As, Props) ->
[substitute_negations_1(As, P) || P <- Props].
@@ -472,10 +462,6 @@ substitute_negations_1([], P) ->
%% ---------------------------------------------------------------------
-%% @spec expand(Expansions, List::[term()]) -> [term()]
-%%
-%% Expansions = [{property(), [term()]}]
-%%
%% @doc Expands particular properties to corresponding sets of
%% properties (or other terms). For each pair <code>{Property,
%% Expansion}</code> in <code>Expansions</code>, if <code>E</code> is
@@ -510,7 +496,9 @@ substitute_negations_1([], P) ->
%%
%% @see normalize/2
--spec expand(Expansions::expansions(), [term()]) -> [term()].
+-spec expand(Expansions, List) -> List when
+ Expansions :: [{Property :: property(), Expansion :: [term()]}],
+ List :: [term()].
expand(Es, Ps) when is_list(Ps) ->
Es1 = [{property(P), V} || {P, V} <- Es],
@@ -589,15 +577,6 @@ flatten([]) ->
%% ---------------------------------------------------------------------
-%% @spec normalize(List::[term()], Stages::[Operation]) -> [term()]
-%%
-%% Operation = {aliases, Aliases} | {negations, Negations}
-%% | {expand, Expansions}
-%% Aliases = [{Key, Key}]
-%% Negations = [{Key, Key}]
-%% Key = term()
-%% Expansions = [{property(), [term()]}]
-%%
%% @doc Passes <code>List</code> through a sequence of
%% substitution/expansion stages. For an <code>aliases</code> operation,
%% the function <code>substitute_aliases/2</code> is applied using the
@@ -619,11 +598,15 @@ flatten([]) ->
%% @see expand/2
%% @see compact/1
--type operation() :: {'aliases', aliases()}
- | {'negations', negations()}
- | {'expand', expansions()}.
-
--spec normalize(List::[term()], Stages::[operation()]) -> [term()].
+-spec normalize(List, Stages) -> List when
+ List :: [term()],
+ Stages :: [Operation],
+ Operation :: {'aliases', Aliases}
+ | {'negations', Negations}
+ | {'expand', Expansions},
+ Aliases :: [{Key, Key}],
+ Negations :: [{Key, Key}],
+ Expansions :: [{Property :: property(), Expansion :: [term()]}].
normalize(L, [{aliases, As} | Xs]) ->
normalize(substitute_aliases(As, L), Xs);
@@ -636,10 +619,6 @@ normalize(L, []) ->
%% ---------------------------------------------------------------------
-%% @spec split(List::[term()], Keys::[term()]) -> {Lists, Rest}
-%% Lists = [[term()]]
-%% Rest = [term()]
-%%
%% @doc Partitions <code>List</code> into a list of sublists and a
%% remainder. <code>Lists</code> contains one sublist for each key in
%% <code>Keys</code>, in the corresponding order. The relative order of
@@ -654,7 +633,11 @@ normalize(L, []) ->
%% {[[a], [{b, 5}, b],[{c, 2}, {c, 3, 4}]], [{e, 1}, d]}</pre>
%% </p>
--spec split(List::[term()], Keys::[term()]) -> {[[term()]], [term()]}.
+-spec split(List, Keys) -> {Lists, Rest} when
+ List :: [term()],
+ Keys :: [term()],
+ Lists :: [[term()]],
+ Rest :: [term()].
split(List, Keys) ->
{Store, Rest} = split(List, dict:from_list([{K, []} || K <- Keys]), []),
diff --git a/lib/stdlib/src/qlc.erl b/lib/stdlib/src/qlc.erl
index bc6944e520..5ca04ff023 100644
--- a/lib/stdlib/src/qlc.erl
+++ b/lib/stdlib/src/qlc.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2004-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2004-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
@@ -60,7 +60,7 @@
-record(qlc_table, % qlc:table/2
{trav_fun, % traverse fun
- trav_MS, % bool(); true iff traverse fun takes a match spec
+ trav_MS, % boolean(); true iff traverse fun takes a match spec
pre_fun,
post_fun,
info_fun,
@@ -110,12 +110,12 @@
-record(qlc_cursor, {c}).
-record(qlc_opt,
- {unique = false, % bool()
- cache = false, % bool() | list (true~ets, false~no)
+ {unique = false, % boolean()
+ cache = false, % boolean() | list (true~ets, false~no)
max_lookup = -1, % int() >= 0 | -1 (represents infinity)
join = any, % any | nested_loop | merge | lookup
tmpdir = "", % global tmpdir
- lookup = any, % any | bool()
+ lookup = any, % any | boolean()
max_list = ?MAX_LIST_SIZE, % int() >= 0
tmpdir_usage = allowed % allowed | not_allowed
% | warning_msg | error_msg | info_msg
@@ -125,6 +125,8 @@
-define(THROWN_ERROR, {?MODULE, throw_error, _}).
+-export_type([query_handle/0]).
+
%%% A query handle is a tuple {qlc_handle, Handle} where Handle is one
%%% of #qlc_append, #qlc_table, #qlc_sort, and #qlc_lc.
@@ -144,6 +146,35 @@ get_handle(_) ->
%%% Exported functions
%%%
+-type(query_list_comprehension() :: term()).
+-opaque(query_cursor() :: {qlc_cursor, term()}).
+-opaque(query_handle() :: {qlc_handle, term()}).
+-type(query_handle_or_list() :: query_handle() | list()).
+-type(answers() :: [answer()]).
+-type(answer() :: term()).
+-type(abstract_expr() :: erl_parse:abstract_expr()).
+-type(match_expression() :: ets:match_spec()).
+-type(spawn_options() :: default | [proc_lib:spawn_option()]).
+-type(sort_options() :: [sort_option()] | sort_option()).
+-type(sort_option() :: {compressed, boolean()}
+ | {no_files, no_files()}
+ | {order, order()}
+ | {size, pos_integer()}
+ | {tmpdir, tmp_directory()}
+ | {unique, boolean()}).
+-type(order() :: ascending | descending | order_fun()).
+-type(order_fun() :: fun((term(), term()) -> boolean())).
+-type(tmp_directory() :: [] | file:name()).
+-type(no_files() :: pos_integer()). % > 1
+-type(key_pos() :: pos_integer() | [pos_integer()]).
+-type(max_list_size() :: non_neg_integer()).
+-type(cache() :: ets | list | no).
+-type(tmp_file_usage() :: allowed | not_allowed | info_msg
+ | warning_msg | error_msg).
+
+-spec(append(QHL) -> QH when
+ QHL :: [query_handle_or_list()],
+ QH :: query_handle()).
append(QHs) ->
Hs = [case get_handle(QH) of
badarg -> erlang:error(badarg, [QHs]);
@@ -151,6 +182,10 @@ append(QHs) ->
end || QH <- QHs],
#qlc_handle{h = #qlc_append{hl = Hs}}.
+-spec(append(QH1, QH2) -> QH3 when
+ QH1 :: query_handle_or_list(),
+ QH2 :: query_handle_or_list(),
+ QH3 :: query_handle()).
append(QH1, QH2) ->
Hs = [case get_handle(QH) of
badarg -> erlang:error(badarg, [QH1, QH2]);
@@ -158,9 +193,22 @@ append(QH1, QH2) ->
end || QH <- [QH1, QH2]],
#qlc_handle{h = #qlc_append{hl = Hs}}.
+-spec(cursor(QH) -> Cursor when
+ QH :: query_handle_or_list(),
+ Cursor :: query_cursor()).
cursor(QH) ->
cursor(QH, []).
+-spec(cursor(QH, Options) -> Cursor when
+ QH :: query_handle_or_list(),
+ Options :: [Option] | Option,
+ Option :: {cache_all, cache()} | cache_all
+ | {max_list_size, max_list_size()}
+ | {spawn_options, spawn_options()}
+ | {tmpdir_usage, tmp_file_usage()}
+ | {tmpdir, tmp_directory()}
+ | {unique_all, boolean()} | unique_all,
+ Cursor :: query_cursor()).
cursor(QH, Options) ->
case {options(Options, [unique_all, cache_all, tmpdir,
spawn_options, max_list_size,
@@ -179,6 +227,8 @@ cursor(QH, Options) ->
end
end.
+-spec(delete_cursor(QueryCursor) -> ok when
+ QueryCursor :: query_cursor()).
delete_cursor(#qlc_cursor{c = {_, Owner}}=C) when Owner =/= self() ->
erlang:error(not_cursor_owner, [C]);
delete_cursor(#qlc_cursor{c = {Pid, _}}) ->
@@ -186,15 +236,47 @@ delete_cursor(#qlc_cursor{c = {Pid, _}}) ->
delete_cursor(T) ->
erlang:error(badarg, [T]).
+-spec(e(QH) -> Answers | Error when
+ QH :: query_handle_or_list(),
+ Answers :: answers(),
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
e(QH) ->
eval(QH, []).
+-spec(e(QH, Options) -> Answers | Error when
+ QH :: query_handle_or_list(),
+ Options :: [Option] | Option,
+ Option :: {cache_all, cache()} | cache_all
+ | {max_list_size, max_list_size()}
+ | {tmpdir_usage, tmp_file_usage()}
+ | {tmpdir, tmp_directory()}
+ | {unique_all, boolean()} | unique_all,
+ Answers :: answers(),
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
e(QH, Options) ->
eval(QH, Options).
+-spec(eval(QH) -> Answers | Error when
+ QH :: query_handle_or_list(),
+ Answers :: answers(),
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
eval(QH) ->
eval(QH, []).
+-spec(eval(QH, Options) -> Answers | Error when
+ QH :: query_handle_or_list(),
+ Answers :: answers(),
+ Options :: [Option] | Option,
+ Option :: {cache_all, cache()} | cache_all
+ | {max_list_size, max_list_size()}
+ | {tmpdir_usage, tmp_file_usage()}
+ | {tmpdir, tmp_directory()}
+ | {unique_all, boolean()} | unique_all,
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
eval(QH, Options) ->
case {options(Options, [unique_all, cache_all, tmpdir, max_list_size,
tmpdir_usage]),
@@ -226,9 +308,35 @@ eval(QH, Options) ->
end
end.
+-spec(fold(Function, Acc0, QH) ->
+ Acc1 | Error when
+ QH :: query_handle_or_list(),
+ Function :: fun((answer(), AccIn) -> AccOut),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
fold(Fun, Acc0, QH) ->
fold(Fun, Acc0, QH, []).
+-spec(fold(Function, Acc0, QH, Options) ->
+ Acc1 | Error when
+ QH :: query_handle_or_list(),
+ Function :: fun((answer(), AccIn) -> AccOut),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ Options :: [Option] | Option,
+ Option :: {cache_all, cache()} | cache_all
+ | {max_list_size, max_list_size()}
+ | {tmpdir_usage, tmp_file_usage()}
+ | {tmpdir, tmp_directory()}
+ | {unique_all, boolean()} | unique_all,
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
fold(Fun, Acc0, QH, Options) ->
case {options(Options, [unique_all, cache_all, tmpdir, max_list_size,
tmpdir_usage]),
@@ -258,6 +366,9 @@ fold(Fun, Acc0, QH, Options) ->
end
end.
+-spec(format_error(Error) -> Chars when
+ Error :: {error, module(), term()},
+ Chars :: io_lib:chars()).
format_error(not_a_query_list_comprehension) ->
io_lib:format("argument is not a query list comprehension", []);
format_error({used_generator_variable, V}) ->
@@ -295,9 +406,29 @@ format_error({error, Module, Reason}) ->
format_error(E) ->
io_lib:format("~p~n", [E]).
+-spec(info(QH) -> Info when
+ QH :: query_handle_or_list(),
+ Info :: abstract_expr() | string()).
info(QH) ->
info(QH, []).
+-spec(info(QH, Options) -> Info when
+ QH :: query_handle_or_list(),
+ Options :: [Option] | Option,
+ Option :: EvalOption | ReturnOption,
+ EvalOption :: {cache_all, cache()} | cache_all
+ | {max_list_size, max_list_size()}
+ | {tmpdir_usage, tmp_file_usage()}
+ | {tmpdir, tmp_directory()}
+ | {unique_all, boolean()} | unique_all,
+ ReturnOption :: {depth, Depth}
+ | {flat, boolean()}
+ | {format, Format}
+ | {n_elements, NElements},
+ Depth :: infinity | non_neg_integer(),
+ Format :: abstract_code | string,
+ NElements :: infinity | pos_integer(),
+ Info :: abstract_expr() | string()).
info(QH, Options) ->
case {options(Options, [unique_all, cache_all, flat, format, n_elements,
depth, tmpdir, max_list_size, tmpdir_usage]),
@@ -333,9 +464,18 @@ info(QH, Options) ->
end
end.
+-spec(keysort(KeyPos, QH1) -> QH2 when
+ KeyPos :: key_pos(),
+ QH1 :: query_handle_or_list(),
+ QH2 :: query_handle()).
keysort(KeyPos, QH) ->
keysort(KeyPos, QH, []).
+-spec(keysort(KeyPos, QH1, SortOptions) -> QH2 when
+ KeyPos :: key_pos(),
+ SortOptions :: sort_options(),
+ QH1 :: query_handle_or_list(),
+ QH2 :: query_handle()).
keysort(KeyPos, QH, Options) ->
case {is_keypos(KeyPos),
options(Options, [tmpdir, order, unique, compressed,
@@ -354,9 +494,22 @@ keysort(KeyPos, QH, Options) ->
-define(DEFAULT_NUM_OF_ANSWERS, 10).
+-spec(next_answers(QueryCursor) ->
+ Answers | Error when
+ QueryCursor :: query_cursor(),
+ Answers :: answers(),
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
next_answers(C) ->
next_answers(C, ?DEFAULT_NUM_OF_ANSWERS).
+-spec(next_answers(QueryCursor, NumberOfAnswers) ->
+ Answers | Error when
+ QueryCursor :: query_cursor(),
+ Answers :: answers(),
+ NumberOfAnswers :: all_remaining | pos_integer(),
+ Error :: {error, module(), Reason},
+ Reason :: file_sorter:reason()).
next_answers(#qlc_cursor{c = {_, Owner}}=C,
NumOfAnswers) when Owner =/= self() ->
erlang:error(not_cursor_owner, [C, NumOfAnswers]);
@@ -370,14 +523,35 @@ next_answers(#qlc_cursor{c = {Pid, _}}=C, NumOfAnswers) ->
next_answers(T1, T2) ->
erlang:error(badarg, [T1, T2]).
+-spec(parse_transform(Forms, Options) -> Forms2 when
+ Forms :: [erl_parse:abstract_form()],
+ Forms2 :: [erl_parse:abstract_form()],
+ Options :: [Option],
+ Option :: type_checker | compile:option()).
+
parse_transform(Forms, Options) ->
qlc_pt:parse_transform(Forms, Options).
%% The funcspecs qlc:q/1 and qlc:q/2 are known by erl_eval.erl and
%% erl_lint.erl.
+-spec(q(QLC) -> QH when
+ QLC :: query_list_comprehension(),
+ QH :: query_handle()).
q(QLC_lc) ->
q(QLC_lc, []).
+-spec(q(QLC, Options) -> QH when
+ QH :: query_handle(),
+ Options :: [Option] | Option,
+ Option :: {max_lookup, MaxLookup}
+ | {cache, cache()} | cache
+ | {join, Join}
+ | {lookup, Lookup}
+ | {unique, boolean()} | unique,
+ MaxLookup :: non_neg_integer() | infinity,
+ Join :: any | lookup | merge | nested_loop,
+ Lookup :: boolean() | any,
+ QLC :: query_list_comprehension()).
q(#qlc_lc{}=QLC_lc, Options) ->
case options(Options, [unique, cache, max_lookup, join, lookup]) of
[Unique, Cache, Max, Join, Lookup] ->
@@ -390,9 +564,16 @@ q(#qlc_lc{}=QLC_lc, Options) ->
q(T1, T2) ->
erlang:error(badarg, [T1, T2]).
+-spec(sort(QH1) -> QH2 when
+ QH1 :: query_handle_or_list(),
+ QH2 :: query_handle()).
sort(QH) ->
sort(QH, []).
+-spec(sort(QH1, SortOptions) -> QH2 when
+ SortOptions :: sort_options(),
+ QH1 :: query_handle_or_list(),
+ QH2 :: query_handle()).
sort(QH, Options) ->
case {options(Options, [tmpdir, order, unique, compressed,
size, no_files]), get_handle(QH)} of
@@ -406,14 +587,47 @@ sort(QH, Options) ->
end.
%% Note that the generated code is evaluated by (the slow) erl_eval.
+-spec(string_to_handle(QueryString) -> QH | Error when
+ QueryString :: string(),
+ QH :: query_handle(),
+ Error :: {error, module(), Reason},
+ Reason :: erl_parse:error_info() | erl_scan:error_info()).
string_to_handle(Str) ->
string_to_handle(Str, []).
+-spec(string_to_handle(QueryString, Options) -> QH | Error when
+ QueryString :: string(),
+ Options :: [Option] | Option,
+ Option :: {max_lookup, MaxLookup}
+ | {cache, cache()} | cache
+ | {join, Join}
+ | {lookup, Lookup}
+ | {unique, boolean()} | unique,
+ MaxLookup :: non_neg_integer() | infinity,
+ Join :: any | lookup | merge | nested_loop,
+ Lookup :: boolean() | any,
+ QH :: query_handle(),
+ Error :: {error, module(), Reason},
+ Reason :: erl_parse:error_info() | erl_scan:error_info()).
string_to_handle(Str, Options) ->
- string_to_handle(Str, Options, []).
-
-string_to_handle(Str, Options, Bindings) when is_list(Str),
- is_list(Bindings) ->
+ string_to_handle(Str, Options, erl_eval:new_bindings()).
+
+-spec(string_to_handle(QueryString, Options, Bindings) -> QH | Error when
+ QueryString :: string(),
+ Options :: [Option] | Option,
+ Option :: {max_lookup, MaxLookup}
+ | {cache, cache()} | cache
+ | {join, Join}
+ | {lookup, Lookup}
+ | {unique, boolean()} | unique,
+ MaxLookup :: non_neg_integer() | infinity,
+ Join :: any | lookup | merge | nested_loop,
+ Lookup :: boolean() | any,
+ Bindings :: erl_eval:binding_struct(),
+ QH :: query_handle(),
+ Error :: {error, module(), Reason},
+ Reason :: erl_parse:error_info() | erl_scan:error_info()).
+string_to_handle(Str, Options, Bindings) when is_list(Str) ->
case options(Options, [unique, cache, max_lookup, join, lookup]) of
badarg ->
erlang:error(badarg, [Str, Options, Bindings]);
@@ -447,6 +661,51 @@ string_to_handle(Str, Options, Bindings) when is_list(Str),
string_to_handle(T1, T2, T3) ->
erlang:error(badarg, [T1, T2, T3]).
+-spec(table(TraverseFun, Options) -> QH when
+ TraverseFun :: TraverseFun0 | TraverseFun1,
+ TraverseFun0 :: fun(() -> TraverseResult),
+ TraverseFun1 :: fun((match_expression()) -> TraverseResult),
+ TraverseResult :: Objects | term(),
+ Objects :: [] | [term() | ObjectList],
+ ObjectList :: TraverseFun0 | Objects,
+ Options :: [Option] | Option,
+ Option :: {format_fun, FormatFun}
+ | {info_fun, InfoFun}
+ | {lookup_fun, LookupFun}
+ | {parent_fun, ParentFun}
+ | {post_fun, PostFun}
+ | {pre_fun, PreFun}
+ | {key_equality, KeyComparison},
+ FormatFun :: undefined | fun((SelectedObjects) -> FormatedTable),
+ SelectedObjects :: all
+ | {all, NElements, DepthFun}
+ | {match_spec, match_expression()}
+ | {lookup, Position, Keys}
+ | {lookup, Position, Keys, NElements, DepthFun},
+ NElements :: infinity | pos_integer(),
+ DepthFun :: fun((term()) -> term()),
+ FormatedTable :: {Mod, Fun, Args}
+ | abstract_expr()
+ | string(),
+ InfoFun :: undefined | fun((InfoTag) -> InfoValue),
+ InfoTag :: indices | is_unique_objects | keypos | num_of_objects,
+ InfoValue :: undefined | term(),
+ LookupFun :: undefined | fun((Position, Keys) -> LookupResult),
+ LookupResult :: [term()] | term(),
+ ParentFun :: undefined | fun(() -> ParentFunValue),
+ PostFun :: undefined | fun(() -> term()),
+ PreFun :: undefined | fun((PreArgs) -> term()),
+ PreArgs :: [PreArg],
+ PreArg :: {parent_value, ParentFunValue} | {stop_fun, StopFun},
+ ParentFunValue :: undefined | term(),
+ StopFun :: undefined | fun(() -> term()),
+ KeyComparison :: '=:=' | '==',
+ Position :: pos_integer(),
+ Keys :: [term()],
+ Mod :: atom(),
+ Fun :: atom(),
+ Args :: [term()],
+ QH :: query_handle()).
table(TraverseFun, Options) when is_function(TraverseFun) ->
case {is_function(TraverseFun, 0),
IsFun1 = is_function(TraverseFun, 1)} of
@@ -472,6 +731,11 @@ table(TraverseFun, Options) when is_function(TraverseFun) ->
table(T1, T2) ->
erlang:error(badarg, [T1, T2]).
+-spec(transform_from_evaluator(LC, Bs) -> Expr when
+ LC :: abstract_expr(),
+ Expr :: abstract_expr(),
+ Bs :: erl_eval:binding_struct()).
+
transform_from_evaluator(LC, Bs0) ->
qlc_pt:transform_from_evaluator(LC, Bs0).
@@ -722,8 +986,8 @@ listify(T) ->
%% Optimizations to be carried out.
-record(optz,
- {unique = false, % bool()
- cache = false, % bool() | list
+ {unique = false, % boolean()
+ cache = false, % boolean() | list
join_option = any, % constraint set by the 'join' option
fast_join = no, % no | #qlc_join. 'no' means nested loop.
opt % #qlc_opt
@@ -756,8 +1020,8 @@ listify(T) ->
lu_skip_quals = [], % qualifiers to skip due to lookup
join = {[],[]}, % {Lookup, Merge}
n_objs = undefined, % for join (not used yet)
- is_unique_objects = false, % bool()
- is_cached = false % bool() (true means 'ets' or 'list')
+ is_unique_objects = false, % boolean()
+ is_cached = false % boolean() (true means 'ets' or 'list')
}).
%%% Cursor process functions.
@@ -1143,20 +1407,20 @@ monitor_request(Pid, Req) ->
%% QueryDesc = {qlc, TemplateDesc, [QualDesc], [QueryOpt]}
%% | {table, TableDesc}
%% | {append, [QueryDesc]}
-%% | {sort, QueryDesc, [SortOption]}
-%% | {keysort, KeyPos, QueryDesc, [SortOption]}
+%% | {sort, QueryDesc, [sort_option()]}
+%% | {keysort, key_pos(), QueryDesc, [sort_option()]}
%% | {list, list()}
-%% | {list, QueryDesc, MatchExpression}
+%% | {list, QueryDesc, match_expression()}
%% TableDesc = {Mod, Fun, Args}
-%% | AbstractExpression
-%% | character_list()
+%% | erl_parse:abstract_expr()
+%% | string()
%% Mod = module()
%% Fun = atom()
%% Args = [term()]
%% QualDesc = FilterDesc
%% | {generate, PatternDesc, QueryDesc}
-%% QueryOpt = {cache, bool()} | cache
-%% | {unique, bool()} | unique
+%% QueryOpt = {cache, boolean()} | cache
+%% | {unique, boolean()} | unique
%% FilterDesc = PatternDesc = TemplateDesc = binary()
le_info(#prepared{qh = #simple_qlc{le = LE, p = P, line = L, optz = Optz}},
diff --git a/lib/stdlib/src/qlc_pt.erl b/lib/stdlib/src/qlc_pt.erl
index 24378a0698..21504d707b 100644
--- a/lib/stdlib/src/qlc_pt.erl
+++ b/lib/stdlib/src/qlc_pt.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2004-2010. All Rights Reserved.
+%% Copyright Ericsson AB 2004-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
@@ -63,6 +63,12 @@
%%% Exported functions
%%%
+-spec(parse_transform(Forms, Options) -> Forms2 when
+ Forms :: [erl_parse:abstract_form()],
+ Forms2 :: [erl_parse:abstract_form()],
+ Options :: [Option],
+ Option :: type_checker | compile:option()).
+
parse_transform(Forms, Options) ->
?DEBUG("qlc Parse Transform~n", []),
State = #state{imp = is_qlc_q_imported(Forms),
@@ -96,10 +102,20 @@ parse_transform(Forms, Options) ->
end
end.
+-spec(transform_from_evaluator(LC, Bs) -> Expr when
+ LC :: erl_parse:abstract_expr(),
+ Expr :: erl_parse:abstract_expr(),
+ Bs :: erl_eval:binding_struct()).
+
transform_from_evaluator(LC, Bindings) ->
?DEBUG("qlc Parse Transform (Evaluator Version)~n", []),
transform_expression(LC, Bindings, false).
+-spec(transform_expression(LC, Bs) -> Expr when
+ LC :: erl_parse:abstract_expr(),
+ Expr :: erl_parse:abstract_expr(),
+ Bs :: erl_eval:binding_struct()).
+
transform_expression(LC, Bindings) ->
transform_expression(LC, Bindings, true).
diff --git a/lib/stdlib/src/queue.erl b/lib/stdlib/src/queue.erl
index c09079e8d2..4c6b4d710b 100644
--- a/lib/stdlib/src/queue.erl
+++ b/lib/stdlib/src/queue.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -56,14 +56,16 @@
new() -> {[],[]}. %{RearList,FrontList}
%% O(1)
--spec is_queue(term()) -> boolean().
+-spec is_queue(Term) -> boolean() when
+ Term :: term().
is_queue({R,F}) when is_list(R), is_list(F) ->
true;
is_queue(_) ->
false.
%% O(1)
--spec is_empty(queue()) -> boolean().
+-spec is_empty(Q) -> boolean() when
+ Q :: queue().
is_empty({[],[]}) ->
true;
is_empty({In,Out}) when is_list(In), is_list(Out) ->
@@ -72,14 +74,16 @@ is_empty(Q) ->
erlang:error(badarg, [Q]).
%% O(len(Q))
--spec len(queue()) -> non_neg_integer().
+-spec len(Q) -> non_neg_integer() when
+ Q :: queue().
len({R,F}) when is_list(R), is_list(F) ->
length(R)+length(F);
len(Q) ->
erlang:error(badarg, [Q]).
%% O(len(Q))
--spec to_list(queue()) -> list().
+-spec to_list(Q) -> list() when
+ Q :: queue().
to_list({In,Out}) when is_list(In), is_list(Out) ->
Out++lists:reverse(In, []);
to_list(Q) ->
@@ -88,7 +92,8 @@ to_list(Q) ->
%% Create queue from list
%%
%% O(length(L))
--spec from_list(list()) -> queue().
+-spec from_list(L) -> queue() when
+ L :: list().
from_list(L) when is_list(L) ->
f2r(L);
from_list(L) ->
@@ -97,7 +102,9 @@ from_list(L) ->
%% Return true or false depending on if element is in queue
%%
%% O(length(Q)) worst case
--spec member(term(), queue()) -> boolean().
+-spec member(Item, Q) -> boolean() when
+ Item :: term(),
+ Q :: queue().
member(X, {R,F}) when is_list(R), is_list(F) ->
lists:member(X, R) orelse lists:member(X, F);
member(X, Q) ->
@@ -110,7 +117,10 @@ member(X, Q) ->
%% Put at least one element in each list, if it is cheap
%%
%% O(1)
--spec in(term(), queue()) -> queue().
+-spec in(Item, Q1) -> Q2 when
+ Item :: term(),
+ Q1 :: queue(),
+ Q2 :: queue().
in(X, {[_]=In,[]}) ->
{[X], In};
in(X, {In,Out}) when is_list(In), is_list(Out) ->
@@ -122,7 +132,10 @@ in(X, Q) ->
%% Put at least one element in each list, if it is cheap
%%
%% O(1)
--spec in_r(term(), queue()) -> queue().
+-spec in_r(Item, Q1) -> Q2 when
+ Item :: term(),
+ Q1 :: queue(),
+ Q2 :: queue().
in_r(X, {[],[_]=F}) ->
{F,[X]};
in_r(X, {R,F}) when is_list(R), is_list(F) ->
@@ -133,7 +146,10 @@ in_r(X, Q) ->
%% Take from head/front
%%
%% O(1) amortized, O(len(Q)) worst case
--spec out(queue()) -> {'empty' | {'value',term()}, queue()}.
+-spec out(Q1) -> Result when
+ Q1 :: queue(),
+ Q2 :: queue(),
+ Result :: {{value, Item :: term()}, Q2} | {empty, Q1}.
out({[],[]}=Q) ->
{empty,Q};
out({[V],[]}) ->
@@ -151,7 +167,10 @@ out(Q) ->
%% Take from tail/rear
%%
%% O(1) amortized, O(len(Q)) worst case
--spec out_r(queue()) -> {'empty' | {'value',term()}, queue()}.
+-spec out_r(Q1) -> Result when
+ Q1 :: queue(),
+ Q2 :: queue(),
+ Result :: {{value, Item :: term()}, Q2} | {empty, Q1}.
out_r({[],[]}=Q) ->
{empty,Q};
out_r({[],[V]}) ->
@@ -172,7 +191,9 @@ out_r(Q) ->
%% Return the first element in the queue
%%
%% O(1) since the queue is supposed to be well formed
--spec get(queue()) -> term().
+-spec get(Q) -> Item when
+ Q :: queue(),
+ Item :: term().
get({[],[]}=Q) ->
erlang:error(empty, [Q]);
get({R,F}) when is_list(R), is_list(F) ->
@@ -191,7 +212,9 @@ get([_|R], []) -> % malformed queue -> O(len(Q))
%% Return the last element in the queue
%%
%% O(1) since the queue is supposed to be well formed
--spec get_r(queue()) -> term().
+-spec get_r(Q) -> Item when
+ Q :: queue(),
+ Item :: term().
get_r({[],[]}=Q) ->
erlang:error(empty, [Q]);
get_r({[H|_],F}) when is_list(F) ->
@@ -206,7 +229,9 @@ get_r(Q) ->
%% Return the first element in the queue
%%
%% O(1) since the queue is supposed to be well formed
--spec peek(queue()) -> 'empty' | {'value',term()}.
+-spec peek(Q) -> 'empty' | {'value',Item} when
+ Q :: queue(),
+ Item :: term().
peek({[],[]}) ->
empty;
peek({R,[H|_]}) when is_list(R) ->
@@ -221,7 +246,9 @@ peek(Q) ->
%% Return the last element in the queue
%%
%% O(1) since the queue is supposed to be well formed
--spec peek_r(queue()) -> 'empty' | {'value',term()}.
+-spec peek_r(Q) -> 'empty' | {'value',Item} when
+ Q :: queue(),
+ Item :: term().
peek_r({[],[]}) ->
empty;
peek_r({[H|_],F}) when is_list(F) ->
@@ -236,7 +263,9 @@ peek_r(Q) ->
%% Remove the first element and return resulting queue
%%
%% O(1) amortized
--spec drop(queue()) -> queue().
+-spec drop(Q1) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue().
drop({[],[]}=Q) ->
erlang:error(empty, [Q]);
drop({[_],[]}) ->
@@ -254,7 +283,9 @@ drop(Q) ->
%% Remove the last element and return resulting queue
%%
%% O(1) amortized
--spec drop_r(queue()) -> queue().
+-spec drop_r(Q1) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue().
drop_r({[],[]}=Q) ->
erlang:error(empty, [Q]);
drop_r({[],[_]}) ->
@@ -275,7 +306,9 @@ drop_r(Q) ->
%% Return reversed queue
%%
%% O(1)
--spec reverse(queue()) -> queue().
+-spec reverse(Q1) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue().
reverse({R,F}) when is_list(R), is_list(F) ->
{F,R};
reverse(Q) ->
@@ -285,7 +318,10 @@ reverse(Q) ->
%%
%% Q2 empty: O(1)
%% else: O(len(Q1))
--spec join(queue(), queue()) -> queue().
+-spec join(Q1, Q2) -> Q3 when
+ Q1 :: queue(),
+ Q2 :: queue(),
+ Q3 :: queue().
join({R,F}=Q, {[],[]}) when is_list(R), is_list(F) ->
Q;
join({[],[]}, {R,F}=Q) when is_list(R), is_list(F) ->
@@ -299,7 +335,11 @@ join(Q1, Q2) ->
%%
%% N = 0..len(Q)
%% O(max(N, len(Q)))
--spec split(non_neg_integer(), queue()) -> {queue(),queue()}.
+-spec split(N, Q1) -> {Q2,Q3} when
+ N :: non_neg_integer(),
+ Q1 :: queue(),
+ Q2 :: queue(),
+ Q3 :: queue().
split(0, {R,F}=Q) when is_list(R), is_list(F) ->
{{[],[]},Q};
split(N, {R,F}=Q) when is_integer(N), N >= 1, is_list(R), is_list(F) ->
@@ -340,7 +380,10 @@ split_r1_to_f2(N, [X|R1], F1, R2, F2) ->
%%
%% Fun(_) -> List: O(length(List) * len(Q))
%% else: O(len(Q)
--spec filter(fun((term()) -> boolean() | list()), queue()) -> queue().
+-spec filter(Fun, Q1) -> Q2 when
+ Fun :: fun((Item :: term()) -> boolean() | list()),
+ Q1 :: queue(),
+ Q2 :: queue().
filter(Fun, {R0,F0}) when is_function(Fun, 1), is_list(R0), is_list(F0) ->
F = filter_f(Fun, F0),
R = filter_r(Fun, R0),
@@ -416,7 +459,10 @@ filter_r(Fun, [X|R0]) ->
%% Cons to head
%%
--spec cons(term(), queue()) -> queue().
+-spec cons(Item, Q1) -> Q2 when
+ Item :: term(),
+ Q1 :: queue(),
+ Q2 :: queue().
cons(X, Q) ->
in_r(X, Q).
@@ -425,7 +471,9 @@ cons(X, Q) ->
%% Return the first element in the queue
%%
%% O(1) since the queue is supposed to be well formed
--spec head(queue()) -> term().
+-spec head(Q) -> Item when
+ Q :: queue(),
+ Item :: term().
head({[],[]}=Q) ->
erlang:error(empty, [Q]);
head({R,F}) when is_list(R), is_list(F) ->
@@ -435,7 +483,9 @@ head(Q) ->
%% Remove head element and return resulting queue
%%
--spec tail(queue()) -> queue().
+-spec tail(Q1) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue().
tail(Q) ->
drop(Q).
@@ -443,22 +493,35 @@ tail(Q) ->
%% Cons to tail
%%
--spec snoc(queue(), term()) -> queue().
+-spec snoc(Q1, Item) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue(),
+ Item :: term().
snoc(Q, X) ->
in(X, Q).
%% Return last element
--spec daeh(queue()) -> term().
+-spec daeh(Q) -> Item when
+ Q :: queue(),
+ Item :: term().
daeh(Q) -> get_r(Q).
--spec last(queue()) -> term().
+-spec last(Q) -> Item when
+ Q :: queue(),
+ Item :: term().
last(Q) -> get_r(Q).
%% Remove last element and return resulting queue
--spec liat(queue()) -> queue().
+-spec liat(Q1) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue().
liat(Q) -> drop_r(Q).
--spec lait(queue()) -> queue().
+-spec lait(Q1) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue().
lait(Q) -> drop_r(Q). %% Oops, mis-spelled 'tail' reversed. Forget this one.
--spec init(queue()) -> queue().
+-spec init(Q1) -> Q2 when
+ Q1 :: queue(),
+ Q2 :: queue().
init(Q) -> drop_r(Q).
%%--------------------------------------------------------------------------
diff --git a/lib/stdlib/src/random.erl b/lib/stdlib/src/random.erl
index 01227c29b4..dbb524cc74 100644
--- a/lib/stdlib/src/random.erl
+++ b/lib/stdlib/src/random.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -49,7 +49,10 @@ seed() ->
%% seed({A1, A2, A3})
%% Seed random number generation
--spec seed({integer(), integer(), integer()}) -> 'undefined' | ran().
+-spec seed({A1, A2, A3}) -> 'undefined' | ran() when
+ A1 :: integer(),
+ A2 :: integer(),
+ A3 :: integer().
seed({A1, A2, A3}) ->
seed(A1, A2, A3).
@@ -57,7 +60,10 @@ seed({A1, A2, A3}) ->
%% seed(A1, A2, A3)
%% Seed random number generation
--spec seed(integer(), integer(), integer()) -> 'undefined' | ran().
+-spec seed(A1, A2, A3) -> 'undefined' | ran() when
+ A1 :: integer(),
+ A2 :: integer(),
+ A3 :: integer().
seed(A1, A2, A3) ->
put(random_seed,
@@ -93,7 +99,8 @@ uniform() ->
%% Given an integer N >= 1, uniform(N) returns a random integer
%% between 1 and N.
--spec uniform(pos_integer()) -> pos_integer().
+-spec uniform(N) -> pos_integer() when
+ N :: pos_integer().
uniform(N) when is_integer(N), N >= 1 ->
trunc(uniform() * N) + 1.
@@ -104,7 +111,9 @@ uniform(N) when is_integer(N), N >= 1 ->
%% uniform_s(State) -> {F, NewState}
%% Returns a random float between 0 and 1.
--spec uniform_s(ran()) -> {float(), ran()}.
+-spec uniform_s(State0) -> {float(), State1} when
+ State0 :: ran(),
+ State1 :: ran().
uniform_s({A1, A2, A3}) ->
B1 = (A1*171) rem 30269,
@@ -117,7 +126,10 @@ uniform_s({A1, A2, A3}) ->
%% Given an integer N >= 1, uniform(N) returns a random integer
%% between 1 and N.
--spec uniform_s(pos_integer(), ran()) -> {integer(), ran()}.
+-spec uniform_s(N, State0) -> {integer(), State1} when
+ N :: pos_integer(),
+ State0 :: ran(),
+ State1 :: ran().
uniform_s(N, State0) when is_integer(N), N >= 1 ->
{F, State1} = uniform_s(State0),
diff --git a/lib/stdlib/src/re.erl b/lib/stdlib/src/re.erl
index e2cc9f57ce..02dbe60741 100644
--- a/lib/stdlib/src/re.erl
+++ b/lib/stdlib/src/re.erl
@@ -19,15 +19,46 @@
-module(re).
-export([grun/3,urun/3,ucompile/2,replace/3,replace/4,split/2,split/3]).
+%-opaque mp() :: {re_pattern, _, _, _}.
+-type mp() :: {re_pattern, _, _, _}.
+
+-type nl_spec() :: cr | crlf | lf | anycrlf | any.
+
+-type compile_option() :: unicode | anchored | caseless | dollar_endonly
+ | dotall | extended | firstline | multiline
+ | no_auto_capture | dupnames | ungreedy
+ | {newline, nl_spec()}| bsr_anycrlf
+ | bsr_unicode.
+
%% Emulator builtins in this module:
%% re:compile/1
%% re:compile/2
%% re:run/2
%% re:run/3
+-spec split(Subject, RE) -> SplitList when
+ Subject :: iodata() | unicode:charlist(),
+ RE :: mp() | iodata(),
+ SplitList :: [iodata() | unicode:charlist()].
+
split(Subject,RE) ->
split(Subject,RE,[]).
+-spec split(Subject, RE, Options) -> SplitList when
+ Subject :: iodata() | unicode:charlist(),
+ RE :: mp() | iodata(),
+ Options :: [ Option ],
+ Option :: anchored | global | notbol | noteol | notempty
+ | {offset, non_neg_integer()} | {newline, nl_spec()}
+ | bsr_anycrlf | bsr_unicode | {return, ReturnType}
+ | {parts, NumParts} | group | trim | CompileOpt,
+ NumParts :: non_neg_integer() | infinity,
+ ReturnType :: iodata | list | binary,
+ CompileOpt :: compile_option(),
+ SplitList :: [RetData] | [GroupedRetData],
+ GroupedRetData :: [RetData],
+ RetData :: iodata() | unicode:charlist() | binary() | list().
+
split(Subject,RE,Options) ->
try
{NewOpt,Convert,Unicode,Limit,Strip,Group} =
@@ -197,10 +228,26 @@ compile_split(Pat,Options0) when not is_tuple(Pat) ->
compile_split(_,_) ->
throw(badre).
+-spec replace(Subject, RE, Replacement) -> iodata() | unicode:charlist() when
+ Subject :: iodata() | unicode:charlist(),
+ RE :: mp() | iodata(),
+ Replacement :: iodata() | unicode:charlist().
replace(Subject,RE,Replacement) ->
replace(Subject,RE,Replacement,[]).
+-spec replace(Subject, RE, Replacement, Options) -> iodata() | unicode:charlist() when
+ Subject :: iodata() | unicode:charlist(),
+ RE :: mp() | iodata(),
+ Replacement :: iodata() | unicode:charlist(),
+ Options :: [Option],
+ Option :: anchored | global | notbol | noteol | notempty
+ | {offset, non_neg_integer()} | {newline, NLSpec} | bsr_anycrlf
+ | bsr_unicode | {return, ReturnType} | CompileOpt,
+ ReturnType :: iodata | list | binary,
+ CompileOpt :: compile_option(),
+ NLSpec :: cr | crlf | lf | anycrlf | any.
+
replace(Subject,RE,Replacement,Options) ->
try
{NewOpt,Convert,Unicode} =
diff --git a/lib/stdlib/src/regexp.erl b/lib/stdlib/src/regexp.erl
index 8f5994bbee..65f9ca247d 100644
--- a/lib/stdlib/src/regexp.erl
+++ b/lib/stdlib/src/regexp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -37,6 +37,9 @@
-import(string, [substr/2,substr/3]).
-import(lists, [reverse/1]).
+-type errordesc() :: term().
+-opaque regexp() :: term().
+
%% -type matchres() = {match,Start,Length} | nomatch | {error,E}.
%% -type subres() = {ok,RepString,RepCount} | {error,E}.
%% -type splitres() = {ok,[SubString]} | {error,E}.
@@ -287,6 +290,10 @@ re_apply_or(R1, nomatch) -> R1.
%% Convert a sh style regexp into a full AWK one. The main difficulty is
%% getting character sets right as the conventions are different.
+-spec sh_to_awk(ShRegExp) -> AwkRegExp when
+ ShRegExp :: string(),
+ AwkRegExp :: string().
+
sh_to_awk(Sh) -> "^(" ++ sh_to_awk_1(Sh). %Fix the beginning
sh_to_awk_1([$*|Sh]) -> %This matches any string
@@ -336,6 +343,12 @@ special_char(_C) -> false.
%% parse(RegExp) -> {ok,RE} | {error,E}.
%% Parse the regexp described in the string RegExp.
+-spec parse(RegExp) -> ParseRes when
+ RegExp :: string(),
+ ParseRes :: {ok, RE} | {error, Error},
+ RE :: regexp(),
+ Error :: errordesc().
+
parse(S) ->
case catch reg(S) of
{R,[]} -> {ok,R};
@@ -345,6 +358,10 @@ parse(S) ->
%% format_error(Error) -> String.
+-spec format_error(ErrorDescriptor) -> Chars when
+ ErrorDescriptor :: errordesc(),
+ Chars :: io_lib:chars().
+
format_error({illegal,What}) -> ["illegal character `",What,"'"];
format_error({unterminated,What}) -> ["unterminated `",What,"'"];
format_error({char_class,What}) ->
@@ -353,6 +370,14 @@ format_error({char_class,What}) ->
%% -type match(String, RegExp) -> matchres().
%% Find the longest match of RegExp in String.
+-spec match(String, RegExp) -> MatchRes when
+ String :: string(),
+ RegExp :: string() | regexp(),
+ MatchRes :: {match, Start, Length} | nomatch | {error, Error},
+ Start :: pos_integer(),
+ Length :: pos_integer(),
+ Error :: errordesc().
+
match(S, RegExp) when is_list(RegExp) ->
case parse(RegExp) of
{ok,RE} -> match(S, RE);
@@ -378,6 +403,14 @@ match(RE, S, St, Pos, L) ->
%% -type first_match(String, RegExp) -> matchres().
%% Find the first match of RegExp in String.
+-spec first_match(String, RegExp) -> MatchRes when
+ String :: string(),
+ RegExp :: string() | regexp(),
+ MatchRes :: {match, Start, Length} | nomatch | {error, Error},
+ Start :: pos_integer(),
+ Length :: pos_integer(),
+ Error :: errordesc().
+
first_match(S, RegExp) when is_list(RegExp) ->
case parse(RegExp) of
{ok,RE} -> first_match(S, RE);
@@ -400,6 +433,15 @@ first_match(_RE, [], _St) -> nomatch.
%% -type matches(String, RegExp) -> {match,[{Start,Length}]} | {error,E}.
%% Return the all the non-overlapping matches of RegExp in String.
+-spec matches(String, RegExp) -> MatchRes when
+ String :: string(),
+ RegExp :: string() | regexp(),
+ MatchRes :: {match, Matches} | {error, Error},
+ Matches :: [{Start, Length}],
+ Start :: pos_integer(),
+ Length :: pos_integer(),
+ Error :: errordesc().
+
matches(S, RegExp) when is_list(RegExp) ->
case parse(RegExp) of
{ok,RE} -> matches(S, RE);
@@ -420,6 +462,15 @@ matches(S, RE, St) ->
%% the string Replace in String. Accept pre-parsed regular
%% expressions.
+-spec sub(String, RegExp, New) -> SubRes when
+ String :: string(),
+ RegExp :: string() | regexp(),
+ New :: string(),
+ NewString :: string(),
+ SubRes :: {ok, NewString, RepCount} | {error, Error},
+ RepCount :: 0 | 1,
+ Error :: errordesc().
+
sub(String, RegExp, Rep) when is_list(RegExp) ->
case parse(RegExp) of
{ok,RE} -> sub(String, RE, Rep);
@@ -449,6 +500,15 @@ sub_repl([], _M, Rest) -> Rest.
%% Substitute every match of the regular expression RegExp with the
%% string New in String. Accept pre-parsed regular expressions.
+-spec gsub(String, RegExp, New) -> SubRes when
+ String :: string(),
+ RegExp :: string() | regexp(),
+ New :: string(),
+ NewString :: string(),
+ SubRes :: {ok, NewString, RepCount} | {error, Error},
+ RepCount :: non_neg_integer(),
+ Error :: errordesc().
+
gsub(String, RegExp, Rep) when is_list(RegExp) ->
case parse(RegExp) of
{ok,RE} -> gsub(String, RE, Rep);
@@ -462,6 +522,13 @@ gsub(String, RE, Rep) ->
%% Split a string into substrings where the RegExp describes the
%% field seperator. The RegExp " " is specially treated.
+-spec split(String, RegExp) -> SplitRes when
+ String :: string(),
+ RegExp :: string() | regexp(),
+ SplitRes :: {ok, FieldList} | {error, Error},
+ FieldList :: [string()],
+ Error :: errordesc().
+
split(String, " ") -> %This is really special
{ok,RE} = parse("[ \t]+"),
case split_apply(String, RE, true) of
diff --git a/lib/stdlib/src/sets.erl b/lib/stdlib/src/sets.erl
index bcddca2567..3fd6c81e5f 100644
--- a/lib/stdlib/src/sets.erl
+++ b/lib/stdlib/src/sets.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2000-2009. All Rights Reserved.
+%% 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
@@ -84,30 +84,38 @@ new() ->
%% is_set(Set) -> boolean().
%% Return 'true' if Set is a set of elements, else 'false'.
--spec is_set(term()) -> boolean().
+-spec is_set(Set) -> boolean() when
+ Set :: term().
is_set(#set{}) -> true;
is_set(_) -> false.
%% size(Set) -> int().
%% Return the number of elements in Set.
--spec size(set()) -> non_neg_integer().
+-spec size(Set) -> non_neg_integer() when
+ Set :: set().
size(S) -> S#set.size.
%% to_list(Set) -> [Elem].
%% Return the elements in Set as a list.
--spec to_list(set()) -> [term()].
+-spec to_list(Set) -> List when
+ Set :: set(),
+ List :: [term()].
to_list(S) ->
fold(fun (Elem, List) -> [Elem|List] end, [], S).
%% from_list([Elem]) -> Set.
%% Build a set from the elements in List.
--spec from_list([term()]) -> set().
+-spec from_list(List) -> Set when
+ List :: [term()],
+ Set :: set().
from_list(L) ->
lists:foldl(fun (E, S) -> add_element(E, S) end, new(), L).
%% is_element(Element, Set) -> boolean().
%% Return 'true' if Element is an element of Set, else 'false'.
--spec is_element(term(), set()) -> boolean().
+-spec is_element(Element, Set) -> boolean() when
+ Element :: term(),
+ Set :: set().
is_element(E, S) ->
Slot = get_slot(S, E),
Bkt = get_bucket(S, Slot),
@@ -115,7 +123,10 @@ is_element(E, S) ->
%% add_element(Element, Set) -> Set.
%% Return Set with Element inserted in it.
--spec add_element(term(), set()) -> set().
+-spec add_element(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: set(),
+ Set2 :: set().
add_element(E, S0) ->
Slot = get_slot(S0, E),
{S1,Ic} = on_bucket(fun (B0) -> add_bkt_el(E, B0, B0) end, S0, Slot),
@@ -129,7 +140,10 @@ add_bkt_el(E, [], Bkt) -> {[E|Bkt],1}.
%% del_element(Element, Set) -> Set.
%% Return Set but with Element removed.
--spec del_element(term(), set()) -> set().
+-spec del_element(Element, Set1) -> Set2 when
+ Element :: term(),
+ Set1 :: set(),
+ Set2 :: set().
del_element(E, S0) ->
Slot = get_slot(S0, E),
{S1,Dc} = on_bucket(fun (B0) -> del_bkt_el(E, B0) end, S0, Slot),
@@ -144,7 +158,10 @@ del_bkt_el(_, []) -> {[],0}.
%% union(Set1, Set2) -> Set
%% Return the union of Set1 and Set2.
--spec union(set(), set()) -> set().
+-spec union(Set1, Set2) -> Set3 when
+ Set1 :: set(),
+ Set2 :: set(),
+ Set3 :: set().
union(S1, S2) when S1#set.size < S2#set.size ->
fold(fun (E, S) -> add_element(E, S) end, S2, S1);
union(S1, S2) ->
@@ -152,7 +169,9 @@ union(S1, S2) ->
%% union([Set]) -> Set
%% Return the union of the list of sets.
--spec union([set()]) -> set().
+-spec union(SetList) -> Set when
+ SetList :: [set()],
+ Set :: set().
union([S1,S2|Ss]) ->
union1(union(S1, S2), Ss);
union([S]) -> S;
@@ -165,7 +184,10 @@ union1(S1, []) -> S1.
%% intersection(Set1, Set2) -> Set.
%% Return the intersection of Set1 and Set2.
--spec intersection(set(), set()) -> set().
+-spec intersection(Set1, Set2) -> Set3 when
+ Set1 :: set(),
+ Set2 :: set(),
+ Set3 :: set().
intersection(S1, S2) when S1#set.size < S2#set.size ->
filter(fun (E) -> is_element(E, S2) end, S1);
intersection(S1, S2) ->
@@ -173,7 +195,9 @@ intersection(S1, S2) ->
%% intersection([Set]) -> Set.
%% Return the intersection of the list of sets.
--spec intersection([set(),...]) -> set().
+-spec intersection(SetList) -> Set when
+ SetList :: [set(),...],
+ Set :: set().
intersection([S1,S2|Ss]) ->
intersection1(intersection(S1, S2), Ss);
intersection([S]) -> S.
@@ -185,7 +209,9 @@ intersection1(S1, []) -> S1.
%% is_disjoint(Set1, Set2) -> boolean().
%% Check whether Set1 and Set2 are disjoint.
--spec is_disjoint(set(), set()) -> boolean().
+-spec is_disjoint(Set1, Set2) -> boolean() when
+ Set1 :: set(),
+ Set2 :: set().
is_disjoint(S1, S2) when S1#set.size < S2#set.size ->
fold(fun (_, false) -> false;
(E, true) -> not is_element(E, S2)
@@ -198,25 +224,39 @@ is_disjoint(S1, S2) ->
%% subtract(Set1, Set2) -> Set.
%% Return all and only the elements of Set1 which are not also in
%% Set2.
--spec subtract(set(), set()) -> set().
+-spec subtract(Set1, Set2) -> Set3 when
+ Set1 :: set(),
+ Set2 :: set(),
+ Set3 :: set().
subtract(S1, S2) ->
filter(fun (E) -> not is_element(E, S2) end, S1).
%% is_subset(Set1, Set2) -> boolean().
%% Return 'true' when every element of Set1 is also a member of
%% Set2, else 'false'.
--spec is_subset(set(), set()) -> boolean().
+-spec is_subset(Set1, Set2) -> boolean() when
+ Set1 :: set(),
+ Set2 :: set().
is_subset(S1, S2) ->
fold(fun (E, Sub) -> Sub andalso is_element(E, S2) end, true, S1).
%% fold(Fun, Accumulator, Set) -> Accumulator.
%% Fold function Fun over all elements in Set and return Accumulator.
--spec fold(fun((_,_) -> _), T, set()) -> T.
+-spec fold(Function, Acc0, Set) -> Acc1 when
+ Function :: fun((E :: term(),AccIn) -> AccOut),
+ Set :: set(),
+ Acc0 :: T,
+ Acc1 :: T,
+ AccIn :: T,
+ AccOut :: T.
fold(F, Acc, D) -> fold_set(F, Acc, D).
%% filter(Fun, Set) -> Set.
%% Filter Set with Fun.
--spec filter(fun((_) -> boolean()), set()) -> set().
+-spec filter(Pred, Set1) -> Set2 when
+ Pred :: fun((E :: term()) -> boolean()),
+ Set1 :: set(),
+ Set2 :: set().
filter(F, D) -> filter_set(F, D).
%% get_slot(Hashdb, Key) -> Slot.
diff --git a/lib/stdlib/src/shell.erl b/lib/stdlib/src/shell.erl
index ebb221c151..e3e23e09bc 100644
--- a/lib/stdlib/src/shell.erl
+++ b/lib/stdlib/src/shell.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2010. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -115,7 +115,9 @@ whereis_evaluator(Shell) ->
%% Call this function to start a user restricted shell
%% from a normal shell session.
--spec start_restricted(module()) -> {'error', code:load_error_rsn()}.
+-spec start_restricted(Module) -> {'error', Reason} when
+ Module :: module(),
+ Reason :: code:load_error_rsn().
start_restricted(RShMod) when is_atom(RShMod) ->
case code:ensure_loaded(RShMod) of
@@ -465,7 +467,7 @@ getc(N) ->
{get({command,N}), get({result,N}), N}.
get_cmd(Num, C) ->
- case catch erl_eval:expr(Num, []) of
+ case catch erl_eval:expr(Num, erl_eval:new_bindings()) of
{value,N,_} when N < 0 -> getc(C+N);
{value,N,_} -> getc(N);
_Other -> {undefined,undefined,undefined}
@@ -1184,6 +1186,8 @@ expr(E, Bs, Lf, Ef) ->
expr_list(Es, Bs, Lf, Ef) ->
erl_eval:expr_list(Es, strip_bindings(Bs), Lf, Ef).
+-spec strip_bindings(erl_eval:binding_struct()) -> erl_eval:binding_struct().
+
strip_bindings(Bs) ->
Bs -- [B || {{module,_},_}=B <- Bs].
@@ -1468,23 +1472,26 @@ set_env(App, Name, Val, Default) ->
application_controller:set_env(App, Name, Val),
Prev.
--spec history(non_neg_integer()) -> non_neg_integer().
+-spec history(N) -> non_neg_integer() when
+ N :: non_neg_integer().
history(L) when is_integer(L), L >= 0 ->
set_env(stdlib, shell_history_length, L, ?DEF_HISTORY).
--spec results(non_neg_integer()) -> non_neg_integer().
+-spec results(N) -> non_neg_integer() when
+ N :: non_neg_integer().
results(L) when is_integer(L), L >= 0 ->
set_env(stdlib, shell_saved_results, L, ?DEF_RESULTS).
--spec catch_exception(boolean()) -> boolean().
+-spec catch_exception(Bool) -> Bool when
+ Bool :: boolean().
catch_exception(Bool) ->
set_env(stdlib, shell_catch_exception, Bool, ?DEF_CATCH_EXCEPTION).
--type prompt_func() :: 'default' | {module(),atom()}.
--spec prompt_func(prompt_func()) -> prompt_func().
+-spec prompt_func(PromptFunc) -> PromptFunc when
+ PromptFunc :: 'default' | {module(),atom()}.
prompt_func(String) ->
set_env(stdlib, shell_prompt_func, String, ?DEF_PROMPT_FUNC).
diff --git a/lib/stdlib/src/slave.erl b/lib/stdlib/src/slave.erl
index 196b659938..d79ee676d9 100644
--- a/lib/stdlib/src/slave.erl
+++ b/lib/stdlib/src/slave.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -54,6 +54,10 @@ pseudo([Master | ServerList]) ->
pseudo(_) ->
error_msg("No master node given to slave:pseudo/1~n",[]).
+-spec pseudo(Master, ServerList) -> ok when
+ Master :: node(),
+ ServerList :: [atom()].
+
pseudo(_, []) -> ok;
pseudo(Master, [S|Tail]) ->
start_pseudo(S, whereis(S), Master),
@@ -68,6 +72,9 @@ start_pseudo(_,_,_) -> ok. %% It's already there
%% This relay can be used to relay all messages directed to a process.
+-spec relay(Pid) -> none() when
+ Pid :: pid().
+
relay({badrpc,Reason}) ->
error_msg(" ** exiting relay server ~w :~w **~n", [self(),Reason]),
exit(Reason);
@@ -120,25 +127,61 @@ relay1(Pid) ->
%% {error, no_rsh} |
%% {error, {already_running, Name@Host}}
+-spec start(Host) -> {ok, Node} | {error, Reason} when
+ Host :: atom(),
+ Node :: node(),
+ Reason :: timeout | no_rsh | {already_running, Node}.
+
start(Host) ->
L = atom_to_list(node()),
Name = upto($@, L),
- start(Host, Name).
+ start(Host, Name, [], no_link).
+
+-spec start(Host, Name) -> {ok, Node} | {error, Reason} when
+ Host :: atom(),
+ Name :: atom(),
+ Node :: node(),
+ Reason :: timeout | no_rsh | {already_running, Node}.
start(Host, Name) ->
start(Host, Name, []).
+-spec start(Host, Name, Args) -> {ok, Node} | {error, Reason} when
+ Host :: atom(),
+ Name :: atom(),
+ Args :: string(),
+ Node :: node(),
+ Reason :: timeout | no_rsh | {already_running, Node}.
+
start(Host, Name, Args) ->
start(Host, Name, Args, no_link).
+-spec start_link(Host) -> {ok, Node} | {error, Reason} when
+ Host :: atom(),
+ Node :: node(),
+ Reason :: timeout | no_rsh | {already_running, Node}.
+
start_link(Host) ->
L = atom_to_list(node()),
Name = upto($@, L),
- start_link(Host, Name).
+ start(Host, Name, [], self()).
+
+-spec start_link(Host, Name) -> {ok, Node} | {error, Reason} when
+ Host :: atom(),
+ Name :: atom(),
+ Node :: node(),
+ Reason :: timeout | no_rsh | {already_running, Node}.
start_link(Host, Name) ->
start_link(Host, Name, []).
+-spec start_link(Host, Name, Args) -> {ok, Node} | {error, Reason} when
+ Host :: atom(),
+ Name :: atom(),
+ Args :: string(),
+ Node :: node(),
+ Reason :: timeout | no_rsh | {already_running, Node}.
+
start_link(Host, Name, Args) ->
start(Host, Name, Args, self()).
@@ -163,6 +206,9 @@ start(Host0, Name, Args, LinkTo, Prog) ->
%% Stops a running node.
+-spec stop(Node) -> ok when
+ Node :: node().
+
stop(Node) ->
% io:format("stop(~p)~n", [Node]),
rpc:call(Node, erlang, halt, []),
diff --git a/lib/stdlib/src/sofs.erl b/lib/stdlib/src/sofs.erl
index a83f803330..d38b8ab37a 100644
--- a/lib/stdlib/src/sofs.erl
+++ b/lib/stdlib/src/sofs.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2001-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2001-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(sofs).
@@ -40,11 +40,11 @@
substitution/2, projection/2, partition/1, partition/2,
partition/3, multiple_relative_product/2, join/4]).
--export([family_to_relation/1, family_specification/2,
+-export([family_to_relation/1, family_specification/2,
union_of_family/1, intersection_of_family/1,
family_union/1, family_intersection/1,
family_domain/1, family_range/1, family_field/1,
- family_union/2, family_intersection/2, family_difference/2,
+ family_union/2, family_intersection/2, family_difference/2,
partition_family/2, family_projection/2]).
-export([family_to_digraph/1, family_to_digraph/2,
@@ -64,9 +64,9 @@
-compile({inline, [{external_fun,1},{element_type,1}]}).
--compile({inline,
+-compile({inline,
[{unify_types,2}, {match_types,2},
- {test_rel,3}, {symdiff,3},
+ {test_rel,3}, {symdiff,3},
{subst,3}]}).
-compile({inline, [{fam_binop,3}]}).
@@ -80,13 +80,13 @@
-define(TAG, 'Set').
-define(ORDTAG, 'OrdSet').
--record(?TAG, {data = [], type = type}).
--record(?ORDTAG, {orddata = {}, ordtype = type}).
+-record(?TAG, {data = [] :: list(), type = type :: term()}).
+-record(?ORDTAG, {orddata = {} :: tuple(), ordtype = type :: term()}).
-define(LIST(S), (S)#?TAG.data).
-define(TYPE(S), (S)#?TAG.type).
-%%-define(SET(L, T),
-%% case is_type(T) of
+%%-define(SET(L, T),
+%% case is_type(T) of
%% true -> #?TAG{data = L, type = T};
%% false -> erlang:error(badtype, [T])
%% end
@@ -113,14 +113,40 @@
-define(IS_SET_OF(X), is_list(X)).
-define(FAMILY(X, Y), ?BINREL(X, ?SET_OF(Y))).
+-export_type([anyset/0, binary_relation/0, external_set/0, a_function/0,
+ family/0, relation/0, set_of_sets/0, set_fun/0, spec_fun/0,
+ type/0]).
+-export_type([ordset/0, a_set/0]).
+
+-type(anyset() :: ordset() | a_set()).
+-type(binary_relation() :: relation()).
+-type(external_set() :: term()).
+-type(a_function() :: relation()).
+-type(family() :: a_function()).
+-opaque(ordset() :: #?ORDTAG{}).
+-type(relation() :: a_set()).
+-opaque(a_set() :: #?TAG{}).
+-type(set_of_sets() :: a_set()).
+-type(set_fun() :: pos_integer()
+ | {external, fun((external_set()) -> external_set())}
+ | fun((anyset()) -> anyset())).
+-type(spec_fun() :: {external, fun((external_set()) -> boolean())}
+ | fun((anyset()) -> boolean())).
+-type(type() :: term()).
+
+-type(tuple_of(_T) :: tuple()).
+
%%
%% Exported functions
%%
-%%%
+%%%
%%% Create sets
-%%%
+%%%
+-spec(from_term(Term) -> AnySet when
+ AnySet :: anyset(),
+ Term :: term()).
from_term(T) ->
Type = case T of
_ when is_list(T) -> [?ANYTYPE];
@@ -133,6 +159,10 @@ from_term(T) ->
Set
end.
+-spec(from_term(Term, Type) -> AnySet when
+ AnySet :: anyset(),
+ Term :: term(),
+ Type :: type()).
from_term(L, T) ->
case is_type(T) of
true ->
@@ -146,14 +176,23 @@ from_term(L, T) ->
erlang:error(badarg, [L, T])
end.
+-spec(from_external(ExternalSet, Type) -> AnySet when
+ ExternalSet :: external_set(),
+ AnySet :: anyset(),
+ Type :: type()).
from_external(L, ?SET_OF(Type)) ->
?SET(L, Type);
from_external(T, Type) ->
?ORDSET(T, Type).
+-spec(empty_set() -> Set when
+ Set :: a_set()).
empty_set() ->
?SET([], ?ANYTYPE).
+-spec(is_type(Term) -> Bool when
+ Bool :: boolean(),
+ Term :: term()).
is_type(Atom) when ?IS_ATOM_TYPE(Atom), Atom =/= ?ANYTYPE ->
true;
is_type(?SET_OF(T)) ->
@@ -163,19 +202,26 @@ is_type(T) when tuple_size(T) > 0 ->
is_type(_T) ->
false.
+-spec(set(Terms) -> Set when
+ Set :: a_set(),
+ Terms :: [term()]).
set(L) ->
case catch usort(L) of
{'EXIT', _} ->
erlang:error(badarg, [L]);
- SL ->
+ SL ->
?SET(SL, ?ATOM_TYPE)
end.
+-spec(set(Terms, Type) -> Set when
+ Set :: a_set(),
+ Terms :: [term()],
+ Type :: type()).
set(L, ?SET_OF(Type) = T) when ?IS_ATOM_TYPE(Type), Type =/= ?ANYTYPE ->
case catch usort(L) of
{'EXIT', _} ->
erlang:error(badarg, [L, T]);
- SL ->
+ SL ->
?SET(SL, Type)
end;
set(L, ?SET_OF(_) = T) ->
@@ -188,6 +234,12 @@ set(L, ?SET_OF(_) = T) ->
set(L, T) ->
erlang:error(badarg, [L, T]).
+-spec(from_sets(ListOfSets) -> Set when
+ Set :: a_set(),
+ ListOfSets :: [anyset()];
+ (TupleOfSets) -> Ordset when
+ Ordset :: ordset(),
+ TupleOfSets :: tuple_of(anyset())).
from_sets(Ss) when is_list(Ss) ->
case set_of_sets(Ss, [], ?ANYTYPE) of
{error, Error} ->
@@ -205,6 +257,9 @@ from_sets(Tuple) when is_tuple(Tuple) ->
from_sets(T) ->
erlang:error(badarg, [T]).
+-spec(relation(Tuples) -> Relation when
+ Relation :: relation(),
+ Tuples :: [tuple()]).
relation([]) ->
?SET([], ?BINREL(?ATOM_TYPE, ?ATOM_TYPE));
relation(Ts = [T | _]) when is_tuple(T) ->
@@ -217,6 +272,11 @@ relation(Ts = [T | _]) when is_tuple(T) ->
relation(E) ->
erlang:error(badarg, [E]).
+-spec(relation(Tuples, Type) -> Relation when
+ N :: integer(),
+ Type :: N | type(),
+ Relation :: relation(),
+ Tuples :: [tuple()]).
relation(Ts, TS) ->
case catch rel(Ts, TS) of
{'EXIT', _} ->
@@ -225,6 +285,9 @@ relation(Ts, TS) ->
Set
end.
+-spec(a_function(Tuples) -> Function when
+ Function :: a_function(),
+ Tuples :: [tuple()]).
a_function(Ts) ->
case catch func(Ts, ?BINREL(?ATOM_TYPE, ?ATOM_TYPE)) of
{'EXIT', _} ->
@@ -235,6 +298,10 @@ a_function(Ts) ->
Set
end.
+-spec(a_function(Tuples, Type) -> Function when
+ Function :: a_function(),
+ Tuples :: [tuple()],
+ Type :: type()).
a_function(Ts, T) ->
case catch a_func(Ts, T) of
{'EXIT', _} ->
@@ -245,6 +312,9 @@ a_function(Ts, T) ->
Set
end.
+-spec(family(Tuples) -> Family when
+ Family :: family(),
+ Tuples :: [tuple()]).
family(Ts) ->
case catch fam2(Ts, ?FAMILY(?ATOM_TYPE, ?ATOM_TYPE)) of
{'EXIT', _} ->
@@ -255,6 +325,10 @@ family(Ts) ->
Set
end.
+-spec(family(Tuples, Type) -> Family when
+ Family :: family(),
+ Tuples :: [tuple()],
+ Type :: type()).
family(Ts, T) ->
case catch fam(Ts, T) of
{'EXIT', _} ->
@@ -265,20 +339,30 @@ family(Ts, T) ->
Set
end.
-%%%
+%%%
%%% Functions on sets.
-%%%
+%%%
+-spec(to_external(AnySet) -> ExternalSet when
+ ExternalSet :: external_set(),
+ AnySet :: anyset()).
to_external(S) when ?IS_SET(S) ->
?LIST(S);
to_external(S) when ?IS_ORDSET(S) ->
?ORDDATA(S).
+-spec(type(AnySet) -> Type when
+ AnySet :: anyset(),
+ Type :: type()).
type(S) when ?IS_SET(S) ->
?SET_OF(?TYPE(S));
type(S) when ?IS_ORDSET(S) ->
?ORDTYPE(S).
+-spec(to_sets(ASet) -> Sets when
+ ASet :: a_set() | ordset(),
+ Sets :: tuple_of(AnySet) | [AnySet],
+ AnySet :: anyset()).
to_sets(S) when ?IS_SET(S) ->
case ?TYPE(S) of
?SET_OF(Type) -> list_of_sets(?LIST(S), Type, []);
@@ -289,6 +373,9 @@ to_sets(S) when ?IS_ORDSET(S), is_tuple(?ORDTYPE(S)) ->
to_sets(S) when ?IS_ORDSET(S) ->
erlang:error(badarg, [S]).
+-spec(no_elements(ASet) -> NoElements when
+ ASet :: a_set() | ordset(),
+ NoElements :: pos_integer()).
no_elements(S) when ?IS_SET(S) ->
length(?LIST(S));
no_elements(S) when ?IS_ORDSET(S), is_tuple(?ORDTYPE(S)) ->
@@ -296,6 +383,10 @@ no_elements(S) when ?IS_ORDSET(S), is_tuple(?ORDTYPE(S)) ->
no_elements(S) when ?IS_ORDSET(S) ->
erlang:error(badarg, [S]).
+-spec(specification(Fun, Set1) -> Set2 when
+ Fun :: spec_fun(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
specification(Fun, S) when ?IS_SET(S) ->
Type = ?TYPE(S),
R = case external_fun(Fun) of
@@ -311,36 +402,62 @@ specification(Fun, S) when ?IS_SET(S) ->
erlang:error(Bad, [Fun, S])
end.
+-spec(union(Set1, Set2) -> Set3 when
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set()).
union(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case unify_types(?TYPE(S1), ?TYPE(S2)) of
[] -> erlang:error(type_mismatch, [S1, S2]);
Type -> ?SET(umerge(?LIST(S1), ?LIST(S2)), Type)
end.
+-spec(intersection(Set1, Set2) -> Set3 when
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set()).
intersection(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case unify_types(?TYPE(S1), ?TYPE(S2)) of
[] -> erlang:error(type_mismatch, [S1, S2]);
Type -> ?SET(intersection(?LIST(S1), ?LIST(S2), []), Type)
end.
+-spec(difference(Set1, Set2) -> Set3 when
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set()).
difference(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case unify_types(?TYPE(S1), ?TYPE(S2)) of
[] -> erlang:error(type_mismatch, [S1, S2]);
Type -> ?SET(difference(?LIST(S1), ?LIST(S2), []), Type)
end.
+-spec(symdiff(Set1, Set2) -> Set3 when
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set()).
symdiff(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case unify_types(?TYPE(S1), ?TYPE(S2)) of
[] -> erlang:error(type_mismatch, [S1, S2]);
Type -> ?SET(symdiff(?LIST(S1), ?LIST(S2), []), Type)
end.
+-spec(symmetric_partition(Set1, Set2) -> {Set3, Set4, Set5} when
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set(),
+ Set4 :: a_set(),
+ Set5 :: a_set()).
symmetric_partition(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case unify_types(?TYPE(S1), ?TYPE(S2)) of
[] -> erlang:error(type_mismatch, [S1, S2]);
Type -> sympart(?LIST(S1), ?LIST(S2), [], [], [], Type)
end.
+-spec(product(Set1, Set2) -> BinRel when
+ BinRel :: binary_relation(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
product(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
if
?TYPE(S1) =:= ?ANYTYPE -> S1;
@@ -351,6 +468,9 @@ product(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
?SET(relprod(map(F, ?LIST(S1)), map(F, ?LIST(S2))), T)
end.
+-spec(product(TupleOfSets) -> Relation when
+ Relation :: relation(),
+ TupleOfSets :: tuple_of(a_set())).
product({S1, S2}) ->
product(S1, S2);
product(T) when is_tuple(T) ->
@@ -365,11 +485,15 @@ product(T) when is_tuple(T) ->
case member([], L) of
true ->
empty_set();
- false ->
+ false ->
?SET(reverse(prod(L, [], [])), Type)
end
end.
+-spec(constant_function(Set, AnySet) -> Function when
+ AnySet :: anyset(),
+ Function :: a_function(),
+ Set :: a_set()).
constant_function(S, E) when ?IS_SET(S) ->
case {?TYPE(S), is_sofs_set(E)} of
{?ANYTYPE, true} -> S;
@@ -381,6 +505,10 @@ constant_function(S, E) when ?IS_SET(S) ->
constant_function(S, E) when ?IS_ORDSET(S) ->
erlang:error(badarg, [S, E]).
+-spec(is_equal(AnySet1, AnySet2) -> Bool when
+ AnySet1 :: anyset(),
+ AnySet2 :: anyset(),
+ Bool :: boolean()).
is_equal(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case match_types(?TYPE(S1), ?TYPE(S2)) of
true -> ?LIST(S1) == ?LIST(S2);
@@ -396,12 +524,19 @@ is_equal(S1, S2) when ?IS_SET(S1), ?IS_ORDSET(S2) ->
is_equal(S1, S2) when ?IS_ORDSET(S1), ?IS_SET(S2) ->
erlang:error(type_mismatch, [S1, S2]).
+-spec(is_subset(Set1, Set2) -> Bool when
+ Bool :: boolean(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
is_subset(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case match_types(?TYPE(S1), ?TYPE(S2)) of
true -> subset(?LIST(S1), ?LIST(S2));
false -> erlang:error(type_mismatch, [S1, S2])
end.
+-spec(is_sofs_set(Term) -> Bool when
+ Bool :: boolean(),
+ Term :: term()).
is_sofs_set(S) when ?IS_SET(S) ->
true;
is_sofs_set(S) when ?IS_ORDSET(S) ->
@@ -409,16 +544,26 @@ is_sofs_set(S) when ?IS_ORDSET(S) ->
is_sofs_set(_S) ->
false.
+-spec(is_set(AnySet) -> Bool when
+ AnySet :: anyset(),
+ Bool :: boolean()).
is_set(S) when ?IS_SET(S) ->
true;
is_set(S) when ?IS_ORDSET(S) ->
false.
-is_empty_set(S) when ?IS_SET(S) ->
+-spec(is_empty_set(AnySet) -> Bool when
+ AnySet :: anyset(),
+ Bool :: boolean()).
+is_empty_set(S) when ?IS_SET(S) ->
?LIST(S) =:= [];
is_empty_set(S) when ?IS_ORDSET(S) ->
false.
+-spec(is_disjoint(Set1, Set2) -> Bool when
+ Bool :: boolean(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
is_disjoint(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
case match_types(?TYPE(S1), ?TYPE(S2)) of
true ->
@@ -433,6 +578,9 @@ is_disjoint(S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
%%% Functions on set-of-sets.
%%%
+-spec(union(SetOfSets) -> Set when
+ Set :: a_set(),
+ SetOfSets :: set_of_sets()).
union(Sets) when ?IS_SET(Sets) ->
case ?TYPE(Sets) of
?SET_OF(Type) -> ?SET(lunion(?LIST(Sets)), Type);
@@ -440,6 +588,9 @@ union(Sets) when ?IS_SET(Sets) ->
_ -> erlang:error(badarg, [Sets])
end.
+-spec(intersection(SetOfSets) -> Set when
+ Set :: a_set(),
+ SetOfSets :: set_of_sets()).
intersection(Sets) when ?IS_SET(Sets) ->
case ?LIST(Sets) of
[] -> erlang:error(badarg, [Sets]);
@@ -451,32 +602,41 @@ intersection(Sets) when ?IS_SET(Sets) ->
end
end.
+-spec(canonical_relation(SetOfSets) -> BinRel when
+ BinRel :: binary_relation(),
+ SetOfSets :: set_of_sets()).
canonical_relation(Sets) when ?IS_SET(Sets) ->
ST = ?TYPE(Sets),
case ST of
?SET_OF(?ANYTYPE) -> empty_set();
- ?SET_OF(Type) ->
+ ?SET_OF(Type) ->
?SET(can_rel(?LIST(Sets), []), ?BINREL(Type, ST));
?ANYTYPE -> Sets;
_ -> erlang:error(badarg, [Sets])
end.
-%%%
+%%%
%%% Functions on binary relations only.
-%%%
+%%%
rel2fam(R) ->
relation_to_family(R).
+-spec(relation_to_family(BinRel) -> Family when
+ Family :: family(),
+ BinRel :: binary_relation()).
%% Inlined.
relation_to_family(R) when ?IS_SET(R) ->
case ?TYPE(R) of
- ?BINREL(DT, RT) ->
+ ?BINREL(DT, RT) ->
?SET(rel2family(?LIST(R)), ?FAMILY(DT, RT));
?ANYTYPE -> R;
_Else -> erlang:error(badarg, [R])
end.
+-spec(domain(BinRel) -> Set when
+ BinRel :: binary_relation(),
+ Set :: a_set()).
domain(R) when ?IS_SET(R) ->
case ?TYPE(R) of
?BINREL(DT, _) -> ?SET(dom(?LIST(R)), DT);
@@ -484,6 +644,9 @@ domain(R) when ?IS_SET(R) ->
_Else -> erlang:error(badarg, [R])
end.
+-spec(range(BinRel) -> Set when
+ BinRel :: binary_relation(),
+ Set :: a_set()).
range(R) when ?IS_SET(R) ->
case ?TYPE(R) of
?BINREL(_, RT) -> ?SET(ran(?LIST(R), []), RT);
@@ -491,35 +654,63 @@ range(R) when ?IS_SET(R) ->
_ -> erlang:error(badarg, [R])
end.
+-spec(field(BinRel) -> Set when
+ BinRel :: binary_relation(),
+ Set :: a_set()).
%% In "Introduction to LOGIC", Suppes defines the field of a binary
%% relation to be the union of the domain and the range (or
%% counterdomain).
field(R) ->
union(domain(R), range(R)).
+-spec(relative_product(ListOfBinRels) -> BinRel2 when
+ ListOfBinRels :: [BinRel, ...],
+ BinRel :: binary_relation(),
+ BinRel2 :: binary_relation()).
+%% The following clause is kept for backward compatibility.
+%% The list is due to Dialyzer's specs.
relative_product(RT) when is_tuple(RT) ->
- case relprod_n(RT, foo, false, false) of
- {error, Reason} ->
- erlang:error(Reason, [RT]);
+ relative_product(tuple_to_list(RT));
+relative_product(RL) when is_list(RL) ->
+ case relprod_n(RL, foo, false, false) of
+ {error, Reason} ->
+ erlang:error(Reason, [RL]);
Reply ->
Reply
end.
+-spec(relative_product(ListOfBinRels, BinRel1) -> BinRel2 when
+ ListOfBinRels :: [BinRel, ...],
+ BinRel :: binary_relation(),
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation();
+ (BinRel1, BinRel2) -> BinRel3 when
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation(),
+ BinRel3 :: binary_relation()).
relative_product(R1, R2) when ?IS_SET(R1), ?IS_SET(R2) ->
relative_product1(converse(R1), R2);
+%% The following clause is kept for backward compatibility.
+%% The list is due to Dialyzer's specs.
relative_product(RT, R) when is_tuple(RT), ?IS_SET(R) ->
+ relative_product(tuple_to_list(RT), R);
+relative_product(RL, R) when is_list(RL), ?IS_SET(R) ->
EmptyR = case ?TYPE(R) of
?BINREL(_, _) -> ?LIST(R) =:= [];
?ANYTYPE -> true;
- _ -> erlang:error(badarg, [RT, R])
+ _ -> erlang:error(badarg, [RL, R])
end,
- case relprod_n(RT, R, EmptyR, true) of
- {error, Reason} ->
- erlang:error(Reason, [RT, R]);
+ case relprod_n(RL, R, EmptyR, true) of
+ {error, Reason} ->
+ erlang:error(Reason, [RL, R]);
Reply ->
Reply
end.
+-spec(relative_product1(BinRel1, BinRel2) -> BinRel3 when
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation(),
+ BinRel3 :: binary_relation()).
relative_product1(R1, R2) when ?IS_SET(R1), ?IS_SET(R2) ->
{DTR1, RTR1} = case ?TYPE(R1) of
?BINREL(_, _) = R1T -> R1T;
@@ -538,16 +729,23 @@ relative_product1(R1, R2) when ?IS_SET(R1), ?IS_SET(R2) ->
false -> erlang:error(type_mismatch, [R1, R2])
end.
+-spec(converse(BinRel1) -> BinRel2 when
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation()).
converse(R) when ?IS_SET(R) ->
case ?TYPE(R) of
?BINREL(DT, RT) -> ?SET(converse(?LIST(R), []), ?BINREL(RT, DT));
?ANYTYPE -> R;
_ -> erlang:error(badarg, [R])
end.
-
+
+-spec(image(BinRel, Set1) -> Set2 when
+ BinRel :: binary_relation(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
image(R, S) when ?IS_SET(R), ?IS_SET(S) ->
case ?TYPE(R) of
- ?BINREL(DT, RT) ->
+ ?BINREL(DT, RT) ->
case match_types(DT, ?TYPE(S)) of
true ->
?SET(usort(restrict(?LIST(S), ?LIST(R))), RT);
@@ -558,9 +756,13 @@ image(R, S) when ?IS_SET(R), ?IS_SET(S) ->
_ -> erlang:error(badarg, [R, S])
end.
+-spec(inverse_image(BinRel, Set1) -> Set2 when
+ BinRel :: binary_relation(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
inverse_image(R, S) when ?IS_SET(R), ?IS_SET(S) ->
case ?TYPE(R) of
- ?BINREL(DT, RT) ->
+ ?BINREL(DT, RT) ->
case match_types(RT, ?TYPE(S)) of
true ->
NL = restrict(?LIST(S), converse(?LIST(R), [])),
@@ -572,17 +774,23 @@ inverse_image(R, S) when ?IS_SET(R), ?IS_SET(S) ->
_ -> erlang:error(badarg, [R, S])
end.
+-spec(strict_relation(BinRel1) -> BinRel2 when
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation()).
strict_relation(R) when ?IS_SET(R) ->
case ?TYPE(R) of
- Type = ?BINREL(_, _) ->
+ Type = ?BINREL(_, _) ->
?SET(strict(?LIST(R), []), Type);
?ANYTYPE -> R;
_ -> erlang:error(badarg, [R])
end.
-
+
+-spec(weak_relation(BinRel1) -> BinRel2 when
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation()).
weak_relation(R) when ?IS_SET(R) ->
case ?TYPE(R) of
- ?BINREL(DT, RT) ->
+ ?BINREL(DT, RT) ->
case unify_types(DT, RT) of
[] ->
erlang:error(badarg, [R]);
@@ -592,7 +800,12 @@ weak_relation(R) when ?IS_SET(R) ->
?ANYTYPE -> R;
_ -> erlang:error(badarg, [R])
end.
-
+
+-spec(extension(BinRel1, Set, AnySet) -> BinRel2 when
+ AnySet :: anyset(),
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation(),
+ Set :: a_set()).
extension(R, S, E) when ?IS_SET(R), ?IS_SET(S) ->
case {?TYPE(R), ?TYPE(S), is_sofs_set(E)} of
{T=?BINREL(DT, RT), ST, true} ->
@@ -621,9 +834,12 @@ extension(R, S, E) when ?IS_SET(R), ?IS_SET(S) ->
erlang:error(badarg, [R, S, E])
end.
+-spec(is_a_function(BinRel) -> Bool when
+ Bool :: boolean(),
+ BinRel :: binary_relation()).
is_a_function(R) when ?IS_SET(R) ->
case ?TYPE(R) of
- ?BINREL(_, _) ->
+ ?BINREL(_, _) ->
case ?LIST(R) of
[] -> true;
[{V,_} | Es] -> is_a_func(Es, V)
@@ -632,16 +848,28 @@ is_a_function(R) when ?IS_SET(R) ->
_ -> erlang:error(badarg, [R])
end.
+-spec(restriction(BinRel1, Set) -> BinRel2 when
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation(),
+ Set :: a_set()).
restriction(Relation, Set) ->
restriction(1, Relation, Set).
+-spec(drestriction(BinRel1, Set) -> BinRel2 when
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation(),
+ Set :: a_set()).
drestriction(Relation, Set) ->
drestriction(1, Relation, Set).
-%%%
+%%%
%%% Functions on functions only.
-%%%
+%%%
+-spec(composite(Function1, Function2) -> Function3 when
+ Function1 :: a_function(),
+ Function2 :: a_function(),
+ Function3 :: a_function()).
composite(Fn1, Fn2) when ?IS_SET(Fn1), ?IS_SET(Fn2) ->
?BINREL(DTF1, RTF1) = case ?TYPE(Fn1)of
?BINREL(_, _) = F1T -> F1T;
@@ -656,7 +884,7 @@ composite(Fn1, Fn2) when ?IS_SET(Fn1), ?IS_SET(Fn2) ->
case match_types(RTF1, DTF2) of
true when DTF1 =:= ?ANYTYPE -> Fn1;
true when DTF2 =:= ?ANYTYPE -> Fn2;
- true ->
+ true ->
case comp(?LIST(Fn1), ?LIST(Fn2)) of
SL when is_list(SL) ->
?SET(sort(SL), ?BINREL(DTF1, RTF2));
@@ -666,9 +894,12 @@ composite(Fn1, Fn2) when ?IS_SET(Fn1), ?IS_SET(Fn2) ->
false -> erlang:error(type_mismatch, [Fn1, Fn2])
end.
+-spec(inverse(Function1) -> Function2 when
+ Function1 :: a_function(),
+ Function2 :: a_function()).
inverse(Fn) when ?IS_SET(Fn) ->
case ?TYPE(Fn) of
- ?BINREL(DT, RT) ->
+ ?BINREL(DT, RT) ->
case inverse1(?LIST(Fn)) of
SL when is_list(SL) ->
?SET(SL, ?BINREL(RT, DT));
@@ -678,11 +909,16 @@ inverse(Fn) when ?IS_SET(Fn) ->
?ANYTYPE -> Fn;
_ -> erlang:error(badarg, [Fn])
end.
-
-%%%
+
+%%%
%%% Functions on relations (binary or other).
-%%%
+%%%
+-spec(restriction(SetFun, Set1, Set2) -> Set3 when
+ SetFun :: set_fun(),
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set()).
%% Equivalent to range(restriction(inverse(substitution(Fun, S1)), S2)).
restriction(I, R, S) when is_integer(I), ?IS_SET(R), ?IS_SET(S) ->
RT = ?TYPE(R),
@@ -747,6 +983,11 @@ restriction(SetFun, S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
end
end.
+-spec(drestriction(SetFun, Set1, Set2) -> Set3 when
+ SetFun :: set_fun(),
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set()).
drestriction(I, R, S) when is_integer(I), ?IS_SET(R), ?IS_SET(S) ->
RT = ?TYPE(R),
ST = ?TYPE(S),
@@ -812,6 +1053,10 @@ drestriction(SetFun, S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
end
end.
+-spec(projection(SetFun, Set1) -> Set2 when
+ SetFun :: set_fun(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
projection(I, Set) when is_integer(I), ?IS_SET(Set) ->
Type = ?TYPE(Set),
case check_for_sort(Type, I) of
@@ -827,6 +1072,10 @@ projection(I, Set) when is_integer(I), ?IS_SET(Set) ->
projection(Fun, Set) ->
range(substitution(Fun, Set)).
+-spec(substitution(SetFun, Set1) -> Set2 when
+ SetFun :: set_fun(),
+ Set1 :: a_set(),
+ Set2 :: a_set()).
substitution(I, Set) when is_integer(I), ?IS_SET(Set) ->
Type = ?TYPE(Set),
case check_for_sort(Type, I) of
@@ -867,11 +1116,18 @@ substitution(SetFun, Set) when ?IS_SET(Set) ->
end
end.
+-spec(partition(SetOfSets) -> Partition when
+ SetOfSets :: set_of_sets(),
+ Partition :: a_set()).
partition(Sets) ->
F1 = relation_to_family(canonical_relation(Sets)),
F2 = relation_to_family(converse(F1)),
range(F2).
+-spec(partition(SetFun, Set) -> Partition when
+ SetFun :: set_fun(),
+ Partition :: a_set(),
+ Set :: a_set()).
partition(I, Set) when is_integer(I), ?IS_SET(Set) ->
Type = ?TYPE(Set),
case check_for_sort(Type, I) of
@@ -887,6 +1143,12 @@ partition(I, Set) when is_integer(I), ?IS_SET(Set) ->
partition(Fun, Set) ->
range(partition_family(Fun, Set)).
+-spec(partition(SetFun, Set1, Set2) -> {Set3, Set4} when
+ SetFun :: set_fun(),
+ Set1 :: a_set(),
+ Set2 :: a_set(),
+ Set3 :: a_set(),
+ Set4 :: a_set()).
partition(I, R, S) when is_integer(I), ?IS_SET(R), ?IS_SET(S) ->
RT = ?TYPE(R),
ST = ?TYPE(S),
@@ -954,21 +1216,32 @@ partition(SetFun, S1, S2) when ?IS_SET(S1), ?IS_SET(S2) ->
end
end.
+-spec(multiple_relative_product(TupleOfBinRels, BinRel1) -> BinRel2 when
+ TupleOfBinRels :: tuple_of(BinRel),
+ BinRel :: binary_relation(),
+ BinRel1 :: binary_relation(),
+ BinRel2 :: binary_relation()).
multiple_relative_product(T, R) when is_tuple(T), ?IS_SET(R) ->
case test_rel(R, tuple_size(T), eq) of
true when ?TYPE(R) =:= ?ANYTYPE ->
empty_set();
- true ->
+ true ->
MProd = mul_relprod(tuple_to_list(T), 1, R),
- relative_product(list_to_tuple(MProd));
- false ->
+ relative_product(MProd);
+ false ->
erlang:error(badarg, [T, R])
end.
-join(R1, I1, R2, I2)
+-spec(join(Relation1, I, Relation2, J) -> Relation3 when
+ Relation1 :: relation(),
+ Relation2 :: relation(),
+ Relation3 :: relation(),
+ I :: pos_integer(),
+ J :: pos_integer()).
+join(R1, I1, R2, I2)
when ?IS_SET(R1), ?IS_SET(R2), is_integer(I1), is_integer(I2) ->
case test_rel(R1, I1, lte) and test_rel(R2, I2, lte) of
- false ->
+ false ->
erlang:error(badarg, [R1, I1, R2, I2]);
true when ?TYPE(R1) =:= ?ANYTYPE -> R1;
true when ?TYPE(R2) =:= ?ANYTYPE -> R2;
@@ -980,8 +1253,8 @@ join(R1, I1, R2, I2)
true ->
fun({X,Y}) -> join_element(X, Y) end;
false ->
- fun({X,Y}) ->
- list_to_tuple(join_element(X, Y, I2))
+ fun({X,Y}) ->
+ list_to_tuple(join_element(X, Y, I2))
end
end,
?SET(replace(T, F, []), F({?TYPE(R1), ?TYPE(R2)}))
@@ -1001,9 +1274,15 @@ test_rel(R, I, C) ->
%%% Family functions
%%%
+-spec(fam2rel(Family) -> BinRel when
+ Family :: family(),
+ BinRel :: binary_relation()).
fam2rel(F) ->
family_to_relation(F).
+-spec(family_to_relation(Family) -> BinRel when
+ Family :: family(),
+ BinRel :: binary_relation()).
%% Inlined.
family_to_relation(F) when ?IS_SET(F) ->
case ?TYPE(F) of
@@ -1013,6 +1292,10 @@ family_to_relation(F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [F])
end.
+-spec(family_specification(Fun, Family1) -> Family2 when
+ Fun :: spec_fun(),
+ Family1 :: family(),
+ Family2 :: family()).
family_specification(Fun, F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(_DT, Type) = FType ->
@@ -1032,6 +1315,9 @@ family_specification(Fun, F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [Fun, F])
end.
+-spec(union_of_family(Family) -> Set when
+ Family :: family(),
+ Set :: a_set()).
union_of_family(F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(_DT, Type) ->
@@ -1040,6 +1326,9 @@ union_of_family(F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [F])
end.
+-spec(intersection_of_family(Family) -> Set when
+ Family :: family(),
+ Set :: a_set()).
intersection_of_family(F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(_DT, Type) ->
@@ -1052,6 +1341,9 @@ intersection_of_family(F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [F])
end.
+-spec(family_union(Family1) -> Family2 when
+ Family1 :: family(),
+ Family2 :: family()).
family_union(F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(DT, ?SET_OF(Type)) ->
@@ -1060,6 +1352,9 @@ family_union(F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [F])
end.
+-spec(family_intersection(Family1) -> Family2 when
+ Family1 :: family(),
+ Family2 :: family()).
family_intersection(F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(DT, ?SET_OF(Type)) ->
@@ -1073,6 +1368,9 @@ family_intersection(F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [F])
end.
+-spec(family_domain(Family1) -> Family2 when
+ Family1 :: family(),
+ Family2 :: family()).
family_domain(F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(FDT, ?BINREL(DT, _)) ->
@@ -1082,6 +1380,9 @@ family_domain(F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [F])
end.
+-spec(family_range(Family1) -> Family2 when
+ Family1 :: family(),
+ Family2 :: family()).
family_range(F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(DT, ?BINREL(_, RT)) ->
@@ -1091,15 +1392,30 @@ family_range(F) when ?IS_SET(F) ->
_ -> erlang:error(badarg, [F])
end.
+-spec(family_field(Family1) -> Family2 when
+ Family1 :: family(),
+ Family2 :: family()).
family_field(F) ->
family_union(family_domain(F), family_range(F)).
+-spec(family_union(Family1, Family2) -> Family3 when
+ Family1 :: family(),
+ Family2 :: family(),
+ Family3 :: family()).
family_union(F1, F2) ->
fam_binop(F1, F2, fun fam_union/3).
+-spec(family_intersection(Family1, Family2) -> Family3 when
+ Family1 :: family(),
+ Family2 :: family(),
+ Family3 :: family()).
family_intersection(F1, F2) ->
fam_binop(F1, F2, fun fam_intersect/3).
+-spec(family_difference(Family1, Family2) -> Family3 when
+ Family1 :: family(),
+ Family2 :: family(),
+ Family3 :: family()).
family_difference(F1, F2) ->
fam_binop(F1, F2, fun fam_difference/3).
@@ -1108,13 +1424,17 @@ fam_binop(F1, F2, FF) when ?IS_SET(F1), ?IS_SET(F2) ->
case unify_types(?TYPE(F1), ?TYPE(F2)) of
[] ->
erlang:error(type_mismatch, [F1, F2]);
- ?ANYTYPE ->
+ ?ANYTYPE ->
F1;
- Type = ?FAMILY(_, _) ->
+ Type = ?FAMILY(_, _) ->
?SET(FF(?LIST(F1), ?LIST(F2), []), Type);
_ -> erlang:error(badarg, [F1, F2])
end.
+-spec(partition_family(SetFun, Set) -> Family when
+ Family :: family(),
+ SetFun :: set_fun(),
+ Set :: a_set()).
partition_family(I, Set) when is_integer(I), ?IS_SET(Set) ->
Type = ?TYPE(Set),
case check_for_sort(Type, I) of
@@ -1159,8 +1479,12 @@ partition_family(SetFun, Set) when ?IS_SET(Set) ->
end
end.
+-spec(family_projection(SetFun, Family1) -> Family2 when
+ SetFun :: set_fun(),
+ Family1 :: family(),
+ Family2 :: family()).
family_projection(SetFun, F) when ?IS_SET(F) ->
- case ?TYPE(F) of
+ case ?TYPE(F) of
?FAMILY(_, _) when [] =:= ?LIST(F) ->
empty_set();
?FAMILY(DT, Type) ->
@@ -1172,7 +1496,7 @@ family_projection(SetFun, F) when ?IS_SET(F) ->
Bad ->
erlang:error(Bad, [SetFun, F])
end;
- _ ->
+ _ ->
erlang:error(badarg, [SetFun, F])
end;
?ANYTYPE -> F;
@@ -1183,6 +1507,9 @@ family_projection(SetFun, F) when ?IS_SET(F) ->
%%% Digraph functions
%%%
+-spec(family_to_digraph(Family) -> Graph when
+ Graph :: digraph(),
+ Family :: family()).
family_to_digraph(F) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(_, _) -> fam2digraph(F, digraph:new());
@@ -1190,6 +1517,10 @@ family_to_digraph(F) when ?IS_SET(F) ->
_Else -> erlang:error(badarg, [F])
end.
+-spec(family_to_digraph(Family, GraphType) -> Graph when
+ Graph :: digraph(),
+ Family :: family(),
+ GraphType :: [digraph:d_type()]).
family_to_digraph(F, Type) when ?IS_SET(F) ->
case ?TYPE(F) of
?FAMILY(_, _) -> ok;
@@ -1208,12 +1539,19 @@ family_to_digraph(F, Type) when ?IS_SET(F) ->
error:badarg -> erlang:error(badarg, [F, Type])
end.
+-spec(digraph_to_family(Graph) -> Family when
+ Graph :: digraph(),
+ Family :: family()).
digraph_to_family(G) ->
case catch digraph_family(G) of
{'EXIT', _} -> erlang:error(badarg, [G]);
L -> ?SET(L, ?FAMILY(?ATOM_TYPE, ?ATOM_TYPE))
end.
+-spec(digraph_to_family(Graph, Type) -> Family when
+ Graph :: digraph(),
+ Family :: family(),
+ Type :: type()).
digraph_to_family(G, T) ->
case {is_type(T), T} of
{true, ?SET_OF(?FAMILY(_,_) = Type)} ->
@@ -1284,7 +1622,7 @@ rel(Ts, [Type]) ->
end;
rel(Ts, Sz) ->
rel(Ts, Sz, erlang:make_tuple(Sz, ?ATOM_TYPE)).
-
+
atoms_only(Type, I) when ?IS_ATOM_TYPE(?REL_TYPE(I, Type)) ->
atoms_only(Type, I+1);
atoms_only(Type, I) when I > tuple_size(Type), ?IS_RELATION(Type) ->
@@ -1312,7 +1650,7 @@ rel_type([], SL, Type) when ?IS_RELATION(Type) ->
%% Inlined.
a_func(Ts, T) ->
case {T, is_type(T)} of
- {[?BINREL(DT, RT) = Type], true} when ?IS_ATOM_TYPE(DT),
+ {[?BINREL(DT, RT) = Type], true} when ?IS_ATOM_TYPE(DT),
?IS_ATOM_TYPE(RT) ->
func(Ts, Type);
{[Type], true} ->
@@ -1333,16 +1671,16 @@ func([], _X0, L, Type) ->
%% Inlined.
fam(Ts, T) ->
case {T, is_type(T)} of
- {[?FAMILY(DT, RT) = Type], true} when ?IS_ATOM_TYPE(DT),
+ {[?FAMILY(DT, RT) = Type], true} when ?IS_ATOM_TYPE(DT),
?IS_ATOM_TYPE(RT) ->
fam2(Ts, Type);
{[Type], true} ->
func_type(Ts, [], Type, fun(?FAMILY(_,_)) -> true end)
end.
-fam2([], Type) ->
+fam2([], Type) ->
?SET([], Type);
-fam2(Ts, Type) ->
+fam2(Ts, Type) ->
fam2(sort(Ts), Ts, [], Type).
fam2([{I,L} | T], I0, SL, Type) when I /= I0 ->
@@ -1383,7 +1721,7 @@ setify(E, Type0) ->
{Type, OrdSet} = make_element(E, Type0, Type0),
?ORDSET(OrdSet, Type).
-is_no_lists(T) when is_tuple(T) ->
+is_no_lists(T) when is_tuple(T) ->
Sz = tuple_size(T),
is_no_lists(T, Sz, Sz, []).
@@ -1404,7 +1742,7 @@ create([], T, _T0, L) ->
make_element(C, ?ANYTYPE, _T0) ->
make_element(C);
-make_element(C, Atom, ?ANYTYPE) when ?IS_ATOM_TYPE(Atom),
+make_element(C, Atom, ?ANYTYPE) when ?IS_ATOM_TYPE(Atom),
not is_list(C), not is_tuple(C) ->
{Atom, C};
make_element(C, Atom, Atom) when ?IS_ATOM_TYPE(Atom) ->
@@ -1585,12 +1923,12 @@ sympart([H1 | T1], [H2 | T2], L1, L12, L2, T) when H1 == H2 ->
sympart([H1 | T1], [H2 | T2], L1, L12, L2, T) ->
sympart2(T1, T2, L1, L12, [H2 | L2], T, H1);
sympart(S1, [], L1, L12, L2, T) ->
- {?SET(reverse(L1, S1), T),
- ?SET(reverse(L12), T),
+ {?SET(reverse(L1, S1), T),
+ ?SET(reverse(L12), T),
?SET(reverse(L2), T)};
sympart(_, S2, L1, L12, L2, T) ->
- {?SET(reverse(L1), T),
- ?SET(reverse(L12), T),
+ {?SET(reverse(L1), T),
+ ?SET(reverse(L12), T),
?SET(reverse(L2, S2), T)}.
sympart1([H1 | T1], T2, L1, L12, L2, T, H2) when H1 < H2 ->
@@ -1600,8 +1938,8 @@ sympart1([H1 | T1], T2, L1, L12, L2, T, H2) when H1 == H2 ->
sympart1([H1 | T1], T2, L1, L12, L2, T, H2) ->
sympart2(T1, T2, L1, L12, [H2 | L2], T, H1);
sympart1(_, T2, L1, L12, L2, T, H2) ->
- {?SET(reverse(L1), T),
- ?SET(reverse(L12), T),
+ {?SET(reverse(L1), T),
+ ?SET(reverse(L12), T),
?SET(reverse(L2, [H2 | T2]), T)}.
sympart2(T1, [H2 | T2], L1, L12, L2, T, H1) when H1 > H2 ->
@@ -1611,8 +1949,8 @@ sympart2(T1, [H2 | T2], L1, L12, L2, T, H1) when H1 == H2 ->
sympart2(T1, [H2 | T2], L1, L12, L2, T, H1) ->
sympart1(T1, T2, [H1 | L1], L12, L2, T, H2);
sympart2(T1, _, L1, L12, L2, T, H1) ->
- {?SET(reverse(L1, [H1 | T1]), T),
- ?SET(reverse(L12), T),
+ {?SET(reverse(L1, [H1 | T1]), T),
+ ?SET(reverse(L12), T),
?SET(reverse(L2), T)}.
prod([[E | Es] | Xs], T, L) ->
@@ -1660,7 +1998,7 @@ lunion([[] | Ls]) ->
lunion(Ls);
lunion([S | Ss]) ->
umerge(lunion(Ss, last(S), [S], []));
-lunion([]) ->
+lunion([]) ->
[].
lunion([[E] = S | Ss], Last, SL, Ls) when E > Last -> % optimization
@@ -1669,7 +2007,7 @@ lunion([S | Ss], Last, SL, Ls) when hd(S) > Last ->
lunion(Ss, last(S), [S | SL], Ls);
lunion([S | Ss], _Last, SL, Ls) ->
lunion(Ss, last(S), [S], [append(reverse(SL)) | Ls]);
-lunion([], _Last, SL, Ls) ->
+lunion([], _Last, SL, Ls) ->
[append(reverse(SL)) | Ls].
%% The empty list is always the first list, if present.
@@ -1752,18 +2090,17 @@ relprod(B0, Bx0, By0, A0, L, Ax, [{Bx,By} | B], Ay) when Ay == Bx ->
relprod(B0, Bx0, By0, A0, L, _Ax, _B, _Ay) ->
relprod2(B0, Bx0, By0, A0, L).
-relprod_n({}, _R, _EmptyG, _IsR) ->
+relprod_n([], _R, _EmptyG, _IsR) ->
{error, badarg};
-relprod_n(RT, R, EmptyR, IsR) ->
- RL = tuple_to_list(RT),
+relprod_n(RL, R, EmptyR, IsR) ->
case domain_type(RL, ?ANYTYPE) of
- Error = {error, _Reason} ->
+ Error = {error, _Reason} ->
Error;
DType ->
Empty = any(fun is_empty_set/1, RL) or EmptyR,
RType = range_type(RL, []),
Type = ?BINREL(DType, RType),
- Prod =
+ Prod =
case Empty of
true when DType =:= ?ANYTYPE; RType =:= ?ANYTYPE ->
empty_set();
@@ -1771,7 +2108,7 @@ relprod_n(RT, R, EmptyR, IsR) ->
?SET([], Type);
false ->
TL = ?LIST((relprod_n(RL))),
- Sz = tuple_size(RT),
+ Sz = length(RL),
Fun = fun({X,A}) -> {X, flat(Sz, A, [])} end,
?SET(map(Fun, TL), Type)
end,
@@ -1799,12 +2136,12 @@ flat(N, {T,A}, L) ->
domain_type([T | Ts], T0) when ?IS_SET(T) ->
case ?TYPE(T) of
- ?BINREL(DT, _RT) ->
+ ?BINREL(DT, _RT) ->
case unify_types(DT, T0) of
[] -> {error, type_mismatch};
T1 -> domain_type(Ts, T1)
end;
- ?ANYTYPE ->
+ ?ANYTYPE ->
domain_type(Ts, T0);
_ -> {error, badarg}
end;
@@ -1813,12 +2150,12 @@ domain_type([], T0) ->
range_type([T | Ts], L) ->
case ?TYPE(T) of
- ?BINREL(_DT, RT) ->
+ ?BINREL(_DT, RT) ->
range_type(Ts, [RT | L]);
- ?ANYTYPE ->
+ ?ANYTYPE ->
?ANYTYPE
end;
-range_type([], L) ->
+range_type([], L) ->
list_to_tuple(reverse(L)).
converse([{A,B} | X], L) ->
@@ -1861,7 +2198,7 @@ weak1([E={X,_Y} | Es], Ys, L, X0) when X == X0 -> % when X < Y
weak1(Es, Ys, L, X) ->
weak(Es, Ys, [{X,X} | L]).
-weak2([E={X,_Y} | Es], Ys, L, X0) when X == X0 -> % when X < _Y
+weak2([E={X,_Y} | Es], Ys, L, X0) when X == X0 -> % when X < _Y
weak2(Es, Ys, [E | L], X);
weak2(Es, Ys, L, _X) ->
weak(Es, Ys, L).
@@ -1910,7 +2247,7 @@ restrict_n(I, [T | Ts], Key, Keys, L) ->
end;
restrict_n(_I, _Ts, _Key, _Keys, L) ->
L.
-
+
restrict_n(I, K, Ts, [Key | Keys], L, E) when K > Key ->
restrict_n(I, K, Ts, Keys, L, E);
restrict_n(I, K, Ts, [Key | Keys], L, E) when K == Key ->
@@ -1933,7 +2270,7 @@ restrict([{K,E} | Ts], _Key, Keys, L) ->
restrict(Ts, K, Keys, L, E);
restrict(_Ts, _Key, _Keys, L) ->
L.
-
+
restrict(Ts, K, [Key | Keys], L, E) when K > Key ->
restrict(Ts, K, Keys, L, E);
restrict(Ts, K, [Key | Keys], L, E) when K == Key ->
@@ -1956,7 +2293,7 @@ diff_restrict_n(I, _Ts, _Key, _Keys, L) when I =:= 1 ->
reverse(L);
diff_restrict_n(_I, _Ts, _Key, _Keys, L) ->
sort(L).
-
+
diff_restrict_n(I, K, Ts, [Key | Keys], L, T) when K > Key ->
diff_restrict_n(I, K, Ts, Keys, L, T);
diff_restrict_n(I, K, Ts, [Key | Keys], L, _T) when K == Key ->
@@ -1981,7 +2318,7 @@ diff_restrict([{K,E} | Ts], _Key, Keys, L) ->
diff_restrict(Ts, K, Keys, L, E);
diff_restrict(_Ts, _Key, _Keys, L) ->
L.
-
+
diff_restrict(Ts, K, [Key | Keys], L, E) when K > Key ->
diff_restrict(Ts, K, Keys, L, E);
diff_restrict(Ts, K, [Key | Keys], L, _E) when K == Key ->
@@ -2041,7 +2378,7 @@ external_fun({external, Function}) when is_atom(Function) ->
false;
external_fun({external, Fun}) ->
Fun;
-external_fun(_) ->
+external_fun(_) ->
false.
%% Inlined.
@@ -2121,7 +2458,7 @@ partition3_n(I, _Ts, _Key, _Keys, L1, L2) when I =:= 1 ->
[reverse(L1) | reverse(L2)];
partition3_n(_I, _Ts, _Key, _Keys, L1, L2) ->
[sort(L1) | sort(L2)].
-
+
partition3_n(I, K, Ts, [Key | Keys], L1, L2, T) when K > Key ->
partition3_n(I, K, Ts, Keys, L1, L2, T);
partition3_n(I, K, Ts, [Key | Keys], L1, L2, T) when K == Key ->
@@ -2146,7 +2483,7 @@ partition3([{K,E} | Ts], _Key, Keys, L1, L2) ->
partition3(Ts, K, Keys, L1, L2, E);
partition3(_Ts, _Key, _Keys, L1, L2) ->
[L1 | L2].
-
+
partition3(Ts, K, [Key | Keys], L1, L2, E) when K > Key ->
partition3(Ts, K, Keys, L1, L2, E);
partition3(Ts, K, [Key | Keys], L1, L2, E) when K == Key ->
@@ -2192,7 +2529,7 @@ join_element(E1, E2, I2) ->
join_element2([B | Bs], C, I2) when C =/= I2 ->
[B | join_element2(Bs, C+1, I2)];
-join_element2([_ | Bs], _C, _I2) ->
+join_element2([_ | Bs], _C, _I2) ->
Bs.
family2rel([{X,S} | F], L) ->
@@ -2297,7 +2634,7 @@ check_function([{X,_} | XL], R) ->
check_function(X, XL, R);
check_function([], R) ->
R.
-
+
check_function(X0, [{X,_} | XL], R) when X0 /= X ->
check_function(X, XL, R);
check_function(X0, [{X,_} | _XL], _R) when X0 == X ->
@@ -2371,14 +2708,14 @@ term2set(T, Type) ->
?ORDSET(T, Type).
fam2digraph(F, G) ->
- Fun = fun({From, ToL}) ->
+ Fun = fun({From, ToL}) ->
digraph:add_vertex(G, From),
Fun2 = fun(To) ->
digraph:add_vertex(G, To),
case digraph:add_edge(G, From, To) of
- {error, {bad_edge, _}} ->
+ {error, {bad_edge, _}} ->
throw({error, cyclic});
- _ ->
+ _ ->
true
end
end,
@@ -2397,7 +2734,7 @@ digraph_fam([V | Vs], V0, G, L) when V /= V0 ->
digraph_fam([], _V0, _G, L) ->
reverse(L).
-%% -> bool()
+%% -> boolean()
check_fun(T, F, FunT) ->
true = is_type(FunT),
{NT, _MaxI} = number_tuples(T, 1),
@@ -2424,7 +2761,7 @@ check_for_sort(T, _I) when T =:= ?ANYTYPE ->
check_for_sort(T, I) when ?IS_RELATION(T), I =< ?REL_ARITY(T), I >= 1 ->
I > 1;
check_for_sort(_T, _I) ->
- error.
+ error.
inverse_substitution(L, Fun, Sort) ->
%% One easily sees that the inverse of the tuples created by
@@ -2477,11 +2814,11 @@ match_types(Type1, Type2) -> match_types1(Type1, Type2).
match_types1(Atom, Atom) when ?IS_ATOM_TYPE(Atom) ->
true;
-match_types1(?ANYTYPE, _) ->
+match_types1(?ANYTYPE, _) ->
true;
-match_types1(_, ?ANYTYPE) ->
+match_types1(_, ?ANYTYPE) ->
true;
-match_types1(?SET_OF(Type1), ?SET_OF(Type2)) ->
+match_types1(?SET_OF(Type1), ?SET_OF(Type2)) ->
match_types1(Type1, Type2);
match_types1(T1, T2) when tuple_size(T1) =:= tuple_size(T2) ->
match_typesl(tuple_size(T1), T1, T2);
diff --git a/lib/stdlib/src/string.erl b/lib/stdlib/src/string.erl
index 264348180f..30eac4f07d 100644
--- a/lib/stdlib/src/string.erl
+++ b/lib/stdlib/src/string.erl
@@ -29,23 +29,23 @@
%%---------------------------------------------------------------------------
--type direction() :: 'left' | 'right' | 'both'.
-
-%%---------------------------------------------------------------------------
-
%% Robert's bit
%% len(String)
%% Return the length of a string.
--spec len(string()) -> non_neg_integer().
+-spec len(String) -> Length when
+ String :: string(),
+ Length :: non_neg_integer().
len(S) -> length(S).
%% equal(String1, String2)
%% Test if 2 strings are equal.
--spec equal(string(), string()) -> boolean().
+-spec equal(String1, String2) -> boolean() when
+ String1 :: string(),
+ String2 :: string().
equal(S, S) -> true;
equal(_, _) -> false.
@@ -53,7 +53,10 @@ equal(_, _) -> false.
%% concat(String1, String2)
%% Concatenate 2 strings.
--spec concat(string(), string()) -> string().
+-spec concat(String1, String2) -> String3 when
+ String1 :: string(),
+ String2 :: string(),
+ String3 :: string().
concat(S1, S2) -> S1 ++ S2.
@@ -61,7 +64,10 @@ concat(S1, S2) -> S1 ++ S2.
%% rchr(String, Char)
%% Return the first/last index of the character in a string.
--spec chr(string(), char()) -> non_neg_integer().
+-spec chr(String, Character) -> Index when
+ String :: string(),
+ Character :: char(),
+ Index :: non_neg_integer().
chr(S, C) when is_integer(C) -> chr(S, C, 1).
@@ -69,7 +75,10 @@ chr([C|_Cs], C, I) -> I;
chr([_|Cs], C, I) -> chr(Cs, C, I+1);
chr([], _C, _I) -> 0.
--spec rchr(string(), char()) -> non_neg_integer().
+-spec rchr(String, Character) -> Index when
+ String :: string(),
+ Character :: char(),
+ Index :: non_neg_integer().
rchr(S, C) when is_integer(C) -> rchr(S, C, 1, 0).
@@ -85,7 +94,10 @@ rchr([], _C, _I, L) -> L.
%% Return the first/last index of the sub-string in a string.
%% index/2 is kept for backwards compatibility.
--spec str(string(), string()) -> non_neg_integer().
+-spec str(String, SubString) -> Index when
+ String :: string(),
+ SubString :: string(),
+ Index :: non_neg_integer().
str(S, Sub) when is_list(Sub) -> str(S, Sub, 1).
@@ -97,7 +109,10 @@ str([C|S], [C|Sub], I) ->
str([_|S], Sub, I) -> str(S, Sub, I+1);
str([], _Sub, _I) -> 0.
--spec rstr(string(), string()) -> non_neg_integer().
+-spec rstr(String, SubString) -> Index when
+ String :: string(),
+ SubString :: string(),
+ Index :: non_neg_integer().
rstr(S, Sub) when is_list(Sub) -> rstr(S, Sub, 1, 0).
@@ -116,7 +131,10 @@ prefix(Pre, String) when is_list(Pre), is_list(String) -> false.
%% span(String, Chars) -> Length.
%% cspan(String, Chars) -> Length.
--spec span(string(), string()) -> non_neg_integer().
+-spec span(String, Chars) -> Length when
+ String :: string(),
+ Chars :: string(),
+ Length :: non_neg_integer().
span(S, Cs) when is_list(Cs) -> span(S, Cs, 0).
@@ -127,7 +145,10 @@ span([C|S], Cs, I) ->
end;
span([], _Cs, I) -> I.
--spec cspan(string(), string()) -> non_neg_integer().
+-spec cspan(String, Chars) -> Length when
+ String :: string(),
+ Chars :: string(),
+ Length :: non_neg_integer().
cspan(S, Cs) when is_list(Cs) -> cspan(S, Cs, 0).
@@ -142,14 +163,21 @@ cspan([], _Cs, I) -> I.
%% substr(String, Start, Length)
%% Extract a sub-string from String.
--spec substr(string(), pos_integer()) -> string().
+-spec substr(String, Start) -> SubString when
+ String :: string(),
+ SubString :: string(),
+ Start :: pos_integer().
substr(String, 1) when is_list(String) ->
String;
substr(String, S) when is_integer(S), S > 1 ->
substr2(String, S).
--spec substr(string(), pos_integer(), non_neg_integer()) -> string().
+-spec substr(String, Start, Length) -> SubString when
+ String :: string(),
+ SubString :: string(),
+ Start :: pos_integer(),
+ Length :: non_neg_integer().
substr(String, S, L) when is_integer(S), S >= 1, is_integer(L), L >= 0 ->
substr1(substr2(String, S), L).
@@ -163,7 +191,10 @@ substr2([_|String], S) -> substr2(String, S-1).
%% tokens(String, Seperators).
%% Return a list of tokens seperated by characters in Seperators.
--spec tokens(string(), string()) -> [[char(),...]].
+-spec tokens(String, SeparatorList) -> Tokens when
+ String :: string(),
+ SeparatorList :: string(),
+ Tokens :: [Token :: nonempty_string()].
tokens(S, Seps) ->
tokens1(S, Seps, []).
@@ -184,11 +215,18 @@ tokens2([C|S], Seps, Toks, Cs) ->
tokens2([], _Seps, Toks, Cs) ->
reverse([reverse(Cs)|Toks]).
--spec chars(char(), non_neg_integer()) -> string().
+-spec chars(Character, Number) -> String when
+ Character :: char(),
+ Number :: non_neg_integer(),
+ String :: string().
chars(C, N) -> chars(C, N, []).
--spec chars(char(), non_neg_integer(), string()) -> string().
+-spec chars(Character, Number, Tail) -> String when
+ Character :: char(),
+ Number :: non_neg_integer(),
+ Tail :: string(),
+ String :: string().
chars(C, N, Tail) when N > 0 ->
chars(C, N-1, [C|Tail]);
@@ -199,7 +237,10 @@ chars(C, 0, Tail) when is_integer(C) ->
%%% COPIES %%%
--spec copies(string(), non_neg_integer()) -> string().
+-spec copies(String, Number) -> Copies when
+ String :: string(),
+ Copies :: string(),
+ Number :: non_neg_integer().
copies(CharList, Num) when is_list(CharList), is_integer(Num), Num >= 0 ->
copies(CharList, Num, []).
@@ -211,11 +252,16 @@ copies(CharList, Num, R) ->
%%% WORDS %%%
--spec words(string()) -> pos_integer().
+-spec words(String) -> Count when
+ String :: string(),
+ Count :: pos_integer().
words(String) -> words(String, $\s).
--spec words(string(), char()) -> pos_integer().
+-spec words(String, Character) -> Count when
+ String :: string(),
+ Character :: char(),
+ Count :: pos_integer().
words(String, Char) when is_integer(Char) ->
w_count(strip(String, both, Char), Char, 0).
@@ -226,11 +272,18 @@ w_count([_H|T], Char, Num) -> w_count(T, Char, Num).
%%% SUB_WORDS %%%
--spec sub_word(string(), integer()) -> string().
+-spec sub_word(String, Number) -> Word when
+ String :: string(),
+ Word :: string(),
+ Number :: integer().
sub_word(String, Index) -> sub_word(String, Index, $\s).
--spec sub_word(string(), integer(), char()) -> string().
+-spec sub_word(String, Number, Character) -> Word when
+ String :: string(),
+ Word :: string(),
+ Number :: integer(),
+ Character :: char().
sub_word(String, Index, Char) when is_integer(Index), is_integer(Char) ->
case words(String, Char) of
@@ -254,14 +307,21 @@ s_word([_|T],Stop,Char,Index,Res) when Index < Stop ->
strip(String) -> strip(String, both).
--spec strip(string(), direction()) -> string().
+-spec strip(String, Direction) -> Stripped when
+ String :: string(),
+ Stripped :: string(),
+ Direction :: left | right | both.
strip(String, left) -> strip_left(String, $\s);
strip(String, right) -> strip_right(String, $\s);
strip(String, both) ->
strip_right(strip_left(String, $\s), $\s).
--spec strip(string(), direction(), char()) -> string().
+-spec strip(String, Direction, Character) -> Stripped when
+ String :: string(),
+ Stripped :: string(),
+ Direction :: left | right | both,
+ Character :: char().
strip(String, right, Char) -> strip_right(String, Char);
strip(String, left, Char) -> strip_left(String, Char);
@@ -285,11 +345,18 @@ strip_right([], Sc) when is_integer(Sc) ->
%%% LEFT %%%
--spec left(string(), non_neg_integer()) -> string().
+-spec left(String, Number) -> Left when
+ String :: string(),
+ Left :: string(),
+ Number :: non_neg_integer().
left(String, Len) when is_integer(Len) -> left(String, Len, $\s).
--spec left(string(), non_neg_integer(), char()) -> string().
+-spec left(String, Number, Character) -> Left when
+ String :: string(),
+ Left :: string(),
+ Number :: non_neg_integer(),
+ Character :: char().
left(String, Len, Char) when is_integer(Char) ->
Slen = length(String),
@@ -303,11 +370,18 @@ l_pad(String, Num, Char) -> String ++ chars(Char, Num).
%%% RIGHT %%%
--spec right(string(), non_neg_integer()) -> string().
+-spec right(String, Number) -> Right when
+ String :: string(),
+ Right :: string(),
+ Number :: non_neg_integer().
right(String, Len) when is_integer(Len) -> right(String, Len, $\s).
--spec right(string(), non_neg_integer(), char()) -> string().
+-spec right(String, Number, Character) -> Right when
+ String :: string(),
+ Right :: string(),
+ Number :: non_neg_integer(),
+ Character :: char().
right(String, Len, Char) when is_integer(Char) ->
Slen = length(String),
@@ -321,11 +395,18 @@ r_pad(String, Num, Char) -> chars(Char, Num, String).
%%% CENTRE %%%
--spec centre(string(), non_neg_integer()) -> string().
+-spec centre(String, Number) -> Centered when
+ String :: string(),
+ Centered :: string(),
+ Number :: non_neg_integer().
centre(String, Len) when is_integer(Len) -> centre(String, Len, $\s).
--spec centre(string(), non_neg_integer(), char()) -> string().
+-spec centre(String, Number, Character) -> Centered when
+ String :: string(),
+ Centered :: string(),
+ Number :: non_neg_integer(),
+ Character :: char().
centre(String, 0, Char) when is_list(String), is_integer(Char) ->
[]; % Strange cases to centre string
@@ -341,11 +422,18 @@ centre(String, Len, Char) when is_integer(Char) ->
%%% SUB_STRING %%%
--spec sub_string(string(), pos_integer()) -> string().
+-spec sub_string(String, Start) -> SubString when
+ String :: string(),
+ SubString :: string(),
+ Start :: pos_integer().
sub_string(String, Start) -> substr(String, Start).
--spec sub_string(string(), pos_integer(), pos_integer()) -> string().
+-spec sub_string(String, Start, Stop) -> SubString when
+ String :: string(),
+ SubString :: string(),
+ Start :: pos_integer(),
+ Stop :: pos_integer().
sub_string(String, Start, Stop) -> substr(String, Start, Stop - Start + 1).
@@ -370,23 +458,34 @@ to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE ->
to_upper_char(C) ->
C.
--spec to_lower(string()) -> string()
- ; (char()) -> char().
+-spec to_lower(String) -> Result when
+ String :: string(),
+ Result :: string()
+ ; (Char) -> CharResult when
+ Char :: char(),
+ CharResult :: char().
to_lower(S) when is_list(S) ->
[to_lower_char(C) || C <- S];
to_lower(C) when is_integer(C) ->
to_lower_char(C).
--spec to_upper(string()) -> string()
- ; (char()) -> char().
+-spec to_upper(String) -> Result when
+ String :: string(),
+ Result :: string()
+ ; (Char) -> CharResult when
+ Char :: char(),
+ CharResult :: char().
to_upper(S) when is_list(S) ->
[to_upper_char(C) || C <- S];
to_upper(C) when is_integer(C) ->
to_upper_char(C).
--spec join([string()], string()) -> string().
+-spec join(StringList, Separator) -> String when
+ StringList :: [string()],
+ Separator :: string(),
+ String :: string().
join([], Sep) when is_list(Sep) ->
[];
diff --git a/lib/stdlib/src/supervisor.erl b/lib/stdlib/src/supervisor.erl
index 09a01a9aea..e60706ed05 100644
--- a/lib/stdlib/src/supervisor.erl
+++ b/lib/stdlib/src/supervisor.erl
@@ -35,19 +35,28 @@
%%--------------------------------------------------------------------------
--export_type([child_spec/0, del_err/0, startchild_ret/0, strategy/0]).
+-export_type([child_spec/0, startchild_ret/0, strategy/0]).
%%--------------------------------------------------------------------------
--type child_id() :: pid() | 'undefined'.
--type mfargs() :: {module(), atom(), [term()] | undefined}.
+-type child() :: pid() | 'undefined'.
+-type child_id() :: term().
+-type mfargs() :: {M :: module(), F :: atom(), A :: [term()] | undefined}.
-type modules() :: [module()] | 'dynamic'.
-type restart() :: 'permanent' | 'transient' | 'temporary'.
-type shutdown() :: 'brutal_kill' | timeout().
-type worker() :: 'worker' | 'supervisor'.
--type sup_name() :: {'local', atom()} | {'global', atom()}.
--type sup_ref() :: atom() | {atom(), atom()} | {'global', atom()} | pid().
--type child_spec() :: {term(),mfargs(),restart(),shutdown(),worker(),modules()}.
+-type sup_name() :: {'local', Name :: atom()} | {'global', Name :: atom()}.
+-type sup_ref() :: (Name :: atom())
+ | {Name :: atom(), Node :: node()}
+ | {'global', Name :: atom()}
+ | pid().
+-type child_spec() :: {Id :: child_id(),
+ StartFunc :: mfargs(),
+ Restart :: restart(),
+ Shutdown :: shutdown(),
+ Type :: worker(),
+ Modules :: modules()}.
-type strategy() :: 'one_for_all' | 'one_for_one'
| 'rest_for_one' | 'simple_one_for_one'.
@@ -55,14 +64,14 @@
%%--------------------------------------------------------------------------
-record(child, {% pid is undefined when child is not running
- pid = undefined :: child_id(),
+ pid = undefined :: child(),
name,
mfargs :: mfargs(),
restart_type :: restart(),
shutdown :: shutdown(),
child_type :: worker(),
modules = [] :: modules()}).
--type child() :: #child{}.
+-type child_rec() :: #child{}.
-define(DICT, dict).
-define(SETS, sets).
@@ -70,7 +79,7 @@
-record(state, {name,
strategy :: strategy(),
- children = [] :: [child()],
+ children = [] :: [child_rec()],
dynamics :: ?DICT() | ?SET(),
intensity :: non_neg_integer(),
period :: pos_integer(),
@@ -99,11 +108,16 @@ behaviour_info(_Other) ->
-type startlink_err() :: {'already_started', pid()} | 'shutdown' | term().
-type startlink_ret() :: {'ok', pid()} | 'ignore' | {'error', startlink_err()}.
--spec start_link(module(), term()) -> startlink_ret().
+-spec start_link(Module, Args) -> startlink_ret() when
+ Module :: module(),
+ Args :: term().
start_link(Mod, Args) ->
gen_server:start_link(supervisor, {self, Mod, Args}, []).
--spec start_link(sup_name(), module(), term()) -> startlink_ret().
+-spec start_link(SupName, Module, Args) -> startlink_ret() when
+ SupName :: sup_name(),
+ Module :: module(),
+ Args :: term().
start_link(SupName, Mod, Args) ->
gen_server:start_link(SupName, supervisor, {SupName, Mod, Args}, []).
@@ -111,24 +125,33 @@ start_link(SupName, Mod, Args) ->
%%% Interface functions.
%%% ---------------------------------------------------
--type info() :: term().
-type startchild_err() :: 'already_present'
- | {'already_started', child_id()} | term().
--type startchild_ret() :: {'ok', child_id()} | {'ok', child_id(), info()}
+ | {'already_started', Child :: child()} | term().
+-type startchild_ret() :: {'ok', Child :: child()}
+ | {'ok', Child :: child(), Info :: term()}
| {'error', startchild_err()}.
--spec start_child(sup_ref(), child_spec() | [term()]) -> startchild_ret().
+-spec start_child(SupRef, ChildSpec) -> startchild_ret() when
+ SupRef :: sup_ref(),
+ ChildSpec :: child_spec() | (List :: [term()]).
start_child(Supervisor, ChildSpec) ->
call(Supervisor, {start_child, ChildSpec}).
--type restart_err() :: 'running' | 'not_found' | 'simple_one_for_one' | term().
--spec restart_child(sup_ref(), term()) ->
- {'ok', child_id()} | {'ok', child_id(), info()} | {'error', restart_err()}.
+-spec restart_child(SupRef, Id) -> Result when
+ SupRef :: sup_ref(),
+ Id :: child_id(),
+ Result :: {'ok', Child :: child()}
+ | {'ok', Child :: child(), Info :: term()}
+ | {'error', Error},
+ Error :: 'running' | 'not_found' | 'simple_one_for_one' | term().
restart_child(Supervisor, Name) ->
call(Supervisor, {restart_child, Name}).
--type del_err() :: 'running' | 'not_found' | 'simple_one_for_one'.
--spec delete_child(sup_ref(), term()) -> 'ok' | {'error', del_err()}.
+-spec delete_child(SupRef, Id) -> Result when
+ SupRef :: sup_ref(),
+ Id :: child_id(),
+ Result :: 'ok' | {'error', Error},
+ Error :: 'running' | 'not_found' | 'simple_one_for_one'.
delete_child(Supervisor, Name) ->
call(Supervisor, {delete_child, Name}).
@@ -139,22 +162,39 @@ delete_child(Supervisor, Name) ->
%% way (maybe killed).
%%-----------------------------------------------------------------
--type term_err() :: 'not_found' | 'simple_one_for_one'.
--spec terminate_child(sup_ref(), pid() | term()) -> 'ok' | {'error', term_err()}.
+-spec terminate_child(SupRef, Id) -> Result when
+ SupRef :: sup_ref(),
+ Id :: pid() | child_id(),
+ Result :: 'ok' | {'error', Error},
+ Error :: 'not_found' | 'simple_one_for_one'.
terminate_child(Supervisor, Name) ->
call(Supervisor, {terminate_child, Name}).
--spec which_children(sup_ref()) -> [{term(), child_id(), worker(), modules()}].
+-spec which_children(SupRef) -> [{Id,Child,Type,Modules}] when
+ SupRef :: sup_ref(),
+ Id :: child_id() | undefined,
+ Child :: child(),
+ Type :: worker(),
+ Modules :: modules().
which_children(Supervisor) ->
call(Supervisor, which_children).
+-spec count_children(SupRef) -> PropListOfCounts when
+ SupRef :: sup_ref(),
+ PropListOfCounts :: [Count],
+ Count :: {specs, ChildSpecCount :: non_neg_integer()}
+ | {active, ActiveProcessCount :: non_neg_integer()}
+ | {supervisors, ChildSupervisorCount :: non_neg_integer()}
+ |{workers, ChildWorkerCount :: non_neg_integer()}.
count_children(Supervisor) ->
call(Supervisor, count_children).
call(Supervisor, Req) ->
gen_server:call(Supervisor, Req, infinity).
--spec check_childspecs([child_spec()]) -> 'ok' | {'error', term()}.
+-spec check_childspecs(ChildSpecs) -> Result when
+ ChildSpecs :: [child_spec()],
+ Result :: 'ok' | {'error', Error :: term()}.
check_childspecs(ChildSpecs) when is_list(ChildSpecs) ->
case check_startspec(ChildSpecs) of
{ok, _} -> ok;
@@ -222,12 +262,12 @@ init_dynamic(_State, StartSpec) ->
%%-----------------------------------------------------------------
%% Func: start_children/2
-%% Args: Children = [child()] in start order
+%% Args: Children = [child_rec()] in start order
%% SupName = {local, atom()} | {global, atom()} | {pid(), Mod}
%% Purpose: Start all children. The new list contains #child's
%% with pids.
%% Returns: {ok, NChildren} | {error, NChildren}
-%% NChildren = [child()] in termination order (reversed
+%% NChildren = [child_rec()] in termination order (reversed
%% start order)
%%-----------------------------------------------------------------
start_children(Children, SupName) -> start_children(Children, [], SupName).
@@ -687,9 +727,9 @@ restart(one_for_all, Child, State) ->
%%-----------------------------------------------------------------
%% Func: terminate_children/2
-%% Args: Children = [child()] in termination order
+%% Args: Children = [child_rec()] in termination order
%% SupName = {local, atom()} | {global, atom()} | {pid(),Mod}
-%% Returns: NChildren = [child()] in
+%% Returns: NChildren = [child_rec()] in
%% startup order (reversed termination order)
%%-----------------------------------------------------------------
terminate_children(Children, SupName) ->
@@ -958,7 +998,7 @@ supname(N, _) -> N.
%%% Shutdown = integer() | infinity | brutal_kill
%%% ChildType = supervisor | worker
%%% Modules = [atom()] | dynamic
-%%% Returns: {ok, [child()]} | Error
+%%% Returns: {ok, [child_rec()]} | Error
%%% ------------------------------------------------------
check_startspec(Children) -> check_startspec(Children, []).
diff --git a/lib/stdlib/src/supervisor_bridge.erl b/lib/stdlib/src/supervisor_bridge.erl
index 3d2bd2c9a5..555cb5a66f 100644
--- a/lib/stdlib/src/supervisor_bridge.erl
+++ b/lib/stdlib/src/supervisor_bridge.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -49,9 +49,25 @@ behaviour_info(_Other) ->
%%%-----------------------------------------------------------------
-record(state, {mod, pid, child_state, name}).
+-spec start_link(Module, Args) -> Result when
+ Module :: module(),
+ Args :: term(),
+ Result :: {ok, Pid} | ignore | {error, Error},
+ Error :: {already_started, Pid} | term(),
+ Pid :: pid().
+
start_link(Mod, StartArgs) ->
gen_server:start_link(supervisor_bridge, [Mod, StartArgs, self], []).
+-spec start_link(SupBridgeName, Module, Args) -> Result when
+ SupBridgeName :: {local, Name} | {global, Name},
+ Name :: atom(),
+ Module :: module(),
+ Args :: term(),
+ Result :: {ok, Pid} | ignore | {error, Error},
+ Error :: {already_started, Pid} | term(),
+ Pid :: pid().
+
start_link(Name, Mod, StartArgs) ->
gen_server:start_link(Name, supervisor_bridge, [Mod, StartArgs, Name], []).
diff --git a/lib/stdlib/src/sys.erl b/lib/stdlib/src/sys.erl
index 12209c16d7..8ab72c9b50 100644
--- a/lib/stdlib/src/sys.erl
+++ b/lib/stdlib/src/sys.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
+%% Copyright Ericsson AB 1996-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
@@ -33,22 +33,74 @@
%%-----------------------------------------------------------------
-type name() :: pid() | atom() | {'global', atom()}.
--type system_event() :: {'in', _Msg} | {'in', _Msg, _From} | {'out', _Msg, _To}.
+-type system_event() :: {'in', Msg :: _}
+ | {'in', Msg :: _, From :: _}
+ | {'out', Msg :: _, To :: _}
+ | term().
+-opaque dbg_opt() :: list().
+-type dbg_fun() :: fun((FuncState :: _,
+ Event :: system_event(),
+ ProcState :: _) -> 'done' | (NewFuncState :: _)).
%%-----------------------------------------------------------------
%% System messages
%%-----------------------------------------------------------------
+-spec suspend(Name) -> Void when
+ Name :: name(),
+ Void :: term().
suspend(Name) -> send_system_msg(Name, suspend).
+-spec suspend(Name, Timeout) -> Void when
+ Name :: name(),
+ Timeout :: timeout(),
+ Void :: term().
suspend(Name, Timeout) -> send_system_msg(Name, suspend, Timeout).
+-spec resume(Name) -> Void when
+ Name :: name(),
+ Void :: term().
resume(Name) -> send_system_msg(Name, resume).
+-spec resume(Name, Timeout) -> Void when
+ Name :: name(),
+ Timeout :: timeout(),
+ Void :: term().
resume(Name, Timeout) -> send_system_msg(Name, resume, Timeout).
+-spec get_status(Name) -> Status when
+ Name :: name(),
+ Status :: {status, Pid :: pid(), {module, Module :: module()}, [SItem]},
+ SItem :: (PDict :: [{Key :: term(), Value :: term()}])
+ | (SysState :: 'running' | 'suspended')
+ | (Parent :: pid())
+ | (Dbg :: dbg_opt())
+ | (Misc :: term()).
get_status(Name) -> send_system_msg(Name, get_status).
+-spec get_status(Name, Timeout) -> Status when
+ Name :: name(),
+ Timeout :: timeout(),
+ Status :: {status, Pid :: pid(), {module, Module :: module()}, [SItem]},
+ SItem :: (PDict :: [{Key :: term(), Value :: term()}])
+ | (SysState :: 'running' | 'suspended')
+ | (Parent :: pid())
+ | (Dbg :: dbg_opt())
+ | (Misc :: term()).
get_status(Name, Timeout) -> send_system_msg(Name, get_status, Timeout).
+-spec change_code(Name, Module, OldVsn, Extra) -> 'ok' | {error, Reason} when
+ Name :: name(),
+ Module :: module(),
+ OldVsn :: 'undefined' | term(),
+ Extra :: term(),
+ Reason :: term().
change_code(Name, Mod, Vsn, Extra) ->
send_system_msg(Name, {change_code, Mod, Vsn, Extra}).
+-spec change_code(Name, Module, OldVsn, Extra, Timeout) ->
+ 'ok' | {error, Reason} when
+ Name :: name(),
+ Module :: module(),
+ OldVsn :: 'undefined' | term(),
+ Extra :: term(),
+ Timeout :: timeout(),
+ Reason :: term().
change_code(Name, Mod, Vsn, Extra, Timeout) ->
send_system_msg(Name, {change_code, Mod, Vsn, Extra}, Timeout).
@@ -56,52 +108,116 @@ change_code(Name, Mod, Vsn, Extra, Timeout) ->
%% Debug commands
%%-----------------------------------------------------------------
--type log_flag() :: 'true' | {'true',pos_integer()} | 'false' | 'get' | 'print'.
-
--spec log(name(), log_flag()) -> 'ok' | {'ok', [system_event()]}.
+-spec log(Name, Flag) -> 'ok' | {'ok', [system_event()]} when
+ Name :: name(),
+ Flag :: 'true' |
+ {'true', N :: pos_integer()}
+ | 'false' | 'get' | 'print'.
log(Name, Flag) ->
send_system_msg(Name, {debug, {log, Flag}}).
--spec log(name(), log_flag(), timeout()) -> 'ok' | {'ok', [system_event()]}.
+-spec log(Name, Flag, Timeout) -> 'ok' | {'ok', [system_event()]} when
+ Name :: name(),
+ Flag :: 'true' |
+ {'true', N :: pos_integer()}
+ | 'false' | 'get' | 'print',
+ Timeout :: timeout().
log(Name, Flag, Timeout) ->
send_system_msg(Name, {debug, {log, Flag}}, Timeout).
--spec trace(name(), boolean()) -> 'ok'.
+-spec trace(Name, Flag) -> 'ok' when
+ Name :: name(),
+ Flag :: boolean().
trace(Name, Flag) ->
send_system_msg(Name, {debug, {trace, Flag}}).
--spec trace(name(), boolean(), timeout()) -> 'ok'.
+-spec trace(Name, Flag, Timeout) -> 'ok' when
+ Name :: name(),
+ Flag :: boolean(),
+ Timeout :: timeout().
trace(Name, Flag, Timeout) ->
send_system_msg(Name, {debug, {trace, Flag}}, Timeout).
--type l2f_fname() :: string() | 'false'.
-
--spec log_to_file(name(), l2f_fname()) -> 'ok' | {'error','open_file'}.
+-spec log_to_file(Name, Flag) -> 'ok' | {'error','open_file'} when
+ Name :: name(),
+ Flag :: (FileName :: string()) | 'false'.
log_to_file(Name, FileName) ->
send_system_msg(Name, {debug, {log_to_file, FileName}}).
--spec log_to_file(name(), l2f_fname(), timeout()) -> 'ok' | {'error','open_file'}.
+-spec log_to_file(Name, Flag, Timeout) -> 'ok' | {'error','open_file'} when
+ Name :: name(),
+ Flag :: (FileName :: string()) | 'false',
+ Timeout :: timeout().
log_to_file(Name, FileName, Timeout) ->
send_system_msg(Name, {debug, {log_to_file, FileName}}, Timeout).
+-spec statistics(Name, Flag) -> 'ok' | {'ok', Statistics} when
+ Name :: name(),
+ Flag :: 'true' | 'false' | 'get',
+ Statistics :: [StatisticsTuple],
+ StatisticsTuple :: {'start_time', DateTime1}
+ | {'current_time', DateTime2}
+ | {'reductions', non_neg_integer()}
+ | {'messages_in', non_neg_integer()}
+ | {'messages_out', non_neg_integer()},
+ DateTime1 :: file:date_time(),
+ DateTime2 :: file:date_time().
statistics(Name, Flag) ->
send_system_msg(Name, {debug, {statistics, Flag}}).
+
+-spec statistics(Name, Flag, Timeout) -> 'ok' | {'ok', Statistics} when
+ Name :: name(),
+ Flag :: 'true' | 'false' | 'get',
+ Statistics :: [StatisticsTuple],
+ StatisticsTuple :: {'start_time', DateTime1}
+ | {'current_time', DateTime2}
+ | {'reductions', non_neg_integer()}
+ | {'messages_in', non_neg_integer()}
+ | {'messages_out', non_neg_integer()},
+ DateTime1 :: file:date_time(),
+ DateTime2 :: file:date_time(),
+ Timeout :: timeout().
statistics(Name, Flag, Timeout) ->
send_system_msg(Name, {debug, {statistics, Flag}}, Timeout).
--spec no_debug(name()) -> 'ok'.
+-spec no_debug(Name) -> 'ok' when
+ Name :: name().
no_debug(Name) -> send_system_msg(Name, {debug, no_debug}).
--spec no_debug(name(), timeout()) -> 'ok'.
+-spec no_debug(Name, Timeout) -> 'ok' when
+ Name :: name(),
+ Timeout :: timeout().
no_debug(Name, Timeout) -> send_system_msg(Name, {debug, no_debug}, Timeout).
+-spec install(Name, FuncSpec) -> Void when
+ Name :: name(),
+ FuncSpec :: {Func, FuncState},
+ Func :: dbg_fun(),
+ FuncState :: term(),
+ Void :: term().
install(Name, {Func, FuncState}) ->
send_system_msg(Name, {debug, {install, {Func, FuncState}}}).
+-spec install(Name, FuncSpec, Timeout) -> Void when
+ Name :: name(),
+ FuncSpec :: {Func, FuncState},
+ Func :: dbg_fun(),
+ FuncState :: term(),
+ Timeout :: timeout(),
+ Void :: term().
install(Name, {Func, FuncState}, Timeout) ->
send_system_msg(Name, {debug, {install, {Func, FuncState}}}, Timeout).
+-spec remove(Name, Func) -> Void when
+ Name :: name(),
+ Func :: dbg_fun(),
+ Void :: term().
remove(Name, Func) ->
send_system_msg(Name, {debug, {remove, Func}}).
+-spec remove(Name, Func, Timeout) -> Void when
+ Name :: name(),
+ Func :: dbg_fun(),
+ Timeout :: timeout(),
+ Void :: term().
remove(Name, Func, Timeout) ->
send_system_msg(Name, {debug, {remove, Func}}, Timeout).
@@ -150,6 +266,14 @@ mfa(Name, Req, Timeout) ->
%% The Module must export system_continue/3, system_terminate/4
%% and format_status/2 for status information.
%%-----------------------------------------------------------------
+-spec handle_system_msg(Msg, From, Parent, Module, Debug, Misc) -> Void when
+ Msg :: term(),
+ From :: {pid(), Tag :: _},
+ Parent :: pid(),
+ Module :: module(),
+ Debug :: [dbg_opt()],
+ Misc :: term(),
+ Void :: term().
handle_system_msg(Msg, From, Parent, Module, Debug, Misc) ->
handle_system_msg(running, Msg, From, Parent, Module, Debug, Misc, false).
@@ -176,6 +300,11 @@ handle_system_msg(SysState, Msg, From, Parent, Mod, Debug, Misc, Hib) ->
%% Func is a formatting function, called as Func(Device, Event).
%% Returns: [debug_opts()]
%%-----------------------------------------------------------------
+-spec handle_debug(Debug, FormFunc, Extra, Event) -> [dbg_opt()] when
+ Debug :: [dbg_opt()],
+ FormFunc :: dbg_fun(),
+ Extra :: term(),
+ Event :: system_event().
handle_debug([{trace, true} | T], FormFunc, State, Event) ->
print_event({Event, State, FormFunc}),
[{trace, true} | handle_debug(T, FormFunc, State, Event)];
@@ -341,24 +470,36 @@ trim(N, LogData) ->
%% Debug structure manipulating functions
%%-----------------------------------------------------------------
install_debug(Item, Data, Debug) ->
- case get_debug(Item, Debug, undefined) of
+ case get_debug2(Item, Debug, undefined) of
undefined -> [{Item, Data} | Debug];
_ -> Debug
end.
remove_debug(Item, Debug) -> lists:keydelete(Item, 1, Debug).
+
+-spec get_debug(Item, Debug, Default) -> term() when
+ Item :: 'log' | 'statistics',
+ Debug :: [dbg_opt()],
+ Default :: term().
get_debug(Item, Debug, Default) ->
+ get_debug2(Item, Debug, Default).
+
+%% Workaround: accepts more Item types than get_debug/3.
+get_debug2(Item, Debug, Default) ->
case lists:keysearch(Item, 1, Debug) of
{value, {Item, Data}} -> Data;
_ -> Default
end.
+-spec print_log(Debug) -> Void when
+ Debug :: [dbg_opt()],
+ Void :: term().
print_log(Debug) ->
{_N, Logs} = get_debug(log, Debug, {0, []}),
lists:foreach(fun print_event/1,
lists:reverse(Logs)).
close_log_file(Debug) ->
- case get_debug(log_to_file, Debug, []) of
+ case get_debug2(log_to_file, Debug, []) of
[] ->
Debug;
Fd ->
@@ -375,6 +516,15 @@ close_log_file(Debug) ->
%% system messages.
%% Returns: [debug_opts()]
%%-----------------------------------------------------------------
+
+-spec debug_options(Options) -> [dbg_opt()] when
+ Options :: [Opt],
+ Opt :: 'trace' | 'log' | 'statistics' | {'log_to_file', FileName}
+ | {'install', FuncSpec},
+ FileName :: file:name(),
+ FuncSpec :: {Func, FuncState},
+ Func :: dbg_fun(),
+ FuncState :: term().
debug_options(Options) ->
debug_options(Options, []).
debug_options([trace | T], Debug) ->
diff --git a/lib/stdlib/src/timer.erl b/lib/stdlib/src/timer.erl
index 78e897b877..89fae05e4f 100644
--- a/lib/stdlib/src/timer.erl
+++ b/lib/stdlib/src/timer.erl
@@ -46,56 +46,108 @@
%%
-opaque tref() :: {integer(), reference()}.
-type time() :: non_neg_integer().
--type timestamp() :: {non_neg_integer(), non_neg_integer(), non_neg_integer()}.
%%
%% Interface functions
%%
--spec apply_after(time(), atom(), atom(), [term()]) -> {'ok', tref()} | {'error', term()}.
+-spec apply_after(Time, Module, Function, Arguments) ->
+ {'ok', TRef} | {'error', Reason} when
+ Time :: time(),
+ Module :: module(),
+ Function :: atom(),
+ Arguments :: [term()],
+ TRef :: tref(),
+ Reason :: term().
+
apply_after(Time, M, F, A) ->
req(apply_after, {Time, {M, F, A}}).
--spec send_after(time(), pid() | atom(), term()) -> {'ok', tref()} | {'error', term()}.
+-spec send_after(Time, Pid, Message) -> {'ok', TRef} | {'error', Reason} when
+ Time :: time(),
+ Pid :: pid() | (RegName :: atom()),
+ Message :: term(),
+ TRef :: tref(),
+ Reason :: term().
send_after(Time, Pid, Message) ->
req(apply_after, {Time, {?MODULE, send, [Pid, Message]}}).
--spec send_after(time(), term()) -> {'ok', tref()} | {'error', term()}.
+-spec send_after(Time, Message) -> {'ok', TRef} | {'error', Reason} when
+ Time :: time(),
+ Message :: term(),
+ TRef :: tref(),
+ Reason :: term().
send_after(Time, Message) ->
send_after(Time, self(), Message).
--spec exit_after(time(), pid() | atom(), term()) -> {'ok', tref()} | {'error', term()}.
+-spec exit_after(Time, Pid, Reason1) -> {'ok', TRef} | {'error', Reason2} when
+ Time :: time(),
+ Pid :: pid() | (RegName :: atom()),
+ TRef :: tref(),
+ Reason1 :: term(),
+ Reason2 :: term().
exit_after(Time, Pid, Reason) ->
req(apply_after, {Time, {erlang, exit, [Pid, Reason]}}).
--spec exit_after(time(), term()) -> {'ok', tref()} | {'error', term()}.
+-spec exit_after(Time, Reason1) -> {'ok', TRef} | {'error', Reason2} when
+ Time :: time(),
+ TRef :: tref(),
+ Reason1 :: term(),
+ Reason2 :: term().
exit_after(Time, Reason) ->
exit_after(Time, self(), Reason).
--spec kill_after(time(), pid() | atom()) -> {'ok', tref()} | {'error', term()}.
+-spec kill_after(Time, Pid) -> {'ok', TRef} | {'error', Reason2} when
+ Time :: time(),
+ Pid :: pid() | (RegName :: atom()),
+ TRef :: tref(),
+ Reason2 :: term().
kill_after(Time, Pid) ->
exit_after(Time, Pid, kill).
--spec kill_after(time()) -> {'ok', tref()} | {'error', term()}.
+-spec kill_after(Time) -> {'ok', TRef} | {'error', Reason2} when
+ Time :: time(),
+ TRef :: tref(),
+ Reason2 :: term().
kill_after(Time) ->
exit_after(Time, self(), kill).
--spec apply_interval(time(), atom(), atom(), [term()]) -> {'ok', tref()} | {'error', term()}.
+-spec apply_interval(Time, Module, Function, Arguments) ->
+ {'ok', TRef} | {'error', Reason} when
+ Time :: time(),
+ Module :: module(),
+ Function :: atom(),
+ Arguments :: [term()],
+ TRef :: tref(),
+ Reason :: term().
apply_interval(Time, M, F, A) ->
req(apply_interval, {Time, self(), {M, F, A}}).
--spec send_interval(time(), pid() | atom(), term()) -> {'ok', tref()} | {'error', term()}.
+-spec send_interval(Time, Pid, Message) ->
+ {'ok', TRef} | {'error', Reason} when
+ Time :: time(),
+ Pid :: pid() | (RegName :: atom()),
+ Message :: term(),
+ TRef :: tref(),
+ Reason :: term().
send_interval(Time, Pid, Message) ->
req(apply_interval, {Time, Pid, {?MODULE, send, [Pid, Message]}}).
--spec send_interval(time(), term()) -> {'ok', tref()} | {'error', term()}.
+-spec send_interval(Time, Message) -> {'ok', TRef} | {'error', Reason} when
+ Time :: time(),
+ Message :: term(),
+ TRef :: tref(),
+ Reason :: term().
send_interval(Time, Message) ->
send_interval(Time, self(), Message).
--spec cancel(tref()) -> {'ok', 'cancel'} | {'error', term()}.
+-spec cancel(TRef) -> {'ok', 'cancel'} | {'error', Reason} when
+ TRef :: tref(),
+ Reason :: term().
cancel(BRef) ->
req(cancel, BRef).
--spec sleep(timeout()) -> 'ok'.
+-spec sleep(Time) -> 'ok' when
+ Time :: timeout().
sleep(T) ->
receive
after T -> ok
@@ -104,7 +156,10 @@ sleep(T) ->
%%
%% Measure the execution time (in microseconds) for Fun().
%%
--spec tc(function()) -> {time(), term()}.
+-spec tc(Fun) -> {Time, Value} when
+ Fun :: function(),
+ Time :: integer(),
+ Value :: term().
tc(F) ->
Before = os:timestamp(),
Val = F(),
@@ -114,7 +169,11 @@ tc(F) ->
%%
%% Measure the execution time (in microseconds) for Fun(Args).
%%
--spec tc(function(), [_]) -> {time(), term()}.
+-spec tc(Fun, Arguments) -> {Time, Value} when
+ Fun :: function(),
+ Arguments :: [term()],
+ Time :: integer(),
+ Value :: term().
tc(F, A) ->
Before = os:timestamp(),
Val = apply(F, A),
@@ -124,7 +183,12 @@ tc(F, A) ->
%%
%% Measure the execution time (in microseconds) for an MFA.
%%
--spec tc(atom(), atom(), [term()]) -> {time(), term()}.
+-spec tc(Module, Function, Arguments) -> {Time, Value} when
+ Module :: module(),
+ Function :: atom(),
+ Arguments :: [term()],
+ Time :: integer(),
+ Value :: term().
tc(M, F, A) ->
Before = os:timestamp(),
Val = apply(M, F, A),
@@ -135,23 +199,36 @@ tc(M, F, A) ->
%% Calculate the time difference (in microseconds) of two
%% erlang:now() timestamps, T2-T1.
%%
--spec now_diff(timestamp(), timestamp()) -> integer().
+-spec now_diff(T1, T2) -> Tdiff when
+ T1 :: calendar:t_now(),
+ T2 :: calendar:t_now(),
+ Tdiff :: integer().
now_diff({A2, B2, C2}, {A1, B1, C1}) ->
((A2-A1)*1000000 + B2-B1)*1000000 + C2-C1.
%%
%% Convert seconds, minutes etc. to milliseconds.
%%
--spec seconds(non_neg_integer()) -> non_neg_integer().
+-spec seconds(Seconds) -> MilliSeconds when
+ Seconds :: non_neg_integer(),
+ MilliSeconds :: non_neg_integer().
seconds(Seconds) ->
1000*Seconds.
--spec minutes(non_neg_integer()) -> non_neg_integer().
+-spec minutes(Minutes) -> MilliSeconds when
+ Minutes :: non_neg_integer(),
+ MilliSeconds :: non_neg_integer().
minutes(Minutes) ->
1000*60*Minutes.
--spec hours(non_neg_integer()) -> non_neg_integer().
+-spec hours(Hours) -> MilliSeconds when
+ Hours :: non_neg_integer(),
+ MilliSeconds :: non_neg_integer().
hours(Hours) ->
1000*60*60*Hours.
--spec hms(non_neg_integer(), non_neg_integer(), non_neg_integer()) -> non_neg_integer().
+-spec hms(Hours, Minutes, Seconds) -> MilliSeconds when
+ Hours :: non_neg_integer(),
+ Minutes :: non_neg_integer(),
+ Seconds :: non_neg_integer(),
+ MilliSeconds :: non_neg_integer().
hms(H, M, S) ->
hours(H) + minutes(M) + seconds(S).
diff --git a/lib/stdlib/src/unicode.erl b/lib/stdlib/src/unicode.erl
index 12bc60623d..a5d9965ca2 100644
--- a/lib/stdlib/src/unicode.erl
+++ b/lib/stdlib/src/unicode.erl
@@ -30,12 +30,34 @@
characters_to_binary/3,
bom_to_encoding/1, encoding_to_bom/1]).
--export_type([encoding/0]).
+-export_type([chardata/0, charlist/0, encoding/0, external_chardata/0,
+ external_charlist/0, latin1_chardata/0,
+ latin1_charlist/0, unicode_binary/0, unicode_char/0]).
-type encoding() :: 'latin1' | 'unicode' | 'utf8'
| 'utf16' | {'utf16', endian()}
| 'utf32' | {'utf32', endian()}.
-type endian() :: 'big' | 'little'.
+-type unicode_binary() :: binary().
+-type unicode_char() :: non_neg_integer().
+-type charlist() :: [unicode_char() | unicode_binary() | charlist()].
+-type chardata() :: charlist() | unicode_binary().
+-type external_unicode_binary() :: binary().
+-type external_chardata() :: external_charlist() | external_unicode_binary().
+-type external_charlist() :: [unicode_char() | external_unicode_binary()
+ | external_charlist()].
+-type latin1_binary() :: binary().
+-type latin1_char() :: byte().
+-type latin1_chardata() :: latin1_charlist() | latin1_binary().
+-type latin1_charlist() :: [latin1_char() | latin1_binary()
+ | latin1_charlist()].
+
+-spec characters_to_list(Data) -> Result when
+ Data :: latin1_chardata() | chardata() | external_chardata(),
+ Result :: list()
+ | {error, list(), RestData}
+ | {incomplete, list(), binary()},
+ RestData :: latin1_chardata() | chardata() | external_chardata().
characters_to_list(ML) ->
unicode:characters_to_list(ML,unicode).
@@ -69,6 +91,13 @@ do_characters_to_list(ML, Encoding) ->
end.
+-spec characters_to_binary(Data) -> Result when
+ Data :: latin1_chardata() | chardata() | external_chardata(),
+ Result :: binary()
+ | {error, binary(), RestData}
+ | {incomplete, binary(), binary()},
+ RestData :: latin1_chardata() | chardata() | external_chardata().
+
characters_to_binary(ML) ->
try
unicode:characters_to_binary(ML,unicode)
@@ -104,6 +133,15 @@ characters_to_binary_int(ML,InEncoding) ->
erlang:raise(error,TheError,[{Mod,characters_to_binary,L}|Rest])
end.
+-spec characters_to_binary(Data, InEncoding, OutEncoding) -> Result when
+ Data :: latin1_chardata() | chardata() | external_chardata(),
+ InEncoding :: encoding(),
+ OutEncoding :: encoding(),
+ Result :: binary()
+ | {error, binary(), RestData}
+ | {incomplete, binary(), binary()},
+ RestData :: latin1_chardata() | chardata() | external_chardata().
+
characters_to_binary(ML, latin1, latin1) when is_binary(ML) ->
ML;
characters_to_binary(ML, latin1, Uni) when is_binary(ML) and ((Uni =:= utf8) or (Uni =:= unicode)) ->
@@ -215,6 +253,13 @@ characters_to_binary_int(ML, InEncoding, OutEncoding) ->
Res
end.
+-spec bom_to_encoding(Bin) -> {Encoding, Length} when
+ Bin :: binary(),
+ Encoding :: 'latin1' | 'utf8'
+ | {'utf16', endian()}
+ | {'utf32', endian()},
+ Length :: non_neg_integer().
+
bom_to_encoding(<<239,187,191,_/binary>>) ->
{utf8,3};
bom_to_encoding(<<0,0,254,255,_/binary>>) ->
@@ -228,6 +273,10 @@ bom_to_encoding(<<255,254,_/binary>>) ->
bom_to_encoding(Bin) when is_binary(Bin) ->
{latin1,0}.
+-spec encoding_to_bom(InEncoding) -> Bin when
+ Bin :: binary(),
+ InEncoding :: encoding().
+
encoding_to_bom(unicode) ->
<<239,187,191>>;
encoding_to_bom(utf8) ->
diff --git a/lib/stdlib/src/win32reg.erl b/lib/stdlib/src/win32reg.erl
index ee0d17bc94..598e77ffdc 100644
--- a/lib/stdlib/src/win32reg.erl
+++ b/lib/stdlib/src/win32reg.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
+%% 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
@@ -52,14 +52,17 @@
-define(reg_dword, 4).
%% Basic types internal to this file.
--type open_mode() :: 'read' | 'write'.
--type reg_handle() :: {'win32reg',port()}.
+-opaque reg_handle() :: {'win32reg',port()}.
-type name() :: string() | 'default'.
-type value() :: string() | integer() | binary().
%%% Exported functions.
--spec open([open_mode()]) -> {'ok', reg_handle()} | {'error', 'enotsup'}.
+-spec open(OpenModeList) -> ReturnValue when
+ OpenModeList :: [OpenMode],
+ OpenMode :: 'read' | 'write',
+ ReturnValue :: {'ok', RegHandle} | {'error', ErrorId :: 'enotsup'},
+ RegHandle :: reg_handle().
open(Modes) ->
case os:type() of
@@ -75,14 +78,17 @@ open(Modes) ->
{error, enotsup}
end.
--spec close(reg_handle()) -> 'ok'.
+-spec close(RegHandle) -> 'ok' when
+ RegHandle :: reg_handle().
close({win32reg, Reg}) when is_port(Reg) ->
unlink(Reg),
exit(Reg, die),
ok.
--spec current_key(reg_handle()) -> {'ok', string()}.
+-spec current_key(RegHandle) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ ReturnValue :: {'ok', string()}.
current_key({win32reg, Reg}) when is_port(Reg) ->
Cmd = [?cmd_get_current],
@@ -94,12 +100,18 @@ current_key({win32reg, Reg}) when is_port(Reg) ->
_ -> Root ++ [$\\|Name]
end}.
--spec change_key(reg_handle(), string()) -> 'ok' | {'error', atom()}.
+-spec change_key(RegHandle, Key) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ Key :: string(),
+ ReturnValue :: 'ok' | {'error', ErrorId :: atom()}.
change_key({win32reg, Reg}, Key) when is_port(Reg) ->
change_key(Reg, ?cmd_open_key, Key).
--spec change_key_create(reg_handle(), string()) -> 'ok' | {'error', atom()}.
+-spec change_key_create(RegHandle, Key) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ Key :: string(),
+ ReturnValue :: 'ok' | {'error', ErrorId :: atom()}.
change_key_create({win32reg, Reg}, Key) when is_port(Reg) ->
change_key(Reg, ?cmd_create_key, Key).
@@ -113,21 +125,30 @@ change_key(Reg, Cmd, Key) ->
{error, Reason}
end.
--spec sub_keys(reg_handle()) -> {'ok', [string()]} | {'error', atom()}.
+-spec sub_keys(RegHandle) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ ReturnValue :: {'ok', [SubKey]} | {'error', ErrorId :: atom()},
+ SubKey :: string().
sub_keys({win32reg, Reg}) when is_port(Reg) ->
Cmd = [?cmd_get_all_subkeys],
Reg ! {self(), {command, Cmd}},
collect_keys(Reg, []).
--spec delete_key(reg_handle()) -> 'ok' | {'error', atom()}.
+-spec delete_key(RegHandle) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ ReturnValue :: 'ok' | {'error', ErrorId :: atom()}.
delete_key({win32reg, Reg}) when is_port(Reg) ->
Cmd = [?cmd_delete_key],
Reg ! {self(), {command, Cmd}},
get_result(Reg).
--spec set_value(reg_handle(), name(), value()) -> 'ok' | {'error', atom()}.
+-spec set_value(RegHandle, Name, Value) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ Name :: name(),
+ Value :: value(),
+ ReturnValue :: 'ok' | {'error', ErrorId :: atom()}.
set_value({win32reg, Reg}, Name0, Value) when is_port(Reg) ->
Name =
@@ -140,7 +161,10 @@ set_value({win32reg, Reg}, Name0, Value) when is_port(Reg) ->
Reg ! {self(), {command, Cmd}},
get_result(Reg).
--spec value(reg_handle(), name()) -> {'ok', value()} | {'error', atom()}.
+-spec value(RegHandle, Name) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ Name :: name(),
+ ReturnValue :: {'ok', Value :: value()} | {'error', ErrorId :: atom()}.
value({win32reg, Reg}, Name) when is_port(Reg) ->
Cmd = [?cmd_get_value, Name, 0],
@@ -152,14 +176,20 @@ value({win32reg, Reg}, Name) when is_port(Reg) ->
{error, Reason}
end.
--spec values(reg_handle()) -> {'ok', [{name(), value()}]} | {'error', atom()}.
+-spec values(RegHandle) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ ReturnValue :: {'ok', [ValuePair]} | {'error', ErrorId :: atom()},
+ ValuePair :: {Name :: name(), Value :: value()}.
values({win32reg, Reg}) when is_port(Reg) ->
Cmd = [?cmd_get_all_values],
Reg ! {self(), {command, Cmd}},
collect_values(Reg, []).
--spec delete_value(reg_handle(), name()) -> 'ok' | {'error', atom()}.
+-spec delete_value(RegHandle, Name) -> ReturnValue when
+ RegHandle :: reg_handle(),
+ Name :: name(),
+ ReturnValue :: 'ok' | {'error', ErrorId :: atom()}.
delete_value({win32reg, Reg}, Name0) when is_port(Reg) ->
Name =
@@ -171,7 +201,9 @@ delete_value({win32reg, Reg}, Name0) when is_port(Reg) ->
Reg ! {self(), {command, Cmd}},
get_result(Reg).
--spec expand(string()) -> string().
+-spec expand(String) -> ExpandedString when
+ String :: string(),
+ ExpandedString :: string().
expand(Value) ->
expand(Value, [], []).
@@ -195,7 +227,9 @@ expand([C|Rest], Env, Result) ->
expand([], [], Result) ->
lists:reverse(Result).
--spec format_error(atom()) -> string().
+-spec format_error(ErrorId) -> ErrorString when
+ ErrorId :: atom(),
+ ErrorString :: string().
format_error(ErrorId) ->
erl_posix_msg:message(ErrorId).
@@ -203,7 +237,7 @@ format_error(ErrorId) ->
%%% Implementation.
-spec collect_values(port(), [{name(), value()}]) ->
- {'ok', [{name(), value()}]} | {'error', atom()}.
+ {'ok', [{name(), value()}]} | {'error', ErrorId :: atom()}.
collect_values(P, Result) ->
case get_result(P) of
@@ -215,7 +249,7 @@ collect_values(P, Result) ->
{error, Reason}
end.
--spec collect_keys(port(), string()) -> {'ok', [string()]} | {'error', atom()}.
+-spec collect_keys(port(), string()) -> {'ok', [string()]} | {'error', ErrorId :: atom()}.
collect_keys(P, Result) ->
case get_result(P) of
diff --git a/lib/stdlib/src/zip.erl b/lib/stdlib/src/zip.erl
index d41aeefa59..524d709431 100644
--- a/lib/stdlib/src/zip.erl
+++ b/lib/stdlib/src/zip.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2006-2010. All Rights Reserved.
+%% 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
@@ -203,6 +203,9 @@
zip_comment_length}).
+-type zip_file() :: #zip_file{}.
+-type zip_comment() :: #zip_comment{}.
+
%% Open a zip archive with options
%%
@@ -323,8 +326,33 @@ openzip_close(_) ->
%% Accepted options:
%% verbose, cooked, file_list, keep_old_files, file_filter, memory
+-spec(unzip(Archive) -> RetValue when
+ Archive :: file:name() | binary(),
+ RetValue :: {ok, FileList}
+ | {ok, FileBinList}
+ | {error, Reason :: term()}
+ | {error, {Name :: file:name(), Reason :: term()}},
+ FileList :: [file:name()],
+ FileBinList :: [{file:name(),binary()}]).
+
unzip(F) -> unzip(F, []).
+-spec(unzip(Archive, Options) -> RetValue when
+ Archive :: file:name() | binary(),
+ Options :: [Option],
+ Option :: {file_list, FileList}
+ | keep_old_files | verbose | memory |
+ {file_filter, FileFilter} | {cwd, CWD},
+ FileList :: [file:name()],
+ FileBinList :: [{file:name(),binary()}],
+ FileFilter :: fun((ZipFile) -> boolean()),
+ CWD :: string(),
+ ZipFile :: zip_file(),
+ RetValue :: {ok, FileList}
+ | {ok, FileBinList}
+ | {error, Reason :: term()}
+ | {error, {Name :: file:name(), Reason :: term()}}).
+
unzip(F, Options) ->
case ?CATCH do_unzip(F, Options) of
{ok, R} -> {ok, R};
@@ -345,6 +373,18 @@ do_unzip(F, Options) ->
{ok, Files}.
%% Iterate over all files in a zip archive
+-spec(foldl(Fun, Acc0, Archive) -> {ok, Acc1} | {error, Reason} when
+ Fun :: fun((FileInArchive, GetInfo, GetBin, AccIn) -> AccOut),
+ FileInArchive :: file:name(),
+ GetInfo :: fun(() -> file:file_info()),
+ GetBin :: fun(() -> binary()),
+ Acc0 :: term(),
+ Acc1 :: term(),
+ AccIn :: term(),
+ AccOut :: term(),
+ Archive :: file:name() | {file:name(), binary()},
+ Reason :: term()).
+
foldl(Fun, Acc0, Archive) when is_function(Fun, 4) ->
ZipFun =
fun({Name, GetInfo, GetBin}, A) ->
@@ -368,8 +408,33 @@ foldl(_,_, _) ->
%% Accepted options:
%% verbose, cooked, memory, comment
+-spec(zip(Name, FileList) -> RetValue when
+ Name :: file:name(),
+ FileList :: [FileSpec],
+ FileSpec :: file:name() | {file:name(), binary()}
+ | {file:name(), binary(), file:file_info()},
+ RetValue :: {ok, FileName :: file:name()}
+ | {ok, {FileName :: file:name(), binary()}}
+ | {error, Reason :: term()}).
+
zip(F, Files) -> zip(F, Files, []).
+-spec(zip(Name, FileList, Options) -> RetValue when
+ Name :: file:name(),
+ FileList :: [FileSpec],
+ FileSpec :: file:name() | {file:name(), binary()}
+ | {file:name(), binary(), file:file_info()},
+ Options :: [Option],
+ Option :: memory | cooked | verbose | {comment, Comment}
+ | {cwd, CWD} | {compress, What} | {uncompress, What},
+ What :: all | [Extension] | {add, [Extension]} | {del, [Extension]},
+ Extension :: string(),
+ Comment :: string(),
+ CWD :: string(),
+ RetValue :: {ok, FileName :: file:name()}
+ | {ok, {FileName :: file:name(), binary()}}
+ | {error, Reason :: term()}).
+
zip(F, Files, Options) ->
case ?CATCH do_zip(F, Files, Options) of
{ok, R} -> {ok, R};
@@ -392,8 +457,20 @@ do_zip(F, Files, Options) ->
%% Accepted options:
%% cooked, file_filter, file_output (latter 2 undocumented)
+-spec(list_dir(Archive) -> RetValue when
+ Archive :: file:name() | binary(),
+ RetValue :: {ok, CommentAndFiles} | {error, Reason :: term()},
+ CommentAndFiles :: [zip_comment() | zip_file()]).
+
list_dir(F) -> list_dir(F, []).
+-spec(list_dir(Archive, Options) -> RetValue when
+ Archive :: file:name() | binary(),
+ RetValue :: {ok, CommentAndFiles} | {error, Reason :: term()},
+ CommentAndFiles :: [zip_comment() | zip_file()],
+ Options :: [Option],
+ Option :: cooked).
+
list_dir(F, Options) ->
case ?CATCH do_list_dir(F, Options) of
{ok, R} -> {ok, R};
@@ -411,6 +488,10 @@ do_list_dir(F, Options) ->
%% Print zip directory in short form
+-spec(t(Archive) -> ok when
+ Archive :: file:name() | binary | ZipHandle,
+ ZipHandle :: pid()).
+
t(F) when is_pid(F) -> zip_t(F);
t(F) when is_record(F, openzip) -> openzip_t(F);
t(F) -> t(F, fun raw_short_print_info_etc/5).
@@ -431,6 +512,10 @@ do_t(F, RawPrint) ->
%% Print zip directory in long form (like ls -l)
+-spec(tt(Archive) -> ok when
+ Archive :: file:name() | binary | ZipHandle,
+ ZipHandle :: pid()).
+
tt(F) when is_pid(F) -> zip_tt(F);
tt(F) when is_record(F, openzip) -> openzip_tt(F);
tt(F) -> t(F, fun raw_long_print_info_etc/5).
@@ -605,11 +690,78 @@ get_list_dir_options(F, Options) ->
get_list_dir_opt(Options, Opts).
%% aliases for erl_tar compatibility
+-spec(table(Archive) -> RetValue when
+ Archive :: file:name() | binary(),
+ RetValue :: {ok, CommentAndFiles} | {error, Reason :: term()},
+ CommentAndFiles :: [zip_comment() | zip_file()]).
+
table(F) -> list_dir(F).
+
+-spec(table(Archive, Options) -> RetValue when
+ Archive :: file:name() | binary(),
+ RetValue :: {ok, CommentAndFiles} | {error, Reason :: term()},
+ CommentAndFiles :: [zip_comment() | zip_file()],
+
+ Options :: [Option],
+ Option :: cooked).
+
table(F, O) -> list_dir(F, O).
+
+-spec(create(Name, FileList) -> RetValue when
+ Name :: file:name(),
+ FileList :: [FileSpec],
+ FileSpec :: file:name() | {file:name(), binary()}
+ | {file:name(), binary(), file:file_info()},
+ RetValue :: {ok, FileName :: file:name()}
+ | {ok, {FileName :: file:name(), binary()}}
+ | {error, Reason :: term()}).
+
create(F, Fs) -> zip(F, Fs).
+
+-spec(create(Name, FileList, Options) -> RetValue when
+ Name :: file:name(),
+ FileList :: [FileSpec],
+ FileSpec :: file:name() | {file:name(), binary()}
+ | {file:name(), binary(), file:file_info()},
+ Options :: [Option],
+ Option :: memory | cooked | verbose | {comment, Comment}
+ | {cwd, CWD} | {compress, What} | {uncompress, What},
+ What :: all | [Extension] | {add, [Extension]} | {del, [Extension]},
+ Extension :: string(),
+ Comment :: string(),
+ CWD :: string(),
+ RetValue :: {ok, FileName :: file:name()}
+ | {ok, {FileName :: file:name(), binary()}}
+ | {error, Reason :: term()}).
create(F, Fs, O) -> zip(F, Fs, O).
+
+-spec(extract(Archive) -> RetValue when
+ Archive :: file:name() | binary(),
+ RetValue :: {ok, FileList}
+ | {ok, FileBinList}
+ | {error, Reason :: term()}
+ | {error, {Name :: file:name(), Reason :: term()}},
+ FileList :: [file:name()],
+ FileBinList :: [{file:name(),binary()}]).
+
extract(F) -> unzip(F).
+
+-spec(extract(Archive, Options) -> RetValue when
+ Archive :: file:name() | binary(),
+ Options :: [Option],
+ Option :: {file_list, FileList}
+ | keep_old_files | verbose | memory |
+ {file_filter, FileFilter} | {cwd, CWD},
+ FileList :: [file:name()],
+ FileBinList :: [{file:name(),binary()}],
+ FileFilter :: fun((ZipFile) -> boolean()),
+ CWD :: string(),
+ ZipFile :: zip_file(),
+ RetValue :: {ok, FileList}
+ | {ok, FileBinList}
+ | {error, Reason :: term()}
+ | {error, {Name :: file:name(), Reason :: term()}}).
+
extract(F, O) -> unzip(F, O).
@@ -990,21 +1142,52 @@ server_loop(OpenZip) ->
{error, bad_msg}
end.
+-spec(zip_open(Archive) -> {ok, ZipHandle} | {error, Reason} when
+ Archive :: file:name() | binary(),
+ ZipHandle :: pid(),
+ Reason :: term()).
+
zip_open(Archive) -> zip_open(Archive, []).
+-spec(zip_open(Archive, Options) -> {ok, ZipHandle} | {error, Reason} when
+ Archive :: file:name() | binary(),
+ ZipHandle :: pid(),
+ Options :: [Option],
+ Option :: cooked | memory | {cwd, CWD :: string()},
+ Reason :: term()).
+
zip_open(Archive, Options) ->
Pid = spawn(fun() -> server_loop(not_open) end),
request(self(), Pid, {open, Archive, Options}).
+-spec(zip_get(ZipHandle) -> {ok, [Result]} | {error, Reason} when
+ ZipHandle :: pid(),
+ Result :: file:name() | {file:name(), binary()},
+ Reason :: term()).
+
zip_get(Pid) when is_pid(Pid) ->
request(self(), Pid, get).
+-spec(zip_close(ZipHandle) -> ok | {error, einval} when
+ ZipHandle :: pid()).
+
zip_close(Pid) when is_pid(Pid) ->
request(self(), Pid, close).
+-spec(zip_get(FileName, ZipHandle) -> {ok, [Result]} | {error, Reason} when
+ FileName :: file:name(),
+ ZipHandle :: pid(),
+ Result :: file:name() | {file:name(), binary()},
+ Reason :: term()).
+
zip_get(FileName, Pid) when is_pid(Pid) ->
request(self(), Pid, {get, FileName}).
+-spec(zip_list_dir(ZipHandle) -> Result | {error, Reason} when
+ Result :: [zip_comment() | zip_file()],
+ ZipHandle :: pid(),
+ Reason :: term()).
+
zip_list_dir(Pid) when is_pid(Pid) ->
request(self(), Pid, list_dir).
diff --git a/lib/stdlib/test/dets_SUITE.erl b/lib/stdlib/test/dets_SUITE.erl
index 9fcc9e6aaf..698070368f 100644
--- a/lib/stdlib/test/dets_SUITE.erl
+++ b/lib/stdlib/test/dets_SUITE.erl
@@ -53,7 +53,7 @@
simultaneous_open/1, insert_new/1, repair_continuation/1,
otp_5487/1, otp_6206/1, otp_6359/1, otp_4738/1, otp_7146/1,
otp_8070/1, otp_8856/1, otp_8898/1, otp_8899/1, otp_8903/1,
- otp_8923/1]).
+ otp_8923/1, otp_9282/1]).
-export([dets_dirty_loop/0]).
@@ -112,7 +112,7 @@ all() ->
many_clients, otp_4906, otp_5402, simultaneous_open,
insert_new, repair_continuation, otp_5487, otp_6206,
otp_6359, otp_4738, otp_7146, otp_8070, otp_8856, otp_8898,
- otp_8899, otp_8903, otp_8923]
+ otp_8899, otp_8903, otp_8923, otp_9282]
end.
groups() ->
@@ -3857,6 +3857,28 @@ otp_8923(Config) when is_list(Config) ->
file:delete(File),
ok.
+otp_9282(doc) ->
+ ["OTP-9282. The name of a table can be an arbitrary term"];
+otp_9282(suite) ->
+ [];
+otp_9282(Config) when is_list(Config) ->
+ some_calls(make_ref(), Config),
+ some_calls({a,typical,name}, Config),
+ some_calls(fun() -> a_funny_name end, Config),
+ ok.
+
+some_calls(Tab, Config) ->
+ File = filename(ref, Config),
+ ?line {ok,T} = dets:open_file(Tab, [{file,File}]),
+ ?line T = Tab,
+ ?line false = dets:info(T, safe_fixed),
+ ?line File = dets:info(T, filename),
+ ?line ok = dets:insert(Tab, [{3,0}]),
+ ?line [{3,0}] = dets:lookup(Tab, 3),
+ ?line [{3,0}] = dets:traverse(Tab, fun(X) -> {continue, X} end),
+ ?line ok = dets:close(T),
+ file:delete(File).
+
%%
%% Parts common to several test cases
%%
diff --git a/lib/stdlib/test/erl_eval_SUITE.erl b/lib/stdlib/test/erl_eval_SUITE.erl
index 4b59cee99e..0bcf3c5b71 100644
--- a/lib/stdlib/test/erl_eval_SUITE.erl
+++ b/lib/stdlib/test/erl_eval_SUITE.erl
@@ -1199,7 +1199,7 @@ local_func(F, As0, Bs0) when is_atom(F) ->
lfh_value_extra() ->
%% Not documented.
- {value, fun(F, As) -> local_func_value(F, As) end, []}.
+ {value, fun(F, As, a1, a2) -> local_func_value(F, As) end, [a1, a2]}.
lfh_value() ->
{value, fun(F, As) -> local_func_value(F, As) end}.
diff --git a/lib/stdlib/test/erl_pp_SUITE.erl b/lib/stdlib/test/erl_pp_SUITE.erl
index bc811355ab..280c95b1aa 100644
--- a/lib/stdlib/test/erl_pp_SUITE.erl
+++ b/lib/stdlib/test/erl_pp_SUITE.erl
@@ -1161,7 +1161,7 @@ parse_forms2(String, Cont0, Line, Forms) ->
{done, {ok, Tokens, EndLine}, Chars} ->
{ok, Form} = erl_parse:parse_form(Tokens),
parse_forms2(Chars, [], EndLine, [Form | Forms]);
- {more, Cont} when element(3, Cont) =:= [] ->
+ {more, Cont} when element(4, Cont) =:= [] ->
%% extra spaces after forms...
parse_forms2([], Cont, Line, Forms);
{more, Cont} ->
diff --git a/lib/stdlib/test/sofs_SUITE.erl b/lib/stdlib/test/sofs_SUITE.erl
index 01de1f0600..d6f88a655e 100644
--- a/lib/stdlib/test/sofs_SUITE.erl
+++ b/lib/stdlib/test/sofs_SUITE.erl
@@ -1602,19 +1602,15 @@ relative_product_2(Conf) when is_list(Conf) ->
from_term([{{a},b}])}, ER)),
?line {'EXIT', {badarg, _}} = (catch relative_product({}, ER)),
- ?line eval(relative_product({relation([{a,b}])},
- from_term([],[{{atom},atom}])),
- ER),
- ?line eval(relative_product({relation([{a,b}]),relation([{a,1}])},
- from_term([{{b,1},{tjo,hej,sa}}])),
- from_term([{a,{tjo,hej,sa}}])),
- ?line eval(relative_product({relation([{a,b}]), ER},
- from_term([{{a,b},b}])),
- ER),
- ?line eval(relative_product({relation([{a,b},{c,a}]),
- relation([{a,1},{a,2}])},
- from_term([{{b,1},b1},{{b,2},b2}])),
- relation([{a,b1},{a,b2}])),
+ ?line relprod2({relation([{a,b}])}, from_term([],[{{atom},atom}]), ER),
+ ?line relprod2({relation([{a,b}]),relation([{a,1}])},
+ from_term([{{b,1},{tjo,hej,sa}}]),
+ from_term([{a,{tjo,hej,sa}}])),
+ ?line relprod2({relation([{a,b}]), ER}, from_term([{{a,b},b}]), ER),
+ ?line relprod2({relation([{a,b},{c,a}]),
+ relation([{a,1},{a,2}])},
+ from_term([{{b,1},b1},{{b,2},b2}]),
+ relation([{a,b1},{a,b2}])),
?line eval(relative_product({relation([{a,b}]), ER}),
from_term([],[{atom,{atom,atom}}])),
?line eval(relative_product({from_term([{{a,[a,b]},[a]}]),
@@ -1622,6 +1618,11 @@ relative_product_2(Conf) when is_list(Conf) ->
from_term([{{a,[a,b]},{[a],[[a,b]]}}])),
ok.
+relprod2(A1T, A2, R) ->
+ %% A tuple as first argument is the old interface:
+ eval(relative_product(A1T, A2), R),
+ eval(relative_product(tuple_to_list(A1T), A2), R).
+
product_1(suite) -> [];
product_1(doc) -> [""];
product_1(Conf) when is_list(Conf) ->
diff --git a/lib/test_server/doc/src/notes.xml b/lib/test_server/doc/src/notes.xml
index 9c62b0fcf6..3a10bb209d 100644
--- a/lib/test_server/doc/src/notes.xml
+++ b/lib/test_server/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/test_server/src/configure.in b/lib/test_server/src/configure.in
index 2bbbc18966..ff4ba1dfaf 100644
--- a/lib/test_server/src/configure.in
+++ b/lib/test_server/src/configure.in
@@ -136,7 +136,7 @@ case $system in
fi
SHLIB_EXTRACT_ALL=""
;;
- NetBSD-*|FreeBSD-*|OpenBSD-*)
+ NetBSD-*|FreeBSD-*|OpenBSD-*|DragonFly*)
# Not available on all versions: check for include file.
AC_CHECK_HEADER(dlfcn.h, [
SHLIB_CFLAGS="-fpic"
diff --git a/lib/test_server/src/ts_run.erl b/lib/test_server/src/ts_run.erl
index d145290820..885a3c9b96 100644
--- a/lib/test_server/src/ts_run.erl
+++ b/lib/test_server/src/ts_run.erl
@@ -365,6 +365,14 @@ make_common_test_args(Args0, Options, _Vars) ->
[{logdir,"../test_server"}]
end,
+ TimeTrap = case test_server:timetrap_scale_factor() of
+ 1 ->
+ [];
+ Scale ->
+ [{multiply_timetraps, Scale},
+ {scale_timetraps, true}]
+ end,
+
ConfigPath = case {os:getenv("TEST_CONFIG_PATH"),
lists:keysearch(config, 1, Options)} of
{false,{value, {config, Path}}} ->
@@ -377,7 +385,7 @@ make_common_test_args(Args0, Options, _Vars) ->
ConfigFiles = [{config,[filename:join(ConfigPath,File)
|| File <- get_config_files()]}],
io_lib:format("~100000p",[Args0++Trace++Cover++Logdir++
- ConfigFiles++Options]).
+ ConfigFiles++Options++TimeTrap]).
to_list(X) when is_atom(X) ->
atom_to_list(X);
diff --git a/lib/tools/doc/src/notes.xml b/lib/tools/doc/src/notes.xml
index 118800e44a..93bb6b71c9 100644
--- a/lib/tools/doc/src/notes.xml
+++ b/lib/tools/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/tools/src/cover.erl b/lib/tools/src/cover.erl
index 73a736f0e8..905ad895c9 100644
--- a/lib/tools/src/cover.erl
+++ b/lib/tools/src/cover.erl
@@ -662,6 +662,7 @@ main_process_loop(State) ->
Imported = do_import_to_table(Fd,File,
State#main_state.imported),
reply(From, ok),
+ file:close(Fd),
main_process_loop(State#main_state{imported=Imported});
{error,Reason} ->
reply(From, {error, {cant_open_file,File,Reason}}),
diff --git a/lib/tools/test/cover_SUITE.erl b/lib/tools/test/cover_SUITE.erl
index b5c8e8a1b7..fe7f92de78 100644
--- a/lib/tools/test/cover_SUITE.erl
+++ b/lib/tools/test/cover_SUITE.erl
@@ -395,6 +395,7 @@ export_import(suite) -> [];
export_import(Config) when is_list(Config) ->
?line DataDir = ?config(data_dir, Config),
?line ok = file:set_cwd(DataDir),
+ ?line PortCount = length(erlang:ports()),
%% Export one module
?line {ok,f} = cover:compile(f),
@@ -484,6 +485,9 @@ export_import(Config) when is_list(Config) ->
?line ?t:capture_stop(),
?line check_f_calls(1,0),
+ %% Check no raw files are left open
+ ?line PortCount = length(erlang:ports()),
+
%% Cleanup
?line ok = cover:stop(),
?line Files = lsfiles(),
diff --git a/lib/wx/doc/src/notes.xml b/lib/wx/doc/src/notes.xml
index 3d27cf671b..4282e19769 100644
--- a/lib/wx/doc/src/notes.xml
+++ b/lib/wx/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2009</year><year>2010</year>
+ <year>2009</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/xmerl/doc/src/notes.xml b/lib/xmerl/doc/src/notes.xml
index 8542435456..654bbbc05d 100644
--- a/lib/xmerl/doc/src/notes.xml
+++ b/lib/xmerl/doc/src/notes.xml
@@ -4,7 +4,7 @@
<chapter>
<header>
<copyright>
- <year>2004</year><year>2010</year>
+ <year>2004</year><year>2011</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/xmerl/src/xmerl_sax_parser.erl b/lib/xmerl/src/xmerl_sax_parser.erl
index c1acf51b8a..571feabee0 100644
--- a/lib/xmerl/src/xmerl_sax_parser.erl
+++ b/lib/xmerl/src/xmerl_sax_parser.erl
@@ -263,11 +263,11 @@ detect_charset_1(<<16#3C, 16#3F, 16#78, 16#6D, 16#6C, Xml2/binary>> = Xml, State
{Xml, State#xmerl_sax_parser_state{encoding=Enc}}
end;
_ ->
- {Xml, State#xmerl_sax_parser_state{encoding=utf8}}
+ {Xml, State}
end
end;
detect_charset_1(Xml, State) ->
- {Xml, State#xmerl_sax_parser_state{encoding=utf8}}.
+ {Xml, State}.
%%----------------------------------------------------------------------
%% Function: convert_encoding(Enc)
diff --git a/lib/xmerl/vsn.mk b/lib/xmerl/vsn.mk
index 280ff10efa..965a0ae7b4 100644
--- a/lib/xmerl/vsn.mk
+++ b/lib/xmerl/vsn.mk
@@ -1 +1 @@
-XMERL_VSN = 1.2.8
+XMERL_VSN = 1.2.9
diff --git a/make/otp.mk.in b/make/otp.mk.in
index bf287be416..a4e9dad46f 100644
--- a/make/otp.mk.in
+++ b/make/otp.mk.in
@@ -4,7 +4,7 @@
#
# %CopyrightBegin%
#
-# Copyright Ericsson AB 1997-2010. All Rights Reserved.
+# 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
@@ -240,9 +240,10 @@ FOP = @FOP@
DOCGEN=$(ERL_TOP)/lib/erl_docgen
SPECS_ESRC = ../../src
+SPECS_EXTRACTOR=$(DOCGEN)/priv/bin/specs_gen.escript
# Extract specifications and types from Erlang source files (-spec, -type)
$(SPECDIR)/specs_%.xml: $(SPECS_ESRC)/%.erl
- escript $(DOCGEN)/priv/bin/specs_gen.escript $(SPECS_FLAGS) -o$(dir $@) $<
+ escript $(SPECS_EXTRACTOR) $(SPECS_FLAGS) -o$(dir $@) $<
$(MAN1DIR)/%.1: %.xml
diff --git a/otp_build b/otp_build
index 1172592415..aebb91372c 100755
--- a/otp_build
+++ b/otp_build
@@ -186,15 +186,16 @@ set_config_flags ()
if target_contains free_source; then
CONFIG_FLAGS="$CONFIG_FLAGS --host=$TARGET"
fi
+ # Link SSL static for all binary distributions if not overridden
+ # Even for win32 starting with R14B03
+ XX=`echo $* | grep -v dynamic-ssl-lib`
+ if [ "$*" = "$XX" ]; then
+ CONFIG_FLAGS="--disable-dynamic-ssl-lib $CONFIG_FLAGS"
+ fi
if target_contains win32; then
- CONFIG_FLAGS="--build=$BUILDSYS build_alias=win32 --host=win32 --target=win32 $CONFIG_FLAGS"
- else
- # Link SSL static for all binary distributions if not overridden
- XX=`echo $* | grep -v dynamic-ssl-lib`
- if [ "$*" = "$XX" ]; then
- CONFIG_FLAGS="--disable-dynamic-ssl-lib $CONFIG_FLAGS"
- fi
+ CONFIG_FLAGS="--build=$BUILDSYS build_alias=win32 --host=win32 --target=win32 $CONFIG_FLAGS"
fi
+
if [ "x$OVERRIDE_CONFIG_CACHE" = "x" ]; then
CONFIG_FLAGS="$CONFIG_FLAGS --cache-file=/dev/null"
else