aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/asn1/src/asn1ct.erl1
-rw-r--r--lib/compiler/src/beam_type.erl2
-rw-r--r--lib/compiler/src/sys_core_fold.erl27
-rw-r--r--lib/compiler/src/v3_core.erl26
-rw-r--r--lib/compiler/test/float_SUITE.erl12
-rw-r--r--lib/compiler/test/inline_SUITE_data/decode1.erl48
-rw-r--r--lib/compiler/test/match_SUITE.erl26
-rw-r--r--lib/compiler/test/num_bif_SUITE.erl14
-rw-r--r--lib/compiler/test/record_SUITE.erl39
-rw-r--r--lib/compiler/test/warnings_SUITE.erl17
-rw-r--r--lib/crypto/c_src/Makefile.in20
-rw-r--r--lib/crypto/c_src/crypto.c1531
-rw-r--r--lib/crypto/c_src/crypto_drv.c1817
-rw-r--r--lib/crypto/priv/Makefile28
-rw-r--r--lib/crypto/src/Makefile12
-rw-r--r--lib/crypto/src/crypto.erl497
-rw-r--r--lib/crypto/src/crypto_server.erl88
-rw-r--r--lib/crypto/test/blowfish_SUITE.erl15
-rw-r--r--lib/crypto/test/crypto_SUITE.erl12
-rw-r--r--lib/crypto/vsn.mk2
-rw-r--r--lib/erl_interface/test/ei_tmo_SUITE_data/ei_tmo_test.c12
-rw-r--r--lib/hipe/cerl/erl_bif_types.erl18
-rw-r--r--lib/inets/doc/src/notes.xml52
-rw-r--r--lib/inets/src/http_client/httpc.erl8
-rw-r--r--lib/inets/src/http_client/httpc_handler.erl10
-rw-r--r--lib/inets/src/http_client/httpc_manager.erl18
-rw-r--r--lib/inets/src/inets_app/inets.appup.src22
-rw-r--r--lib/inets/vsn.mk8
-rw-r--r--lib/kernel/src/application_controller.erl191
-rw-r--r--lib/kernel/src/application_starter.erl22
-rw-r--r--lib/kernel/src/auth.erl20
-rw-r--r--lib/kernel/src/code.erl6
-rw-r--r--lib/kernel/src/code_server.erl147
-rw-r--r--lib/kernel/src/erl_boot_server.erl18
-rw-r--r--lib/kernel/src/erl_epmd.erl4
-rw-r--r--lib/kernel/src/error_handler.erl18
-rw-r--r--lib/kernel/src/file_io_server.erl45
-rw-r--r--lib/kernel/src/heart.erl19
-rw-r--r--lib/kernel/src/inet_db.erl50
-rw-r--r--lib/kernel/src/inet_gethost_native.erl15
-rw-r--r--lib/kernel/src/kernel_config.erl4
-rw-r--r--lib/kernel/src/rpc.erl25
-rw-r--r--lib/kernel/src/standard_error.erl24
-rw-r--r--lib/kernel/src/user.erl21
-rw-r--r--lib/kernel/test/code_SUITE.erl40
-rw-r--r--lib/kernel/test/file_SUITE.erl5
-rw-r--r--lib/kernel/test/inet_sockopt_SUITE_data/sockopt_helper.c2
-rw-r--r--lib/kernel/test/prim_file_SUITE.erl15
-rw-r--r--lib/megaco/doc/src/megaco_user.xml3
-rw-r--r--lib/megaco/doc/src/notes.xml53
-rw-r--r--lib/megaco/src/app/megaco.appup.src13
-rw-r--r--lib/megaco/src/engine/megaco_config.erl401
-rw-r--r--lib/megaco/test/megaco_config_test.erl362
-rw-r--r--lib/megaco/vsn.mk6
-rw-r--r--lib/public_key/src/public_key.appup.src26
-rw-r--r--lib/reltool/bin/reltool.escript249
-rw-r--r--lib/reltool/doc/src/reltool.xml185
-rw-r--r--lib/reltool/doc/src/reltool_examples.xml4
-rw-r--r--lib/reltool/src/Makefile42
-rw-r--r--lib/reltool/src/files.mk32
-rw-r--r--lib/reltool/src/reltool.app.src45
-rw-r--r--lib/reltool/src/reltool.appup.src22
-rw-r--r--lib/reltool/src/reltool.erl97
-rw-r--r--lib/reltool/src/reltool.hrl142
-rw-r--r--lib/reltool/src/reltool_mod_win.erl4
-rw-r--r--lib/reltool/src/reltool_server.erl561
-rw-r--r--lib/reltool/src/reltool_sys_win.erl2
-rw-r--r--lib/reltool/src/reltool_target.erl493
-rw-r--r--lib/reltool/src/reltool_utils.erl82
-rw-r--r--lib/reltool/test/Makefile11
-rw-r--r--lib/reltool/test/reltool_app_SUITE.erl291
-rw-r--r--lib/reltool/test/reltool_server_SUITE.erl38
-rw-r--r--lib/reltool/test/reltool_test_lib.erl14
-rw-r--r--lib/reltool/test/reltool_test_lib.hrl11
-rwxr-xr-xlib/reltool/test/rtt12
-rw-r--r--lib/sasl/doc/src/notes.xml27
-rw-r--r--lib/sasl/src/release_handler_1.erl18
-rw-r--r--lib/sasl/vsn.mk2
-rw-r--r--lib/snmp/doc/src/notes.xml62
-rw-r--r--lib/snmp/doc/src/snmpc.xml152
-rw-r--r--lib/snmp/src/agent/snmpa_usm.erl8
-rw-r--r--lib/snmp/src/app/snmp.appup.src38
-rw-r--r--lib/snmp/src/compile/snmpc.erl187
-rw-r--r--lib/snmp/src/compile/snmpc_lib.erl13
-rw-r--r--lib/snmp/src/misc/snmp_pdus.erl51
-rw-r--r--lib/snmp/src/misc/snmp_usm.erl10
-rw-r--r--lib/snmp/test/modules.mk14
-rw-r--r--lib/snmp/test/snmp_compiler_test.erl70
-rw-r--r--lib/snmp/test/snmp_manager_config_test.erl90
-rw-r--r--lib/snmp/test/snmp_pdus_test.erl64
-rw-r--r--lib/snmp/test/snmp_test_data/OLD-SNMPEA-MIB.mib18
-rw-r--r--lib/snmp/test/snmp_test_data/OTP8574-MIB.mib77
-rw-r--r--lib/snmp/test/snmp_test_data/OTP8595-MIB.mib45
-rw-r--r--lib/snmp/test/snmp_test_mgr_misc.erl14
-rw-r--r--lib/snmp/vsn.mk6
-rw-r--r--lib/ssh/Makefile10
-rw-r--r--lib/ssh/doc/src/book.xml6
-rw-r--r--lib/ssh/doc/src/notes.xml11
-rw-r--r--lib/ssh/doc/src/ref_man.xml6
-rw-r--r--lib/ssh/doc/src/ssh_sftp.xml6
-rw-r--r--lib/ssh/doc/src/ssh_sftpd.xml6
-rw-r--r--lib/ssh/examples/Makefile10
-rw-r--r--lib/ssh/examples/ssh_sample_cli.erl66
-rw-r--r--lib/ssh/src/Makefile13
-rw-r--r--lib/ssh/src/ssh.app.src3
-rw-r--r--lib/ssh/src/ssh.appup.src28
-rw-r--r--lib/ssh/src/ssh.hrl10
-rw-r--r--lib/ssh/src/ssh_acceptor.erl10
-rw-r--r--lib/ssh/src/ssh_acceptor_sup.erl10
-rw-r--r--lib/ssh/src/ssh_app.erl10
-rw-r--r--lib/ssh/src/ssh_auth.erl10
-rw-r--r--lib/ssh/src/ssh_auth.hrl10
-rwxr-xr-xlib/ssh/src/ssh_bits.erl10
-rw-r--r--lib/ssh/src/ssh_channel.erl10
-rw-r--r--lib/ssh/src/ssh_channel_sup.erl10
-rwxr-xr-xlib/ssh/src/ssh_cm.erl237
-rwxr-xr-xlib/ssh/src/ssh_connect.hrl10
-rw-r--r--lib/ssh/src/ssh_connection_controler.erl10
-rwxr-xr-xlib/ssh/src/ssh_dsa.erl10
-rwxr-xr-xlib/ssh/src/ssh_file.erl10
-rwxr-xr-xlib/ssh/src/ssh_io.erl10
-rwxr-xr-xlib/ssh/src/ssh_math.erl10
-rw-r--r--lib/ssh/src/ssh_no_io.erl10
-rwxr-xr-xlib/ssh/src/ssh_rsa.erl10
-rwxr-xr-xlib/ssh/src/ssh_sftp.erl48
-rw-r--r--lib/ssh/src/ssh_sftpd.erl10
-rw-r--r--lib/ssh/src/ssh_sftpd_file.erl10
-rw-r--r--lib/ssh/src/ssh_sftpd_file_api.erl10
-rw-r--r--lib/ssh/src/ssh_shell.erl10
-rw-r--r--lib/ssh/src/ssh_ssh.erl65
-rw-r--r--lib/ssh/src/ssh_sshd.erl48
-rw-r--r--lib/ssh/src/ssh_subsystem_sup.erl10
-rw-r--r--lib/ssh/src/ssh_sup.erl10
-rw-r--r--lib/ssh/src/ssh_system_sup.erl10
-rw-r--r--lib/ssh/src/ssh_transport.erl10
-rw-r--r--lib/ssh/src/ssh_transport.hrl10
-rwxr-xr-xlib/ssh/src/ssh_userauth.hrl10
-rw-r--r--lib/ssh/src/ssh_userreg.erl10
-rw-r--r--lib/ssh/src/ssh_xfer.erl10
-rwxr-xr-xlib/ssh/src/ssh_xfer.hrl10
-rw-r--r--lib/ssh/src/sshc_sup.erl10
-rw-r--r--lib/ssh/src/sshd_sup.erl10
-rw-r--r--lib/ssh/vsn.mk5
-rw-r--r--lib/ssl/doc/src/new_ssl.xml4
-rw-r--r--lib/ssl/src/ssl.appup.src6
-rw-r--r--lib/ssl/src/ssl.erl83
-rw-r--r--lib/ssl/src/ssl_alert.erl60
-rw-r--r--lib/ssl/src/ssl_cipher.hrl15
-rw-r--r--lib/ssl/src/ssl_connection.erl996
-rw-r--r--lib/ssl/src/ssl_handshake.erl299
-rw-r--r--lib/ssl/src/ssl_handshake.hrl15
-rw-r--r--lib/ssl/src/ssl_internal.hrl1
-rw-r--r--lib/ssl/src/ssl_record.erl105
-rw-r--r--lib/ssl/src/ssl_record.hrl6
-rw-r--r--lib/ssl/test/ssl.cover14
-rw-r--r--lib/ssl/test/ssl_basic_SUITE.erl137
-rw-r--r--lib/ssl/test/ssl_packet_SUITE.erl587
-rw-r--r--lib/ssl/test/ssl_test_lib.erl35
-rw-r--r--lib/ssl/test/ssl_to_openssl_SUITE.erl58
-rw-r--r--lib/ssl/vsn.mk20
-rw-r--r--lib/stdlib/doc/src/erl_scan.xml19
-rw-r--r--lib/stdlib/src/erl_parse.yrl105
-rw-r--r--lib/stdlib/src/erl_scan.erl87
-rw-r--r--lib/stdlib/src/ets.erl2
-rw-r--r--lib/stdlib/src/lists.erl21
-rw-r--r--lib/stdlib/src/otp_internal.erl136
-rw-r--r--lib/stdlib/test/erl_pp_SUITE.erl130
-rw-r--r--lib/stdlib/test/erl_scan_SUITE.erl210
-rw-r--r--lib/stdlib/test/re_SUITE.erl18
-rw-r--r--lib/syntax_tools/src/erl_comment_scan.erl4
-rw-r--r--lib/syntax_tools/src/erl_prettypr.erl6
-rw-r--r--lib/syntax_tools/src/igor.erl22
-rw-r--r--lib/test_server/doc/src/test_server_ctrl.xml3
-rw-r--r--lib/test_server/doc/src/ts.xml4
-rw-r--r--lib/test_server/src/test_server.erl12
-rw-r--r--lib/test_server/src/test_server_internal.hrl12
-rw-r--r--lib/test_server/src/ts.erl12
-rw-r--r--lib/test_server/src/ts_erl_config.erl13
-rw-r--r--lib/test_server/src/ts_run.erl80
-rw-r--r--lib/tools/emacs/erlang-eunit.el13
180 files changed, 7758 insertions, 5720 deletions
diff --git a/lib/asn1/src/asn1ct.erl b/lib/asn1/src/asn1ct.erl
index 1859428c49..ae681a4a78 100644
--- a/lib/asn1/src/asn1ct.erl
+++ b/lib/asn1/src/asn1ct.erl
@@ -1215,7 +1215,6 @@ compile(File, _OutFile, Options) ->
%% io:format("~p~n~s~n",[_Reason,"error"]),
error;
ok ->
- io:format("ok~n"),
ok;
ParseRes when is_tuple(ParseRes) ->
io:format("~p~n",[ParseRes]),
diff --git a/lib/compiler/src/beam_type.erl b/lib/compiler/src/beam_type.erl
index 66c8816409..3729ccb0da 100644
--- a/lib/compiler/src/beam_type.erl
+++ b/lib/compiler/src/beam_type.erl
@@ -183,7 +183,7 @@ simplify_float_1([], Ts, Rs, Acc0) ->
{Is,Ts}.
opt_fmoves([{set,[{x,_}=R],[{fr,_}]=Src,fmove}=I1,
- {set,[{y,_}]=Dst,[{x,_}=R],move}=I2|Is], Acc) ->
+ {set,[_]=Dst,[{x,_}=R],move}=I2|Is], Acc) ->
case beam_utils:is_killed_block(R, Is) of
false -> opt_fmoves(Is, [I2,I1|Acc]);
true -> opt_fmoves(Is, [{set,Dst,Src,fmove}|Acc])
diff --git a/lib/compiler/src/sys_core_fold.erl b/lib/compiler/src/sys_core_fold.erl
index 068478496b..6202f07479 100644
--- a/lib/compiler/src/sys_core_fold.erl
+++ b/lib/compiler/src/sys_core_fold.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1999-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 1999-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 : Constant folding optimisation for Core
@@ -602,15 +602,23 @@ count_bits_1(Int, Bits) -> count_bits_1(Int bsr 64, Bits+64).
%% a rewritten expression consisting of a sequence of
%% the arguments only is returned.
-useless_call(effect, #c_call{module=#c_literal{val=Mod},
+useless_call(effect, #c_call{anno=Anno,
+ module=#c_literal{val=Mod},
name=#c_literal{val=Name},
args=Args}=Call) ->
A = length(Args),
case erl_bifs:is_safe(Mod, Name, A) of
false ->
case erl_bifs:is_pure(Mod, Name, A) of
- true -> add_warning(Call, result_ignored);
- false -> ok
+ true ->
+ case member(result_not_wanted, Anno) of
+ false ->
+ add_warning(Call, result_ignored);
+ true ->
+ ok
+ end;
+ false ->
+ ok
end,
no;
true ->
@@ -2806,7 +2814,8 @@ format_error({no_effect,{erlang,F,A}}) ->
end,
flatten(io_lib:format(Fmt, Args));
format_error(result_ignored) ->
- "the result of the expression is ignored";
+ "the result of the expression is ignored "
+ "(suppress the warning by assigning the expression to the _ variable)";
format_error(useless_building) ->
"a term is constructed, but never used";
format_error(bin_opt_alias) ->
diff --git a/lib/compiler/src/v3_core.erl b/lib/compiler/src/v3_core.erl
index 4ac2196d79..b2f0ac75c7 100644
--- a/lib/compiler/src/v3_core.erl
+++ b/lib/compiler/src/v3_core.erl
@@ -128,6 +128,7 @@
-record(core, {vcount=0 :: non_neg_integer(), %Variable counter
fcount=0 :: non_neg_integer(), %Function counter
in_guard=false :: boolean(), %In guard or not.
+ wanted=true :: boolean(), %Result wanted or not.
opts :: [compile:option()], %Options.
es=[] :: [error()], %Errors.
ws=[] :: [warning()], %Warnings.
@@ -580,10 +581,14 @@ expr({'fun',L,{function,F,A},{_,_,_}=Id}, St) ->
{#c_var{anno=Lanno++[{id,Id}],name={F,A}},[],St};
expr({'fun',L,{clauses,Cs},Id}, St) ->
fun_tq(Id, Cs, L, St);
-expr({call,L,{remote,_,M,F},As0}, St0) ->
+expr({call,L,{remote,_,M,F},As0}, #core{wanted=Wanted}=St0) ->
{[M1,F1|As1],Aps,St1} = safe_list([M,F|As0], St0),
Lanno = lineno_anno(L, St1),
- {#icall{anno=#a{anno=Lanno},module=M1,name=F1,args=As1},Aps,St1};
+ Anno = case Wanted of
+ false -> [result_not_wanted|Lanno];
+ true -> Lanno
+ end,
+ {#icall{anno=#a{anno=Anno},module=M1,name=F1,args=As1},Aps,St1};
expr({call,Lc,{atom,Lf,F},As0}, St0) ->
{As1,Aps,St1} = safe_list(As0, St0),
Op = #c_var{anno=lineno_anno(Lf, St1),name={F,length(As1)}},
@@ -596,23 +601,28 @@ expr({call,L,FunExp,As0}, St0) ->
expr({match,L,P0,E0}, St0) ->
%% First fold matches together to create aliases.
{P1,E1} = fold_match(E0, P0),
- {E2,Eps,St1} = novars(E1, St0),
+ St1 = case P1 of
+ {var,_,'_'} -> St0#core{wanted=false};
+ _ -> St0
+ end,
+ {E2,Eps,St2} = novars(E1, St1),
+ St3 = St2#core{wanted=St0#core.wanted},
P2 = try
- pattern(P1, St1)
+ pattern(P1, St3)
catch
throw:Thrown ->
Thrown
end,
- {Fpat,St2} = new_var(St1),
+ {Fpat,St4} = new_var(St3),
Fc = fail_clause([Fpat], c_tuple([#c_literal{val=badmatch},Fpat])),
- Lanno = lineno_anno(L, St2),
+ Lanno = lineno_anno(L, St4),
case P2 of
nomatch ->
- St = add_warning(L, nomatch, St2),
+ St = add_warning(L, nomatch, St4),
{#icase{anno=#a{anno=Lanno},
args=[E2],clauses=[],fc=Fc},Eps,St};
Other when not is_atom(Other) ->
- {#imatch{anno=#a{anno=Lanno},pat=P2,arg=E2,fc=Fc},Eps,St2}
+ {#imatch{anno=#a{anno=Lanno},pat=P2,arg=E2,fc=Fc},Eps,St4}
end;
expr({op,_,'++',{lc,Llc,E,Qs},More}, St0) ->
%% Optimise '++' here because of the list comprehension algorithm.
diff --git a/lib/compiler/test/float_SUITE.erl b/lib/compiler/test/float_SUITE.erl
index 3d2dbf47e9..07779ddd5a 100644
--- a/lib/compiler/test/float_SUITE.erl
+++ b/lib/compiler/test/float_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2002-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2002-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(float_SUITE).
@@ -41,7 +41,7 @@ float_sub(A)->
float_mul(0, _, _)->
ok;
float_mul(Iter, A, B) when is_float(A), is_float(B) ->
- A*B,
+ _ = A*B,
float_mul(Iter-1, A, B).
%% Thanks to Mikael Pettersson and Tobias Lindahl (HiPE).
diff --git a/lib/compiler/test/inline_SUITE_data/decode1.erl b/lib/compiler/test/inline_SUITE_data/decode1.erl
index d51bedcb2e..9b4fc071a3 100644
--- a/lib/compiler/test/inline_SUITE_data/decode1.erl
+++ b/lib/compiler/test/inline_SUITE_data/decode1.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2006-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
%----------------------------------------------------------------------
@@ -37,25 +37,25 @@
FrameList = [89,128,0,8,132,0,26,133,133,0,38,148,94,
128,0,2,129,128,92,128,0,2,0,0,112,128,0,
10,194,69,0,0,0,0,0,18,52,95],
- Frame = concat_binary([list_to_binary([89]),list_to_binary([128]),
- list_to_binary([0]),list_to_binary([8]),
- list_to_binary([132]),list_to_binary([0]),
- list_to_binary([26]),list_to_binary([133]),
- list_to_binary([133]),list_to_binary([0]),
- list_to_binary([38]),list_to_binary([148]),
- list_to_binary([94]),list_to_binary([128]),
- list_to_binary([0]),list_to_binary([2]),
- list_to_binary([129]),list_to_binary([128]),
- list_to_binary([92]),list_to_binary([128]),
- list_to_binary([0]),list_to_binary([2]),
- list_to_binary([0]),list_to_binary([0]),
- list_to_binary([112]),list_to_binary([128]),
- list_to_binary([0]),list_to_binary([10]),
- list_to_binary([194]),list_to_binary([69]),
- list_to_binary([0]),list_to_binary([0]),
- list_to_binary([0]),list_to_binary([0]),
- list_to_binary([0]),list_to_binary([18]),
- list_to_binary([52]),list_to_binary([95])]),
+ Frame = list_to_binary([list_to_binary([89]),list_to_binary([128]),
+ list_to_binary([0]),list_to_binary([8]),
+ list_to_binary([132]),list_to_binary([0]),
+ list_to_binary([26]),list_to_binary([133]),
+ list_to_binary([133]),list_to_binary([0]),
+ list_to_binary([38]),list_to_binary([148]),
+ list_to_binary([94]),list_to_binary([128]),
+ list_to_binary([0]),list_to_binary([2]),
+ list_to_binary([129]),list_to_binary([128]),
+ list_to_binary([92]),list_to_binary([128]),
+ list_to_binary([0]),list_to_binary([2]),
+ list_to_binary([0]),list_to_binary([0]),
+ list_to_binary([112]),list_to_binary([128]),
+ list_to_binary([0]),list_to_binary([10]),
+ list_to_binary([194]),list_to_binary([69]),
+ list_to_binary([0]),list_to_binary([0]),
+ list_to_binary([0]),list_to_binary([0]),
+ list_to_binary([0]),list_to_binary([18]),
+ list_to_binary([52]),list_to_binary([95])]),
R = loop(2,0,Frame),
{R,R =:= {0,[{ie,112,itu_t_standard,ignore,10,<<194,69,0,0,0,0,0,18,52,95>>},
diff --git a/lib/compiler/test/match_SUITE.erl b/lib/compiler/test/match_SUITE.erl
index 20969c0b26..9c4687efa1 100644
--- a/lib/compiler/test/match_SUITE.erl
+++ b/lib/compiler/test/match_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2004-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2004-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(match_SUITE).
@@ -21,14 +21,14 @@
-export([all/1,
pmatch/1,mixed/1,aliases/1,match_in_call/1,
untuplify/1,shortcut_boolean/1,letify_guard/1,
- selectify/1]).
+ selectify/1,underscore/1]).
-include("test_server.hrl").
all(suite) ->
test_lib:recompile(?MODULE),
[pmatch,mixed,aliases,match_in_call,untuplify,shortcut_boolean,
- letify_guard,selectify].
+ letify_guard,selectify,underscore].
pmatch(Config) when is_list(Config) ->
?line ok = doit(1),
@@ -352,4 +352,16 @@ sel_same_value2(V) when V =:= 42; V =:= 43 ->
sel_same_value2(_) ->
error.
+underscore(Config) when is_list(Config) ->
+ case Config of
+ [] ->
+ %% Assignment to _ at the end of a construct.
+ _ = length(Config);
+ [_|_] ->
+ %% Assignment to _ at the end of a construct.
+ _ = list_to_tuple(Config)
+ end,
+ _ = is_list(Config),
+ ok.
+
id(I) -> I.
diff --git a/lib/compiler/test/num_bif_SUITE.erl b/lib/compiler/test/num_bif_SUITE.erl
index c246f56611..912f7366dd 100644
--- a/lib/compiler/test/num_bif_SUITE.erl
+++ b/lib/compiler/test/num_bif_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2004-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2004-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(num_bif_SUITE).
@@ -166,7 +166,7 @@ t_list_to_float_safe(Config) when is_list(Config) ->
t_list_to_float_risky(Config) when is_list(Config) ->
?line Many_Ones = lists:duplicate(25000, $1),
- ?line list_to_float("2."++Many_Ones),
+ ?line _ = list_to_float("2."++Many_Ones),
?line {'EXIT', {badarg, _}} = (catch list_to_float("2"++Many_Ones)),
ok.
@@ -186,7 +186,7 @@ t_list_to_integer(Config) when is_list(Config) ->
%% Bignums.
?line 123456932798748738738 = list_to_integer("123456932798748738738"),
- ?line list_to_integer(lists:duplicate(2000, $1)),
+ ?line _ = list_to_integer(lists:duplicate(2000, $1)),
ok.
%% Tests round/1.
diff --git a/lib/compiler/test/record_SUITE.erl b/lib/compiler/test/record_SUITE.erl
index bd2ffd7f65..f26ff769c7 100644
--- a/lib/compiler/test/record_SUITE.erl
+++ b/lib/compiler/test/record_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2003-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2003-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 : Test records.
@@ -24,7 +24,7 @@
-export([all/1,init_per_testcase/2,fin_per_testcase/2,
errors/1,record_test_2/1,record_test_3/1,record_access_in_guards/1,
- guard_opt/1,eval_once/1,foobar/1,missing_test_heap/1]).
+ guard_opt/1,eval_once/1,foobar/1,missing_test_heap/1, nested_access/1]).
init_per_testcase(_Case, Config) ->
?line Dog = test_server:timetrap(test_server:minutes(2)),
@@ -38,7 +38,7 @@ fin_per_testcase(_Case, Config) ->
all(suite) ->
test_lib:recompile(?MODULE),
[errors,record_test_2,record_test_3,record_access_in_guards,
- guard_opt,eval_once,foobar,missing_test_heap].
+ guard_opt,eval_once,foobar,missing_test_heap,nested_access].
-record(foo, {a,b,c,d}).
-record(bar, {a,b,c,d}).
@@ -522,4 +522,29 @@ missing_test_heap_1(A = #foo_rec {foo_1 = _B,
foo_3 = C + 1,
foo_2 = D + 1}.
+-record(nrec0, {name = <<"nested0">>}).
+-record(nrec1, {name = <<"nested1">>, nrec0=#nrec0{}}).
+-record(nrec2, {name = <<"nested2">>, nrec1=#nrec1{}}).
+
+nested_access(Config) when is_list(Config) ->
+ N0 = #nrec0{},
+ N1 = #nrec1{},
+ N2 = #nrec2{},
+ ?line <<"nested0">> = N0#nrec0.name,
+ ?line <<"nested1">> = N1#nrec1.name,
+ ?line <<"nested2">> = N2#nrec2.name,
+ ?line <<"nested0">> = N1#nrec1.nrec0#nrec0.name,
+ ?line <<"nested0">> = N2#nrec2.nrec1#nrec1.nrec0#nrec0.name,
+ ?line <<"nested1">> = N2#nrec2.nrec1#nrec1.name,
+ ?line <<"nested0">> = ((N2#nrec2.nrec1)#nrec1.nrec0)#nrec0.name,
+
+ N1a = N2#nrec2.nrec1#nrec1{name = <<"nested1a">>},
+ ?line <<"nested1a">> = N1a#nrec1.name,
+
+ N2a = N2#nrec2.nrec1#nrec1.nrec0#nrec0{name = <<"nested0a">>},
+ N2b = ((N2#nrec2.nrec1)#nrec1.nrec0)#nrec0{name = <<"nested0a">>},
+ ?line <<"nested0a">> = N2a#nrec0.name,
+ ?line N2a = N2b,
+ ok.
+
id(I) -> I.
diff --git a/lib/compiler/test/warnings_SUITE.erl b/lib/compiler/test/warnings_SUITE.erl
index 6e60ab88cb..5ed8836c70 100644
--- a/lib/compiler/test/warnings_SUITE.erl
+++ b/lib/compiler/test/warnings_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2003-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2003-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(warnings_SUITE).
@@ -375,7 +375,12 @@ effect(Config) when is_list(Config) ->
comp_op ->
X =:= 2;
cookie ->
- erlang:get_cookie()
+ erlang:get_cookie();
+ result_ignore ->
+ _ = list_to_integer(X);
+ warn_lc_4 ->
+ %% No warning because of assignment to _.
+ [_ = abs(Z) || Z <- [1,2,3]]
end,
ok.
diff --git a/lib/crypto/c_src/Makefile.in b/lib/crypto/c_src/Makefile.in
index 18040a3b26..e728db18eb 100644
--- a/lib/crypto/c_src/Makefile.in
+++ b/lib/crypto/c_src/Makefile.in
@@ -68,13 +68,13 @@ RELSYSDIR = $(RELEASE_PATH)/lib/crypto-$(VSN)
# ----------------------------------------------------
# Misc Macros
# ----------------------------------------------------
-OBJS = $(OBJDIR)/crypto_drv.o
-DRV_MAKEFILE = $(PRIVDIR)/Makefile
+OBJS = $(OBJDIR)/crypto.o
+NIF_MAKEFILE = $(PRIVDIR)/Makefile
ifeq ($(findstring win32,$(TARGET)), win32)
-DYN_DRIVER = $(LIBDIR)/crypto_drv.dll
+NIF_LIB = $(LIBDIR)/crypto.dll
else
-DYN_DRIVER = $(LIBDIR)/crypto_drv.so
+NIF_LIB = $(LIBDIR)/crypto.so
endif
ifeq ($(HOST_OS),)
@@ -94,7 +94,7 @@ endif
# Targets
# ----------------------------------------------------
-debug opt valgrind: $(OBJDIR) $(LIBDIR) $(DYN_DRIVER)
+debug opt valgrind: $(OBJDIR) $(LIBDIR) $(NIF_LIB)
$(OBJDIR):
-@mkdir -p $(OBJDIR)
@@ -106,16 +106,16 @@ $(OBJDIR)/%.o: %.c
$(INSTALL_DIR) $(OBJDIR)
$(CC) -c -o $@ $(ALL_CFLAGS) $<
-$(LIBDIR)/crypto_drv.so: $(OBJS)
+$(LIBDIR)/crypto.so: $(OBJS)
$(INSTALL_DIR) $(LIBDIR)
$(LD) $(LDFLAGS) -o $@ $^ $(LDLIBS) $(CRYPTO_LINK_LIB)
-$(LIBDIR)/crypto_drv.dll: $(OBJS)
+$(LIBDIR)/crypto.dll: $(OBJS)
$(INSTALL_DIR) $(LIBDIR)
$(LD) $(LDFLAGS) -o $@ $(SSL_DED_LD_RUNTIME_LIBRARY_PATH) -L$(SSL_LIBDIR) $(OBJS) -llibeay32
clean:
- rm -f $(DYN_DRIVER) $(OBJS)
+ rm -f $(NIF_LIB) $(OBJS)
rm -f core *~
docs:
@@ -128,9 +128,9 @@ include $(ERL_TOP)/make/otp_release_targets.mk
release_spec: opt
$(INSTALL_DIR) $(RELSYSDIR)/priv/obj
$(INSTALL_DIR) $(RELSYSDIR)/priv/lib
- $(INSTALL_DATA) $(DRV_MAKEFILE) $(RELSYSDIR)/priv/obj
+ $(INSTALL_DATA) $(NIF_MAKEFILE) $(RELSYSDIR)/priv/obj
$(INSTALL_PROGRAM) $(OBJS) $(RELSYSDIR)/priv/obj
- $(INSTALL_PROGRAM) $(DYN_DRIVER) $(RELSYSDIR)/priv/lib
+ $(INSTALL_PROGRAM) $(NIF_LIB) $(RELSYSDIR)/priv/lib
release_docs_spec:
diff --git a/lib/crypto/c_src/crypto.c b/lib/crypto/c_src/crypto.c
new file mode 100644
index 0000000000..a71df1d7fd
--- /dev/null
+++ b/lib/crypto/c_src/crypto.c
@@ -0,0 +1,1531 @@
+/*
+ * %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: Dynamically loadable NIF library for cryptography.
+ * Based on OpenSSL.
+ */
+
+#ifdef __WIN32__
+ #include <windows.h>
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "erl_nif.h"
+
+#define OPENSSL_THREAD_DEFINES
+#include <openssl/opensslconf.h>
+
+#include <openssl/crypto.h>
+#include <openssl/des.h>
+/* #include <openssl/idea.h> This is not supported on the openssl OTP requires */
+#include <openssl/dsa.h>
+#include <openssl/rsa.h>
+#include <openssl/aes.h>
+#include <openssl/md5.h>
+#include <openssl/md4.h>
+#include <openssl/sha.h>
+#include <openssl/bn.h>
+#include <openssl/objects.h>
+#include <openssl/rc4.h>
+#include <openssl/rc2.h>
+#include <openssl/blowfish.h>
+#include <openssl/rand.h>
+
+#ifdef VALGRIND
+ # include <valgrind/memcheck.h>
+
+/* libcrypto mixes supplied buffer contents into its entropy pool,
+ which makes valgrind complain about the use of uninitialized data.
+ We use this valgrind "request" to make sure that no such seemingly
+ undefined data is returned.
+*/
+ # define ERL_VALGRIND_MAKE_MEM_DEFINED(ptr,size) \
+ VALGRIND_MAKE_MEM_DEFINED(ptr,size)
+
+ # define ERL_VALGRIND_ASSERT_MEM_DEFINED(ptr,size) \
+ ((void) ((VALGRIND_CHECK_MEM_IS_DEFINED(ptr,size) == 0) ? 1 : \
+ (fprintf(stderr,"\r\n####### VALGRIND_ASSSERT(%p,%d) failed at %s:%d\r\n",\
+ (ptr),(size), __FILE__, __LINE__), abort(), 0)))
+#else
+ # define ERL_VALGRIND_MAKE_MEM_DEFINED(ptr,size)
+ # define ERL_VALGRIND_ASSERT_MEM_DEFINED(ptr,size)
+#endif
+
+#ifdef DEBUG
+ # define ASSERT(e) \
+ ((void) ((e) ? 1 : (fprintf(stderr,"Assert '%s' failed at %s:%d\n",\
+ #e, __FILE__, __LINE__), abort(), 0)))
+#else
+ # define ASSERT(e) ((void) 1)
+#endif
+
+#ifdef __GNUC__
+ # define INLINE __inline__
+#elif defined(__WIN32__)
+ # define INLINE __forceinline
+#else
+ # define INLINE
+#endif
+
+
+#define get_int32(s) ((((unsigned char*) (s))[0] << 24) | \
+ (((unsigned char*) (s))[1] << 16) | \
+ (((unsigned char*) (s))[2] << 8) | \
+ (((unsigned char*) (s))[3]))
+
+#define put_int32(s,i) \
+{ (s)[0] = (char)(((i) >> 24) & 0xff);\
+ (s)[1] = (char)(((i) >> 16) & 0xff);\
+ (s)[2] = (char)(((i) >> 8) & 0xff);\
+ (s)[3] = (char)((i) & 0xff);\
+}
+
+/* NIF interface declarations */
+static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info);
+static int reload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info);
+static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info);
+static void unload(ErlNifEnv* env, void* priv_data);
+
+/* The NIFs: */
+static ERL_NIF_TERM info_lib(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md5(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md5_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md5_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md5_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM sha(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM sha_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM sha_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM sha_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md4(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md4_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md4_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md4_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM md5_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM sha_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM des_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM des_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM des_ede3_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM aes_cfb_128_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rand_bytes_1(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rand_bytes_3(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rand_uniform_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM mod_exp_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM dss_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rsa_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM aes_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM exor(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rc4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rc4_set_key(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rc4_encrypt_with_state(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rc2_40_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rsa_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM dss_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rsa_public_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM rsa_private_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM dh_generate_parameters_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM dh_check(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM dh_generate_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM dh_compute_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM bf_cfb64_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM bf_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM bf_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+static ERL_NIF_TERM blowfish_ofb64_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+
+
+/* openssl callbacks */
+#ifdef OPENSSL_THREADS
+static void locking_function(int mode, int n, const char *file, int line);
+static unsigned long id_function(void);
+static struct CRYPTO_dynlock_value* dyn_create_function(const char *file,
+ int line);
+static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value* ptr,
+ const char *file, int line);
+static void dyn_destroy_function(struct CRYPTO_dynlock_value *ptr,
+ const char *file, int line);
+#endif /* OPENSSL_THREADS */
+
+/* helpers */
+static void hmac_md5(unsigned char *key, int klen,
+ unsigned char *dbuf, int dlen,
+ unsigned char *hmacbuf);
+static void hmac_sha1(unsigned char *key, int klen,
+ unsigned char *dbuf, int dlen,
+ unsigned char *hmacbuf);
+
+static int library_refc = 0; /* number of users of this dynamic library */
+
+static ErlNifFunc nif_funcs[] = {
+ {"info_lib", 0, info_lib},
+ {"md5", 1, md5},
+ {"md5_init", 0, md5_init},
+ {"md5_update", 2, md5_update},
+ {"md5_final", 1, md5_final},
+ {"sha", 1, sha},
+ {"sha_init", 0, sha_init},
+ {"sha_update", 2, sha_update},
+ {"sha_final", 1, sha_final},
+ {"md4", 1, md4},
+ {"md4_init", 0, md4_init},
+ {"md4_update", 2, md4_update},
+ {"md4_final", 1, md4_final},
+ {"md5_mac_n", 3, md5_mac_n},
+ {"sha_mac_n", 3, sha_mac_n},
+ {"des_cbc_crypt", 4, des_cbc_crypt},
+ {"des_ecb_crypt", 3, des_ecb_crypt},
+ {"des_ede3_cbc_crypt", 6, des_ede3_cbc_crypt},
+ {"aes_cfb_128_crypt", 4, aes_cfb_128_crypt},
+ {"rand_bytes", 1, rand_bytes_1},
+ {"rand_bytes", 3, rand_bytes_3},
+ {"rand_uniform_nif", 2, rand_uniform_nif},
+ {"mod_exp_nif", 3, mod_exp_nif},
+ {"dss_verify", 3, dss_verify},
+ {"rsa_verify", 4, rsa_verify},
+ {"aes_cbc_crypt", 4, aes_cbc_crypt},
+ {"exor", 2, exor},
+ {"rc4_encrypt", 2, rc4_encrypt},
+ {"rc4_set_key", 1, rc4_set_key},
+ {"rc4_encrypt_with_state", 2, rc4_encrypt_with_state},
+ {"rc2_40_cbc_crypt", 4, rc2_40_cbc_crypt},
+ {"rsa_sign_nif", 3, rsa_sign_nif},
+ {"dss_sign_nif", 2, dss_sign_nif},
+ {"rsa_public_crypt", 4, rsa_public_crypt},
+ {"rsa_private_crypt", 4, rsa_private_crypt},
+ {"dh_generate_parameters_nif", 2, dh_generate_parameters_nif},
+ {"dh_check", 1, dh_check},
+ {"dh_generate_key_nif", 2, dh_generate_key_nif},
+ {"dh_compute_key_nif", 3, dh_compute_key_nif},
+ {"bf_cfb64_crypt", 4, bf_cfb64_crypt},
+ {"bf_cbc_crypt", 4, bf_cbc_crypt},
+ {"bf_ecb_crypt", 3, bf_ecb_crypt},
+ {"blowfish_ofb64_encrypt", 3, blowfish_ofb64_encrypt}
+};
+
+ERL_NIF_INIT(crypto,nif_funcs,load,reload,upgrade,unload)
+
+
+#define MD5_CTX_LEN (sizeof(MD5_CTX))
+#define MD5_LEN 16
+#define MD5_LEN_96 12
+#define MD4_CTX_LEN (sizeof(MD4_CTX))
+#define MD4_LEN 16
+#define SHA_CTX_LEN (sizeof(SHA_CTX))
+#define SHA_LEN 20
+#define SHA_LEN_96 12
+#define HMAC_INT_LEN 64
+
+#define HMAC_IPAD 0x36
+#define HMAC_OPAD 0x5c
+
+
+static ErlNifRWLock** lock_vec = NULL; /* Static locks used by openssl */
+static ERL_NIF_TERM atom_true;
+static ERL_NIF_TERM atom_false;
+static ERL_NIF_TERM atom_sha;
+static ERL_NIF_TERM atom_md5;
+static ERL_NIF_TERM atom_error;
+static ERL_NIF_TERM atom_rsa_pkcs1_padding;
+static ERL_NIF_TERM atom_rsa_pkcs1_oaep_padding;
+static ERL_NIF_TERM atom_rsa_no_padding;
+static ERL_NIF_TERM atom_undefined;
+
+static ERL_NIF_TERM atom_ok;
+static ERL_NIF_TERM atom_not_prime;
+static ERL_NIF_TERM atom_not_strong_prime;
+static ERL_NIF_TERM atom_unable_to_check_generator;
+static ERL_NIF_TERM atom_not_suitable_generator;
+static ERL_NIF_TERM atom_check_failed;
+static ERL_NIF_TERM atom_unknown;
+
+
+static int is_ok_load_info(ErlNifEnv* env, ERL_NIF_TERM load_info)
+{
+ int i;
+ return enif_get_int(env,load_info,&i) && i == 101;
+}
+static void* crypto_alloc(size_t size)
+{
+ return enif_alloc(NULL, size);
+}
+static void* crypto_realloc(void* ptr, size_t size)
+{
+ return enif_realloc(NULL, ptr, size);
+}
+static void crypto_free(void* ptr)
+{
+ enif_free(NULL, ptr);
+}
+
+static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
+{
+ ErlNifSysInfo sys_info;
+ CRYPTO_set_mem_functions(crypto_alloc, crypto_realloc, crypto_free);
+
+ if (!is_ok_load_info(env, load_info)) {
+ return -1;
+ }
+
+#ifdef OPENSSL_THREADS
+ enif_system_info(&sys_info, sizeof(sys_info));
+
+ if (sys_info.scheduler_threads > 1) {
+ int i;
+ lock_vec = enif_alloc(env,CRYPTO_num_locks()*sizeof(*lock_vec));
+ if (lock_vec==NULL) return -1;
+ memset(lock_vec,0,CRYPTO_num_locks()*sizeof(*lock_vec));
+
+ for (i=CRYPTO_num_locks()-1; i>=0; --i) {
+ lock_vec[i] = enif_rwlock_create("crypto_stat");
+ if (lock_vec[i]==NULL) return -1;
+ }
+ CRYPTO_set_locking_callback(locking_function);
+ CRYPTO_set_id_callback(id_function);
+ CRYPTO_set_dynlock_create_callback(dyn_create_function);
+ CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
+ CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
+ }
+ /* else no need for locks */
+#endif /* OPENSSL_THREADS */
+
+ atom_true = enif_make_atom(env,"true");
+ atom_false = enif_make_atom(env,"false");
+ atom_sha = enif_make_atom(env,"sha");
+ atom_md5 = enif_make_atom(env,"md5");
+ atom_error = enif_make_atom(env,"error");
+ atom_rsa_pkcs1_padding = enif_make_atom(env,"rsa_pkcs1_padding");
+ atom_rsa_pkcs1_oaep_padding = enif_make_atom(env,"rsa_pkcs1_oaep_padding");
+ atom_rsa_no_padding = enif_make_atom(env,"rsa_no_padding");
+ atom_undefined = enif_make_atom(env,"undefined");
+ atom_ok = enif_make_atom(env,"ok");
+ atom_not_prime = enif_make_atom(env,"not_prime");
+ atom_not_strong_prime = enif_make_atom(env,"not_strong_prime");
+ atom_unable_to_check_generator = enif_make_atom(env,"unable_to_check_generator");
+ atom_not_suitable_generator = enif_make_atom(env,"not_suitable_generator");
+ atom_check_failed = enif_make_atom(env,"check_failed");
+ atom_unknown = enif_make_atom(env,"unknown");
+
+ *priv_data = NULL;
+ library_refc++;
+ return 0;
+}
+
+static int reload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
+{
+ if (*priv_data != NULL) {
+ return -1; /* Don't know how to do that */
+ }
+ if (library_refc == 0) {
+ /* No support for real library upgrade. The tricky thing is to know
+ when to (re)set the callbacks for allocation and locking. */
+ return -2;
+ }
+ if (!is_ok_load_info(env, load_info)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data,
+ ERL_NIF_TERM load_info)
+{
+ int i;
+ if (*old_priv_data != NULL) {
+ return -1; /* Don't know how to do that */
+ }
+ i = reload(env,priv_data,load_info);
+ if (i != 0) {
+ return i;
+ }
+ library_refc++;
+ return 0;
+}
+
+static void unload(ErlNifEnv* env, void* priv_data)
+{
+ if (--library_refc <= 0) {
+ CRYPTO_cleanup_all_ex_data();
+
+ if (lock_vec != NULL) {
+ int i;
+ for (i=CRYPTO_num_locks()-1; i>=0; --i) {
+ if (lock_vec[i] != NULL) {
+ enif_rwlock_destroy(lock_vec[i]);
+ }
+ }
+ enif_free(env,lock_vec);
+ }
+ }
+ /*else NIF library still used by other (new) module code */
+}
+
+static ERL_NIF_TERM info_lib(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{
+ /* [{<<"OpenSSL">>,9470143,<<"OpenSSL 0.9.8k 25 Mar 2009">>}] */
+
+ static const char libname[] = "OpenSSL";
+ unsigned name_sz = strlen(libname);
+ const char* ver = SSLeay_version(SSLEAY_VERSION);
+ unsigned ver_sz = strlen(ver);
+ ERL_NIF_TERM name_term, ver_term;
+
+ memcpy(enif_make_new_binary(env, name_sz, &name_term), libname, name_sz);
+ memcpy(enif_make_new_binary(env, ver_sz, &ver_term), ver, ver_sz);
+
+ return enif_make_list1(env, enif_make_tuple3(env, name_term,
+ enif_make_int(env, SSLeay()),
+ ver_term));
+}
+
+static ERL_NIF_TERM md5(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data) */
+ ErlNifBinary ibin;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &ibin)) {
+ return enif_make_badarg(env);
+ }
+ MD5((unsigned char *) ibin.data, ibin.size,
+ enif_make_new_binary(env,MD5_LEN, &ret));
+ return ret;
+}
+static ERL_NIF_TERM md5_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* () */
+ ERL_NIF_TERM ret;
+ MD5_Init((MD5_CTX *) enif_make_new_binary(env, MD5_CTX_LEN, &ret));
+ return ret;
+}
+static ERL_NIF_TERM md5_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Context, Data) */
+ MD5_CTX* new_ctx;
+ ErlNifBinary ctx_bin, data_bin;
+ ERL_NIF_TERM ret;
+ if (!enif_inspect_binary(env, argv[0], &ctx_bin)
+ || ctx_bin.size != MD5_CTX_LEN
+ || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin)) {
+ return enif_make_badarg(env);
+ }
+ new_ctx = (MD5_CTX*) enif_make_new_binary(env,MD5_CTX_LEN, &ret);
+ memcpy(new_ctx, ctx_bin.data, MD5_CTX_LEN);
+ MD5_Update(new_ctx, data_bin.data, data_bin.size);
+ return ret;
+}
+static ERL_NIF_TERM md5_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Context) */
+ ErlNifBinary ctx_bin;
+ MD5_CTX ctx_clone;
+ ERL_NIF_TERM ret;
+ if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != MD5_CTX_LEN) {
+ return enif_make_badarg(env);
+ }
+ memcpy(&ctx_clone, ctx_bin.data, MD5_CTX_LEN); /* writable */
+ MD5_Final(enif_make_new_binary(env, MD5_LEN, &ret), &ctx_clone);
+ return ret;
+}
+
+static ERL_NIF_TERM sha(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data) */
+ ErlNifBinary ibin;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &ibin)) {
+ return enif_make_badarg(env);
+ }
+ SHA1((unsigned char *) ibin.data, ibin.size,
+ enif_make_new_binary(env,SHA_LEN, &ret));
+ return ret;
+}
+static ERL_NIF_TERM sha_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* () */
+ ERL_NIF_TERM ret;
+ SHA1_Init((SHA_CTX *) enif_make_new_binary(env, SHA_CTX_LEN, &ret));
+ return ret;
+}
+static ERL_NIF_TERM sha_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Context, Data) */
+ SHA_CTX* new_ctx;
+ ErlNifBinary ctx_bin, data_bin;
+ ERL_NIF_TERM ret;
+ if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != SHA_CTX_LEN
+ || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin)) {
+ return enif_make_badarg(env);
+ }
+ new_ctx = (SHA_CTX*) enif_make_new_binary(env,SHA_CTX_LEN, &ret);
+ memcpy(new_ctx, ctx_bin.data, SHA_CTX_LEN);
+ SHA1_Update(new_ctx, data_bin.data, data_bin.size);
+ return ret;
+}
+static ERL_NIF_TERM sha_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Context) */
+ ErlNifBinary ctx_bin;
+ SHA_CTX ctx_clone;
+ ERL_NIF_TERM ret;
+ if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != SHA_CTX_LEN) {
+ return enif_make_badarg(env);
+ }
+ memcpy(&ctx_clone, ctx_bin.data, SHA_CTX_LEN); /* writable */
+ SHA1_Final(enif_make_new_binary(env, SHA_LEN, &ret), &ctx_clone);
+ return ret;
+}
+
+static ERL_NIF_TERM md4(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data) */
+ ErlNifBinary ibin;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &ibin)) {
+ return enif_make_badarg(env);
+ }
+ MD4((unsigned char *) ibin.data, ibin.size,
+ enif_make_new_binary(env,MD4_LEN, &ret));
+ return ret;
+}
+static ERL_NIF_TERM md4_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* () */
+ ERL_NIF_TERM ret;
+ MD4_Init((MD4_CTX *) enif_make_new_binary(env, MD4_CTX_LEN, &ret));
+ return ret;
+}
+static ERL_NIF_TERM md4_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Context, Data) */
+ MD4_CTX* new_ctx;
+ ErlNifBinary ctx_bin, data_bin;
+ ERL_NIF_TERM ret;
+ if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != MD4_CTX_LEN
+ || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin)) {
+ return enif_make_badarg(env);
+ }
+ new_ctx = (MD4_CTX*) enif_make_new_binary(env,MD4_CTX_LEN, &ret);
+ memcpy(new_ctx, ctx_bin.data, MD4_CTX_LEN);
+ MD4_Update(new_ctx, data_bin.data, data_bin.size);
+ return ret;
+}
+static ERL_NIF_TERM md4_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Context) */
+ ErlNifBinary ctx_bin;
+ MD4_CTX ctx_clone;
+ ERL_NIF_TERM ret;
+ if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != MD4_CTX_LEN) {
+ return enif_make_badarg(env);
+ }
+ memcpy(&ctx_clone, ctx_bin.data, MD4_CTX_LEN); /* writable */
+ MD4_Final(enif_make_new_binary(env, MD4_LEN, &ret), &ctx_clone);
+ return ret;
+}
+
+static ERL_NIF_TERM md5_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Data, MacSize) */
+ unsigned char hmacbuf[SHA_DIGEST_LENGTH];
+ ErlNifBinary key, data;
+ unsigned mac_sz;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key)
+ || !enif_inspect_iolist_as_binary(env, argv[1], &data)
+ || !enif_get_uint(env,argv[2],&mac_sz) || mac_sz > MD5_LEN) {
+ return enif_make_badarg(env);
+ }
+ hmac_md5(key.data, key.size, data.data, data.size, hmacbuf);
+ memcpy(enif_make_new_binary(env, mac_sz, &ret), hmacbuf, mac_sz);
+ return ret;
+}
+
+static ERL_NIF_TERM sha_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Data, MacSize) */
+ unsigned char hmacbuf[SHA_DIGEST_LENGTH];
+ ErlNifBinary key, data;
+ unsigned mac_sz;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key)
+ || !enif_inspect_iolist_as_binary(env, argv[1], &data)
+ || !enif_get_uint(env,argv[2],&mac_sz) || mac_sz > SHA_LEN) {
+ return enif_make_badarg(env);
+ }
+ hmac_sha1(key.data, key.size, data.data, data.size, hmacbuf);
+ memcpy(enif_make_new_binary(env, mac_sz, &ret),
+ hmacbuf, mac_sz);
+ return ret;
+}
+
+static ERL_NIF_TERM des_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Ivec, Text, IsEncrypt) */
+ ErlNifBinary key, ivec, text;
+ DES_key_schedule schedule;
+ DES_cblock ivec_clone; /* writable copy */
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || key.size != 8
+ || !enif_inspect_binary(env, argv[1], &ivec) || ivec.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[2], &text)
+ || text.size % 8 != 0) {
+ return enif_make_badarg(env);
+ }
+ memcpy(&ivec_clone, ivec.data, 8);
+ DES_set_key((const_DES_cblock*)key.data, &schedule);
+ DES_ncbc_encrypt(text.data, enif_make_new_binary(env, text.size, &ret),
+ text.size, &schedule, &ivec_clone, (argv[3] == atom_true));
+ return ret;
+}
+
+static ERL_NIF_TERM des_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Text/Cipher, IsEncrypt) */
+ ErlNifBinary key, text;
+ DES_key_schedule schedule;
+ ERL_NIF_TERM ret;
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || key.size != 8 ||
+ !enif_inspect_iolist_as_binary(env, argv[1], &text) || text.size != 8) {
+ return enif_make_badarg(env);
+ }
+ DES_set_key((const_DES_cblock*)key.data, &schedule);
+ DES_ecb_encrypt((const_DES_cblock*)text.data,
+ (DES_cblock*)enif_make_new_binary(env, 8, &ret),
+ &schedule, (argv[2] == atom_true));
+ return ret;
+}
+
+static ERL_NIF_TERM des_ede3_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key1, Key2, Key3, IVec, Text/Cipher, IsEncrypt) */
+ ErlNifBinary key1, key2, key3, ivec, text;
+ DES_key_schedule schedule1, schedule2, schedule3;
+ DES_cblock ivec_clone; /* writable copy */
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key1) || key1.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[1], &key2) || key2.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[2], &key3) || key3.size != 8
+ || !enif_inspect_binary(env, argv[3], &ivec) || ivec.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[4], &text)
+ || text.size % 8 != 0) {
+ return enif_make_badarg(env);
+ }
+
+ memcpy(&ivec_clone, ivec.data, 8);
+ DES_set_key((const_DES_cblock*)key1.data, &schedule1);
+ DES_set_key((const_DES_cblock*)key2.data, &schedule2);
+ DES_set_key((const_DES_cblock*)key3.data, &schedule3);
+ DES_ede3_cbc_encrypt(text.data, enif_make_new_binary(env,text.size,&ret),
+ text.size, &schedule1, &schedule2, &schedule3,
+ &ivec_clone, (argv[5] == atom_true));
+ return ret;
+}
+
+static ERL_NIF_TERM aes_cfb_128_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, IVec, Data, IsEncrypt) */
+ ErlNifBinary key, ivec, text;
+ AES_KEY aes_key;
+ unsigned char ivec_clone[16]; /* writable copy */
+ int new_ivlen = 0;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || key.size != 16
+ || !enif_inspect_binary(env, argv[1], &ivec) || ivec.size != 16
+ || !enif_inspect_iolist_as_binary(env, argv[2], &text)
+ || text.size % 16 != 0) {
+ return enif_make_badarg(env);
+ }
+
+ memcpy(ivec_clone, ivec.data, 16);
+ AES_set_encrypt_key(key.data, 128, &aes_key);
+ AES_cfb128_encrypt((unsigned char *) text.data,
+ enif_make_new_binary(env, text.size, &ret),
+ text.size, &aes_key, ivec_clone, &new_ivlen,
+ (argv[3] == atom_true));
+ return ret;
+}
+
+static ERL_NIF_TERM rand_bytes_1(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Bytes) */
+ unsigned bytes;
+ unsigned char* data;
+ ERL_NIF_TERM ret;
+ if (!enif_get_uint(env, argv[0], &bytes)) {
+ return enif_make_badarg(env);
+ }
+ data = enif_make_new_binary(env, bytes, &ret);
+ RAND_pseudo_bytes(data, bytes);
+ ERL_VALGRIND_MAKE_MEM_DEFINED(data, bytes);
+ return ret;
+}
+static ERL_NIF_TERM rand_bytes_3(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Bytes, TopMask, BottomMask) */
+ unsigned bytes;
+ unsigned char* data;
+ unsigned top_mask, bot_mask;
+ ERL_NIF_TERM ret;
+ if (!enif_get_uint(env, argv[0], &bytes)
+ || !enif_get_uint(env, argv[1], &top_mask)
+ || !enif_get_uint(env, argv[2], &bot_mask)) {
+ return enif_make_badarg(env);
+ }
+ data = enif_make_new_binary(env, bytes, &ret);
+ RAND_pseudo_bytes(data, bytes);
+ ERL_VALGRIND_MAKE_MEM_DEFINED(data, bytes);
+ if (bytes > 0) {
+ data[bytes-1] |= top_mask;
+ data[0] |= bot_mask;
+ }
+ return ret;
+}
+
+static int get_bn_from_mpint(ErlNifEnv* env, ERL_NIF_TERM term, BIGNUM** bnp)
+{
+ ErlNifBinary bin;
+ int sz;
+ if (!enif_inspect_binary(env,term,&bin)) {
+ return 0;
+ }
+ ERL_VALGRIND_ASSERT_MEM_DEFINED(bin.data, bin.size);
+ sz = bin.size - 4;
+ if (sz < 0 || get_int32(bin.data) != sz) {
+ return 0;
+ }
+ *bnp = BN_bin2bn(bin.data+4, sz, NULL);
+ return 1;
+}
+
+static ERL_NIF_TERM rand_uniform_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Lo,Hi) */
+ BIGNUM *bn_from, *bn_to, *bn_rand;
+ unsigned char* data;
+ unsigned dlen;
+ ERL_NIF_TERM ret;
+ if (!get_bn_from_mpint(env, argv[0], &bn_from)
+ || !get_bn_from_mpint(env, argv[1], &bn_rand)) {
+ return enif_make_badarg(env);
+ }
+
+ bn_to = BN_new();
+ BN_sub(bn_to, bn_rand, bn_from);
+ BN_pseudo_rand_range(bn_rand, bn_to);
+ BN_add(bn_rand, bn_rand, bn_from);
+ dlen = BN_num_bytes(bn_rand);
+ data = enif_make_new_binary(env, dlen+4, &ret);
+ put_int32(data, dlen);
+ BN_bn2bin(bn_rand, data+4);
+ ERL_VALGRIND_MAKE_MEM_DEFINED(data+4, dlen);
+ BN_free(bn_rand);
+ BN_free(bn_from);
+ BN_free(bn_to);
+ return ret;
+}
+
+static ERL_NIF_TERM mod_exp_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Base,Exponent,Modulo) */
+ BIGNUM *bn_base=NULL, *bn_exponent=NULL, *bn_modulo, *bn_result;
+ BN_CTX *bn_ctx;
+ unsigned char* ptr;
+ unsigned dlen;
+ ERL_NIF_TERM ret;
+
+ if (!get_bn_from_mpint(env, argv[0], &bn_base)
+ || !get_bn_from_mpint(env, argv[1], &bn_exponent)
+ || !get_bn_from_mpint(env, argv[2], &bn_modulo)) {
+
+ if (bn_base) BN_free(bn_base);
+ if (bn_exponent) BN_free(bn_exponent);
+ return enif_make_badarg(env);
+ }
+ bn_result = BN_new();
+ bn_ctx = BN_CTX_new();
+ BN_mod_exp(bn_result, bn_base, bn_exponent, bn_modulo, bn_ctx);
+ dlen = BN_num_bytes(bn_result);
+ ptr = enif_make_new_binary(env, dlen+4, &ret);
+ put_int32(ptr, dlen);
+ BN_bn2bin(bn_result, ptr+4);
+ BN_free(bn_result);
+ BN_CTX_free(bn_ctx);
+ BN_free(bn_modulo);
+ BN_free(bn_exponent);
+ BN_free(bn_base);
+ return ret;
+}
+
+static int inspect_mpint(ErlNifEnv* env, ERL_NIF_TERM term, ErlNifBinary* bin)
+{
+ return enif_inspect_binary(env, term, bin) &&
+ bin->size >= 4 && get_int32(bin->data) == bin->size-4;
+}
+
+static ERL_NIF_TERM dss_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data,Signature,Key=[P, Q, G, Y]) */
+ ErlNifBinary data_bin, sign_bin;
+ BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_y;
+ unsigned char hmacbuf[SHA_DIGEST_LENGTH];
+ ERL_NIF_TERM head, tail;
+ DSA *dsa;
+ int i;
+
+ if (!inspect_mpint(env,argv[0],&data_bin)
+ || !inspect_mpint(env,argv[1],&sign_bin)
+ || !enif_get_list_cell(env, argv[2], &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa_p)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa_q)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa_g)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa_y)
+ || !enif_is_empty_list(env,tail)) {
+
+ return enif_make_badarg(env);
+ }
+ SHA1(data_bin.data+4, data_bin.size-4, hmacbuf);
+
+ dsa = DSA_new();
+ dsa->p = dsa_p;
+ dsa->q = dsa_q;
+ dsa->g = dsa_g;
+ dsa->priv_key = NULL;
+ dsa->pub_key = dsa_y;
+ i = DSA_verify(0, hmacbuf, SHA_DIGEST_LENGTH,
+ sign_bin.data+4, sign_bin.size-4, dsa);
+ DSA_free(dsa);
+ return(i > 0) ? atom_true : atom_false;
+}
+
+static ERL_NIF_TERM rsa_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Type, Data, Signature, Key=[E,N]) */
+ ErlNifBinary data_bin, sign_bin;
+ unsigned char hmacbuf[SHA_DIGEST_LENGTH];
+ ERL_NIF_TERM head, tail, ret;
+ int i, is_sha;
+ RSA* rsa = RSA_new();
+
+ if (argv[0] == atom_sha) is_sha = 1;
+ else if (argv[0] == atom_md5) is_sha = 0;
+ else goto badarg;
+
+ if (!inspect_mpint(env, argv[1], &data_bin)
+ || !inspect_mpint(env, argv[2], &sign_bin)
+ || !enif_get_list_cell(env, argv[3], &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->e)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->n)
+ || !enif_is_empty_list(env, tail)) {
+ badarg:
+ ret = enif_make_badarg(env);
+ }
+ else {
+ if (is_sha) {
+ SHA1(data_bin.data+4, data_bin.size-4, hmacbuf);
+ i = RSA_verify(NID_sha1, hmacbuf, SHA_DIGEST_LENGTH,
+ sign_bin.data+4, sign_bin.size-4, rsa);
+ }
+ else {
+ MD5(data_bin.data+4, data_bin.size-4, hmacbuf);
+ i = RSA_verify(NID_md5, hmacbuf, MD5_DIGEST_LENGTH,
+ sign_bin.data+4, sign_bin.size-4, rsa);
+ }
+ ret = (i==1 ? atom_true : atom_false);
+ }
+ RSA_free(rsa);
+ return ret;
+}
+
+static ERL_NIF_TERM aes_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, IVec, Data, IsEncrypt) */
+ ErlNifBinary key_bin, ivec_bin, data_bin;
+ AES_KEY aes_key;
+ unsigned char ivec[16];
+ int i;
+ unsigned char* ret_ptr;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin)
+ || (key_bin.size != 16 && key_bin.size != 32)
+ || !enif_inspect_binary(env, argv[1], &ivec_bin)
+ || ivec_bin.size != 16
+ || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)
+ || data_bin.size % 16 != 0) {
+
+ return enif_make_badarg(env);
+ }
+
+ if (argv[3] == atom_true) {
+ i = AES_ENCRYPT;
+ AES_set_encrypt_key(key_bin.data, key_bin.size*8, &aes_key);
+ }
+ else {
+ i = AES_DECRYPT;
+ AES_set_decrypt_key(key_bin.data, key_bin.size*8, &aes_key);
+ }
+
+ ret_ptr = enif_make_new_binary(env, data_bin.size, &ret);
+ memcpy(ivec, ivec_bin.data, 16); /* writable copy */
+ AES_cbc_encrypt(data_bin.data, ret_ptr, data_bin.size, &aes_key, ivec, i);
+ return ret;
+}
+
+static ERL_NIF_TERM exor(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data1, Data2) */
+ ErlNifBinary d1, d2;
+ unsigned char* ret_ptr;
+ int i;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env,argv[0], &d1)
+ || !enif_inspect_iolist_as_binary(env,argv[1], &d2)
+ || d1.size != d2.size) {
+ return enif_make_badarg(env);
+ }
+ ret_ptr = enif_make_new_binary(env, d1.size, &ret);
+
+ for (i=0; i<d1.size; i++) {
+ ret_ptr[i] = d1.data[i] ^ d2.data[i];
+ }
+ return ret;
+}
+
+static ERL_NIF_TERM rc4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Data) */
+ ErlNifBinary key, data;
+ RC4_KEY rc4_key;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env,argv[0], &key)
+ || !enif_inspect_iolist_as_binary(env,argv[1], &data)) {
+ return enif_make_badarg(env);
+ }
+ RC4_set_key(&rc4_key, key.size, key.data);
+ RC4(&rc4_key, data.size, data.data,
+ enif_make_new_binary(env, data.size, &ret));
+ return ret;
+}
+
+static ERL_NIF_TERM rc4_set_key(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key) */
+ ErlNifBinary key;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env,argv[0], &key)) {
+ return enif_make_badarg(env);
+ }
+ RC4_set_key((RC4_KEY*)enif_make_new_binary(env, sizeof(RC4_KEY), &ret),
+ key.size, key.data);
+ return ret;
+}
+
+static ERL_NIF_TERM rc4_encrypt_with_state(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (State, Data) */
+
+ ErlNifBinary state, data;
+ RC4_KEY* rc4_key;
+ ERL_NIF_TERM new_state, new_data;
+
+ if (!enif_inspect_iolist_as_binary(env,argv[0], &state)
+ || state.size != sizeof(RC4_KEY)
+ || !enif_inspect_iolist_as_binary(env,argv[1], &data)) {
+ return enif_make_badarg(env);
+ }
+ rc4_key = (RC4_KEY*)enif_make_new_binary(env, sizeof(RC4_KEY), &new_state);
+ memcpy(rc4_key, state.data, sizeof(RC4_KEY));
+ RC4(rc4_key, data.size, data.data,
+ enif_make_new_binary(env, data.size, &new_data));
+
+ return enif_make_tuple2(env,argv[0],new_data);
+}
+
+static ERL_NIF_TERM rc2_40_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key,IVec,Data,IsEncrypt) */
+ ErlNifBinary key_bin, ivec_bin, data_bin;
+ RC2_KEY rc2_key;
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin)
+ || key_bin.size != 5
+ || !enif_inspect_binary(env, argv[1], &ivec_bin)
+ || ivec_bin.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)) {
+
+ return enif_make_badarg(env);
+ }
+
+ RC2_set_key(&rc2_key, 5, key_bin.data, 40);
+ RC2_cbc_encrypt(data_bin.data,
+ enif_make_new_binary(env, data_bin.size, &ret),
+ data_bin.size, &rc2_key,
+ ivec_bin.data,
+ (argv[3] == atom_true));
+
+ return ret;
+}
+
+static ERL_NIF_TERM rsa_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Type,Data,Key=[E,N,D]) */
+ ErlNifBinary data_bin, ret_bin;
+ ERL_NIF_TERM head, tail;
+ unsigned char hmacbuf[SHA_DIGEST_LENGTH];
+ unsigned rsa_s_len;
+ RSA *rsa = RSA_new();
+ int i, is_sha;
+
+ if (argv[0] == atom_sha) is_sha = 1;
+ else if (argv[0] == atom_md5) is_sha = 0;
+ else goto badarg;
+
+ if (!inspect_mpint(env,argv[1],&data_bin)
+ || !enif_get_list_cell(env, argv[2], &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->e)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->n)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->d)
+ || !enif_is_empty_list(env,tail)) {
+ badarg:
+ RSA_free(rsa);
+ return enif_make_badarg(env);
+ }
+ enif_alloc_binary(env, RSA_size(rsa), &ret_bin);
+ if (is_sha) {
+ SHA1(data_bin.data+4, data_bin.size-4, hmacbuf);
+ ERL_VALGRIND_ASSERT_MEM_DEFINED(hmacbuf, SHA_DIGEST_LENGTH);
+ i = RSA_sign(NID_sha1, hmacbuf, SHA_DIGEST_LENGTH,
+ ret_bin.data, &rsa_s_len, rsa);
+ }
+ else {
+ MD5(data_bin.data+4, data_bin.size-4, hmacbuf);
+ ERL_VALGRIND_ASSERT_MEM_DEFINED(hmacbuf, MD5_DIGEST_LENGTH);
+ i = RSA_sign(NID_md5, hmacbuf,MD5_DIGEST_LENGTH,
+ ret_bin.data, &rsa_s_len, rsa);
+ }
+ RSA_free(rsa);
+ if (i) {
+ ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, rsa_s_len);
+ if (rsa_s_len != data_bin.size) {
+ enif_realloc_binary(env, &ret_bin, rsa_s_len);
+ ERL_VALGRIND_ASSERT_MEM_DEFINED(ret_bin.data, rsa_s_len);
+ }
+ return enif_make_binary(env,&ret_bin);
+ }
+ else {
+ enif_release_binary(env, &ret_bin);
+ return atom_error;
+ }
+}
+
+static ERL_NIF_TERM dss_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data,Key=[P,Q,G,PrivKey]) */
+ ErlNifBinary data_bin, ret_bin;
+ ERL_NIF_TERM head, tail;
+ unsigned char hmacbuf[SHA_DIGEST_LENGTH];
+ unsigned int dsa_s_len;
+ DSA* dsa = DSA_new();
+ int i;
+
+ dsa->pub_key = NULL;
+ if (!inspect_mpint(env, argv[0], &data_bin)
+ || !enif_get_list_cell(env, argv[1], &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa->p)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa->q)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa->g)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dsa->priv_key)
+ || !enif_is_empty_list(env,tail)) {
+
+ DSA_free(dsa);
+ return enif_make_badarg(env);
+ }
+
+ SHA1(data_bin.data+4, data_bin.size-4, hmacbuf);
+
+ enif_alloc_binary(env, DSA_size(dsa), &ret_bin);
+ i = DSA_sign(NID_sha1, hmacbuf, SHA_DIGEST_LENGTH,
+ ret_bin.data, &dsa_s_len, dsa);
+ DSA_free(dsa);
+ if (i) {
+ if (dsa_s_len != ret_bin.size) {
+ enif_realloc_binary(env, &ret_bin, dsa_s_len);
+ }
+ return enif_make_binary(env, &ret_bin);
+ }
+ else {
+ return atom_error;
+ }
+}
+
+static int rsa_pad(ERL_NIF_TERM term, int* padding)
+{
+ if (term == atom_rsa_pkcs1_padding) {
+ *padding = RSA_PKCS1_PADDING;
+ }
+ else if (term == atom_rsa_pkcs1_oaep_padding) {
+ *padding = RSA_PKCS1_OAEP_PADDING;
+ }
+ else if (term == atom_rsa_no_padding) {
+ *padding = RSA_NO_PADDING;
+ }
+ else {
+ return 0;
+ }
+ return 1;
+}
+
+static ERL_NIF_TERM rsa_public_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data, PublKey=[E,N], Padding, IsEncrypt) */
+ ErlNifBinary data_bin, ret_bin;
+ ERL_NIF_TERM head, tail;
+ int padding, i;
+ RSA* rsa = RSA_new();
+
+ if (!enif_inspect_binary(env, argv[0], &data_bin)
+ || !enif_get_list_cell(env, argv[1], &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->e)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->n)
+ || !enif_is_empty_list(env,tail)
+ || !rsa_pad(argv[2], &padding)) {
+
+ RSA_free(rsa);
+ return enif_make_badarg(env);
+ }
+
+ enif_alloc_binary(env, RSA_size(rsa), &ret_bin);
+
+ if (argv[3] == atom_true) {
+ ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,data_len);
+ i = RSA_public_encrypt(data_bin.size, data_bin.data,
+ ret_bin.data, rsa, padding);
+ if (i > 0) {
+ ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i);
+ }
+ }
+ else {
+ i = RSA_public_decrypt(data_bin.size, data_bin.data,
+ ret_bin.data, rsa, padding);
+ if (i > 0) {
+ ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i);
+ enif_realloc_binary(env, &ret_bin, i);
+ }
+ }
+ RSA_free(rsa);
+ if (i > 0) {
+ return enif_make_binary(env,&ret_bin);
+ }
+ else {
+ return atom_error;
+ }
+}
+
+static ERL_NIF_TERM rsa_private_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Data, PublKey=[E,N,D], Padding, IsEncrypt) */
+ ErlNifBinary data_bin, ret_bin;
+ ERL_NIF_TERM head, tail;
+ int padding, i;
+ RSA* rsa = RSA_new();
+
+ if (!enif_inspect_binary(env, argv[0], &data_bin)
+ || !enif_get_list_cell(env, argv[1], &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->e)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->n)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &rsa->d)
+ || !enif_is_empty_list(env,tail)
+ || !rsa_pad(argv[2], &padding)) {
+
+ RSA_free(rsa);
+ return enif_make_badarg(env);
+ }
+
+ enif_alloc_binary(env, RSA_size(rsa), &ret_bin);
+
+ if (argv[3] == atom_true) {
+ ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,data_len);
+ i = RSA_private_encrypt(data_bin.size, data_bin.data,
+ ret_bin.data, rsa, padding);
+ if (i > 0) {
+ ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i);
+ }
+ }
+ else {
+ i = RSA_private_decrypt(data_bin.size, data_bin.data,
+ ret_bin.data, rsa, padding);
+ if (i > 0) {
+ ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i);
+ enif_realloc_binary(env, &ret_bin, i);
+ }
+ }
+ RSA_free(rsa);
+ if (i > 0) {
+ return enif_make_binary(env,&ret_bin);
+ }
+ else {
+ return atom_error;
+ }
+}
+
+static ERL_NIF_TERM dh_generate_parameters_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (PrimeLen, Generator) */
+ int prime_len, generator;
+ DH* dh_params;
+ int p_len, g_len;
+ unsigned char *p_ptr, *g_ptr;
+ ERL_NIF_TERM ret_p, ret_g;
+
+ if (!enif_get_int(env, argv[0], &prime_len)
+ || !enif_get_int(env, argv[1], &generator)) {
+
+ return enif_make_badarg(env);
+ }
+ dh_params = DH_generate_parameters(prime_len, generator, NULL, NULL);
+ if (dh_params == NULL) {
+ return atom_error;
+ }
+ p_len = BN_num_bytes(dh_params->p);
+ g_len = BN_num_bytes(dh_params->g);
+ p_ptr = enif_make_new_binary(env, p_len+4, &ret_p);
+ g_ptr = enif_make_new_binary(env, g_len+4, &ret_g);
+ put_int32(p_ptr, p_len);
+ put_int32(g_ptr, g_len);
+ BN_bn2bin(dh_params->p, p_ptr+4);
+ BN_bn2bin(dh_params->g, g_ptr+4);
+ ERL_VALGRIND_MAKE_MEM_DEFINED(p_ptr+4, p_len);
+ ERL_VALGRIND_MAKE_MEM_DEFINED(g_ptr+4, g_len);
+ DH_free(dh_params);
+ return enif_make_list2(env, ret_p, ret_g);
+}
+
+static ERL_NIF_TERM dh_check(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* ([PrimeLen, Generator]) */
+ DH* dh_params = DH_new();
+ int i;
+ ERL_NIF_TERM ret, head, tail;
+
+ if (!enif_get_list_cell(env, argv[0], &head, &tail)
+ || !get_bn_from_mpint(env, head, &dh_params->p)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dh_params->g)
+ || !enif_is_empty_list(env,tail)) {
+
+ DH_free(dh_params);
+ return enif_make_badarg(env);
+ }
+ if (DH_check(dh_params, &i)) {
+ if (i == 0) ret = atom_ok;
+ else if (i & DH_CHECK_P_NOT_PRIME) ret = atom_not_prime;
+ else if (i & DH_CHECK_P_NOT_SAFE_PRIME) ret = atom_not_strong_prime;
+ else if (i & DH_UNABLE_TO_CHECK_GENERATOR) ret = atom_unable_to_check_generator;
+ else if (i & DH_NOT_SUITABLE_GENERATOR) ret = atom_not_suitable_generator;
+ else ret = enif_make_tuple2(env, atom_unknown, enif_make_uint(env, i));
+ }
+ else { /* Check Failed */
+ ret = enif_make_tuple2(env, atom_error, atom_check_failed);
+ }
+ DH_free(dh_params);
+ return ret;
+}
+
+static ERL_NIF_TERM dh_generate_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (PrivKey, DHParams=[P,G]) */
+ DH* dh_params = DH_new();
+ int pub_len, prv_len;
+ unsigned char *pub_ptr, *prv_ptr;
+ ERL_NIF_TERM ret, ret_pub, ret_prv, head, tail;
+
+ if (!(get_bn_from_mpint(env, argv[0], &dh_params->priv_key)
+ || argv[0] == atom_undefined)
+ || !enif_get_list_cell(env, argv[1], &head, &tail)
+ || !get_bn_from_mpint(env, head, &dh_params->p)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dh_params->g)
+ || !enif_is_empty_list(env, tail)) {
+
+ return enif_make_badarg(env);
+ }
+
+ if (DH_generate_key(dh_params)) {
+ pub_len = BN_num_bytes(dh_params->pub_key);
+ prv_len = BN_num_bytes(dh_params->priv_key);
+ pub_ptr = enif_make_new_binary(env, pub_len+4, &ret_pub);
+ prv_ptr = enif_make_new_binary(env, prv_len+4, &ret_prv);
+ put_int32(pub_ptr, pub_len);
+ put_int32(prv_ptr, prv_len);
+ BN_bn2bin(dh_params->pub_key, pub_ptr+4);
+ BN_bn2bin(dh_params->priv_key, prv_ptr+4);
+ ERL_VALGRIND_MAKE_MEM_DEFINED(pub_ptr+4, pub_len);
+ ERL_VALGRIND_MAKE_MEM_DEFINED(prv_ptr+4, prv_len);
+ ret = enif_make_tuple2(env, ret_pub, ret_prv);
+ }
+ else {
+ ret = atom_error;
+ }
+ DH_free(dh_params);
+ return ret;
+}
+
+static ERL_NIF_TERM dh_compute_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (OthersPublicKey, MyPrivateKey, DHParams=[P,G]) */
+ DH* dh_params = DH_new();
+ BIGNUM* pubkey;
+ int i;
+ ErlNifBinary ret_bin;
+ ERL_NIF_TERM ret, head, tail;
+
+ if (!get_bn_from_mpint(env, argv[0], &pubkey)
+ || !get_bn_from_mpint(env, argv[1], &dh_params->priv_key)
+ || !enif_get_list_cell(env, argv[2], &head, &tail)
+ || !get_bn_from_mpint(env, head, &dh_params->p)
+ || !enif_get_list_cell(env, tail, &head, &tail)
+ || !get_bn_from_mpint(env, head, &dh_params->g)
+ || !enif_is_empty_list(env, tail)) {
+
+ ret = enif_make_badarg(env);
+ }
+ else {
+ enif_alloc_binary(env, DH_size(dh_params), &ret_bin);
+ i = DH_compute_key(ret_bin.data, pubkey, dh_params);
+ if (i > 0) {
+ if (i != ret_bin.size) {
+ enif_realloc_binary(env, &ret_bin, i);
+ }
+ ret = enif_make_binary(env, &ret_bin);
+ }
+ else {
+ ret = atom_error;
+ }
+ }
+ DH_free(dh_params);
+ return ret;
+}
+
+static ERL_NIF_TERM bf_cfb64_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Ivec, Data, IsEncrypt) */
+ ErlNifBinary key_bin, ivec_bin, data_bin;
+ BF_KEY bf_key; /* blowfish key 8 */
+ unsigned char bf_tkey[8]; /* blowfish ivec */
+ int bf_n = 0; /* blowfish ivec pos */
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin)
+ || !enif_inspect_binary(env, argv[1], &ivec_bin)
+ || ivec_bin.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)) {
+ return enif_make_badarg(env);
+ }
+
+ BF_set_key(&bf_key, key_bin.size, key_bin.data);
+ memcpy(bf_tkey, ivec_bin.data, 8);
+ BF_cfb64_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret),
+ data_bin.size, &bf_key, bf_tkey, &bf_n,
+ (argv[3] == atom_true ? BF_ENCRYPT : BF_DECRYPT));
+ return ret;
+}
+
+static ERL_NIF_TERM bf_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Ivec, Data, IsEncrypt) */
+ ErlNifBinary key_bin, ivec_bin, data_bin;
+ BF_KEY bf_key; /* blowfish key 8 */
+ unsigned char bf_tkey[8]; /* blowfish ivec */
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin)
+ || !enif_inspect_binary(env, argv[1], &ivec_bin)
+ || ivec_bin.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)
+ || data_bin.size % 8 != 0) {
+ return enif_make_badarg(env);
+ }
+
+ BF_set_key(&bf_key, key_bin.size, key_bin.data);
+ memcpy(bf_tkey, ivec_bin.data, 8);
+ BF_cbc_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret),
+ data_bin.size, &bf_key, bf_tkey,
+ (argv[3] == atom_true ? BF_ENCRYPT : BF_DECRYPT));
+ return ret;
+}
+
+static ERL_NIF_TERM bf_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, Data, IsEncrypt) */
+ ErlNifBinary key_bin, data_bin;
+ BF_KEY bf_key; /* blowfish key 8 */
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin)
+ || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin)
+ || data_bin.size < 8) {
+ return enif_make_badarg(env);
+ }
+ BF_set_key(&bf_key, key_bin.size, key_bin.data);
+ BF_ecb_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret),
+ &bf_key, (argv[2] == atom_true ? BF_ENCRYPT : BF_DECRYPT));
+ return ret;
+}
+
+static ERL_NIF_TERM blowfish_ofb64_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{/* (Key, IVec, Data) */
+ ErlNifBinary key_bin, ivec_bin, data_bin;
+ BF_KEY bf_key; /* blowfish key 8 */
+ unsigned char bf_tkey[8]; /* blowfish ivec */
+ int bf_n = 0; /* blowfish ivec pos */
+ ERL_NIF_TERM ret;
+
+ if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin)
+ || !enif_inspect_binary(env, argv[1], &ivec_bin)
+ || ivec_bin.size != 8
+ || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)) {
+ return enif_make_badarg(env);
+ }
+
+ BF_set_key(&bf_key, key_bin.size, key_bin.data);
+ memcpy(bf_tkey, ivec_bin.data, 8);
+ BF_ofb64_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret),
+ data_bin.size, &bf_key, bf_tkey, &bf_n);
+ return ret;
+}
+
+
+
+#ifdef OPENSSL_THREADS /* vvvvvvvvvvvvvvv OPENSSL_THREADS vvvvvvvvvvvvvvvv */
+
+static INLINE void locking(int mode, ErlNifRWLock* lock)
+{
+ switch (mode) {
+ case CRYPTO_LOCK|CRYPTO_READ:
+ enif_rwlock_rlock(lock);
+ break;
+ case CRYPTO_LOCK|CRYPTO_WRITE:
+ enif_rwlock_rwlock(lock);
+ break;
+ case CRYPTO_UNLOCK|CRYPTO_READ:
+ enif_rwlock_runlock(lock);
+ break;
+ case CRYPTO_UNLOCK|CRYPTO_WRITE:
+ enif_rwlock_rwunlock(lock);
+ break;
+ default:
+ ASSERT(!"Invalid lock mode");
+ }
+}
+
+/* Callback from openssl for static locking
+ */
+static void locking_function(int mode, int n, const char *file, int line)
+{
+ ASSERT(n>=0 && n<CRYPTO_num_locks());
+
+ locking(mode, lock_vec[n]);
+}
+
+/* Callback from openssl for thread id
+ */
+static unsigned long id_function(void)
+{
+ return(unsigned long) enif_thread_self();
+}
+
+/* Callbacks for dynamic locking, not used by current openssl version (0.9.8)
+ */
+static struct CRYPTO_dynlock_value* dyn_create_function(const char *file, int line) {
+ return(struct CRYPTO_dynlock_value*) enif_rwlock_create("crypto_dyn");
+}
+static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value* ptr,const char *file, int line)
+{
+ locking(mode, (ErlNifRWLock*)ptr);
+}
+static void dyn_destroy_function(struct CRYPTO_dynlock_value *ptr, const char *file, int line)
+{
+ enif_rwlock_destroy((ErlNifRWLock*)ptr);
+}
+
+#endif /* ^^^^^^^^^^^^^^^^^^^^^^ OPENSSL_THREADS ^^^^^^^^^^^^^^^^^^^^^^ */
+
+/* HMAC */
+
+static void hmac_md5(unsigned char *key, int klen, unsigned char *dbuf, int dlen,
+ unsigned char *hmacbuf)
+{
+ MD5_CTX ctx;
+ char ipad[HMAC_INT_LEN];
+ char opad[HMAC_INT_LEN];
+ unsigned char nkey[MD5_LEN];
+ int i;
+
+ /* Change key if longer than 64 bytes */
+ if (klen > HMAC_INT_LEN) {
+ MD5(key, klen, nkey);
+ key = nkey;
+ klen = MD5_LEN;
+ }
+
+ memset(ipad, '\0', sizeof(ipad));
+ memset(opad, '\0', sizeof(opad));
+ memcpy(ipad, key, klen);
+ memcpy(opad, key, klen);
+
+ for (i = 0; i < HMAC_INT_LEN; i++) {
+ ipad[i] ^= HMAC_IPAD;
+ opad[i] ^= HMAC_OPAD;
+ }
+
+ /* inner MD5 */
+ MD5_Init(&ctx);
+ MD5_Update(&ctx, ipad, HMAC_INT_LEN);
+ MD5_Update(&ctx, dbuf, dlen);
+ MD5_Final((unsigned char *) hmacbuf, &ctx);
+ /* outer MD5 */
+ MD5_Init(&ctx);
+ MD5_Update(&ctx, opad, HMAC_INT_LEN);
+ MD5_Update(&ctx, hmacbuf, MD5_LEN);
+ MD5_Final((unsigned char *) hmacbuf, &ctx);
+}
+
+static void hmac_sha1(unsigned char *key, int klen,
+ unsigned char *dbuf, int dlen,
+ unsigned char *hmacbuf)
+{
+ SHA_CTX ctx;
+ char ipad[HMAC_INT_LEN];
+ char opad[HMAC_INT_LEN];
+ unsigned char nkey[SHA_LEN];
+ int i;
+
+ /* Change key if longer than 64 bytes */
+ if (klen > HMAC_INT_LEN) {
+ SHA1(key, klen, nkey);
+ key = nkey;
+ klen = SHA_LEN;
+ }
+
+ memset(ipad, '\0', sizeof(ipad));
+ memset(opad, '\0', sizeof(opad));
+ memcpy(ipad, key, klen);
+ memcpy(opad, key, klen);
+
+ for (i = 0; i < HMAC_INT_LEN; i++) {
+ ipad[i] ^= HMAC_IPAD;
+ opad[i] ^= HMAC_OPAD;
+ }
+
+ /* inner SHA */
+ SHA1_Init(&ctx);
+ SHA1_Update(&ctx, ipad, HMAC_INT_LEN);
+ SHA1_Update(&ctx, dbuf, dlen);
+ SHA1_Final((unsigned char *) hmacbuf, &ctx);
+ /* outer SHA */
+ SHA1_Init(&ctx);
+ SHA1_Update(&ctx, opad, HMAC_INT_LEN);
+ SHA1_Update(&ctx, hmacbuf, SHA_LEN);
+ SHA1_Final((unsigned char *) hmacbuf, &ctx);
+}
+
diff --git a/lib/crypto/c_src/crypto_drv.c b/lib/crypto/c_src/crypto_drv.c
deleted file mode 100644
index 8c1356c4cf..0000000000
--- a/lib/crypto/c_src/crypto_drv.c
+++ /dev/null
@@ -1,1817 +0,0 @@
-/*
- * %CopyrightBegin%
- *
- * Copyright Ericsson AB 1999-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: Dynamically loadable driver for cryptography libraries.
- * Based on OpenSSL.
- */
-
-#ifdef __WIN32__
-#include <windows.h>
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include "erl_driver.h"
-
-#define OPENSSL_THREAD_DEFINES
-#include <openssl/opensslconf.h>
-#ifndef OPENSSL_THREADS
-# ifdef __GNUC__
-# warning No thread support by openssl. Driver will use coarse grain locking.
-# endif
-#endif
-
-#include <openssl/crypto.h>
-#include <openssl/des.h>
-/* #include <openssl/idea.h> This is not supported on the openssl OTP requires */
-#include <openssl/dsa.h>
-#include <openssl/rsa.h>
-#include <openssl/aes.h>
-#include <openssl/md5.h>
-#include <openssl/md4.h>
-#include <openssl/sha.h>
-#include <openssl/bn.h>
-#include <openssl/objects.h>
-#include <openssl/rc4.h>
-#include <openssl/rc2.h>
-#include <openssl/blowfish.h>
-#include <openssl/rand.h>
-
-#ifdef VALGRIND
-# include <valgrind/memcheck.h>
-
-/* libcrypto mixes supplied buffer contents into its entropy pool,
- which makes valgrind complain about the use of uninitialized data.
- We use this valgrind "request" to make sure that no such seemingly
- undefined data escapes the driver.
-*/
-# define ERL_VALGRIND_MAKE_MEM_DEFINED(ptr,size) \
- VALGRIND_MAKE_MEM_DEFINED(ptr,size)
-
-# define ERL_VALGRIND_ASSERT_MEM_DEFINED(ptr,size) \
- ((void) ((VALGRIND_CHECK_MEM_IS_DEFINED(ptr,size) == 0) ? 1 : \
- (fprintf(stderr,"\r\n####### VALGRIND_ASSSERT(%p,%d) failed at %s:%d\r\n",\
- (ptr),(size), __FILE__, __LINE__), abort(), 0)))
-#else
-# define ERL_VALGRIND_MAKE_MEM_DEFINED(ptr,size)
-# define ERL_VALGRIND_ASSERT_MEM_DEFINED(ptr,size)
-#endif
-
-#ifdef DEBUG
-# define ASSERT(e) \
- ((void) ((e) ? 1 : (fprintf(stderr,"Assert '%s' failed at %s:%d\n",\
- #e, __FILE__, __LINE__), abort(), 0)))
-#else
-# define ASSERT(e) ((void) 1)
-#endif
-
-#ifdef __GNUC__
-# define INLINE __inline__
-#elif defined(__WIN32__)
-# define INLINE __forceinline
-#else
-# define INLINE
-#endif
-
-
-#define get_int32(s) ((((unsigned char*) (s))[0] << 24) | \
- (((unsigned char*) (s))[1] << 16) | \
- (((unsigned char*) (s))[2] << 8) | \
- (((unsigned char*) (s))[3]))
-
-#define put_int32(s,i) \
-{ (s)[0] = (char)(((i) >> 24) & 0xff);\
- (s)[1] = (char)(((i) >> 16) & 0xff);\
- (s)[2] = (char)(((i) >> 8) & 0xff);\
- (s)[3] = (char)((i) & 0xff);\
-}
-
-/* Driver interface declarations */
-static int init(void);
-static void finish(void);
-static ErlDrvData start(ErlDrvPort port, char *command);
-static void stop(ErlDrvData drv_data);
-static int crypto_control(ErlDrvData drv_data, unsigned int command, char *buf,
- int len, char **rbuf, int rlen);
-
-/* openssl callbacks */
-#ifdef OPENSSL_THREADS
-static void locking_function(int mode, int n, const char *file, int line);
-static unsigned long id_function(void);
-static struct CRYPTO_dynlock_value* dyn_create_function(const char *file,
- int line);
-static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value* ptr,
- const char *file, int line);
-static void dyn_destroy_function(struct CRYPTO_dynlock_value *ptr,
- const char *file, int line);
-#endif /* OPENSSL_THREADS */
-
-/* helpers */
-static void hmac_md5(char *key, int klen, char *dbuf, int dlen,
- char *hmacbuf);
-static void hmac_sha1(char *key, int klen, char *dbuf, int dlen,
- char *hmacbuf);
-
-static ErlDrvEntry crypto_driver_entry = {
- init,
- start,
- stop,
- NULL, /* output */
- NULL, /* ready_input */
- NULL, /* ready_output */
- "crypto_drv",
- finish,
- NULL, /* handle */
- crypto_control,
- NULL, /* timeout */
- NULL, /* outputv */
-
- NULL, /* ready_async */
- NULL, /* flush */
- NULL, /* call */
- NULL, /* event */
- ERL_DRV_EXTENDED_MARKER,
- ERL_DRV_EXTENDED_MAJOR_VERSION,
- ERL_DRV_EXTENDED_MINOR_VERSION,
-#ifdef OPENSSL_THREADS
- ERL_DRV_FLAG_USE_PORT_LOCKING,
-#else
- 0,
-#endif
- NULL, /* handle2 */
- NULL /* process_exit */
-};
-
-
-/* Keep the following definitions in alignment with the FUNC_LIST
- * in crypto.erl.
- */
-
-#define DRV_INFO 0
-#define DRV_MD5 1
-#define DRV_MD5_INIT 2
-#define DRV_MD5_UPDATE 3
-#define DRV_MD5_FINAL 4
-#define DRV_SHA 5
-#define DRV_SHA_INIT 6
-#define DRV_SHA_UPDATE 7
-#define DRV_SHA_FINAL 8
-#define DRV_MD5_MAC 9
-#define DRV_MD5_MAC_96 10
-#define DRV_SHA_MAC 11
-#define DRV_SHA_MAC_96 12
-#define DRV_CBC_DES_ENCRYPT 13
-#define DRV_CBC_DES_DECRYPT 14
-#define DRV_EDE3_CBC_DES_ENCRYPT 15
-#define DRV_EDE3_CBC_DES_DECRYPT 16
-#define DRV_AES_CFB_128_ENCRYPT 17
-#define DRV_AES_CFB_128_DECRYPT 18
-#define DRV_RAND_BYTES 19
-#define DRV_RAND_UNIFORM 20
-#define DRV_MOD_EXP 21
-#define DRV_DSS_VERIFY 22
-#define DRV_RSA_VERIFY_SHA 23
-/* #define DRV_RSA_VERIFY_MD5 35 */
-#define DRV_CBC_AES128_ENCRYPT 24
-#define DRV_CBC_AES128_DECRYPT 25
-#define DRV_XOR 26
-#define DRV_RC4_ENCRYPT 27 /* no decrypt needed; symmetric */
-#define DRV_RC4_SETKEY 28
-#define DRV_RC4_ENCRYPT_WITH_STATE 29
-#define DRV_CBC_RC2_40_ENCRYPT 30
-#define DRV_CBC_RC2_40_DECRYPT 31
-#define DRV_CBC_AES256_ENCRYPT 32
-#define DRV_CBC_AES256_DECRYPT 33
-#define DRV_INFO_LIB 34
-/* #define DRV_RSA_VERIFY_SHA 23 */
-#define DRV_RSA_VERIFY_MD5 35
-#define DRV_RSA_SIGN_SHA 36
-#define DRV_RSA_SIGN_MD5 37
-#define DRV_DSS_SIGN 38
-#define DRV_RSA_PUBLIC_ENCRYPT 39
-#define DRV_RSA_PRIVATE_DECRYPT 40
-#define DRV_RSA_PRIVATE_ENCRYPT 41
-#define DRV_RSA_PUBLIC_DECRYPT 42
-#define DRV_DH_GENERATE_PARAMS 43
-#define DRV_DH_CHECK 44
-#define DRV_DH_GENERATE_KEY 45
-#define DRV_DH_COMPUTE_KEY 46
-#define DRV_MD4 47
-#define DRV_MD4_INIT 48
-#define DRV_MD4_UPDATE 49
-#define DRV_MD4_FINAL 50
-
-#define SSL_VERSION_0_9_8 0
-#if SSL_VERSION_0_9_8
-#define DRV_SHA256 51
-#define DRV_SHA256_INIT 52
-#define DRV_SHA256_UPDATE 53
-#define DRV_SHA256_FINAL 54
-#define DRV_SHA512 55
-#define DRV_SHA512_INIT 56
-#define DRV_SHA512_UPDATE 57
-#define DRV_SHA512_FINAL 58
-#endif
-
-#define DRV_BF_CFB64_ENCRYPT 59
-#define DRV_BF_CFB64_DECRYPT 60
-#define DRV_BF_ECB_ENCRYPT 61
-#define DRV_BF_ECB_DECRYPT 62
-#define DRV_BF_OFB64_ENCRYPT 63
-#define DRV_BF_CBC_ENCRYPT 64
-#define DRV_BF_CBC_DECRYPT 65
-
-#define DRV_ECB_DES_ENCRYPT 66
-#define DRV_ECB_DES_DECRYPT 67
-
-/* #define DRV_CBC_IDEA_ENCRYPT 34 */
-/* #define DRV_CBC_IDEA_DECRYPT 35 */
-
-/* Not DRV_DH_GENERATE_PARAMS DRV_DH_CHECK
- * Calc RSA_VERIFY_* and RSA_SIGN once */
-#define NUM_CRYPTO_FUNCS 48
-
-#define MD5_CTX_LEN (sizeof(MD5_CTX))
-#define MD5_LEN 16
-#define MD5_LEN_96 12
-#define MD4_CTX_LEN (sizeof(MD4_CTX))
-#define MD4_LEN 16
-#define SHA_CTX_LEN (sizeof(SHA_CTX))
-#define SHA_LEN 20
-#define SHA_LEN_96 12
-#define HMAC_INT_LEN 64
-
-#define HMAC_IPAD 0x36
-#define HMAC_OPAD 0x5c
-
-#if SSL_VERSION_0_9_8
-#define SHA256_CTX_LEN (sizeof(SHA256_CTX))
-#define SHA256_LEN 32
-
-#define SHA512_CTX_LEN (sizeof(SHA512_CTX))
-#define SHA512_LEN 64
-#endif
-
-/* INITIALIZATION AFTER LOADING */
-
-/*
- * This is the init function called after this driver has been loaded.
- * It must *not* be declared static. Must return the address to
- * the driver entry.
- */
-
-#if !defined(__WIN32__)
-DRIVER_INIT(crypto_drv);
-#endif
-
-DRIVER_INIT(crypto_drv)
-{
- return &crypto_driver_entry;
-}
-
-static ErlDrvRWLock** lock_vec = NULL; /* Static locks used by openssl */
-
-/* DRIVER INTERFACE */
-
-static int init(void)
-{
- ErlDrvSysInfo sys_info;
- int i;
-
- CRYPTO_set_mem_functions(driver_alloc, driver_realloc, driver_free);
-
-#ifdef OPENSSL_THREADS
- driver_system_info(&sys_info, sizeof(sys_info));
-
- if(sys_info.scheduler_threads > 1) {
- lock_vec = driver_alloc(CRYPTO_num_locks()*sizeof(*lock_vec));
- if (lock_vec==NULL) return -1;
- memset(lock_vec,0,CRYPTO_num_locks()*sizeof(*lock_vec));
-
- for(i=CRYPTO_num_locks()-1; i>=0; --i) {
- lock_vec[i] = erl_drv_rwlock_create("crypto_drv_stat");
- if (lock_vec[i]==NULL) return -1;
- }
- CRYPTO_set_locking_callback(locking_function);
- CRYPTO_set_id_callback(id_function);
- CRYPTO_set_dynlock_create_callback(dyn_create_function);
- CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
- CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
- }
- /* else no need for locks */
-#endif /* OPENSSL_THREADS */
-
- return 0;
-}
-
-static void finish(void)
-{
- /* Moved here from crypto_control() as it's not thread safe */
- CRYPTO_cleanup_all_ex_data();
-
- if(lock_vec != NULL) {
- int i;
- for(i=CRYPTO_num_locks()-1; i>=0; --i) {
- if (lock_vec[i] != NULL) {
- erl_drv_rwlock_destroy(lock_vec[i]);
- }
- }
- driver_free(lock_vec);
- }
-}
-
-static ErlDrvData start(ErlDrvPort port, char *command)
-{
- set_port_control_flags(port, PORT_CONTROL_FLAG_BINARY);
- return 0; /* not used */
-}
-
-static void stop(ErlDrvData drv_data)
-{
- return;
-}
-
-/* Helper functions for 'crypto_control'
-*/
-static INLINE unsigned char* return_binary(char **rbuf, int rlen, int len)
-{
- if (len <= rlen) {
- return (unsigned char *) *rbuf;
- }
- else {
- ErlDrvBinary* bin;
- *rbuf = (char*) (bin = driver_alloc_binary(len));
- return (bin==NULL) ? NULL : (unsigned char *) bin->orig_bytes;
- }
-}
-
-static INLINE unsigned char* return_binary_shrink(char **rbuf, int rlen, unsigned char* data, int len)
-{
- if ((char *) data == *rbuf) { /* default buffer */
- ASSERT(len <= rlen);
- return (unsigned char *) data;
- }
- else {
- ErlDrvBinary* bin = (ErlDrvBinary*) *rbuf;
- *rbuf = (char*) (bin=driver_realloc_binary(bin, len));
- return (bin==NULL) ? NULL : (unsigned char *) bin->orig_bytes;
- }
-}
-
-/* Nowadays (R13) it does matter what value control returns
- * as it may return data in default buffer.
- */
-static int crypto_control(ErlDrvData drv_data, unsigned int command, char *buf,
- int len, char **rbuf, int rlen)
-{
- int klen, dlen, macsize, from_len, to_len, i;
- int base_len, exponent_len, modulo_len;
- int data_len, dsa_p_len, dsa_q_len;
- int dsa_s_len, dsa_g_len, dsa_y_len;
- int rsa_e_len, rsa_n_len, rsa_d_len, padding;
- int or_mask;
- int prime_len, generator;
- int privkey_len, pubkey_len, dh_p_len, dh_g_len;
- unsigned int rsa_s_len, j;
- char *key, *key2, *dbuf;
- unsigned char *p;
- const_DES_cblock *des_key, *des_key2, *des_key3;
- const unsigned char *des_dbuf;
- BIGNUM *bn_from, *bn_to, *bn_rand, *bn_result;
- BIGNUM *bn_base, *bn_exponent, *bn_modulo;
- BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_y;
- BIGNUM *rsa_n, *rsa_e, *rsa_d;
- BIGNUM *dh_p, *dh_g, *privkey, *pubkey;
- DES_cblock *des_ivec;
- unsigned char* bin;
- DES_key_schedule schedule, schedule2, schedule3;
- DH *dh_params;
-/* IDEA_KEY_SCHEDULE idea, idea2; */
- char hmacbuf[SHA_DIGEST_LENGTH];
- unsigned char *rsa_s, *dsa_s;
- /* char hmacbuf[SHA_LEN]; */
-#if SSL_VERSION_0_9_8
- SHA256_CTX sha256_ctx;
- SHA512_CTX sha512_ctx;
-#endif
- MD5_CTX md5_ctx;
- MD4_CTX md4_ctx;
- SHA_CTX sha_ctx;
- int new_ivlen = 0;
- BN_CTX *bn_ctx;
- DSA *dsa;
- RSA *rsa;
- AES_KEY aes_key;
- RC4_KEY rc4_key;
- RC2_KEY rc2_key;
-
- switch(command) {
-
- case DRV_INFO:
- bin = return_binary(rbuf,rlen,NUM_CRYPTO_FUNCS);
- if (bin==NULL) return -1;
-
- for (i = 0; i < NUM_CRYPTO_FUNCS; i++) {
- bin[i] = i + 1;
- }
- return NUM_CRYPTO_FUNCS;
-
- case DRV_MD5:
- bin = return_binary(rbuf,rlen,MD5_LEN);
- if (bin==NULL) return -1;
- MD5((unsigned char *) buf, len, bin);
- return MD5_LEN;
-
- case DRV_MD5_INIT:
- bin = return_binary(rbuf,rlen,MD5_CTX_LEN);
- if (bin==NULL) return -1;
- MD5_Init((MD5_CTX *)bin);
- return MD5_CTX_LEN;
-
- case DRV_MD5_UPDATE:
- if (len < MD5_CTX_LEN)
- return -1;
- bin = return_binary(rbuf,rlen,MD5_CTX_LEN);
- if (bin==NULL) return -1;
- memcpy(bin, buf, MD5_CTX_LEN);
- MD5_Update((MD5_CTX *)bin, buf + MD5_CTX_LEN,
- len - MD5_CTX_LEN);
- return MD5_CTX_LEN;
-
- case DRV_MD5_FINAL:
- if (len != MD5_CTX_LEN)
- return -1;
- memcpy(&md5_ctx, buf, MD5_CTX_LEN); /* XXX Use buf only? */
- bin = return_binary(rbuf,rlen,MD5_LEN);
- if (bin==NULL) return -1;
- MD5_Final(bin, &md5_ctx);
- return MD5_LEN;
-
- case DRV_SHA:
- bin = return_binary(rbuf,rlen,SHA_LEN);
- if (bin==NULL) return -1;
- SHA1((unsigned char *) buf, len, bin);
- return SHA_LEN;
-
- case DRV_SHA_INIT:
- bin = return_binary(rbuf,rlen,SHA_CTX_LEN);
- if (bin==NULL) return -1;
- SHA1_Init((SHA_CTX*)bin);
- return SHA_CTX_LEN;
-
- case DRV_SHA_UPDATE:
- if (len < SHA_CTX_LEN)
- return -1;
- bin = return_binary(rbuf,rlen,SHA_CTX_LEN);
- if (bin==NULL) return -1;
- memcpy(bin, buf, SHA_CTX_LEN);
- SHA1_Update((SHA_CTX*)bin, buf + SHA_CTX_LEN, len - SHA_CTX_LEN);
- return SHA_CTX_LEN;
-
- case DRV_SHA_FINAL:
- if (len != SHA_CTX_LEN)
- return -1;
- memcpy(&sha_ctx, buf, SHA_CTX_LEN); /* XXX Use buf only? */
- bin = return_binary(rbuf,rlen,SHA_LEN);
- if (bin==NULL) return -1;
- SHA1_Final(bin, &sha_ctx);
- return SHA_LEN;
-
- case DRV_MD5_MAC:
- case DRV_MD5_MAC_96:
- /* buf = klen[4] key data */
- klen = get_int32(buf);
- key = buf + 4;
- dlen = len - klen - 4;
- dbuf = key + klen;
- hmac_md5(key, klen, dbuf, dlen, hmacbuf);
- macsize = (command == DRV_MD5_MAC) ? MD5_LEN : MD5_LEN_96;
- bin = return_binary(rbuf,rlen,macsize);
- if (bin==NULL) return -1;
- memcpy(bin, hmacbuf, macsize);
- return macsize;
-
- case DRV_SHA_MAC:
- case DRV_SHA_MAC_96:
- /* buf = klen[4] key data */
- klen = get_int32(buf);
- key = buf + 4;
- dlen = len - klen - 4;
- dbuf = key + klen;
- hmac_sha1(key, klen, dbuf, dlen, hmacbuf);
- macsize = (command == DRV_SHA_MAC) ? SHA_LEN : SHA_LEN_96;
- bin = return_binary(rbuf,rlen,macsize);
- if (bin==NULL) return -1;
- memcpy(bin, (unsigned char *) hmacbuf, macsize);
- return macsize;
-
- case DRV_CBC_DES_ENCRYPT:
- case DRV_CBC_DES_DECRYPT:
- /* buf = key[8] ivec[8] data */
- dlen = len - 16;
- if (dlen < 0)
- return -1;
- if (dlen % 8 != 0)
- return -1;
- des_key = (const_DES_cblock*) buf;
- des_ivec = (DES_cblock*)(buf + 8);
- des_dbuf = (unsigned char *) (buf + 16);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- DES_set_key(des_key, &schedule);
- DES_ncbc_encrypt(des_dbuf, bin, dlen, &schedule, des_ivec,
- (command == DRV_CBC_DES_ENCRYPT));
- return dlen;
-
- case DRV_ECB_DES_ENCRYPT:
- case DRV_ECB_DES_DECRYPT:
- /* buf = key[8] data */
- dlen = len - 8;
- if (dlen != 8)
- return -1;
- des_key = (const_DES_cblock*) buf;
- des_dbuf = (unsigned char *) (buf + 8);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- DES_set_key(des_key, &schedule);
- DES_ecb_encrypt((const_DES_cblock*) des_dbuf, (DES_cblock*) bin, &schedule,
- (command == DRV_ECB_DES_ENCRYPT));
- return dlen;
-
- case DRV_BF_ECB_ENCRYPT:
- case DRV_BF_ECB_DECRYPT:
- {
- /* buf = klen[4] key data */
- int bf_direction;
- const unsigned char *ukey;
- const unsigned char *bf_dbuf; /* blowfish input data */
- BF_KEY bf_key; /* blowfish key 8 */
-
- klen = get_int32(buf);
- ukey = (unsigned char *) buf + 4;
- bf_dbuf = ukey + klen;
- dlen = len - 4 - klen;
- if (dlen < 0) return -1;
- BF_set_key(&bf_key, klen, ukey);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- bf_direction = command == DRV_BF_ECB_ENCRYPT ? BF_ENCRYPT : BF_DECRYPT;
- BF_ecb_encrypt(bf_dbuf, bin, &bf_key, bf_direction);
- return dlen;
- }
-
- case DRV_BF_CBC_ENCRYPT:
- case DRV_BF_CBC_DECRYPT:
- {
- /* buf = klen[4] key ivec[8] data */
- unsigned char *ukey;
- unsigned char* ivec;
- unsigned char bf_tkey[8]; /* blowfish ivec */
- int bf_direction;
- const unsigned char *bf_dbuf; /* blowfish input data */
- BF_KEY bf_key; /* blowfish key 8 */
-
- klen = get_int32(buf);
- ukey = (unsigned char *)buf + 4;
- ivec = ukey + klen;
- bf_dbuf = ivec + 8;
- dlen = len - 4 - klen - 8;
- if (dlen < 0) return -1;
- BF_set_key(&bf_key, klen, ukey);
- memcpy(bf_tkey, ivec, 8);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- bf_direction = command == DRV_BF_CBC_ENCRYPT ? BF_ENCRYPT : BF_DECRYPT;
- BF_cbc_encrypt(bf_dbuf, bin, dlen, &bf_key, bf_tkey, bf_direction);
- return dlen;
- }
-
- case DRV_BF_OFB64_ENCRYPT:
- {
- /* buf = klen[4] key ivec[8] data */
- unsigned char *ukey;
- unsigned char* ivec;
- unsigned char bf_tkey[8]; /* blowfish ivec */
- int bf_n; /* blowfish ivec pos */
- const unsigned char *bf_dbuf; /* blowfish input data */
- BF_KEY bf_key; /* blowfish key 8 */
-
- klen = get_int32(buf);
- ukey = (unsigned char *)buf + 4;
- ivec = ukey + klen;
- bf_dbuf = ivec + 8;
- dlen = len - 4 - klen - 8;
- if (dlen < 0) return -1;
- BF_set_key(&bf_key, klen, ukey);
- memcpy(bf_tkey, ivec, 8);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- bf_n = 0;
- BF_ofb64_encrypt(bf_dbuf, bin, dlen, &bf_key, bf_tkey, &bf_n);
- return dlen;
- }
-
- case DRV_BF_CFB64_ENCRYPT:
- case DRV_BF_CFB64_DECRYPT:
- {
- /* buf = klen[4] key ivec[8] data */
- unsigned char* ivec;
- unsigned char bf_tkey[8]; /* blowfish ivec */
- int bf_n; /* blowfish ivec pos */
- int bf_direction;
- const unsigned char *bf_dbuf; /* blowfish input data */
- BF_KEY bf_key; /* blowfish key 8 */
-
- klen = get_int32(buf);
- key = buf + 4;
- ivec = (unsigned char *) (key + klen);
- bf_dbuf = ivec + 8;
- dlen = len - 4 - klen - 8;
- if (dlen < 0) return -1;
- BF_set_key(&bf_key, klen, (unsigned char *) key);
- memcpy(bf_tkey, ivec, 8);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- bf_direction = command == DRV_BF_CFB64_ENCRYPT ? BF_ENCRYPT : BF_DECRYPT;
- bf_n = 0;
- BF_cfb64_encrypt(bf_dbuf, bin, dlen, &bf_key, bf_tkey, &bf_n, bf_direction);
- return dlen;
- }
-
-/* case DRV_CBC_IDEA_ENCRYPT: */
-/* case DRV_CBC_IDEA_DECRYPT: */
- /* buf = key[16] ivec[8] data */
-/* dlen = len - 24; */
-/* if (dlen < 0) */
-/* return -1; */
-/* if (dlen % 8 != 0) */
-/* return -1; */
-/* bin = return_binary(rbuf,rlen,dlen); */
-/* idea_set_encrypt_key(buf, &idea); */
-/* if (command == DRV_CBC_IDEA_DECRYPT) { */
-/* idea_set_decrypt_key(&idea, &idea2); */
-/* memcpy(&idea, &idea2, sizeof(idea)); */
-/* } */
-/* idea_cbc_encrypt(buf + 24, bin, dlen, &idea, buf + 8, */
-/* (command == DRV_CBC_IDEA_ENCRYPT)); */
-/* return dlen; */
-
- case DRV_CBC_RC2_40_ENCRYPT:
- case DRV_CBC_RC2_40_DECRYPT:
- /* buf = key[5] ivec[8] data */
- dlen = len - 13;
- if (dlen < 0)
- return -1;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- RC2_set_key(&rc2_key, 5, (unsigned char *) buf, 40);
- RC2_cbc_encrypt((unsigned char *) (buf + 13), bin, dlen, &rc2_key,
- (unsigned char *) (buf + 5),
- (command == DRV_CBC_RC2_40_ENCRYPT));
- return dlen;
-
- case DRV_EDE3_CBC_DES_ENCRYPT:
- case DRV_EDE3_CBC_DES_DECRYPT:
- dlen = len - 32;
- if (dlen < 0)
- return -1;
- des_key = (const_DES_cblock*) buf;
- des_key2 = (const_DES_cblock*) (buf + 8);
- des_key3 = (const_DES_cblock*) (buf + 16);
- des_ivec = (DES_cblock*) (buf + 24);
- des_dbuf = (unsigned char *) (buf + 32);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- DES_set_key(des_key, &schedule);
- DES_set_key(des_key2, &schedule2);
- DES_set_key(des_key3, &schedule3);
- DES_ede3_cbc_encrypt(des_dbuf, bin, dlen, &schedule,
- &schedule2, &schedule3, des_ivec,
- (command == DRV_EDE3_CBC_DES_ENCRYPT));
- return dlen;
-
- case DRV_AES_CFB_128_ENCRYPT:
- case DRV_AES_CFB_128_DECRYPT:
- /* buf = key[16] ivec[16] data */
- dlen = len - 32;
- if (dlen < 0)
- return -1;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- AES_set_encrypt_key((unsigned char *) buf, 128, &aes_key);
- AES_cfb128_encrypt((unsigned char *) (buf+32), bin, dlen, &aes_key,
- (unsigned char *) (buf+16), &new_ivlen,
- (command == DRV_AES_CFB_128_ENCRYPT));
- return dlen;
-
- case DRV_RC4_ENCRYPT:
- /* buf = klen[4] key data */
- klen = get_int32(buf);
- key = buf + 4;
- dlen = len - klen - 4;
- dbuf = key + klen;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- RC4_set_key(&rc4_key, klen, (unsigned char *) key);
- RC4(&rc4_key, dlen, (unsigned char *) dbuf, bin);
- return dlen;
-
- case DRV_RC4_SETKEY:
- /* buf = key */
- dlen = sizeof(rc4_key);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- RC4_set_key(&rc4_key, len, (unsigned char *) buf);
- memcpy(bin, &rc4_key, dlen);
- return dlen;
-
- case DRV_RC4_ENCRYPT_WITH_STATE:
- /* buf = statelength[4] state data, return statelength[4] state data */
- klen = get_int32(buf);
- key = buf + 4;
- dlen = len - klen - 4;
- dbuf = key + klen;
- bin = return_binary(rbuf,rlen,len);
- if (bin==NULL) return -1;
- memcpy(&rc4_key, key, klen);
- RC4(&rc4_key, dlen, (unsigned char *) dbuf, bin + klen + 4);
- memcpy(bin, buf, 4);
- memcpy(bin + 4, &rc4_key, klen);
- return len;
-
- case DRV_RAND_BYTES:
- /* buf = <<rlen:32/integer,topmask:8/integer,bottommask:8/integer>> */
-
- if (len != 6)
- return -1;
- dlen = get_int32(buf);
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- RAND_pseudo_bytes(bin,dlen);
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin, dlen);
- or_mask = ((unsigned char*)buf)[4];
- bin[dlen-1] |= or_mask; /* topmask */
- or_mask = ((unsigned char*)buf)[5];
- bin[0] |= or_mask; /* bottommask */
- return dlen;
-
- case DRV_RAND_UNIFORM:
- /* buf = <<from_len:32/integer,bn_from:from_len/binary, *
- * to_len:32/integer,bn_to:to_len/binary>> */
- if (len < 8)
- return -1;
- from_len = get_int32(buf);
- if (len < (8 + from_len))
- return -1;
- to_len = get_int32(buf + 4 + from_len);
- if (len != (8 + from_len + to_len))
- return -1;
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf, 4 + from_len + 4 + to_len);
- bn_from = BN_new();
- BN_bin2bn((unsigned char *)(buf + 4), from_len, bn_from);
- bn_rand = BN_new();
- BN_bin2bn((unsigned char *)(buf + 8 + from_len), to_len, bn_rand);
- bn_to = BN_new();
- BN_sub(bn_to, bn_rand, bn_from);
- BN_pseudo_rand_range(bn_rand, bn_to);
- BN_add(bn_rand, bn_rand, bn_from);
- dlen = BN_num_bytes(bn_rand);
- bin = return_binary(rbuf,rlen,dlen + 4);
- if (bin==NULL) return -1;
- put_int32(bin, dlen);
- BN_bn2bin(bn_rand,(unsigned char*)(bin + 4));
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+4, dlen);
- BN_free(bn_rand);
- BN_free(bn_from);
- BN_free(bn_to);
- return dlen + 4;
-
- case DRV_MOD_EXP:
- /* buf = <<base_len:32/integer,base/binary, *
- * exponent_len:32/integer,exponent/binary, *
- * modulo_len:32/integer, modulo/binary>> */
- if (len < 12)
- return -1;
- base_len = get_int32(buf);
- if (len < (12 + base_len))
- return -1;
- exponent_len = get_int32(buf + 4 + base_len);
- if (len < (12 + base_len + exponent_len))
- return -1;
- modulo_len = get_int32(buf + 8 + base_len + exponent_len);
- if (len != (12 + base_len + exponent_len + modulo_len))
- return -1;
- bn_base = BN_new();
- BN_bin2bn((unsigned char *)(buf + 4),
- base_len, bn_base);
- bn_exponent = BN_new();
- BN_bin2bn((unsigned char *)(buf + 8 + base_len),
- exponent_len, bn_exponent);
- bn_modulo = BN_new();
- BN_bin2bn((unsigned char *)(buf + 12 + base_len + exponent_len),
- modulo_len, bn_modulo);
- bn_result = BN_new();
- bn_ctx = BN_CTX_new();
- BN_mod_exp(bn_result, bn_base, bn_exponent,
- bn_modulo, bn_ctx);
- dlen = BN_num_bytes(bn_result);
- bin = return_binary(rbuf,rlen,dlen + 4);
- if (bin==NULL) return -1;
- put_int32(bin, dlen);
- BN_bn2bin(bn_result,(unsigned char*)(bin + 4));
- BN_free(bn_result);
- BN_free(bn_modulo);
- BN_free(bn_exponent);
- BN_free(bn_base);
- BN_CTX_free(bn_ctx);
- return dlen + 4;
-
- case DRV_DSS_VERIFY:
- /* buf = <<data_len:32/integer, data:data_len/binary,
- * dsa_s_len:32/integer, dsa_s:dsa_s_len/binary,
- * dsa_p_len:32/integer, dsa_p:dsa_p_len/binary,
- * dsa_q_len:32/integer, dsa_q:dsa_q_len/binary,
- * dsa_g_len:32/integer, dsa_g:dsa_g_len/binary,
- * dsa_y_len:32/integer, dsa_y:dsa_y_len/binary>> */
- i = 0;
- j = 0;
- if (len < 24)
- return -1;
- data_len = get_int32(buf + i + j);
- j += data_len; i += 4;
- if (len < (24 + j))
- return -1;
- dsa_s_len = get_int32(buf + i + j);
- j += dsa_s_len; i += 4;
- if (len < (24 + j))
- return -1;
- dsa_p_len = get_int32(buf + i + j);
- j += dsa_p_len; i += 4;
- if (len < (24 + j))
- return -1;
- dsa_q_len = get_int32(buf + i + j);
- j += dsa_q_len; i += 4;
- if (len < (24 + j))
- return -1;
- dsa_g_len = get_int32(buf + i + j);
- j += dsa_g_len; i += 4;
- if (len < (24 + j))
- return -1;
- dsa_y_len = get_int32(buf + i + j);
- j += dsa_y_len;
- if (len != (24 + j))
- return -1;
- i = 4;
- SHA1((unsigned char *) (buf + i), data_len, (unsigned char *) hmacbuf);
- i += data_len + 4;
- dsa_s = (unsigned char *)(buf + i);
- i += (dsa_s_len + 4);
- dsa_p = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_p_len, dsa_p);
- i += (dsa_p_len + 4);
- dsa_q = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_q_len, dsa_q);
- i += (dsa_q_len + 4);
- dsa_g = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_g_len, dsa_g);
- i += (dsa_g_len + 4);
- dsa_y = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_y_len, dsa_y);
- dsa = DSA_new();
- dsa->p = dsa_p;
- dsa->q = dsa_q;
- dsa->g = dsa_g;
- dsa->priv_key = NULL;
- dsa->pub_key = dsa_y;
- i = DSA_verify(0, (unsigned char *) hmacbuf, SHA_DIGEST_LENGTH,
- dsa_s, dsa_s_len, dsa);
- bin = return_binary(rbuf,rlen,1);
- if (bin==NULL) return -1;
-
- DSA_free(dsa);
- bin[0] = (i > 0) ? 1 : 0;
- return 1;
-
- case DRV_DSS_SIGN:
- /* buf = <<data_len:32/integer, data:data_len/binary,
- * dsa_p_len:32/integer, dsa_p:dsa_p_len/binary,
- * dsa_q_len:32/integer, dsa_q:dsa_q_len/binary,
- * dsa_g_len:32/integer, dsa_g:dsa_g_len/binary,
- * dsa_y_len:32/integer, dsa_y:dsa_y_len/binary,
- * dsa_x_len:32/integer, dsa_s:dsa_x_len/binary>> */
- i = 0;
- j = 0;
- if (len < 20)
- return -1;
- data_len = get_int32(buf + i + j);
- j += data_len; i += 4;
- if (len < (20 + j))
- return -1;
- dsa_p_len = get_int32(buf + i + j);
- j += dsa_p_len; i += 4;
- if (len < (20 + j))
- return -1;
- dsa_q_len = get_int32(buf + i + j);
- j += dsa_q_len; i += 4;
- if (len < (20 + j))
- return -1;
- dsa_g_len = get_int32(buf + i + j);
- j += dsa_g_len; i += 4;
- if (len < (20 + j))
- return -1;
- dsa_y_len = get_int32(buf + i + j);
- j += dsa_y_len;
- if (len < (20 + j))
- return -1;
- if (len != (20 + j))
- return -1;
-
- i = 4;
- SHA1((unsigned char *) (buf + i), data_len, (unsigned char *) hmacbuf);
- i += data_len + 4;
- dsa_p = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_p_len, dsa_p);
- i += (dsa_p_len + 4);
- dsa_q = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_q_len, dsa_q);
- i += (dsa_q_len + 4);
- dsa_g = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_g_len, dsa_g);
- i += (dsa_g_len + 4);
- dsa_y = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dsa_y_len, dsa_y);
- /* i += (dsa_y_len + 4); */
-
- dsa = DSA_new();
- dsa->p = dsa_p;
- dsa->q = dsa_q;
- dsa->g = dsa_g;
- dsa->priv_key = dsa_y;
- dsa->pub_key = NULL;
- dlen = DSA_size(dsa);
- bin = return_binary(rbuf,rlen, dlen+1);
- if (bin==NULL) return -1;
- i = DSA_sign(NID_sha1,
- (unsigned char *) hmacbuf,SHA_DIGEST_LENGTH,
- (unsigned char *) &bin[1],
- (unsigned int *) &dsa_s_len, dsa);
- DSA_free(dsa);
- if (i) {
- if (dsa_s_len != dlen) {
- bin = return_binary_shrink(rbuf,rlen,bin,dsa_s_len+1);
- }
- bin[0] = 1;
- return dsa_s_len + 1;
- }
- else {
- bin[0] = 0;
- return 1;
- }
-
- case DRV_RSA_VERIFY_MD5:
- case DRV_RSA_VERIFY_SHA:
- /* buf = <<data_len:32/integer, data:data_len/binary,
- * rsa_s_len:32/integer, rsa_s:rsa_s_len/binary,
- * rsa_e_len:32/integer, rsa_e:rsa_e_len/binary,
- * rsa_n_len:32/integer, rsa_n:rsa_n_len/binary>> */
- i = 0;
- j = 0;
- if (len < 16)
- return -1;
- data_len = get_int32(buf + i + j);
- j += data_len; i += 4;
- if (len < (16 + j))
- return -1;
- rsa_s_len = get_int32(buf + i + j);
- j += rsa_s_len; i += 4;
- if (len < (16 + j))
- return -1;
- rsa_e_len = get_int32(buf + i + j);
- j += rsa_e_len; i += 4;
- if (len < (16 + j))
- return -1;
- rsa_n_len = get_int32(buf + i + j);
- j += rsa_n_len; i += 4;
- if (len != (16 + j))
- return -1;
- i = 4;
- i += (data_len + 4);
- rsa_s = (unsigned char *)(buf + i);
- i += (rsa_s_len + 4);
- rsa_e = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), rsa_e_len, rsa_e);
- i += (rsa_e_len + 4);
- rsa_n = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), rsa_n_len, rsa_n);
- rsa = RSA_new();
- rsa->n = rsa_n;
- rsa->e = rsa_e;
- i = 4;
- if(command == DRV_RSA_VERIFY_SHA) {
- SHA1((unsigned char *) (buf + i), data_len,
- (unsigned char *) hmacbuf);
- i = RSA_verify(NID_sha1, (unsigned char *) hmacbuf, SHA_DIGEST_LENGTH,
- rsa_s, rsa_s_len, rsa);
- } else {
- MD5((unsigned char *) (buf + i), data_len, (unsigned char *) hmacbuf);
- i = RSA_verify(NID_md5, (unsigned char *) hmacbuf, MD5_DIGEST_LENGTH,
- rsa_s, rsa_s_len, rsa);
- }
-
- bin = return_binary(rbuf,rlen,1);
- if (bin==NULL) return -1;
- bin[0] = (char)(i & 0xff);
- RSA_free(rsa);
- return 1;
-
- case DRV_RSA_SIGN_MD5:
- case DRV_RSA_SIGN_SHA:
- /* buf = <<data_len:32/integer, data:data_len/binary,
- * rsa_e_len:32/integer, rsa_e:rsa_e_len/binary,
- * rsa_n_len:32/integer, rsa_n:rsa_n_len/binary,
- * rsa_d_len:32/integer, rsa_d:rsa_d_len/binary>> */
-
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf,len);
-
- i = 0;
- j = 0;
-
- if (len < 16)
- return -1;
- data_len = get_int32(buf + i + j);
- j += data_len; i += 4;
- if (len < (16 + j))
- return -1;
- rsa_e_len = get_int32(buf + i + j);
- j += rsa_e_len; i += 4;
- if (len < (16 + j))
- return -1;
- rsa_n_len = get_int32(buf + i + j);
- j += rsa_n_len; i += 4;
- if (len < (16 + j))
- return -1;
- rsa_d_len = get_int32(buf + i + j);
- j += rsa_d_len; i += 4;
- if (len != (16 + j))
- return -1;
-
- i = 4;
- i += (data_len + 4);
- rsa_e = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), rsa_e_len, rsa_e);
- i += (rsa_e_len + 4);
- rsa_n = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), rsa_n_len, rsa_n);
- i += (rsa_n_len + 4);
- rsa_d = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), rsa_d_len, rsa_d);
- i += (rsa_d_len + 4);
-
- rsa = RSA_new();
- rsa->e = rsa_e;
- rsa->n = rsa_n;
- rsa->d = rsa_d;
-
- dlen = RSA_size(rsa);
- bin = return_binary(rbuf,rlen,dlen+1);
- if (bin==NULL) return -1;
- i = 4;
- if (command == DRV_RSA_SIGN_MD5) {
- MD5((unsigned char *) (buf + i), data_len, (unsigned char *) hmacbuf);
- ERL_VALGRIND_ASSERT_MEM_DEFINED(hmacbuf, MD5_DIGEST_LENGTH);
- i = RSA_sign(NID_md5,
- (unsigned char *) hmacbuf,MD5_DIGEST_LENGTH,
- (unsigned char *) &bin[1],
- &rsa_s_len, rsa);
- } else {
- SHA1((unsigned char *) (buf + i), data_len,
- (unsigned char *) hmacbuf);
- ERL_VALGRIND_ASSERT_MEM_DEFINED(hmacbuf, SHA_DIGEST_LENGTH);
- i = RSA_sign(NID_sha1,
- (unsigned char *) hmacbuf,SHA_DIGEST_LENGTH,
- (unsigned char *) &bin[1],
- &rsa_s_len, rsa);
- }
- RSA_free(rsa);
- if (i) {
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+1, rsa_s_len);
- if (rsa_s_len != dlen) {
- bin = return_binary_shrink(rbuf,rlen,bin,rsa_s_len+1);
- ERL_VALGRIND_ASSERT_MEM_DEFINED(bin+1, rsa_s_len);
- }
- bin[0] = 1;
- return rsa_s_len + 1;
- }
- else {
- bin[0] = 0;
- return 1;
- }
-
- case DRV_RSA_PRIVATE_DECRYPT:
- case DRV_RSA_PRIVATE_ENCRYPT:
- /* buf = <<data_len:32/integer, data:data_len/binary,
- * rsa_e_len:32/integer, rsa_e:rsa_e_len/binary,
- * rsa_n_len:32/integer, rsa_n:rsa_n_len/binary,
- * rsa_d_len:32/integer, rsa_d:rsa_d_len/binary,
- * pad:8/integer >> */
-
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf,len);
- i = 0;
- j = 0;
-
- if (len < 17)
- return -1;
- data_len = get_int32(buf + i + j);
- j += data_len; i += 4;
- if (len < (17 + j))
- return -1;
- rsa_e_len = get_int32(buf + i + j);
- j += rsa_e_len; i += 4;
- if (len < (17 + j))
- return -1;
- rsa_n_len = get_int32(buf + i + j);
- j += rsa_n_len; i += 4;
- if (len < (17 + j))
- return -1;
- rsa_d_len = get_int32(buf + i + j);
- j += rsa_d_len; i += 4;
- padding = *(unsigned char *) (buf+i+j);
- if (len != (17 + j))
- return -1;
-
- i = 4;
- i += (data_len + 4);
- rsa_e = BN_new();
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,rsa_e_len);
- BN_bin2bn((unsigned char *)(buf + i), rsa_e_len, rsa_e);
- i += (rsa_e_len + 4);
- rsa_n = BN_new();
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,rsa_n_len);
- BN_bin2bn((unsigned char *)(buf + i), rsa_n_len, rsa_n);
- i += (rsa_n_len + 4);
- rsa_d = BN_new();
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,rsa_d_len);
- BN_bin2bn((unsigned char *)(buf + i), rsa_d_len, rsa_d);
- i += (rsa_d_len + 4);
-
- switch(padding) {
- case 0:
- padding = RSA_NO_PADDING;
- break;
- case 1:
- padding = RSA_PKCS1_PADDING;
- break;
- case 2:
- padding = RSA_PKCS1_OAEP_PADDING;
- break;
- case 3:
- padding = RSA_SSLV23_PADDING;
- break;
- default:
- return -1;
- }
-
- rsa = RSA_new();
- rsa->e = rsa_e;
- rsa->n = rsa_n;
- rsa->d = rsa_d;
-
- dlen = RSA_size(rsa) + 1;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- i = 4;
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,data_len);
- if(command == DRV_RSA_PRIVATE_DECRYPT) {
- i = RSA_private_decrypt(data_len, (unsigned char *) (buf+i),
- (unsigned char *) &bin[1],
- rsa, padding);
- if(i > 0) {
- ERL_VALGRIND_MAKE_MEM_DEFINED(&bin[1],i);
- bin = return_binary_shrink(rbuf,rlen, bin, i+1);
- if (bin==NULL) return -1;
- }
- } else {
- i = RSA_private_encrypt(data_len, (unsigned char *) (buf+i),
- (unsigned char *) &bin[1],
- rsa, padding);
- if(i > 0) {
- ERL_VALGRIND_MAKE_MEM_DEFINED(&bin[1],i);
- }
- }
- RSA_free(rsa);
- if(i > 0) {
- bin[0] = 1;
- return i + 1;
- } else {
- bin[0] = 0;
- return 1;
- }
- break;
-
- case DRV_RSA_PUBLIC_ENCRYPT:
- case DRV_RSA_PUBLIC_DECRYPT:
- /* buf = <<data_len:32/integer, data:data_len/binary,
- * rsa_e_len:32/integer, rsa_e:rsa_e_len/binary,
- * rsa_n_len:32/integer, rsa_n:rsa_n_len/binary,
- * pad:8/integer >> */
-
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf,len);
- i = 0;
- j = 0;
-
- if (len < 13)
- return -1;
- data_len = get_int32(buf + i + j);
- j += data_len; i += 4;
- if (len < (13 + j))
- return -1;
- rsa_e_len = get_int32(buf + i + j);
- j += rsa_e_len; i += 4;
- if (len < (13 + j))
- return -1;
- rsa_n_len = get_int32(buf + i + j);
- j += rsa_n_len; i += 4;
- if (len < (13 + j))
- return -1;
- padding = *(unsigned char *) (buf + i + j);
- if (len != (13 + j))
- return -1;
-
- i = 4;
- i += (data_len + 4);
- rsa_e = BN_new();
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,rsa_e_len);
- BN_bin2bn((unsigned char *)(buf + i), rsa_e_len, rsa_e);
- i += (rsa_e_len + 4);
- rsa_n = BN_new();
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,rsa_n_len);
- BN_bin2bn((unsigned char *)(buf + i), rsa_n_len, rsa_n);
- i += (rsa_n_len + 4);
-
- switch(padding) {
- case 0:
- padding = RSA_NO_PADDING;
- break;
- case 1:
- padding = RSA_PKCS1_PADDING;
- break;
- case 2:
- padding = RSA_PKCS1_OAEP_PADDING;
- break;
- case 3:
- padding = RSA_SSLV23_PADDING;
- break;
- default:
- return -1;
- }
-
- rsa = RSA_new();
- rsa->e = rsa_e;
- rsa->n = rsa_n;
-
- dlen = RSA_size(rsa) + 1;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- i = 4;
- if(command == DRV_RSA_PUBLIC_ENCRYPT) {
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf+i,data_len);
- i = RSA_public_encrypt(data_len, (unsigned char *) (buf+i),
- (unsigned char *) &bin[1],
- rsa, padding);
- if (i > 0) {
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+1, i);
- }
- } else {
- i = RSA_public_decrypt(data_len, (unsigned char *) (buf+i),
- (unsigned char *) &bin[1],
- rsa, padding);
- if(i > 0) {
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+1, i);
- bin = return_binary_shrink(rbuf,rlen,bin, i+1);
- if (bin==NULL) return -1;
- }
- }
-
- RSA_free(rsa);
- if(i > 0) {
- bin[0] = 1;
- return i + 1;
- } else {
-/* ERR_load_crypto_strings(); */
-/* fprintf(stderr, "%d: %s \r\n", __LINE__, ERR_reason_error_string(ERR_get_error())); */
- bin[0] = 0;
- return 1;
- }
- break;
-
- case DRV_CBC_AES128_ENCRYPT:
- case DRV_CBC_AES256_ENCRYPT:
- case DRV_CBC_AES128_DECRYPT:
- case DRV_CBC_AES256_DECRYPT:
- /* buf = key[klen] ivec[klen] data */
- if (command == DRV_CBC_AES256_ENCRYPT || command == DRV_CBC_AES256_DECRYPT)
- klen = 32;
- else
- klen = 16;
- dlen = len - klen - 16;
- if (dlen < 0)
- return -1;
- if (dlen % 16 != 0)
- return -1;
- if (command == DRV_CBC_AES128_ENCRYPT || command == DRV_CBC_AES256_ENCRYPT) {
- i = AES_ENCRYPT;
- AES_set_encrypt_key((unsigned char *) buf, klen*8, &aes_key);
- } else {
- i = AES_DECRYPT;
- AES_set_decrypt_key((unsigned char *) buf, klen*8, &aes_key);
- }
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- AES_cbc_encrypt((unsigned char *) (buf + klen+16),
- (unsigned char *) bin,
- dlen,
- &aes_key,
- (unsigned char *) (buf + klen),
- i);
- return dlen;
-
-/* case DRV_CBC_AES128_DECRYPT: */
-/* case DRV_CBC_AES256_DECRYPT: */
-/* /\* buf = key[klen] ivec[16] data *\/ */
-/* if (command == DRV_CBC_AES256_DECRYPT) */
-/* klen = 32; */
-/* else */
-/* klen = 16; */
-/* dlen = len - klen - 16; */
-/* if (dlen < 0) */
-/* return -1; */
-/* *rbuf = (char *)(bin = driver_alloc_binary(dlen)); */
-/* AES_set_decrypt_key((unsigned char *) buf, klen*8, &aes_key); */
-/* AES_cbc_encrypt((unsigned char *) (buf + klen+16), */
-/* (unsigned char *) bin->orig_bytes, */
-/* dlen, */
-/* &aes_key, */
-/* (unsigned char *) (buf + klen), */
-/* AES_DECRYPT); */
-/* return dlen; */
-/* break; */
-
- case DRV_XOR:
- /* buf = data1, data2 with same size */
- dlen = len / 2;
- if (len != dlen * 2)
- return -1;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- p = bin,
- dbuf = buf + dlen;
- for (key = buf, key2 = dbuf; key != dbuf; ++key, ++key2, ++p)
- *p = *key ^ *key2;
- return dlen;
-
- case DRV_DH_GENERATE_PARAMS:
- /* buf = <<PrimeLen:32 Generator:32>> */
- if (len != 8)
- return -1;
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf,len);
- prime_len = get_int32(buf);
- generator = get_int32(buf+4);
- dh_params = DH_generate_parameters(prime_len, generator, NULL, NULL);
-
- if(dh_params) {
- dh_p_len = BN_num_bytes(dh_params->p);
- dh_g_len = BN_num_bytes(dh_params->g);
- dlen = 1 + 4 + 4 + dh_g_len + dh_p_len;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- bin[0] = 1;
- put_int32(bin+1, dh_p_len);
- BN_bn2bin(dh_params->p, bin+5);
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+5,dh_p_len);
- put_int32(bin+5+dh_p_len, dh_g_len);
- BN_bn2bin(dh_params->g, bin+5+dh_p_len+4);
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+5+dh_p_len+4,dh_g_len);
- } else {
- dlen = 1;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- bin[0] = 0;
- }
- DH_free(dh_params);
- return dlen;
-
- case DRV_DH_CHECK:
- /* buf = <<dh_p_len:32/integer, dh_p:dh_p_len/binary,
- * dh_g_len:32/integer, dh_g:dh_g_len/binary>> */
- i = 0;
- j = 0;
- if(len < 8) return -1;
- dh_p_len = get_int32(buf + i + j);
- j += dh_p_len; i += 4;
- if (len < (8 + j)) return -1;
- dh_g_len = get_int32(buf + i + j);
- j += dh_g_len; i += 4;
- if(len != (8+j)) return -1;
- i=4;
- dh_p = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dh_p_len, dh_p);
- i += (dh_p_len + 4);
- dh_g = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dh_g_len, dh_g);
- /* i += (dsa_g_len + 4); */
-
- dh_params = DH_new();
- dh_params->p = dh_p;
- dh_params->g = dh_g;
-
- i=0;
- bin = return_binary(rbuf,rlen,4);
- if (bin==NULL) return -1;
- if(DH_check(dh_params, &i)) {
- put_int32(bin, i);
- } else {
- /* Check Failed */
- put_int32(bin, -1);
- }
- DH_free(dh_params);
- return 4;
-
- case DRV_DH_GENERATE_KEY:
- /* buf = <<key_len:32, key:key_len/binary, *
- * dh_p_len:32/integer, dh_p:dh_p_len/binary, *
- * dh_g_len:32/integer, dh_g:dh_g_len/binary>> */
- ERL_VALGRIND_ASSERT_MEM_DEFINED(buf,len);
- i = 0;
- j = 0;
- if(len < 12) return -1;
- base_len = get_int32(buf + i + j);
- j += base_len; i += 4;
- if (len < (12 + j)) return -1;
- dh_p_len = get_int32(buf + i + j);
- j += dh_p_len; i += 4;
- if (len < (12 + j)) return -1;
- dh_g_len = get_int32(buf + i + j);
- j += dh_g_len; i += 4;
- if(len != (12 + j)) return -1;
- i=4;
- i += (base_len + 4);
- dh_p = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dh_p_len, dh_p);
- i += (dh_p_len + 4);
- dh_g = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dh_g_len, dh_g);
- /* i += (dsa_g_len + 4); */
-
- dh_params = DH_new();
- dh_params->p = dh_p;
- dh_params->g = dh_g;
- if(base_len > 0) {
- dh_params->priv_key = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), base_len,
- dh_params->priv_key);
- }
- i=0;
- if(DH_generate_key(dh_params)) {
- privkey_len = BN_num_bytes(dh_params->priv_key);
- pubkey_len = BN_num_bytes(dh_params->pub_key);
- dlen = 1 + 4 + 4 + pubkey_len + privkey_len;
- bin = return_binary(rbuf,rlen, dlen);
- if (bin==NULL) return -1;
- bin[0] = 1;
- put_int32(bin+1, pubkey_len);
- BN_bn2bin(dh_params->pub_key, bin+5);
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+5, pubkey_len);
- put_int32(bin+5+pubkey_len, privkey_len);
- BN_bn2bin(dh_params->priv_key, bin+5+pubkey_len+4);
- ERL_VALGRIND_MAKE_MEM_DEFINED(bin+5+pubkey_len+4, privkey_len);
- } else {
- dlen = 1;
- bin = return_binary(rbuf,rlen,dlen);
- if (bin==NULL) return -1;
- bin[0] = 0;
- }
- DH_free(dh_params);
- return dlen;
-
- case DRV_DH_COMPUTE_KEY:
- /* buf = <<pubkey_len:32, pubkey:pubkey_len/binary, *
- * privkey_len:32, privkey:privkey_len/binary, *
- * dh_p_len:32/integer, dh_p:dh_p_len/binary, *
- * dh_g_len:32/integer, dh_g:dh_g_len/binary>> */
- i = 0;
- j = 0;
- if(len < 16) return -1;
- pubkey_len = get_int32(buf + i + j);
- j += pubkey_len; i += 4;
- if (len < (16 + j)) return -1;
- privkey_len = get_int32(buf + i + j);
- j += privkey_len; i += 4;
- if (len < (16 + j)) return -1;
- dh_p_len = get_int32(buf + i + j);
- j += dh_p_len; i += 4;
- if (len < (16 + j)) return -1;
- dh_g_len = get_int32(buf + i + j);
- j += dh_g_len; i += 4;
- if(len != (16 + j)) return -1;
- i=4;
- pubkey = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), pubkey_len, pubkey);
- i += (pubkey_len + 4);
- privkey = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), privkey_len, privkey);
- i += (privkey_len + 4);
- dh_p = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dh_p_len, dh_p);
- i += (dh_p_len + 4);
- dh_g = BN_new();
- BN_bin2bn((unsigned char *)(buf + i), dh_g_len, dh_g);
- /* i += (dsa_g_len + 4); */
-
- dh_params = DH_new();
- dh_params->p = dh_p;
- dh_params->g = dh_g;
- dh_params->priv_key = privkey;
-
- klen = DH_size(dh_params);
- bin = return_binary(rbuf,rlen,1+klen);
- if (bin==NULL) return -1;
- i = DH_compute_key(&bin[1], pubkey, dh_params);
- DH_free(dh_params);
- if (i > 0) {
- if (i != klen) {
- bin = return_binary_shrink(rbuf,rlen,bin,1+i);
- }
- bin[0] = 1;
- return i + 1;
- }
- else {
- bin[0] = 0;
- return 1;
- }
-
- case DRV_MD4:
- bin = return_binary(rbuf,rlen,MD4_LEN);
- MD4((unsigned char *)buf, len, (unsigned char *)bin);
- return MD4_LEN;
-
- case DRV_MD4_INIT:
- bin = return_binary(rbuf,rlen,MD4_CTX_LEN);
- MD4_Init((MD4_CTX *) bin);
- return MD4_CTX_LEN;
-
- case DRV_MD4_UPDATE:
- if (len < MD4_CTX_LEN)
- return -1;
- bin = return_binary(rbuf,rlen,MD4_CTX_LEN);
- memcpy(bin, buf, MD4_CTX_LEN);
- MD4_Update((MD4_CTX *) bin, buf + MD4_CTX_LEN, len - MD4_CTX_LEN);
- return MD4_CTX_LEN;
-
- case DRV_MD4_FINAL:
- if (len != MD4_CTX_LEN)
- return -1;
- memcpy(&md4_ctx, buf, MD4_CTX_LEN); /* XXX Use buf only? */
- bin = return_binary(rbuf,rlen,MD4_LEN);
- MD4_Final((unsigned char *)bin, &md4_ctx);
- return MD4_LEN;
-
-#if SSL_VERSION_0_9_8
- case DRV_SHA256:
- bin = return_binary(rbuf,rlen,SHA256_LEN);
- SHA256(buf, len, bin);
- return SHA256_LEN;
-
- case DRV_SHA256_INIT:
- bin = return_binary(rbuf,rlen,SHA256_CTX_LEN);
- SHA256_Init((SHA256_CTX *)bin);
- return SHA256_CTX_LEN;
-
- case DRV_SHA256_UPDATE:
- if (len < SHA256_CTX_LEN)
- return -1;
- bin = return_binary(rbuf,rlen,SHA256_CTX_LEN);
- memcpy(bin, buf, SHA256_CTX_LEN);
- SHA256_Update((SHA256_CTX *)bin, buf + SHA256_CTX_LEN,
- len - SHA256_CTX_LEN);
- return SHA256_CTX_LEN;
-
- case DRV_SHA256_FINAL:
- if (len != SHA256_CTX_LEN)
- return -1;
- memcpy(&sha256_ctx, buf, SHA256_CTX_LEN); /* XXX Use buf only? */
- bin = return_binary(rbuf,rlen,SHA256_LEN);
- SHA256_Final(bin, &sha256_ctx);
- return SHA256_LEN;
-
- case DRV_SHA512:
- bin = return_binary(rbuf,rlen,SHA512_LEN);
- SHA512(buf, len, bin);
- return SHA512_LEN;
-
- case DRV_SHA512_INIT:
- bin = return_binary(rbuf,rlen,SHA512_CTX_LEN);
- SHA512_Init((SHA512_CTX *)bin);
- return SHA512_CTX_LEN;
-
- case DRV_SHA512_UPDATE:
- if (len < SHA512_CTX_LEN)
- return -1;
- bin = return_binary(rbuf,rlen,SHA512_CTX_LEN);
- memcpy(bin, buf, SHA512_CTX_LEN);
- SHA512_Update((SHA512_CTX *)bin, buf + SHA512_CTX_LEN,
- len - SHA512_CTX_LEN);
- return SHA512_CTX_LEN;
-
- case DRV_SHA512_FINAL:
- if (len != SHA512_CTX_LEN)
- return -1;
- memcpy(&sha512_ctx, buf, SHA512_CTX_LEN); /* XXX Use buf only? */
- bin = return_binary(rbuf,rlen,SHA512_LEN));
- SHA512_Final(bin, &sha512_ctx);
- return SHA512_LEN;
-#endif
-
- case DRV_INFO_LIB:
- {/* <<DrvVer:8, NameSize:8, Name:NameSize/binary, VerNum:32, VerStr/binary>> */
- static const char libname[] = "OpenSSL";
- unsigned name_sz = strlen(libname);
- const char* ver = SSLeay_version(SSLEAY_VERSION);
- unsigned ver_sz = strlen(ver);
- dlen = 1+1+name_sz+4+ver_sz;
- bin = return_binary(rbuf, rlen, dlen);
- if (bin==NULL) return -1;
- p = bin;
- *p++ = 0; /* "driver version" for future use */
- *p++ = name_sz;
- memcpy(p, libname, name_sz);
- p += name_sz;
- put_int32(p,SSLeay()); /* OPENSSL_VERSION_NUMBER */
- p += 4;
- memcpy(p, ver, ver_sz);
- }
- return dlen;
-
- default:
- break;
- }
- return -1;
-}
-
-
-#ifdef OPENSSL_THREADS /* vvvvvvvvvvvvvvv OPENSSL_THREADS vvvvvvvvvvvvvvvv */
-
-static INLINE void locking(int mode, ErlDrvRWLock* lock)
-{
- switch(mode) {
- case CRYPTO_LOCK|CRYPTO_READ:
- erl_drv_rwlock_rlock(lock);
- break;
- case CRYPTO_LOCK|CRYPTO_WRITE:
- erl_drv_rwlock_rwlock(lock);
- break;
- case CRYPTO_UNLOCK|CRYPTO_READ:
- erl_drv_rwlock_runlock(lock);
- break;
- case CRYPTO_UNLOCK|CRYPTO_WRITE:
- erl_drv_rwlock_rwunlock(lock);
- break;
- default:
- ASSERT(!"Invalid lock mode");
- }
-}
-
-/* Callback from openssl for static locking
- */
-static void locking_function(int mode, int n, const char *file, int line)
-{
- ASSERT(n>=0 && n<CRYPTO_num_locks());
-
- locking(mode, lock_vec[n]);
-}
-
-/* Callback from openssl for thread id
- */
-static unsigned long id_function(void)
-{
- return (unsigned long) erl_drv_thread_self();
-}
-
-/* Callbacks for dynamic locking, not used by current openssl version (0.9.8)
- */
-static struct CRYPTO_dynlock_value* dyn_create_function(const char *file, int line)
-{
- return (struct CRYPTO_dynlock_value*) erl_drv_rwlock_create("crypto_drv_dyn");
-}
-static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value* ptr,const char *file, int line)
-{
- locking(mode, (ErlDrvRWLock*)ptr);
-}
-static void dyn_destroy_function(struct CRYPTO_dynlock_value *ptr, const char *file, int line)
-{
- erl_drv_rwlock_destroy((ErlDrvRWLock*)ptr);
-}
-
-#endif /* ^^^^^^^^^^^^^^^^^^^^^^ OPENSSL_THREADS ^^^^^^^^^^^^^^^^^^^^^^ */
-
-/* HMAC */
-
-static void hmac_md5(char *key, int klen, char *dbuf, int dlen, char *hmacbuf)
-{
- MD5_CTX ctx;
- char ipad[HMAC_INT_LEN];
- char opad[HMAC_INT_LEN];
- unsigned char nkey[MD5_LEN];
- int i;
-
- /* Change key if longer than 64 bytes */
- if (klen > HMAC_INT_LEN) {
- MD5_CTX kctx;
-
- MD5_Init(&kctx);
- MD5_Update(&kctx, key, klen);
- MD5_Final(nkey, &kctx);
- key = (char *) nkey;
- klen = MD5_LEN;
- }
-
- memset(ipad, '\0', sizeof(ipad));
- memset(opad, '\0', sizeof(opad));
- memcpy(ipad, key, klen);
- memcpy(opad, key, klen);
-
- for (i = 0; i < HMAC_INT_LEN; i++) {
- ipad[i] ^= HMAC_IPAD;
- opad[i] ^= HMAC_OPAD;
- }
-
- /* inner MD5 */
- MD5_Init(&ctx);
- MD5_Update(&ctx, ipad, HMAC_INT_LEN);
- MD5_Update(&ctx, dbuf, dlen);
- MD5_Final((unsigned char *) hmacbuf, &ctx);
- /* outer MD5 */
- MD5_Init(&ctx);
- MD5_Update(&ctx, opad, HMAC_INT_LEN);
- MD5_Update(&ctx, hmacbuf, MD5_LEN);
- MD5_Final((unsigned char *) hmacbuf, &ctx);
-}
-
-static void hmac_sha1(char *key, int klen, char *dbuf, int dlen,
- char *hmacbuf)
-{
- SHA_CTX ctx;
- char ipad[HMAC_INT_LEN];
- char opad[HMAC_INT_LEN];
- unsigned char nkey[SHA_LEN];
- int i;
-
- /* Change key if longer than 64 bytes */
- if (klen > HMAC_INT_LEN) {
- SHA_CTX kctx;
-
- SHA1_Init(&kctx);
- SHA1_Update(&kctx, key, klen);
- SHA1_Final(nkey, &kctx);
- key = (char *) nkey;
- klen = SHA_LEN;
- }
-
- memset(ipad, '\0', sizeof(ipad));
- memset(opad, '\0', sizeof(opad));
- memcpy(ipad, key, klen);
- memcpy(opad, key, klen);
-
- for (i = 0; i < HMAC_INT_LEN; i++) {
- ipad[i] ^= HMAC_IPAD;
- opad[i] ^= HMAC_OPAD;
- }
-
- /* inner SHA */
- SHA1_Init(&ctx);
- SHA1_Update(&ctx, ipad, HMAC_INT_LEN);
- SHA1_Update(&ctx, dbuf, dlen);
- SHA1_Final((unsigned char *) hmacbuf, &ctx);
- /* outer SHA */
- SHA1_Init(&ctx);
- SHA1_Update(&ctx, opad, HMAC_INT_LEN);
- SHA1_Update(&ctx, hmacbuf, SHA_LEN);
- SHA1_Final((unsigned char *) hmacbuf, &ctx);
-}
diff --git a/lib/crypto/priv/Makefile b/lib/crypto/priv/Makefile
index b8acdacc00..0989f14c94 100644
--- a/lib/crypto/priv/Makefile
+++ b/lib/crypto/priv/Makefile
@@ -18,21 +18,21 @@
# ----------------------------------------------------
# THIS MAKEFILE SERVES AS AN EXAMPLE OF
-# HOW TO RELINK THE CRYPTO DRIVER
+# HOW TO RELINK THE CRYPTO NIF LIBRARY
# ----------------------------------------------------
# ----------------------------------------------------
-# Variables for linking a .so driver on unix.
+# Variables for linking a .so library on unix.
# Note: These may differ between systems.
# ----------------------------------------------------
SO_LD = gcc
SO_LDFLAGS = -G
SO_SSL_LIBDIR = /usr/local/lib
-SO_DRIVER = $(LIBDIR)/$(DRIVER_NAME).so
+SO_NIFLIB = $(LIBDIR)/$(LIB_NAME).so
# ----------------------------------------------------
-# Variables for linking a win32 .dll driver.
+# Variables for linking a win32 .dll library.
# Note: These may differ between systems.
# ----------------------------------------------------
@@ -42,9 +42,9 @@ DLL_LIBDIR = "c:\\OpenSSL\\lib\\VC"
DLL_LIBS = libeay32.lib MSVCRT.LIB kernel32.lib \
advapi32.lib gdi32.lib user32.lib \
comctl32.lib comdlg32.lib shell32.lib
-DLL_DRIVER = $(LIBDIR)/$(DRIVER_NAME).dll
-DLL_EXP = $(LIBDIR)/$(DRIVER_NAME).exp
-DLL_LIB = $(LIBDIR)/$(DRIVER_NAME).lib
+DLL_NIFLIB = $(LIBDIR)/$(LIB_NAME).dll
+DLL_EXP = $(LIBDIR)/$(LIB_NAME).exp
+DLL_LIB = $(LIBDIR)/$(LIB_NAME).lib
# ----------------------------------------------------
# Common variables
@@ -52,27 +52,27 @@ DLL_LIB = $(LIBDIR)/$(DRIVER_NAME).lib
OBJDIR = ./
LIBDIR = ../lib
-DRIVER_NAME = crypto_drv
-OBJS = $(OBJDIR)/crypto_drv.o
+LIB_NAME = crypto
+OBJS = $(OBJDIR)/crypto.o
# ----------------------------------------------------
# Targets
# ----------------------------------------------------
-$(SO_DRIVER): $(OBJS)
+$(SO_NIFLIB): $(OBJS)
$(SO_LD) $(SO_LDFLAGS) -L$(SO_SSL_LIBDIR) -Wl,-R$(SO_SSL_LIBDIR) \
-o $@ $^ -lcrypto
-$(DLL_DRIVER): $(OBJS)
+$(DLL_NIFLIB): $(OBJS)
$(DLL_LD) $(DLL_LDFLAGS) -out:$@ -libpath:$(DLL_LIBDIR) $(OBJS) \
$(DLL_LIBS)
-so: $(SO_DRIVER)
+so: $(SO_NIFLIB)
-dll: $(DLL_DRIVER)
+dll: $(DLL_NIFLIB)
clean:
- rm -f $(SO_DRIVER) $(DLL_DRIVER)
+ rm -f $(SO_NIFLIB) $(DLL_NIFLIB)
rm -f $(DLL_EXP) $(DLL_LIB)
rm -f core *~
diff --git a/lib/crypto/src/Makefile b/lib/crypto/src/Makefile
index 51092d16a5..0e886ce8bf 100644
--- a/lib/crypto/src/Makefile
+++ b/lib/crypto/src/Makefile
@@ -1,19 +1,19 @@
#
# %CopyrightBegin%
-#
-# Copyright Ericsson AB 1999-2009. All Rights Reserved.
-#
+#
+# Copyright Ericsson AB 1999-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
@@ -57,7 +57,7 @@ APPUP_TARGET= $(EBIN)/$(APPUP_FILE)
# ----------------------------------------------------
# FLAGS
# ----------------------------------------------------
-ERL_COMPILE_FLAGS += +warn_obsolete_guard
+ERL_COMPILE_FLAGS += +warn_obsolete_guard -DCRYPTO_VSN=\"$(VSN)\"
# ----------------------------------------------------
# Targets
diff --git a/lib/crypto/src/crypto.erl b/lib/crypto/src/crypto.erl
index 8cb750759f..5b1ce96caf 100644
--- a/lib/crypto/src/crypto.erl
+++ b/lib/crypto/src/crypto.erl
@@ -21,7 +21,7 @@
-module(crypto).
--export([start/0, stop/0, info/0, info_lib/0]).
+-export([start/0, stop/0, info/0, info_lib/0, version/0]).
-export([md4/1, md4_init/0, md4_update/2, md4_final/1]).
-export([md5/1, md5_init/0, md5_update/2, md5_final/1]).
-export([sha/1, sha_init/0, sha_update/2, sha_final/1]).
@@ -54,82 +54,6 @@
-export([dh_generate_parameters/2, dh_check/1]). %% Testing see below
--define(INFO, 0).
--define(MD5, 1).
--define(MD5_INIT, 2).
--define(MD5_UPDATE, 3).
--define(MD5_FINAL, 4).
--define(SHA, 5).
--define(SHA_INIT, 6).
--define(SHA_UPDATE, 7).
--define(SHA_FINAL, 8).
--define(MD5_MAC, 9).
--define(MD5_MAC_96, 10).
--define(SHA_MAC, 11).
--define(SHA_MAC_96, 12).
--define(DES_CBC_ENCRYPT, 13).
--define(DES_CBC_DECRYPT, 14).
--define(DES_EDE3_CBC_ENCRYPT, 15).
--define(DES_EDE3_CBC_DECRYPT, 16).
--define(AES_CFB_128_ENCRYPT, 17).
--define(AES_CFB_128_DECRYPT, 18).
--define(RAND_BYTES, 19).
--define(RAND_UNIFORM, 20).
--define(MOD_EXP, 21).
--define(DSS_VERIFY, 22).
--define(RSA_VERIFY_SHA, 23).
-%-define(RSA_VERIFY_MD5, 35).
--define(AES_CBC_128_ENCRYPT, 24).
--define(AES_CBC_128_DECRYPT, 25).
--define(XOR, 26).
--define(RC4_ENCRYPT, 27).
--define(RC4_SET_KEY, 28).
--define(RC4_ENCRYPT_WITH_STATE, 29).
--define(RC2_40_CBC_ENCRYPT, 30).
--define(RC2_40_CBC_DECRYPT, 31).
--define(AES_CBC_256_ENCRYPT, 32).
--define(AES_CBC_256_DECRYPT, 33).
--define(INFO_LIB,34).
-%-define(RSA_VERIFY_SHA, 23).
--define(RSA_VERIFY_MD5, 35).
--define(RSA_SIGN_SHA, 36).
--define(RSA_SIGN_MD5, 37).
--define(DSS_SIGN, 38).
--define(RSA_PUBLIC_ENCRYPT, 39).
--define(RSA_PRIVATE_DECRYPT, 40).
--define(RSA_PRIVATE_ENCRYPT, 41).
--define(RSA_PUBLIC_DECRYPT, 42).
--define(DH_GENERATE_PARAMS, 43).
--define(DH_CHECK, 44).
--define(DH_GENERATE_KEY, 45).
--define(DH_COMPUTE_KEY, 46).
--define(MD4, 47).
--define(MD4_INIT, 48).
--define(MD4_UPDATE, 49).
--define(MD4_FINAL, 50).
-
-%% -define(SHA256, 51).
-%% -define(SHA256_INIT, 52).
-%% -define(SHA256_UPDATE, 53).
-%% -define(SHA256_FINAL, 54).
-%% -define(SHA512, 55).
-%% -define(SHA512_INIT, 56).
-%% -define(SHA512_UPDATE, 57).
-%% -define(SHA512_FINAL, 58).
-
--define(BF_CFB64_ENCRYPT, 59).
--define(BF_CFB64_DECRYPT, 60).
--define(BF_ECB_ENCRYPT, 61).
--define(BF_ECB_DECRYPT, 62).
--define(BF_OFB64_ENCRYPT, 63).
--define(BF_CBC_ENCRYPT, 64).
--define(BF_CBC_DECRYPT, 65).
-
--define(DES_ECB_ENCRYPT, 66).
--define(DES_ECB_DECRYPT, 67).
-
-%% -define(IDEA_CBC_ENCRYPT, 34).
-%% -define(IDEA_CBC_DECRYPT, 35).
-define(FUNC_LIST, [md4, md4_init, md4_update, md4_final,
md5, md5_init, md5_update, md5_final,
@@ -158,6 +82,44 @@
aes_cbc_256_encrypt, aes_cbc_256_decrypt,
info_lib]).
+-define(nif_stub,nif_stub_error(?LINE)).
+
+-on_load(on_load/0).
+
+-define(CRYPTO_NIF_VSN,101).
+
+on_load() ->
+ LibName = "crypto",
+ PrivDir = code:priv_dir(crypto),
+ Lib1 = filename:join([PrivDir, "lib", LibName]),
+ Status = case erlang:load_nif(Lib1, ?CRYPTO_NIF_VSN) of
+ ok -> ok;
+ {error, {load_failed, _}}=Error1 ->
+ LibDir2 =
+ filename:join([PrivDir, "lib",
+ erlang:system_info(system_architecture)]),
+ Candidate =
+ filelib:wildcard(filename:join([LibDir2,LibName ++ "*" ])),
+ case Candidate of
+ [] -> Error1;
+ _ ->
+ Lib2 = filename:join([LibDir2, LibName]),
+ erlang:load_nif(Lib2, ?CRYPTO_NIF_VSN)
+ end;
+ Error1 -> Error1
+ end,
+ case Status of
+ ok -> ok;
+ {error, {E, Str}} ->
+ error_logger:error_msg("Unable to load crypto library. Failed with error:~n\"~p, ~s\"~n"
+ "OpenSSL might not be installed on this system.~n",[E,Str]),
+ Status
+ end.
+
+
+nif_stub_error(Line) ->
+ erlang:error({nif_not_loaded,module,?MODULE,line,Line}).
+
start() ->
application:start(crypto).
@@ -165,15 +127,15 @@ stop() ->
application:stop(crypto).
info() ->
- lists:map(fun(I) ->
- lists:nth(I, ?FUNC_LIST)
- end, binary_to_list(control(?INFO, []))).
+ ?FUNC_LIST.
-info_lib() ->
- <<_DrvVer:8, NameSize:8, Name:NameSize/binary,
- VerNum:32, VerStr/binary>> = control(?INFO_LIB,[]),
- [{Name,VerNum,VerStr}].
+info_lib() -> ?nif_stub.
+%% Crypto app version history:
+%% (no version): Driver implementation
+%% 2.0 : NIF implementation, requires OTP R14
+version() -> ?CRYPTO_VSN.
+
%% Below Key and Data are binaries or IO-lists. IVec is a binary.
%% Output is always a binary. Context is a binary.
@@ -184,73 +146,27 @@ info_lib() ->
%%
%% MD5
%%
-md5(Data) ->
- control(?MD5, Data).
-
-md5_init() ->
- control(?MD5_INIT, []).
-
-md5_update(Context, Data) ->
- control(?MD5_UPDATE, [Context, Data]).
-
-md5_final(Context) ->
- control(?MD5_FINAL, Context).
+md5(_Data) -> ?nif_stub.
+md5_init() -> ?nif_stub.
+md5_update(_Context, _Data) -> ?nif_stub.
+md5_final(_Context) -> ?nif_stub.
%%
%% MD4
%%
-md4(Data) ->
- control(?MD4, Data).
-
-md4_init() ->
- control(?MD4_INIT, []).
-
-md4_update(Context, Data) ->
- control(?MD4_UPDATE, [Context, Data]).
-
-md4_final(Context) ->
- control(?MD4_FINAL, Context).
+md4(_Data) -> ?nif_stub.
+md4_init() -> ?nif_stub.
+md4_update(_Context, _Data) -> ?nif_stub.
+md4_final(_Context) -> ?nif_stub.
%%
%% SHA
%%
-sha(Data) ->
- control(?SHA, Data).
-
-sha_init() ->
- control(?SHA_INIT, []).
-
-sha_update(Context, Data) ->
- control(?SHA_UPDATE, [Context, Data]).
-
-sha_final(Context) ->
- control(?SHA_FINAL, Context).
+sha(_Data) -> ?nif_stub.
+sha_init() -> ?nif_stub.
+sha_update(_Context, _Data) -> ?nif_stub.
+sha_final(_Context) -> ?nif_stub.
-%% sha256 and sha512 requires openssl-0.9.8 removed for now
-
-%% sha256(Data) ->
-%% control(?SHA256, Data).
-
-%% sha256_init() ->
-%% control(?SHA256_INIT, []).
-
-%% sha256_update(Context, Data) ->
-%% control(?SHA256_UPDATE, [Context, Data]).
-
-%% sha256_final(Context) ->
-%% control(?SHA256_FINAL, Context).
-
-%% sha512(Data) ->
-%% control(?SHA512, Data).
-
-%% sha512_init() ->
-%% control(?SHA512_INIT, []).
-
-%% sha512_update(Context, Data) ->
-%% control(?SHA512_UPDATE, [Context, Data]).
-
-%% sha512_final(Context) ->
-%% control(?SHA512_FINAL, Context).
%%
%% MESSAGE AUTHENTICATION CODES
@@ -260,20 +176,24 @@ sha_final(Context) ->
%% MD5_MAC
%%
md5_mac(Key, Data) ->
- control_bin(?MD5_MAC, Key, Data).
+ md5_mac_n(Key,Data,16).
md5_mac_96(Key, Data) ->
- control_bin(?MD5_MAC_96, Key, Data).
+ md5_mac_n(Key,Data,12).
+md5_mac_n(_Key,_Data,_MacSz) -> ?nif_stub.
+
%%
%% SHA_MAC
%%
sha_mac(Key, Data) ->
- control_bin(?SHA_MAC, Key, Data).
+ sha_mac_n(Key,Data,20).
sha_mac_96(Key, Data) ->
- control_bin(?SHA_MAC_96, Key, Data).
+ sha_mac_n(Key,Data,12).
+sha_mac_n(_Key,_Data,_MacSz) -> ?nif_stub.
+
%%
%% CRYPTO FUNCTIONS
%%
@@ -282,10 +202,12 @@ sha_mac_96(Key, Data) ->
%% DES - in cipher block chaining mode (CBC)
%%
des_cbc_encrypt(Key, IVec, Data) ->
- control(?DES_CBC_ENCRYPT, [Key, IVec, Data]).
+ des_cbc_crypt(Key, IVec, Data, true).
des_cbc_decrypt(Key, IVec, Data) ->
- control(?DES_CBC_DECRYPT, [Key, IVec, Data]).
+ des_cbc_crypt(Key, IVec, Data, false).
+
+des_cbc_crypt(_Key, _IVec, _Data, _IsEncrypt) -> ?nif_stub.
%%
%% dec_cbc_ivec(Data) -> binary()
@@ -303,10 +225,10 @@ des_cbc_ivec(Data) when is_list(Data) ->
%% DES - in electronic codebook mode (ECB)
%%
des_ecb_encrypt(Key, Data) ->
- control(?DES_ECB_ENCRYPT, [Key, Data]).
-
+ des_ecb_crypt(Key, Data, true).
des_ecb_decrypt(Key, Data) ->
- control(?DES_ECB_DECRYPT, [Key, Data]).
+ des_ecb_crypt(Key, Data, false).
+des_ecb_crypt(_Key, _Data, _IsEncrypt) -> ?nif_stub.
%%
%% DES3 - in cipher block chaining mode (CBC)
@@ -314,71 +236,64 @@ des_ecb_decrypt(Key, Data) ->
des3_cbc_encrypt(Key1, Key2, Key3, IVec, Data) ->
des_ede3_cbc_encrypt(Key1, Key2, Key3, IVec, Data).
des_ede3_cbc_encrypt(Key1, Key2, Key3, IVec, Data) ->
- %%io:format("des_ede3_cbc_encrypt: size(Data)=~p\n", [size(list_to_binary([Data]))]),
- control(?DES_EDE3_CBC_ENCRYPT, [Key1, Key2, Key3, IVec, Data]).
+ des_ede3_cbc_crypt(Key1, Key2, Key3, IVec, Data, true).
des3_cbc_decrypt(Key1, Key2, Key3, IVec, Data) ->
des_ede3_cbc_decrypt(Key1, Key2, Key3, IVec, Data).
des_ede3_cbc_decrypt(Key1, Key2, Key3, IVec, Data) ->
- control(?DES_EDE3_CBC_DECRYPT, [Key1, Key2, Key3, IVec, Data]).
+ des_ede3_cbc_crypt(Key1, Key2, Key3, IVec, Data, false).
+
+des_ede3_cbc_crypt(_Key1, _Key2, _Key3, _IVec, _Data, _IsEncrypt) -> ?nif_stub.
%%
%% Blowfish
%%
-blowfish_ecb_encrypt(Key, Data) when byte_size(Data) >= 8 ->
- control_bin(?BF_ECB_ENCRYPT, Key, list_to_binary([Data])).
+blowfish_ecb_encrypt(Key, Data) ->
+ bf_ecb_crypt(Key,Data, true).
-blowfish_ecb_decrypt(Key, Data) when byte_size(Data) >= 8 ->
- control_bin(?BF_ECB_DECRYPT, Key, list_to_binary([Data])).
+blowfish_ecb_decrypt(Key, Data) ->
+ bf_ecb_crypt(Key,Data, false).
-blowfish_cbc_encrypt(Key, IVec, Data) when byte_size(Data) rem 8 =:= 0 ->
- control_bin(?BF_CBC_ENCRYPT, Key, list_to_binary([IVec, Data])).
+bf_ecb_crypt(_Key,_Data,_IsEncrypt) -> ?nif_stub.
-blowfish_cbc_decrypt(Key, IVec, Data) when byte_size(Data) rem 8 =:= 0 ->
- control_bin(?BF_CBC_DECRYPT, Key, list_to_binary([IVec, Data])).
+blowfish_cbc_encrypt(Key, IVec, Data) ->
+ bf_cbc_crypt(Key,IVec,Data,true).
-blowfish_cfb64_encrypt(Key, IVec, Data) when byte_size(IVec) =:= 8 ->
- control_bin(?BF_CFB64_ENCRYPT, Key, list_to_binary([IVec, Data])).
+blowfish_cbc_decrypt(Key, IVec, Data) ->
+ bf_cbc_crypt(Key,IVec,Data,false).
-blowfish_cfb64_decrypt(Key, IVec, Data) when byte_size(IVec) =:= 8 ->
- control_bin(?BF_CFB64_DECRYPT, Key, list_to_binary([IVec, Data])).
+bf_cbc_crypt(_Key,_IVec,_Data,_IsEncrypt) -> ?nif_stub.
-blowfish_ofb64_encrypt(Key, IVec, Data) when byte_size(IVec) =:= 8 ->
- control_bin(?BF_OFB64_ENCRYPT, Key, list_to_binary([IVec, Data])).
+blowfish_cfb64_encrypt(Key, IVec, Data) ->
+ bf_cfb64_crypt(Key, IVec, Data, true).
+
+blowfish_cfb64_decrypt(Key, IVec, Data) ->
+ bf_cfb64_crypt(Key, IVec, Data, false).
+
+bf_cfb64_crypt(_Key, _IVec, _Data, _IsEncrypt) -> ?nif_stub.
+
+blowfish_ofb64_encrypt(_Key, _IVec, _Data) -> ?nif_stub.
%%
%% AES in cipher feedback mode (CFB)
%%
aes_cfb_128_encrypt(Key, IVec, Data) ->
- control(?AES_CFB_128_ENCRYPT, [Key, IVec, Data]).
+ aes_cfb_128_crypt(Key, IVec, Data, true).
aes_cfb_128_decrypt(Key, IVec, Data) ->
- control(?AES_CFB_128_DECRYPT, [Key, IVec, Data]).
-
+ aes_cfb_128_crypt(Key, IVec, Data, false).
-%% %%
-%% %% IDEA - in cipher block chaining mode (CBC)
-%% %%
-%% idea_cbc_encrypt(Key, IVec, Data) ->
-%% control(?IDEA_CBC_ENCRYPT, [Key, IVec, Data]).
-
-%% idea_cbc_decrypt(Key, IVec, Data) ->
-%% control(?IDEA_CBC_DECRYPT, [Key, IVec, Data]).
+aes_cfb_128_crypt(_Key, _IVec, _Data, _IsEncrypt) -> ?nif_stub.
%%
%% RAND - pseudo random numbers using RN_ functions in crypto lib
%%
-
-rand_bytes(Bytes) ->
- rand_bytes(Bytes, 0, 0).
-rand_bytes(Bytes, Topmask, Bottommask) ->
- control(?RAND_BYTES,[<<Bytes:32/integer,
- Topmask:8/integer,
- Bottommask:8/integer>>]).
+rand_bytes(_Bytes) -> ?nif_stub.
+rand_bytes(_Bytes, _Topmask, _Bottommask) -> ?nif_stub.
rand_uniform(From,To) when is_binary(From), is_binary(To) ->
- case control(?RAND_UNIFORM,[From,To]) of
+ case rand_uniform_nif(From,To) of
<<Len:32/integer, MSB, Rest/binary>> when MSB > 127 ->
<<(Len + 1):32/integer, 0, MSB, Rest/binary>>;
Whatever ->
@@ -394,6 +309,8 @@ rand_uniform(From,To) when is_integer(From),is_integer(To) ->
Other
end.
+rand_uniform_nif(_From,_To) -> ?nif_stub.
+
%%
%% mod_exp - utility for rsa generation
%%
@@ -402,55 +319,51 @@ mod_exp(Base, Exponent, Modulo)
erlint(mod_exp(mpint(Base), mpint(Exponent), mpint(Modulo)));
mod_exp(Base, Exponent, Modulo) ->
- case control(?MOD_EXP,[Base,Exponent,Modulo]) of
+ case mod_exp_nif(Base,Exponent,Modulo) of
<<Len:32/integer, MSB, Rest/binary>> when MSB > 127 ->
<<(Len + 1):32/integer, 0, MSB, Rest/binary>>;
Whatever ->
Whatever
end.
+mod_exp_nif(_Base,_Exp,_Mod) -> ?nif_stub.
+
%%
%% DSS, RSA - verify
%%
%% Key = [P,Q,G,Y] P,Q,G=DSSParams Y=PublicKey
-dss_verify(Data,Signature,Key) ->
- control(?DSS_VERIFY, [Data,Signature,Key]) == <<1>>.
+dss_verify(_Data,_Signature,_Key) -> ?nif_stub.
% Key = [E,N] E=PublicExponent N=PublicModulus
rsa_verify(Data,Signature,Key) ->
rsa_verify(sha, Data,Signature,Key).
-rsa_verify(Type,Data,Signature,Key) ->
- control(rsa_verify_digest_type(Type), [Data,Signature,Key]) == <<1>>.
+rsa_verify(_Type,_Data,_Signature,_Key) -> ?nif_stub.
-rsa_verify_digest_type(md5) -> ?RSA_VERIFY_MD5;
-rsa_verify_digest_type(sha) -> ?RSA_VERIFY_SHA;
-rsa_verify_digest_type(Bad) -> erlang:error(badarg, [Bad]).
%%
%% DSS, RSA - sign
%%
%% Key = [P,Q,G,X] P,Q,G=DSSParams X=PrivateKey
dss_sign(Data, Key) ->
- <<Ret:8, Signature/binary>> = control(?DSS_SIGN, [Data,Key]),
- case Ret of
- 1 -> Signature;
- 0 -> erlang:error(badkey, [Data, Key])
+ case dss_sign_nif(Data,Key) of
+ error -> erlang:error(badkey, [Data, Key]);
+ Sign -> Sign
end.
+dss_sign_nif(_Data,_Key) -> ?nif_stub.
+
%% Key = [E,N,D] E=PublicExponent N=PublicModulus D=PrivateExponent
rsa_sign(Data,Key) ->
rsa_sign(sha, Data, Key).
rsa_sign(Type, Data, Key) ->
- <<Ret:8, Signature/binary>> = control(rsa_sign_digest_type(Type), [Data,Key]),
- case Ret of
- 1 -> Signature;
- 0 -> erlang:error(badkey, [Type,Data,Key])
+ case rsa_sign_nif(Type,Data,Key) of
+ error -> erlang:error(badkey, [Type,Data,Key]);
+ Sign -> Sign
end.
-rsa_sign_digest_type(md5) -> ?RSA_SIGN_MD5;
-rsa_sign_digest_type(sha) -> ?RSA_SIGN_SHA;
-rsa_sign_digest_type(Bad) -> erlang:error(badarg, [Bad]).
+rsa_sign_nif(_Type,_Data,_Key) -> ?nif_stub.
+
%%
%% rsa_public_encrypt
@@ -458,48 +371,39 @@ rsa_sign_digest_type(Bad) -> erlang:error(badarg, [Bad]).
%% Binary, Key = [E,N]
rsa_public_encrypt(BinMesg, Key, Padding) ->
- Size = iolist_size(BinMesg),
- <<Ret:8, Signature/binary>> =
- control(?RSA_PUBLIC_ENCRYPT, [<<Size:32>>,BinMesg,Key,rsa_pad(Padding)]),
- case Ret of
- 1 -> Signature;
- 0 -> erlang:error(encrypt_failed, [BinMesg,Key, Padding])
- end.
+ case rsa_public_crypt(BinMesg, Key, Padding, true) of
+ error ->
+ erlang:error(encrypt_failed, [BinMesg,Key, Padding]);
+ Sign -> Sign
+ end.
+
+rsa_public_crypt(_BinMsg, _Key, _Padding, _IsEncrypt) -> ?nif_stub.
%% Binary, Key = [E,N,D]
rsa_private_decrypt(BinMesg, Key, Padding) ->
- Size = iolist_size(BinMesg),
- <<Ret:8, Signature/binary>> =
- control(?RSA_PRIVATE_DECRYPT, [<<Size:32>>,BinMesg,Key,rsa_pad(Padding)]),
- case Ret of
- 1 -> Signature;
- 0 -> erlang:error(decrypt_failed, [BinMesg,Key, Padding])
- end.
-
-rsa_pad(rsa_pkcs1_padding) -> 1;
-rsa_pad(rsa_pkcs1_oaep_padding) -> 2;
-%% rsa_pad(rsa_sslv23_padding) -> 3;
-rsa_pad(rsa_no_padding) -> 0;
-rsa_pad(Bad) -> erlang:error(badarg, [Bad]).
+ case rsa_private_crypt(BinMesg, Key, Padding, false) of
+ error ->
+ erlang:error(decrypt_failed, [BinMesg,Key, Padding]);
+ Sign -> Sign
+ end.
+
+rsa_private_crypt(_BinMsg, _Key, _Padding, _IsEncrypt) -> ?nif_stub.
+
%% Binary, Key = [E,N,D]
rsa_private_encrypt(BinMesg, Key, Padding) ->
- Size = iolist_size(BinMesg),
- <<Ret:8, Signature/binary>> =
- control(?RSA_PRIVATE_ENCRYPT, [<<Size:32>>,BinMesg,Key,rsa_pad(Padding)]),
- case Ret of
- 1 -> Signature;
- 0 -> erlang:error(encrypt_failed, [BinMesg,Key, Padding])
- end.
+ case rsa_private_crypt(BinMesg, Key, Padding, true) of
+ error ->
+ erlang:error(encrypt_failed, [BinMesg,Key, Padding]);
+ Sign -> Sign
+ end.
%% Binary, Key = [E,N]
rsa_public_decrypt(BinMesg, Key, Padding) ->
- Size = iolist_size(BinMesg),
- <<Ret:8, Signature/binary>> =
- control(?RSA_PUBLIC_DECRYPT, [<<Size:32>>,BinMesg,Key,rsa_pad(Padding)]),
- case Ret of
- 1 -> Signature;
- 0 -> erlang:error(decrypt_failed, [BinMesg,Key, Padding])
+ case rsa_public_crypt(BinMesg, Key, Padding, false) of
+ error ->
+ erlang:error(decrypt_failed, [BinMesg,Key, Padding]);
+ Sign -> Sign
end.
%%
@@ -507,16 +411,18 @@ rsa_public_decrypt(BinMesg, Key, Padding) ->
%%
aes_cbc_128_encrypt(Key, IVec, Data) ->
- control(?AES_CBC_128_ENCRYPT, [Key, IVec, Data]).
+ aes_cbc_crypt(Key, IVec, Data, true).
aes_cbc_128_decrypt(Key, IVec, Data) ->
- control(?AES_CBC_128_DECRYPT, [Key, IVec, Data]).
+ aes_cbc_crypt(Key, IVec, Data, false).
aes_cbc_256_encrypt(Key, IVec, Data) ->
- control(?AES_CBC_256_ENCRYPT, [Key, IVec, Data]).
+ aes_cbc_crypt(Key, IVec, Data, true).
aes_cbc_256_decrypt(Key, IVec, Data) ->
- control(?AES_CBC_256_DECRYPT, [Key, IVec, Data]).
+ aes_cbc_crypt(Key, IVec, Data, false).
+
+aes_cbc_crypt(_Key, _IVec, _Data, _IsEncrypt) -> ?nif_stub.
%%
%% aes_cbc_ivec(Data) -> binary()
@@ -537,31 +443,25 @@ aes_cbc_ivec(Data) when is_list(Data) ->
%% NB doesn't check that they are the same size, just concatenates
%% them and sends them to the driver
%%
-exor(A, B) ->
- control(?XOR, [A, B]).
+exor(_A, _B) -> ?nif_stub.
%%
%% RC4 - symmetric stream cipher
%%
-rc4_encrypt(Key, Data) ->
- control_bin(?RC4_ENCRYPT, Key, Data).
-
-rc4_set_key(Key) ->
- control(?RC4_SET_KEY, Key).
-
-rc4_encrypt_with_state(State, Data) ->
- <<Sz:32/integer-big-unsigned, S:Sz/binary, D/binary>> =
- control_bin(?RC4_ENCRYPT_WITH_STATE, State, Data),
- {S, D}.
+rc4_encrypt(_Key, _Data) -> ?nif_stub.
+rc4_set_key(_Key) -> ?nif_stub.
+rc4_encrypt_with_state(_State, _Data) -> ?nif_stub.
%%
%% RC2 - 40 bits block cipher
%%
rc2_40_cbc_encrypt(Key, IVec, Data) ->
- control(?RC2_40_CBC_ENCRYPT, [Key, IVec, Data]).
+ rc2_40_cbc_crypt(Key,IVec,Data,true).
rc2_40_cbc_decrypt(Key, IVec, Data) ->
- control(?RC2_40_CBC_DECRYPT, [Key, IVec, Data]).
+ rc2_40_cbc_crypt(Key,IVec,Data,false).
+
+rc2_40_cbc_crypt(_Key, _IVec, _Data, _IsEncrypt) -> ?nif_stub.
%%
%% DH Diffie-Hellman functions
@@ -576,87 +476,44 @@ rc2_40_cbc_decrypt(Key, IVec, Data) ->
%%
%% usage: dh_generate_parameters(1024, 2 or 5) ->
%% [Prime=mpint(), SharedGenerator=mpint()]
-dh_generate_parameters(PrimeLen, Generator)
- when is_integer(PrimeLen), is_integer(Generator) ->
- case control(?DH_GENERATE_PARAMS, <<PrimeLen:32, Generator:32>>) of
- <<0:8, _/binary>> ->
- erlang:error(generation_failed, [PrimeLen,Generator]);
- <<1:8, PLen0:32, _:PLen0/binary, GLen0:32,_:GLen0/binary>> = Bin ->
- PLen = PLen0+4,
- GLen = GLen0+4,
- <<_:8, PBin:PLen/binary,GBin:GLen/binary>> = Bin,
- [PBin, GBin]
- end.
+dh_generate_parameters(PrimeLen, Generator) ->
+ case dh_generate_parameters_nif(PrimeLen, Generator) of
+ error -> erlang:error(generation_failed, [PrimeLen,Generator]);
+ Ret -> Ret
+ end.
+
+dh_generate_parameters_nif(_PrimeLen, _Generator) -> ?nif_stub.
%% Checks that the DHParameters are ok.
%% DHParameters = [P (Prime)= mpint(), G(Generator) = mpint()]
-dh_check(DHParameters) ->
- case control(?DH_CHECK, DHParameters) of
- <<0:32>> -> ok;
- <<_:24,_:1,_:1,_:1,1:1>> -> not_prime;
- <<_:24,_:1,_:1,1:1,0:1>> -> not_strong_prime;
- <<_:24,_:1,1:1,0:1,0:1>> -> unable_to_check_generator;
- <<_:24,1:1,0:1,0:1,0:1>> -> not_suitable_generator;
- <<16#FFFF:32>> -> {error, check_failed};
- <<X:32>> -> {unknown, X}
- end.
+dh_check([_Prime,_Gen]) -> ?nif_stub.
%% DHParameters = [P (Prime)= mpint(), G(Generator) = mpint()]
%% PrivKey = mpint()
dh_generate_key(DHParameters) ->
- dh_generate_key(<<0:32>>, DHParameters).
+ dh_generate_key(undefined, DHParameters).
dh_generate_key(PrivateKey, DHParameters) ->
- case control(?DH_GENERATE_KEY, [PrivateKey, DHParameters]) of
- <<0:8, _/binary>> ->
- erlang:error(generation_failed, [PrivateKey,DHParameters]);
- Bin = <<1:8, PubLen0:32, _:PubLen0/binary, PrivLen0:32, _:PrivLen0/binary>> ->
- PubLen = PubLen0+4,
- PrivLen = PrivLen0+4,
- <<_:8, PubBin:PubLen/binary,PrivBin:PrivLen/binary>> = Bin,
- {PubBin, PrivBin}
+ case dh_generate_key_nif(PrivateKey, DHParameters) of
+ error -> erlang:error(generation_failed, [PrivateKey,DHParameters]);
+ Res -> Res
end.
+dh_generate_key_nif(_PrivateKey, _DHParameters) -> ?nif_stub.
+
%% DHParameters = [P (Prime)= mpint(), G(Generator) = mpint()]
%% MyPrivKey, OthersPublicKey = mpint()
dh_compute_key(OthersPublicKey, MyPrivateKey, DHParameters) ->
- case control(?DH_COMPUTE_KEY, [OthersPublicKey, MyPrivateKey, DHParameters]) of
- <<0:8, _/binary>> ->
- erlang:error(computation_failed, [OthersPublicKey,MyPrivateKey,DHParameters]);
- <<1:8, Binary/binary>> -> Binary
+ case dh_compute_key_nif(OthersPublicKey,MyPrivateKey,DHParameters) of
+ error -> erlang:error(computation_failed, [OthersPublicKey,MyPrivateKey,DHParameters]);
+ Ret -> Ret
end.
+dh_compute_key_nif(_OthersPublicKey, _MyPrivateKey, _DHParameters) -> ?nif_stub.
+
%%
%% LOCAL FUNCTIONS
%%
-control_bin(Cmd, Key, Data) ->
- Sz = iolist_size(Key),
- control(Cmd, [<<Sz:32/integer-unsigned>>, Key, Data]).
-
-control(Cmd, Data) ->
- Port = crypto_server:client_port(),
- erlang:port_control(Port, Cmd, Data).
-
-
-%% sizehdr(N) ->
-%% [(N bsr 24) band 255,
-%% (N bsr 16) band 255,
-%% (N bsr 8) band 255,
-%% N band 255].
-
-%% Flat length of IOlist (or binary)
-%% flen(L) when binary(L) ->
-%% size(L);
-%% flen(L) ->
-%% flen(L, 0).
-
-%% flen([H| T], N) when list(H) ->
-%% flen(H, flen(T, N));
-%% flen([H| T], N) when binary(H) ->
-%% flen(T, N + size(H));
-%% flen([H| T], N) when integer(H), 0 =< H, H =< 255 ->
-%% flen(T, N + 1);
-%% flen([], N) ->
-%% N.
+
%% large integer in a binary with 32bit length
%% MP representaion (SSH2)
diff --git a/lib/crypto/src/crypto_server.erl b/lib/crypto/src/crypto_server.erl
index 0b1e5c9b02..89650a9f06 100644
--- a/lib/crypto/src/crypto_server.erl
+++ b/lib/crypto/src/crypto_server.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1999-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 1999-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%
%%
@@ -23,14 +23,12 @@
-behaviour(gen_server).
--export([start_link/0,client_port/0]).
+-export([start_link/0]).
%% Internal exports, call-back functions.
-export([init/1,handle_call/3,handle_cast/2,handle_info/2,code_change/3,
terminate/2]).
-%% Measurements shows that inlining port_names/0 is worth doing.
--compile({inline,[{port_names,0}]}).
%%% --------------------------------------------------------
%%% Interface Functions.
@@ -40,66 +38,8 @@ start_link() ->
gen_server:start_link({local, crypto_server}, crypto_server, [], []).
init([]) ->
- process_flag(trap_exit, true),
- erl_ddll:start(),
- PrivDir = code:priv_dir(crypto),
- LibDir1 = filename:join([PrivDir, "lib"]),
- {Status, LibDir} =
- case erl_ddll:load_driver(LibDir1, crypto_drv) of
- ok -> {ok,LibDir1};
- {error,Error1} ->
- LibDir2 =
- filename:join(LibDir1,
- erlang:system_info(system_architecture)),
- Candidate =
- filelib:wildcard(filename:join([LibDir2,"crypto_drv*"])),
- case Candidate of
- [] ->
- {{error,Error1},LibDir1};
- _ ->
- case erl_ddll:load_driver(LibDir2, crypto_drv) of
- ok ->
- {ok,LibDir2};
- {error, Error2} ->
- {{error,Error2},LibDir2}
- end
- end
- end,
- case Status of
- ok ->
- Cmd = "crypto_drv elibcrypto " ++
- filename:join([LibDir, "elibcrypto"]),
- open_ports(Cmd,size(port_names()));
- {error, E} ->
- Str = erl_ddll:format_error(E),
- error_logger:error_msg("Unable to load crypto_drv. Failed with error:~n\"~s\"~nOpenSSL might not be installed on this system.~n",[Str]),
- {stop,nodriver}
- end.
-
-open_ports(_,0) ->
- {ok, []};
-open_ports(Cmd,N) ->
- Port = open_port({spawn, Cmd}, []),
- %% check that driver is loaded, linked and working
- %% since crypto_drv links towards libcrypto, this is a good thing
- %% since libcrypto is known to be bad with backwards compatibility
- case catch port_control(Port, 0, []) of
- {'EXIT', _} ->
- {stop, nodriver};
- _ ->
- register(element(N,port_names()), Port),
- open_ports(Cmd,N-1)
- end.
-
-port_names() ->
- { crypto_drv01, crypto_drv02, crypto_drv03, crypto_drv04,
- crypto_drv05, crypto_drv06, crypto_drv07, crypto_drv08,
- crypto_drv09, crypto_drv10, crypto_drv11, crypto_drv12,
- crypto_drv13, crypto_drv14, crypto_drv15, crypto_drv16 }.
-
-client_port() ->
- element(erlang:system_info(scheduler_id) rem size(port_names()) + 1,
- port_names()).
+ {ok,[]}.
+
%%% --------------------------------------------------------
@@ -112,11 +52,6 @@ handle_call(_, _, State) ->
handle_cast(_, State) ->
{noreply, State}.
-handle_info({'EXIT', Pid, _Reason}, State) when is_pid(Pid) ->
- {noreply, State};
-
-handle_info({'EXIT', Port, Reason}, State) when is_port(Port) ->
- {stop, {port_died, Reason}, State};
handle_info(_, State) ->
{noreply, State}.
@@ -124,13 +59,8 @@ code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, _State) ->
- close_ports(size(port_names())).
+ [].
-close_ports(0) ->
- ok;
-close_ports(N) ->
- element(N,port_names()) ! {self(), close},
- close_ports(N-1).
diff --git a/lib/crypto/test/blowfish_SUITE.erl b/lib/crypto/test/blowfish_SUITE.erl
index d4cc167ea9..d117e7cc3d 100644
--- a/lib/crypto/test/blowfish_SUITE.erl
+++ b/lib/crypto/test/blowfish_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -116,7 +116,8 @@ all(suite) ->
ecb_test(KeyBytes, ClearBytes, CipherBytes) ->
{Key, Clear, Cipher} =
{to_bin(KeyBytes), to_bin(ClearBytes), to_bin(CipherBytes)},
- crypto:blowfish_ecb_encrypt(Key, Clear) =:= Cipher.
+ ?line m(crypto:blowfish_ecb_encrypt(Key, Clear), Cipher),
+ true.
ecb(doc) ->
"Test that ECB mode is OK";
@@ -208,3 +209,5 @@ to_bin([], Acc) ->
iolist_to_binary(lists:reverse(Acc));
to_bin([C1, C2 | Rest], Acc) ->
to_bin(Rest, [(dehex(C1) bsl 4) bor dehex(C2) | Acc]).
+
+m(X,X) -> ok.
diff --git a/lib/crypto/test/crypto_SUITE.erl b/lib/crypto/test/crypto_SUITE.erl
index 8467ff2274..08d7a0ce99 100644
--- a/lib/crypto/test/crypto_SUITE.erl
+++ b/lib/crypto/test/crypto_SUITE.erl
@@ -119,7 +119,7 @@ link_test(Config) when is_list(Config) ->
link_test_1() ->
?line CryptoPriv = code:priv_dir(crypto),
- ?line Wc = filename:join([CryptoPriv,"lib","crypto_drv.*"]),
+ ?line Wc = filename:join([CryptoPriv,"lib","crypto.*"]),
?line case filelib:wildcard(Wc) of
[] -> {skip,"Didn't find the crypto driver"};
[Drv] -> link_test_2(Drv)
@@ -441,7 +441,7 @@ des_cbc_iter(Config) when is_list(Config) ->
?line Cipher1 = crypto:des_cbc_encrypt(Key, IVec, Plain1),
?line IVec2 = crypto:des_cbc_ivec(Cipher1),
?line Cipher2 = crypto:des_cbc_encrypt(Key, IVec2, Plain2),
- ?line Cipher = concat_binary([Cipher1, Cipher2]),
+ ?line Cipher = list_to_binary([Cipher1, Cipher2]),
?line m(Cipher, hexstr2bin("e5c7cdde872bf27c43e934008c389c"
"0f683788499a7c05f6")).
@@ -843,16 +843,16 @@ dsa_sign_test(Config) when is_list(Config) ->
ParamG = 18320614775012672475365915366944922415598782131828709277168615511695849821411624805195787607930033958243224786899641459701930253094446221381818858674389863050420226114787005820357372837321561754462061849169568607689530279303056075793886577588606958623645901271866346406773590024901668622321064384483571751669,
Params = [crypto:mpint(ParamP), crypto:mpint(ParamQ), crypto:mpint(ParamG)],
- ?line Sig1 = crypto:dss_sign(sized_binary(Msg), [Params, crypto:mpint(PrivKey)]),
+ ?line Sig1 = crypto:dss_sign(sized_binary(Msg), Params ++ [crypto:mpint(PrivKey)]),
?line m(crypto:dss_verify(sized_binary(Msg), sized_binary(Sig1),
- [Params, crypto:mpint(PubKey)]), true),
+ Params ++ [crypto:mpint(PubKey)]), true),
?line m(crypto:dss_verify(sized_binary(one_bit_wrong(Msg)), sized_binary(Sig1),
- [Params, crypto:mpint(PubKey)]), false),
+ Params ++ [crypto:mpint(PubKey)]), false),
?line m(crypto:dss_verify(sized_binary(Msg), sized_binary(one_bit_wrong(Sig1)),
- [Params, crypto:mpint(PubKey)]), false),
+ Params ++ [crypto:mpint(PubKey)]), false),
%%?line Bad = crypto:dss_sign(sized_binary(Msg), [Params, crypto:mpint(PubKey)]),
diff --git a/lib/crypto/vsn.mk b/lib/crypto/vsn.mk
index 68eecfe759..d04736fc2b 100644
--- a/lib/crypto/vsn.mk
+++ b/lib/crypto/vsn.mk
@@ -1 +1 @@
-CRYPTO_VSN = 1.6.4
+CRYPTO_VSN = 2.0
diff --git a/lib/erl_interface/test/ei_tmo_SUITE_data/ei_tmo_test.c b/lib/erl_interface/test/ei_tmo_SUITE_data/ei_tmo_test.c
index 2cc9af975d..db90b1810e 100644
--- a/lib/erl_interface/test/ei_tmo_SUITE_data/ei_tmo_test.c
+++ b/lib/erl_interface/test/ei_tmo_SUITE_data/ei_tmo_test.c
@@ -1,19 +1,19 @@
/*
* %CopyrightBegin%
- *
- * Copyright Ericsson AB 2003-2009. All Rights Reserved.
- *
+ *
+ * Copyright Ericsson AB 2003-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%
*/
@@ -65,7 +65,7 @@ static void debugf_open(int number)
{
char filename[1024];
sprintf(filename,"ei_tmo_test%d.debug",number);
-#if !defined(VXWORKS) && !defined(__WIN32__) && !defined(_OSE_)
+#if !defined(VXWORKS) && !defined(__WIN32__)
close(2);
#endif
debugfile = fopen(filename,"a");
diff --git a/lib/hipe/cerl/erl_bif_types.erl b/lib/hipe/cerl/erl_bif_types.erl
index 213f98dcc0..be3073c0e6 100644
--- a/lib/hipe/cerl/erl_bif_types.erl
+++ b/lib/hipe/cerl/erl_bif_types.erl
@@ -1066,11 +1066,19 @@ type(erlang, list_to_pid, 1, Xs) ->
strict(arg_types(erlang, list_to_pid, 1), Xs, fun (_) -> t_pid() end);
type(erlang, list_to_tuple, 1, Xs) ->
strict(arg_types(erlang, list_to_tuple, 1), Xs, fun (_) -> t_tuple() end);
-type(erlang, loaded, 0, _) ->
- t_list(t_atom());
type(erlang, load_module, 2, Xs) ->
strict(arg_types(erlang, load_module, 2), Xs,
fun ([Mod,_Bin]) -> t_code_load_return(Mod) end);
+type(erlang, load_nif, 2, Xs) ->
+ strict(arg_types(erlang, load_nif, 2), Xs,
+ fun (_) ->
+ Reason = t_atoms(['load_failed', 'bad_lib', 'load',
+ 'reload', 'upgrade', 'old_code']),
+ RsnPair = t_tuple([Reason, t_string()]),
+ t_sup(t_atom('ok'), t_tuple([t_atom('error'), RsnPair]))
+ end);
+type(erlang, loaded, 0, _) ->
+ t_list(t_atom());
type(erlang, localtime, 0, Xs) ->
type(erlang, universaltime, 0, Xs); % same
type(erlang, localtime_to_universaltime, 1, Xs) ->
@@ -3572,10 +3580,12 @@ arg_types(erlang, list_to_pid, 1) ->
[t_string()];
arg_types(erlang, list_to_tuple, 1) ->
[t_list()];
-arg_types(erlang, loaded, 0) ->
- [];
arg_types(erlang, load_module, 2) ->
[t_atom(), t_binary()];
+arg_types(erlang, load_nif, 2) ->
+ [t_string(), t_any()];
+arg_types(erlang, loaded, 0) ->
+ [];
arg_types(erlang, localtime, 0) ->
[];
arg_types(erlang, localtime_to_universaltime, 1) ->
diff --git a/lib/inets/doc/src/notes.xml b/lib/inets/doc/src/notes.xml
index 762c2c84c5..3216b0c2cd 100644
--- a/lib/inets/doc/src/notes.xml
+++ b/lib/inets/doc/src/notes.xml
@@ -32,6 +32,58 @@
<file>notes.xml</file>
</header>
+ <section><title>Inets 5.3.2</title>
+
+ <section><title>Improvements and New Features</title>
+ <p>-</p>
+
+<!--
+ <list>
+ <item>
+ <p>[httpc] - Allow users to pass socket options to the transport
+ module when making requests. </p>
+ <p>See the <c>socket_opts</c> option in the
+ <seealso marker="httpc#request2">request/4</seealso> or
+ <seealso marker="httpc#set_options">set_options/1,2</seealso>
+ for more info, </p>
+ <p>Own Id: OTP-8352</p>
+ </item>
+
+ </list>
+-->
+ </section>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+
+<!--
+ <p>-</p>
+-->
+
+ <list>
+ <item>
+ <p>[httpc] - Memory leak plugged.
+ The profile manager never cleaned up in its handler database.
+ This meant that with each new request handler, another entry
+ was created that was never deleted. Eventually the request
+ id counter (used as a key) would wrap, but the machine would
+ most likely run out of memory before that happened.</p>
+ <p>Own Id: OTP-8542</p>
+ <p>Lev Walkin</p>
+ </item>
+
+ <item>
+ <p>[httpc] - https requests with default port (443) not handled
+ properly. </p>
+ <p>Own Id: OTP-8607</p>
+ <p>jebu ittiachen</p>
+ </item>
+
+ </list>
+ </section>
+
+ </section> <!-- 5.3.2 -->
+
+
<section><title>Inets 5.3.1</title>
<section><title>Improvements and New Features</title>
diff --git a/lib/inets/src/http_client/httpc.erl b/lib/inets/src/http_client/httpc.erl
index 5205605e0a..6deeab6948 100644
--- a/lib/inets/src/http_client/httpc.erl
+++ b/lib/inets/src/http_client/httpc.erl
@@ -432,7 +432,7 @@ handle_request(Method, Url,
Options = request_options(Options0),
Sync = proplists:get_value(sync, Options),
Stream = proplists:get_value(stream, Options),
- Host2 = header_host(Host, Port),
+ 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),
@@ -895,9 +895,11 @@ bad_option(Option, BadValue) ->
throw({error, {bad_option, Option, BadValue}}).
-header_host(Host, 80 = _Port) ->
+header_host(https, Host, 443 = _Port) ->
Host;
-header_host(Host, Port) ->
+header_host(http, Host, 80 = _Port) ->
+ Host;
+header_host(_Scheme, Host, Port) ->
Host ++ ":" ++ integer_to_list(Port).
diff --git a/lib/inets/src/http_client/httpc_handler.erl b/lib/inets/src/http_client/httpc_handler.erl
index 695ff9cf82..5e79d874fb 100644
--- a/lib/inets/src/http_client/httpc_handler.erl
+++ b/lib/inets/src/http_client/httpc_handler.erl
@@ -1424,14 +1424,16 @@ try_to_enable_pipeline_or_keep_alive(
State#state{status = close}
end.
-answer_request(Request, Msg, #state{timers = Timers} = State) ->
+answer_request(#request{id = RequestId, from = From} = Request, Msg,
+ #state{timers = Timers, profile_name = ProfileName} = State) ->
?hcrt("answer request", [{request, Request}]),
- httpc_response:send(Request#request.from, Msg),
+ httpc_response:send(From, Msg),
RequestTimers = Timers#timers.request_timers,
TimerRef =
- proplists:get_value(Request#request.id, RequestTimers, undefined),
- Timer = {Request#request.id, TimerRef},
+ proplists:get_value(RequestId, RequestTimers, undefined),
+ 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 =
diff --git a/lib/inets/src/http_client/httpc_manager.erl b/lib/inets/src/http_client/httpc_manager.erl
index f3cd81f4a7..b278077a66 100644
--- a/lib/inets/src/http_client/httpc_manager.erl
+++ b/lib/inets/src/http_client/httpc_manager.erl
@@ -30,6 +30,7 @@
request/2,
cancel_request/2,
request_canceled/2,
+ request_done/2,
retry_request/2,
redirect_request/2,
insert_session/2,
@@ -171,6 +172,18 @@ request_canceled(RequestId, ProfileName) ->
%%--------------------------------------------------------------------
+%% Function: request_done(RequestId, ProfileName) -> ok
+%% RequestId - ref()
+%% ProfileName = atom()
+%%
+%% Description: Inform tha manager that a request has been completed.
+%%--------------------------------------------------------------------
+
+request_done(RequestId, ProfileName) ->
+ cast(ProfileName, {request_done, RequestId}).
+
+
+%%--------------------------------------------------------------------
%% Function: insert_session(Session, ProfileName) -> _
%% Session - #tcp_session{}
%% ProfileName - atom()
@@ -486,6 +499,11 @@ handle_cast({request_canceled, RequestId}, State) ->
{noreply, State}
end;
+handle_cast({request_done, RequestId}, State) ->
+ ?hcrv("request done", [{request_id, RequestId}]),
+ ets:delete(State#state.handler_db, RequestId),
+ {noreply, State};
+
handle_cast({set_options, Options}, State = #state{options = OldOptions}) ->
?hcrv("set options", [{options, Options}, {old_options, OldOptions}]),
NewOptions =
diff --git a/lib/inets/src/inets_app/inets.appup.src b/lib/inets/src/inets_app/inets.appup.src
index ba1dc8ccdb..dfdfb41373 100644
--- a/lib/inets/src/inets_app/inets.appup.src
+++ b/lib/inets/src/inets_app/inets.appup.src
@@ -18,9 +18,18 @@
{"%VSN%",
[
+ {"5.3.1",
+ [
+ {load_module, httpc, soft_purge, soft_purge, []},
+ {update, httpc_handler, soft, soft_purge, soft_purge, [httpc_manager]},
+ {update, httpc_manager, soft, soft_purge, soft_purge, []}
+ ]
+ },
{"5.3",
[
- {update, httpc_handler, soft, soft_purge, soft_purge, [mod_esi]},
+ {load_module, httpc, soft_purge, soft_purge, []},
+ {update, httpc_handler, soft, soft_purge, soft_purge, [httpc_manager]},
+ {update, httpc_manager, soft, soft_purge, soft_purge, []},
{load_module, mod_esi, soft_purge, soft_purge, []}
]
},
@@ -41,9 +50,18 @@
}
],
[
+ {"5.3.1",
+ [
+ {load_module, httpc, soft_purge, soft_purge, []},
+ {update, httpc_handler, soft, soft_purge, soft_purge, [httpc_manager]},
+ {update, httpc_manager, soft, soft_purge, soft_purge, []}
+ ]
+ },
{"5.3",
[
- {update, httpc_handler, soft, soft_purge, soft_purge, [mod_esi]},
+ {load_module, httpc, soft_purge, soft_purge, []},
+ {update, httpc_handler, soft, soft_purge, soft_purge, [httpc_manager]},
+ {update, httpc_manager, soft, soft_purge, soft_purge, []},
{load_module, mod_esi, soft_purge, soft_purge, []}
]
},
diff --git a/lib/inets/vsn.mk b/lib/inets/vsn.mk
index 401bf4d37d..7776bef0a5 100644
--- a/lib/inets/vsn.mk
+++ b/lib/inets/vsn.mk
@@ -18,11 +18,15 @@
# %CopyrightEnd%
APPLICATION = inets
-INETS_VSN = 5.3.1
+INETS_VSN = 5.3.2
PRE_VSN =
APP_VSN = "$(APPLICATION)-$(INETS_VSN)$(PRE_VSN)"
-TICKETS = OTP-8508 OTP-8509
+TICKETS = OTP-8542 OTP-8607
+
+TICKETS_5_3_1 = \
+ OTP-8508 \
+ OTP-8509
TICKETS_5_3 = \
OTP-8016 \
diff --git a/lib/kernel/src/application_controller.erl b/lib/kernel/src/application_controller.erl
index 5277472ea6..42f527f400 100644
--- a/lib/kernel/src/application_controller.erl
+++ b/lib/kernel/src/application_controller.erl
@@ -40,7 +40,7 @@
-export([test_change_apps/2]).
-import(lists, [zf/2, map/2, foreach/2, foldl/3,
- keysearch/3, keydelete/3, keyreplace/4]).
+ keyfind/3, keydelete/3, keyreplace/4]).
-include("application_master.hrl").
@@ -524,7 +524,9 @@ init(Init, Kernel) ->
end.
-%% Check the syntax of the .config file [{ApplicationName, [{Parameter, Value}]}].
+%% Check the syntax of the .config file
+%% [{ApplicationName, [{Parameter, Value}]}].
+
check_conf_data([]) ->
ok;
check_conf_data(ConfData) when is_list(ConfData) ->
@@ -568,8 +570,8 @@ check_para_kernel([]) ->
ok;
check_para_kernel([{distributed, Apps} | ParaList]) when is_list(Apps) ->
case check_distributed(Apps) of
- {error, ErrorMsg} ->
- {error, ErrorMsg};
+ {error, _ErrorMsg} = Error ->
+ Error;
_ ->
check_para_kernel(ParaList)
end;
@@ -633,9 +635,9 @@ handle_call({load_application, Application}, From, S) ->
false ->
{reply, ok, NewS}
end;
- {error, Error} ->
- {reply, {error, Error}, S};
- {'EXIT',R} ->
+ {error, _} = Error ->
+ {reply, Error, S};
+ {'EXIT', R} ->
{reply, {error, R}, S}
end;
@@ -660,7 +662,7 @@ handle_call({start_application, AppName, RestartType}, From, S) ->
%% Incase of erroneous variables do not start the application,
%% if the application is permanent crash the node.
%% Check if the application is already starting.
- case lists:keysearch(AppName, 1, Start_req) of
+ case lists:keyfind(AppName, 1, Start_req) of
false ->
case catch check_start_cond(AppName, RestartType, Started, Running) of
{ok, Appl} ->
@@ -689,13 +691,12 @@ handle_call({start_application, AppName, RestartType}, From, S) ->
{reply, ok, SS}
end
end;
- {error, R} ->
- {reply, {error, R}, S}
+ {error, _R} = Error ->
+ {reply, Error, S}
end;
- {value, {AppName, _FromX}} ->
+ {AppName, _FromX} ->
SS = S#state{start_req = [{AppName, From} | Start_req]},
{noreply, SS}
-
end;
handle_call({permit_application, AppName, Bool}, From, S) ->
@@ -769,11 +770,11 @@ handle_call({permit_application, AppName, Bool}, From, S) ->
{noreply, SS};
%%==========================
- %% unpermit the applicaition
+ %% unpermit the application
%%==========================
%% running
{false, _, _, _, _, {value, {_AppName, Id}}} ->
- {value, {_AppName2, Type}} = keysearch(AppName, 1, Started),
+ {_AppName2, Type} = lists:keyfind(AppName, 1, Started),
stop_appl(AppName, Id, Type),
NRunning = keydelete(AppName, 1, Running),
{reply, ok, S#state{running = NRunning}};
@@ -803,9 +804,9 @@ handle_call({permit_application, AppName, Bool}, From, S) ->
handle_call({stop_application, AppName}, _From, S) ->
#state{running = Running, started = Started} = S,
- case keysearch(AppName, 1, Running) of
- {value, {_AppName, Id}} ->
- {value, {_AppName2, Type}} = keysearch(AppName, 1, Started),
+ case lists:keyfind(AppName, 1, Running) of
+ {_AppName, Id} ->
+ {_AppName2, Type} = lists:keyfind(AppName, 1, Started),
stop_appl(AppName, Id, Type),
NRunning = keydelete(AppName, 1, Running),
NStarted = keydelete(AppName, 1, Started),
@@ -831,8 +832,8 @@ handle_call({change_application_data, Applications, Config}, _From, S) ->
end,
[]),
case catch do_change_apps(Applications, Config, OldAppls) of
- {error, R} ->
- {reply, {error, R}, S};
+ {error, _} = Error ->
+ {reply, Error, S};
{'EXIT', R} ->
{reply, {error, R}, S};
NewAppls ->
@@ -886,10 +887,10 @@ handle_call({control_application, AppName}, {Pid, _Tag}, S) ->
handle_call({start_type, AppName}, _From, S) ->
Starting = S#state.starting,
- StartType = case keysearch(AppName, 1, Starting) of
+ StartType = case lists:keyfind(AppName, 1, Starting) of
false ->
local;
- {value, {_AppName, _RestartType, Type, _F}} ->
+ {_AppName, _RestartType, Type, _F} ->
Type
end,
{reply, StartType, S};
@@ -913,7 +914,7 @@ handle_application_started(AppName, Res, S) ->
#state{starting = Starting, running = Running, started = Started,
start_req = Start_req} = S,
Start_reqN = reply_to_requester(AppName, Start_req, Res),
- {value, {_AppName, RestartType, _Type, _From}} = keysearch(AppName, 1, Starting),
+ {_AppName, RestartType, _Type, _From} = lists:keyfind(AppName, 1, Starting),
case Res of
{ok, Id} ->
case AppName of
@@ -928,7 +929,6 @@ handle_application_started(AppName, Res, S) ->
running = NRunning,
started = NStarted,
start_req = Start_reqN},
-
%% The permission may have been changed during start
Perm = application:get_env(kernel, permissions),
case {Perm, Id} of
@@ -939,10 +939,10 @@ handle_application_started(AppName, Res, S) ->
case lists:member({AppName, false}, Perms) of
true ->
#state{running = StopRunning, started = StopStarted} = NewS,
- case keysearch(AppName, 1, StopRunning) of
- {value, {_AppName, Id}} ->
- {value, {_AppName2, Type}} =
- keysearch(AppName, 1, StopStarted),
+ case lists:keyfind(AppName, 1, StopRunning) of
+ {_AppName, Id} ->
+ {_AppName2, Type} =
+ lists:keyfind(AppName, 1, StopStarted),
stop_appl(AppName, Id, Type),
NStopRunning = keydelete(AppName, 1, StopRunning),
cntrl(AppName, NewS, {ac_application_stopped, AppName}),
@@ -957,12 +957,8 @@ handle_application_started(AppName, Res, S) ->
_ ->
{noreply, NewS}
end;
-
-
-
-
- {error, R} when RestartType =:= temporary ->
- notify_cntrl_started(AppName, undefined, S, {error, R}),
+ {error, R} = Error when RestartType =:= temporary ->
+ notify_cntrl_started(AppName, undefined, S, Error),
info_exited(AppName, R, RestartType),
{noreply, S#state{starting = keydelete(AppName, 1, Starting),
start_req = Start_reqN}};
@@ -987,8 +983,8 @@ handle_application_started(AppName, Res, S) ->
Reason = {application_start_failure, AppName, R},
{stop, to_string(Reason), S}
end;
- {error, R} -> %% permanent
- notify_cntrl_started(AppName, undefined, S, {error, R}),
+ {error, R} = Error -> %% permanent
+ notify_cntrl_started(AppName, undefined, S, Error),
info_exited(AppName, R, RestartType),
Reason = {application_start_failure, AppName, R},
{stop, to_string(Reason), S};
@@ -1018,12 +1014,12 @@ handle_info({ac_load_application_reply, AppName, Res}, S) ->
handle_info({ac_start_application_reply, AppName, Res}, S) ->
Start_req = S#state.start_req,
- case keysearch(AppName, 1, Starting = S#state.starting) of
- {value, {_AppName, RestartType, Type, From}} ->
+ case lists:keyfind(AppName, 1, Starting = S#state.starting) of
+ {_AppName, RestartType, Type, From} ->
case Res of
start_it ->
{true, Appl} = get_loaded(AppName),
- spawn_starter(From, Appl, S, Type),
+ spawn_starter(From, Appl, S, Type),
{noreply, S};
{started, Node} ->
handle_application_started(AppName,
@@ -1037,23 +1033,19 @@ handle_info({ac_start_application_reply, AppName, Res}, S) ->
S#state{starting = keydelete(AppName, 1, Starting),
started = [{AppName, RestartType} | Started],
start_req = Start_reqN}};
- {takeover, Node} ->
+ {takeover, _Node} = Takeover ->
{true, Appl} = get_loaded(AppName),
- spawn_starter(From, Appl, S, {takeover, Node}),
+ spawn_starter(From, Appl, S, Takeover),
NewStarting1 = keydelete(AppName, 1, Starting),
- NewStarting = [{AppName, RestartType, {takeover, Node}, From} | NewStarting1],
+ NewStarting = [{AppName, RestartType, Takeover, From} | NewStarting1],
{noreply, S#state{starting = NewStarting}};
- {error, Reason} when RestartType =:= permanent ->
- Start_reqN =
- reply_to_requester(AppName, Start_req,
- {error, Reason}),
+ {error, Reason} = Error when RestartType =:= permanent ->
+ Start_reqN = reply_to_requester(AppName, Start_req, Error),
{stop, to_string(Reason), S#state{start_req = Start_reqN}};
- {error, Reason} ->
- Start_reqN =
- reply_to_requester(AppName, Start_req,
- {error, Reason}),
+ {error, _Reason} = Error ->
+ Start_reqN = reply_to_requester(AppName, Start_req, Error),
{noreply, S#state{starting =
- keydelete(AppName, 1, Starting),
+ keydelete(AppName, 1, Starting),
start_req = Start_reqN}}
end;
false ->
@@ -1064,8 +1056,8 @@ handle_info({ac_change_application_req, AppName, Msg}, S) ->
Running = S#state.running,
Started = S#state.started,
Starting = S#state.starting,
- case {keysearch(AppName, 1, Running), keysearch(AppName, 1, Started)} of
- {{value, {AppName, Id}}, {value, {_AppName2, Type}}} ->
+ case {keyfind(AppName, 1, Running), keyfind(AppName, 1, Started)} of
+ {{AppName, Id}, {_AppName2, Type}} ->
case Msg of
{started, Node} ->
stop_appl(AppName, Id, Type),
@@ -1158,17 +1150,17 @@ handle_info({'EXIT', Pid, Reason}, S) ->
ets:match_delete(ac_tab, {{application_master, '_'}, Pid}),
NRunning = keydelete(Pid, 2, S#state.running),
NewS = S#state{running = NRunning},
- case keysearch(Pid, 2, S#state.running) of
- {value, {AppName, _AmPid}} ->
+ case lists:keyfind(Pid, 2, S#state.running) of
+ {AppName, _AmPid} ->
cntrl(AppName, S, {ac_application_stopped, AppName}),
- case keysearch(AppName, 1, S#state.started) of
- {value, {_AppName, temporary}} ->
+ case lists:keyfind(AppName, 1, S#state.started) of
+ {_AppName, temporary} ->
info_exited(AppName, Reason, temporary),
{noreply, NewS};
- {value, {_AppName, transient}} when Reason =:= normal ->
+ {_AppName, transient} when Reason =:= normal ->
info_exited(AppName, Reason, transient),
{noreply, NewS};
- {value, {_AppName, Type}} ->
+ {_AppName, Type} ->
info_exited(AppName, Reason, Type),
{stop, to_string({application_terminated, AppName, Reason}), NewS}
end;
@@ -1209,8 +1201,8 @@ code_change(_OldVsn, State, _Extra) ->
%%% Internal functions
%%%-----------------------------------------------------------------
cntrl(AppName, #state{control = Control}, Msg) ->
- case keysearch(AppName, 1, Control) of
- {value, {_AppName, Pid}} ->
+ case lists:keyfind(AppName, 1, Control) of
+ {_AppName, Pid} ->
Pid ! Msg,
true;
false ->
@@ -1310,8 +1302,8 @@ check_start_cond(AppName, RestartType, Started, Running) ->
end.
do_start(AppName, RT, Type, From, S) ->
- RestartType = case keysearch(AppName, 1, S#state.started) of
- {value, {_AppName2, OldRT}} ->
+ RestartType = case lists:keyfind(AppName, 1, S#state.started) of
+ {_AppName2, OldRT} ->
get_restart_type(RT, OldRT);
false ->
RT
@@ -1323,12 +1315,12 @@ do_start(AppName, RT, Type, From, S) ->
{true, Appl} = get_loaded(AppName),
Start_req = S#state.start_req,
spawn_starter(undefined, Appl, S, Type),
- Starting = case keysearch(AppName, 1, S#state.starting) of
+ Starting = case lists:keymember(AppName, 1, S#state.starting) of
false ->
%% UW: don't know if this is necessary
[{AppName, RestartType, Type, From} |
S#state.starting];
- _ ->
+ true ->
S#state.starting
end,
S#state{starting = Starting,
@@ -1368,10 +1360,10 @@ start_appl(Appl, S, Type) ->
end
end, Appl#appl.apps),
case application_master:start_link(ApplData, Type) of
- {ok, Pid} ->
- {ok, Pid};
- {error, Reason} ->
- throw({error, Reason})
+ {ok, _Pid} = Ok ->
+ Ok;
+ {error, _Reason} = Error ->
+ throw(Error)
end
end.
@@ -1463,15 +1455,15 @@ prim_parse(Tokens, Acc) ->
case erl_parse:parse_term(Tokens2 ++ [Dot]) of
{ok, Term} ->
prim_parse(Rest, [Term | Acc]);
- {error, Reason} ->
- {error, Reason}
+ {error, _R} = Error ->
+ Error
end;
{Tokens2, []} ->
case erl_parse:parse_term(Tokens2) of
{ok, Term} ->
{ok, lists:reverse([Term | Acc])};
- {error, Reason} ->
- {error, Reason}
+ {error, _R} = Error ->
+ Error
end
end.
@@ -1484,7 +1476,7 @@ make_appl_i({application, Name, Opts}) when is_atom(Name), is_list(Opts) ->
Apps = get_opt(applications, Opts, []),
Mod =
case get_opt(mod, Opts, []) of
- {M,A} when is_atom(M) -> {M,A};
+ {M,_A}=MA when is_atom(M) -> MA;
[] -> [];
Other -> throw({error, {badstartspec, Other}})
end,
@@ -1493,8 +1485,8 @@ make_appl_i({application, Name, Opts}) when is_atom(Name), is_list(Opts) ->
MaxP = get_opt(maxP, Opts, infinity),
MaxT = get_opt(maxT, Opts, infinity),
IncApps = get_opt(included_applications, Opts, []),
- {#appl_data{name = Name, regs = Regs, mod = Mod, phases = Phases, mods = Mods,
- inc_apps = IncApps, maxP = MaxP, maxT = MaxT},
+ {#appl_data{name = Name, regs = Regs, mod = Mod, phases = Phases,
+ mods = Mods, inc_apps = IncApps, maxP = MaxP, maxT = MaxT},
Env, IncApps, Descr, Id, Vsn, Apps};
make_appl_i({application, Name, Opts}) when is_list(Opts) ->
throw({error,{invalid_name,Name}});
@@ -1573,12 +1565,12 @@ do_change_appl({ok, {ApplData, Env, IncApps, Descr, Id, Vsn, Apps}},
vsn=Vsn,
inc_apps=IncApps,
apps=Apps};
-do_change_appl({error, R}, _Appl, _ConfData) ->
- throw({error, R}).
+do_change_appl({error, _R} = Error, _Appl, _ConfData) ->
+ throw(Error).
get_opt(Key, List, Default) ->
- case keysearch(Key, 1, List) of
- {value, {_Key, Val}} -> Val;
+ case lists:keyfind(Key, 1, List) of
+ {_Key, Val} -> Val;
_ -> Default
end.
@@ -1612,8 +1604,8 @@ make_term(Str) ->
end.
get_env_i(Name, #state{conf_data = ConfData}) when is_list(ConfData) ->
- case keysearch(Name, 1, ConfData) of
- {value, {_Name, Env}} -> Env;
+ case lists:keyfind(Name, 1, ConfData) of
+ {_Name, Env} -> Env;
_ -> []
end;
get_env_i(_Name, _) -> [].
@@ -1633,9 +1625,6 @@ merge_env([{App, AppEnv1} | T], Env2, Res) ->
merge_env([], Env2, Res) ->
Env2 ++ Res.
-
-
-
%% Merges envs for an application. Env2 overrides Env1
merge_app_env(Env1, Env2) ->
merge_app_env(Env1, Env2, []).
@@ -1699,13 +1688,12 @@ do_config_change([], _EnvBefore, Errors) ->
{error, Errors};
do_config_change([{App, _Id} | Apps], EnvBefore, Errors) ->
AppEnvNow = lists:sort(application:get_all_env(App)),
- AppEnvBefore = case lists:keysearch(App, 1, EnvBefore) of
+ AppEnvBefore = case lists:keyfind(App, 1, EnvBefore) of
false ->
[];
- {value, {App, AppEnvBeforeT}} ->
+ {App, AppEnvBeforeT} ->
lists:sort(AppEnvBeforeT)
end,
-
Res =
case AppEnvNow of
AppEnvBefore ->
@@ -1725,12 +1713,12 @@ do_config_change([{App, _Id} | Apps], EnvBefore, Errors) ->
%% if the cb-function is not defined
{'EXIT', {undef, _}} ->
ok;
- {error, Error} ->
- {error, Error};
+ {error, _} = Error ->
+ Error;
Else ->
{error, Else}
end;
- {ok,[]} ->
+ {ok, []} ->
{error, {module_not_defined, App}};
undefined ->
{error, {application_not_found, App}}
@@ -1744,9 +1732,7 @@ do_config_change([{App, _Id} | Apps], EnvBefore, Errors) ->
{error, NewError} ->
do_config_change(Apps, EnvBefore,[NewError | Errors])
end.
-
-
-
+
%%-----------------------------------------------------------------
%% Check if the configuration is changed in anyway.
@@ -1760,21 +1746,17 @@ do_config_diff([], AppEnvBefore, {Changed, New}) ->
do_config_diff(AppEnvNow, [], {Changed, New}) ->
{Changed, AppEnvNow++New, []};
do_config_diff([{Env, Value} | AppEnvNow], AppEnvBefore, {Changed, New}) ->
- case lists:keysearch(Env, 1, AppEnvBefore) of
- {value, {Env, Value}} ->
+ case lists:keyfind(Env, 1, AppEnvBefore) of
+ {Env, Value} ->
do_config_diff(AppEnvNow, lists:keydelete(Env,1,AppEnvBefore), {Changed, New});
- {value, {Env, _OtherValue}} ->
+ {Env, _OtherValue} ->
do_config_diff(AppEnvNow, lists:keydelete(Env,1,AppEnvBefore),
{[{Env, Value} | Changed], New});
false ->
do_config_diff(AppEnvNow, AppEnvBefore, {Changed, [{Env, Value}|New]})
end.
-
-
-
-
%%-----------------------------------------------------------------
%% Read the .config files.
%%-----------------------------------------------------------------
@@ -1929,14 +1911,13 @@ reply_to_requester(AppName, Start_req, Res) ->
%% Update the environment variable permission for an application.
%%-----------------------------------------------------------------
update_permissions(AppName, Bool) ->
- case ets:lookup(ac_tab, {env, kernel, permissions}) of
+ T = {env, kernel, permissions},
+ case ets:lookup(ac_tab, T) of
[] ->
- ets:insert(ac_tab, {{env, kernel, permissions},
- [{AppName, Bool}]});
+ ets:insert(ac_tab, {T, [{AppName, Bool}]});
[{_, Perm}] ->
Perm2 = lists:keydelete(AppName, 1, Perm),
- ets:insert(ac_tab, {{env, kernel, permissions},
- [{AppName, Bool}| Perm2]})
+ ets:insert(ac_tab, {T, [{AppName, Bool}|Perm2]})
end.
%%-----------------------------------------------------------------
diff --git a/lib/kernel/src/application_starter.erl b/lib/kernel/src/application_starter.erl
index 8d839e4662..564366f304 100644
--- a/lib/kernel/src/application_starter.erl
+++ b/lib/kernel/src/application_starter.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1998-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 1998-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%
%%
%% ----------------------------------------------------------------------
@@ -42,8 +42,8 @@ start([], _Type, _Apps) ->
ok;
start([{Phase,_PhaseArgs}|Phases], Type, Apps) ->
case start_apps(Phase, Type, Apps) of
- {error, Error} ->
- {error, Error};
+ {error, _} = Error ->
+ Error;
_ ->
start(Phases, Type, Apps)
end.
@@ -56,8 +56,8 @@ start_apps(_Phase, _Type, []) ->
ok;
start_apps(Phase, Type, [App | Apps]) ->
case catch run_start_phase(Phase, Type, App) of
- {error, Error} ->
- {error, Error};
+ {error, _} = Error ->
+ Error;
_ ->
start_apps(Phase, Type, Apps)
end.
@@ -91,10 +91,10 @@ run_the_phase(Phase, Type, App, Mod) ->
{ok, Sp} ->
Sp
end,
- case lists:keysearch(Phase, 1, Start_phases) of
+ case lists:keyfind(Phase, 1, Start_phases) of
false ->
ok;
- {value, {Phase, PhaseArgs}} ->
+ {Phase, PhaseArgs} ->
case catch Mod:start_phase(Phase, Type, PhaseArgs) of
ok ->
ok;
diff --git a/lib/kernel/src/auth.erl b/lib/kernel/src/auth.erl
index 31ee1d1ef4..7fe30ae828 100644
--- a/lib/kernel/src/auth.erl
+++ b/lib/kernel/src/auth.erl
@@ -119,8 +119,8 @@ sync_cookie() ->
-spec print(Node :: node(), Format :: string(), Args :: [_]) -> 'ok'.
-print(Node,Format,Args) ->
- (catch gen_server:cast({auth,Node},{print,Format,Args})).
+print(Node, Format, Args) ->
+ (catch gen_server:cast({auth, Node}, {print, Format, Args})).
%%--gen_server callbacks------------------------------------------------
@@ -154,7 +154,7 @@ handle_call({set_cookie, Node, Cookie}, {_From,_Tag}, State)
%%
%% Happens when the distribution is brought up and
-%% Someone wight have set up the cookie for our new nodename.
+%% someone might have set up the cookie for our new node name.
%%
handle_call({set_cookie, Node, Cookie}, {_From,_Tag}, State) ->
@@ -162,9 +162,9 @@ handle_call({set_cookie, Node, Cookie}, {_From,_Tag}, State) ->
{reply, true, State};
handle_call(sync_cookie, _From, State) ->
- case ets:lookup(State#state.other_cookies,node()) of
+ case ets:lookup(State#state.other_cookies, node()) of
[{_N,C}] ->
- ets:delete(State#state.other_cookies,node()),
+ ets:delete(State#state.other_cookies, node()),
{reply, true, State#state{our_cookie = C}};
[] ->
{reply, true, State}
@@ -182,7 +182,7 @@ handle_call(echo, _From, O) ->
handle_cast({print,What,Args}, O) ->
%% always allow print outs
- error_logger:error_msg(What,Args),
+ error_logger:error_msg(What, Args),
{noreply, O}.
%% A series of bad messages that may come (from older distribution versions).
@@ -206,10 +206,10 @@ handle_info({_From,badcookie,ddd_server,_Mess}, O) ->
{noreply, O};
handle_info({From,badcookie,rex,_Msg}, O) ->
auth:print(getnode(From),
- "~n** Unauthorized rpc attempt to ~w **~n",[node()]),
+ "~n** Unauthorized rpc attempt to ~w **~n", [node()]),
disconnect_node(node(From)),
{noreply, O};
-%% These two messages has to do with the old auth:is_auth() call (net_adm:ping)
+%% These two messages have to do with the old auth:is_auth() call (net_adm:ping)
handle_info({From,badcookie,net_kernel,{'$gen_call',{From,Tag},{is_auth,_Node}}}, O) -> %% ho ho
From ! {Tag, no},
{noreply, O};
@@ -233,7 +233,7 @@ handle_info({From,badcookie,Name,Mess}, Opened) ->
end
end,
{noreply, Opened};
-handle_info(_, O)-> % Ignore anything else especially EXIT signals
+handle_info(_, O) -> % Ignore anything else especially EXIT signals
{noreply, O}.
-spec code_change(term(), state(), term()) -> {'ok', state()}.
@@ -282,7 +282,7 @@ init_cookie() ->
end;
_Other ->
#state{our_cookie = nocookie,
- other_cookies = ets:new(cookies,[?COOKIE_ETS_PROTECTION])}
+ other_cookies = ets:new(cookies, [?COOKIE_ETS_PROTECTION])}
end.
read_cookie() ->
diff --git a/lib/kernel/src/code.erl b/lib/kernel/src/code.erl
index ffe58ae7a9..affa5fc0fd 100644
--- a/lib/kernel/src/code.erl
+++ b/lib/kernel/src/code.erl
@@ -425,8 +425,8 @@ where_is_file(Path, File) when is_list(Path), is_list(File) ->
FileInfo :: #file_info{})
-> 'ok' | {'error', atom()}.
-set_primary_archive(ArchiveFile0, ArchiveBin, FileInfo)
- when is_list(ArchiveFile0), is_binary(ArchiveBin), is_record(FileInfo, file_info) ->
+set_primary_archive(ArchiveFile0, ArchiveBin, #file_info{} = FileInfo)
+ when is_list(ArchiveFile0), is_binary(ArchiveBin) ->
ArchiveFile = filename:absname(ArchiveFile0),
case call({set_primary_archive, ArchiveFile, ArchiveBin, FileInfo}) of
{ok, []} ->
@@ -473,7 +473,7 @@ decorate([], _) -> [];
decorate([File|Tail], Dir) ->
[{Dir, File} | decorate(Tail, Dir)].
-filter(_Ext, Dir, {error,_}) ->
+filter(_Ext, Dir, error) ->
io:format("** Bad path can't read ~s~n", [Dir]), [];
filter(Ext, _, {ok,Files}) ->
filter2(Ext, length(Ext), Files).
diff --git a/lib/kernel/src/code_server.erl b/lib/kernel/src/code_server.erl
index 2bc93b8238..4a1fc7df34 100644
--- a/lib/kernel/src/code_server.erl
+++ b/lib/kernel/src/code_server.erl
@@ -66,8 +66,8 @@ init(Ref, Parent, [Root,Mode0]) ->
Mode =
case Mode0 of
- minimal -> interactive;
- _ -> Mode0
+ minimal -> interactive;
+ _ -> Mode0
end,
IPath =
@@ -75,7 +75,7 @@ init(Ref, Parent, [Root,Mode0]) ->
interactive ->
LibDir = filename:append(Root, "lib"),
{ok,Dirs} = erl_prim_loader:list_dir(LibDir),
- {Paths,_Libs} = make_path(LibDir,Dirs),
+ {Paths,_Libs} = make_path(LibDir, Dirs),
UserLibPaths = get_user_lib_dirs(),
["."] ++ UserLibPaths ++ Paths;
_ ->
@@ -98,7 +98,7 @@ init(Ref, Parent, [Root,Mode0]) ->
end,
Parent ! {Ref,{ok,self()}},
- loop(State#state{supervisor=Parent}).
+ loop(State#state{supervisor = Parent}).
get_user_lib_dirs() ->
case os:getenv("ERL_LIBS") of
@@ -170,8 +170,8 @@ loop(#state{supervisor=Supervisor}=State0) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% System upgrade
-handle_system_msg(SysState,Msg,From,Parent,Misc) ->
- case do_sys_cmd(SysState,Msg,Parent, Misc) of
+handle_system_msg(SysState, Msg, From, Parent, Misc) ->
+ case do_sys_cmd(SysState, Msg, Parent, Misc) of
{suspended, Reply, NMisc} ->
gen_reply(From, Reply),
suspend_loop(suspended, Parent, NMisc);
@@ -208,7 +208,7 @@ do_sys_cmd(SysState, {debug, _What}, _Parent, Misc) ->
do_sys_cmd(suspended, {change_code, Module, Vsn, Extra}, _Parent, Misc0) ->
{Res, Misc} =
case catch ?MODULE:system_code_change(Misc0, Module, Vsn, Extra) of
- {ok, Misc1} -> {ok, Misc1};
+ {ok, _} = Ok -> Ok;
Else -> {{error, Else}, Misc0}
end,
{suspended, Res, Misc};
@@ -219,7 +219,7 @@ system_continue(_Parent, _Debug, State) ->
loop(State).
system_terminate(_Reason, _Parent, _Debug, _State) ->
-% error_msg("~p terminating: ~p~n ",[?MODULE,Reason]),
+ %% error_msg("~p terminating: ~p~n ", [?MODULE, Reason]),
exit(shutdown).
-spec system_code_change(state(), module(), term(), term()) -> {'ok', state()}.
@@ -242,7 +242,7 @@ handle_call({stick_mod,Mod}, {_From,_Tag}, S) ->
handle_call({unstick_mod,Mod}, {_From,_Tag}, S) ->
{reply,stick_mod(Mod, false, S),S};
-handle_call({dir,Dir},{_From,_Tag}, S) ->
+handle_call({dir,Dir}, {_From,_Tag}, S) ->
Root = S#state.root,
Resp = do_dir(Root,Dir,S#state.namedb),
{reply,Resp,S};
@@ -255,43 +255,47 @@ handle_call({load_file,Mod}, Caller, St) ->
load_file(Mod, Caller, St)
end;
-handle_call({add_path,Where,Dir0}, {_From,_Tag}, S=#state{cache=Cache0}) ->
+handle_call({add_path,Where,Dir0}, {_From,_Tag},
+ #state{cache=Cache0,namedb=Namedb,path=Path0}=S) ->
case Cache0 of
no_cache ->
- {Resp,Path} = add_path(Where, Dir0, S#state.path, S#state.namedb),
+ {Resp,Path} = add_path(Where, Dir0, Path0, Namedb),
{reply,Resp,S#state{path=Path}};
_ ->
Dir = absname(Dir0), %% Cache always expands the path
- {Resp,Path} = add_path(Where, Dir, S#state.path, S#state.namedb),
- Cache=update_cache([Dir],Where,Cache0),
+ {Resp,Path} = add_path(Where, Dir, Path0, Namedb),
+ Cache = update_cache([Dir], Where, Cache0),
{reply,Resp,S#state{path=Path,cache=Cache}}
end;
-handle_call({add_paths,Where,Dirs0}, {_From,_Tag}, S=#state{cache=Cache0}) ->
+handle_call({add_paths,Where,Dirs0}, {_From,_Tag},
+ #state{cache=Cache0,namedb=Namedb,path=Path0}=S) ->
case Cache0 of
no_cache ->
- {Resp,Path} = add_paths(Where,Dirs0,S#state.path,S#state.namedb),
- {reply,Resp, S#state{path=Path}};
+ {Resp,Path} = add_paths(Where, Dirs0, Path0, Namedb),
+ {reply,Resp,S#state{path=Path}};
_ ->
%% Cache always expands the path
Dirs = [absname(Dir) || Dir <- Dirs0],
- {Resp,Path} = add_paths(Where, Dirs, S#state.path, S#state.namedb),
+ {Resp,Path} = add_paths(Where, Dirs, Path0, Namedb),
Cache=update_cache(Dirs,Where,Cache0),
{reply,Resp,S#state{cache=Cache,path=Path}}
end;
-handle_call({set_path,PathList}, {_From,_Tag}, S) ->
- Path = S#state.path,
- {Resp, NewPath,NewDb} = set_path(PathList, Path, S#state.namedb),
- {reply,Resp,rehash_cache(S#state{path = NewPath, namedb=NewDb})};
+handle_call({set_path,PathList}, {_From,_Tag},
+ #state{path=Path0,namedb=Namedb}=S) ->
+ {Resp,Path,NewDb} = set_path(PathList, Path0, Namedb),
+ {reply,Resp,rehash_cache(S#state{path=Path,namedb=NewDb})};
-handle_call({del_path,Name}, {_From,_Tag}, S) ->
- {Resp,Path} = del_path(Name,S#state.path,S#state.namedb),
- {reply,Resp,rehash_cache(S#state{path = Path})};
+handle_call({del_path,Name}, {_From,_Tag},
+ #state{path=Path0,namedb=Namedb}=S) ->
+ {Resp,Path} = del_path(Name, Path0, Namedb),
+ {reply,Resp,rehash_cache(S#state{path=Path})};
-handle_call({replace_path,Name,Dir}, {_From,_Tag}, S) ->
- {Resp,Path} = replace_path(Name,Dir,S#state.path,S#state.namedb),
- {reply,Resp,rehash_cache(S#state{path = Path})};
+handle_call({replace_path,Name,Dir}, {_From,_Tag},
+ #state{path=Path0,namedb=Namedb}=S) ->
+ {Resp,Path} = replace_path(Name, Dir, Path0, Namedb),
+ {reply,Resp,rehash_cache(S#state{path=Path})};
handle_call(rehash, {_From,_Tag}, S0) ->
S = create_cache(S0),
@@ -313,12 +317,12 @@ handle_call({load_binary,Mod,File,Bin}, Caller, S) ->
do_load_binary(Mod, File, Bin, Caller, S);
handle_call({load_native_partial,Mod,Bin}, {_From,_Tag}, S) ->
- Result = (catch hipe_unified_loader:load(Mod,Bin)),
+ Result = (catch hipe_unified_loader:load(Mod, Bin)),
Status = hipe_result_to_status(Result),
{reply,Status,S};
handle_call({load_native_sticky,Mod,Bin,WholeModule}, {_From,_Tag}, S) ->
- Result = (catch hipe_unified_loader:load_module(Mod,Bin,WholeModule)),
+ Result = (catch hipe_unified_loader:load_module(Mod, Bin, WholeModule)),
Status = hipe_result_to_status(Result),
{reply,Status,S};
@@ -390,8 +394,8 @@ handle_call({set_primary_archive, File, ArchiveBin, FileInfo}, {_From,_Tag}, S=#
case erl_prim_loader:set_primary_archive(File, ArchiveBin, FileInfo) of
{ok, Files} ->
{reply, {ok, Mode, Files}, S};
- {error, Reason} ->
- {reply, {error, Reason}, S}
+ {error, _Reason} = Error ->
+ {reply, Error, S}
end;
handle_call({is_cached,File}, {_From,_Tag}, S=#state{cache=Cache}) ->
@@ -471,8 +475,8 @@ locate_mods([], _, _, Cache, Path) ->
filter_mods([File|Rest], Where, Exts, Dir, Cache) ->
Ext = filename:extension(File),
Root = list_to_atom(filename:rootname(File, Ext)),
- case lists:keysearch(Ext, 2, Exts) of
- {value,{Type,_}} ->
+ case lists:keyfind(Ext, 2, Exts) of
+ {Type, _} ->
Key = {Type,Root},
case Where of
first ->
@@ -489,7 +493,6 @@ filter_mods([File|Rest], Where, Exts, Dir, Cache) ->
ok
end,
filter_mods(Rest, Where, Exts, Dir, Cache);
-
filter_mods([], _, _, _, Cache) ->
Cache.
@@ -500,27 +503,27 @@ filter_mods([], _, _, _, Cache) ->
%%
%% Create the initial path.
%%
-make_path(BundleDir,Bundles0) ->
+make_path(BundleDir, Bundles0) ->
Bundles = choose_bundles(Bundles0),
- make_path(BundleDir,Bundles,[],[]).
+ make_path(BundleDir, Bundles, [], []).
choose_bundles(Bundles) ->
ArchiveExt = archive_extension(),
- Bs = lists:sort([create_bundle(B,ArchiveExt) || B <- Bundles]),
+ Bs = lists:sort([create_bundle(B, ArchiveExt) || B <- Bundles]),
[FullName || {_Name,_NumVsn,FullName} <-
choose(lists:reverse(Bs), [], ArchiveExt)].
-create_bundle(FullName,ArchiveExt) ->
- BaseName = filename:basename(FullName,ArchiveExt),
+create_bundle(FullName, ArchiveExt) ->
+ BaseName = filename:basename(FullName, ArchiveExt),
case split(BaseName, "-") of
- Toks when length(Toks) > 1 ->
+ [_, _|_] = Toks ->
VsnStr = lists:last(Toks),
case vsn_to_num(VsnStr) of
{ok, VsnNum} ->
- Name = join(lists:sublist(Toks,length(Toks)-1),"-"),
+ Name = join(lists:sublist(Toks, length(Toks)-1),"-"),
{Name,VsnNum,FullName};
false ->
- {FullName, [0], FullName}
+ {FullName,[0],FullName}
end;
_ ->
{FullName,[0],FullName}
@@ -571,8 +574,8 @@ join([], _) ->
[].
choose([{Name,NumVsn,NewFullName}=New|Bs], Acc, ArchiveExt) ->
- case lists:keysearch(Name,1,Acc) of
- {value, {_, NV, OldFullName}} when NV =:= NumVsn ->
+ case lists:keyfind(Name, 1, Acc) of
+ {_, NV, OldFullName} when NV =:= NumVsn ->
case filename:extension(OldFullName) =:= ArchiveExt of
false ->
choose(Bs,Acc, ArchiveExt);
@@ -580,7 +583,7 @@ choose([{Name,NumVsn,NewFullName}=New|Bs], Acc, ArchiveExt) ->
Acc2 = lists:keystore(Name, 1, Acc, New),
choose(Bs,Acc2, ArchiveExt)
end;
- {value, {_, _, _}} ->
+ {_, _, _} ->
choose(Bs,Acc, ArchiveExt);
false ->
choose(Bs,[{Name,NumVsn,NewFullName}|Acc], ArchiveExt)
@@ -604,8 +607,8 @@ make_path(BundleDir,[Bundle|Tail],Res,Bs) ->
Ebin2 = filename:join([filename:dirname(Dir), Base ++ Ext, Base, "ebin"]),
Ebins =
case split(Base, "-") of
- Toks when length(Toks) > 1 ->
- AppName = join(lists:sublist(Toks,length(Toks)-1),"-"),
+ [_, _|_] = Toks ->
+ AppName = join(lists:sublist(Toks, length(Toks)-1),"-"),
Ebin3 = filename:join([filename:dirname(Dir), Base ++ Ext, AppName, "ebin"]),
[Ebin3, Ebin2, Dir];
_ ->
@@ -837,30 +840,25 @@ add_path(_,_,Path,_) ->
%% then the table is created :-)
%%
do_add(first,Dir,Path,NameDb) ->
- update(Dir,NameDb),
+ update(Dir, NameDb),
[Dir|lists:delete(Dir,Path)];
do_add(last,Dir,Path,NameDb) ->
case lists:member(Dir,Path) of
true ->
Path;
false ->
- maybe_update(Dir,NameDb),
+ maybe_update(Dir, NameDb),
Path ++ [Dir]
end.
%% Do not update if the same name already exists !
-maybe_update(Dir,NameDb) ->
- case lookup_name(get_name(Dir),NameDb) of
- false -> update(Dir,NameDb);
- _ -> false
- end.
+maybe_update(Dir, NameDb) ->
+ (lookup_name(get_name(Dir), NameDb) =:= false) andalso update(Dir, NameDb).
update(_Dir, false) ->
- ok;
-update(Dir,NameDb) ->
- replace_name(Dir,NameDb).
-
-
+ true;
+update(Dir, NameDb) ->
+ replace_name(Dir, NameDb).
%%
%% Set a completely new path.
@@ -948,8 +946,8 @@ all_archive_subdirs(AppDir) ->
Base = filename:basename(AppDir),
Dirs =
case split(Base, "-") of
- Toks when length(Toks) > 1 ->
- Base2 = join(lists:sublist(Toks,length(Toks)-1),"-"),
+ [_, _|_] = Toks ->
+ Base2 = join(lists:sublist(Toks, length(Toks)-1), "-"),
[Base2, Base];
_ ->
[Base]
@@ -1062,7 +1060,6 @@ check_pars(Name,Dir) ->
{error,bad_name}
end.
-
del_ebin(Dir) ->
case filename:basename(Dir) of
"ebin" ->
@@ -1081,8 +1078,6 @@ del_ebin(Dir) ->
Dir
end.
-
-
replace_name(Dir, Db) ->
case get_name(Dir) of
Dir ->
@@ -1189,15 +1184,7 @@ get_mods([File|Tail], Extension) ->
get_mods([], _) -> [].
is_sticky(Mod, Db) ->
- case erlang:module_loaded(Mod) of
- true ->
- case ets:lookup(Db, {sticky,Mod}) of
- [] -> false;
- _ -> true
- end;
- false ->
- false
- end.
+ erlang:module_loaded(Mod) andalso (ets:lookup(Db, {sticky, Mod}) =/= []).
add_paths(Where,[Dir|Tail],Path,NameDb) ->
{_,NPath} = add_path(Where,Dir,Path,NameDb),
@@ -1205,7 +1192,6 @@ add_paths(Where,[Dir|Tail],Path,NameDb) ->
add_paths(_,_,Path,_) ->
{ok,Path}.
-
do_load_binary(Module, File, Binary, Caller, St) ->
case modp(Module) andalso modp(File) andalso is_binary(Binary) of
true ->
@@ -1222,7 +1208,6 @@ modp(Atom) when is_atom(Atom) -> true;
modp(List) when is_list(List) -> int_list(List);
modp(_) -> false.
-
load_abs(File, Mod0, Caller, St) ->
Ext = objfile_extension(),
FileName0 = lists:concat([File, Ext]),
@@ -1265,20 +1250,20 @@ try_load_module_1(File, Mod, Bin, Caller, #state{moddb=Db}=St) ->
{reply,{error,sticky_directory},St};
false ->
case catch load_native_code(Mod, Bin) of
- {module,Mod} ->
+ {module,Mod} = Module ->
ets:insert(Db, {Mod,File}),
- {reply,{module,Mod},St};
+ {reply,Module,St};
no_native ->
case erlang:load_module(Mod, Bin) of
- {module,Mod} ->
+ {module,Mod} = Module ->
ets:insert(Db, {Mod,File}),
post_beam_load(Mod),
- {reply,{module,Mod},St};
+ {reply,Module,St};
{error,on_load} ->
handle_on_load(Mod, File, Caller, St);
- {error,What} ->
+ {error,What} = Error ->
error_msg("Loading of ~s failed: ~p\n", [File, What]),
- {reply,{error,What},St}
+ {reply,Error,St}
end;
Error ->
error_msg("Native loading of ~s failed: ~p\n",
diff --git a/lib/kernel/src/erl_boot_server.erl b/lib/kernel/src/erl_boot_server.erl
index c5a4305731..b4c5f5e27c 100644
--- a/lib/kernel/src/erl_boot_server.erl
+++ b/lib/kernel/src/erl_boot_server.erl
@@ -179,15 +179,15 @@ init(Slaves) ->
Pid ! {Ref, L},
%% We trap exit inorder to restart boot_init and udp_port
process_flag(trap_exit, true),
- {ok, #state {priority = 0,
- version = erlang:system_info(version),
- udp_sock = U,
- udp_port = UPort,
- listen_sock = L,
- listen_port = Port,
- slaves = ordsets:from_list(Slaves),
- bootp = Pid
- }}.
+ {ok, #state{priority = 0,
+ version = erlang:system_info(version),
+ udp_sock = U,
+ udp_port = UPort,
+ listen_sock = L,
+ listen_port = Port,
+ slaves = ordsets:from_list(Slaves),
+ bootp = Pid
+ }}.
-spec handle_call('which' | {'add',atom()} | {'delete',atom()}, _, state()) ->
{'reply', 'ok' | [atom()], state()}.
diff --git a/lib/kernel/src/erl_epmd.erl b/lib/kernel/src/erl_epmd.erl
index c4ff4c7281..4a22637304 100644
--- a/lib/kernel/src/erl_epmd.erl
+++ b/lib/kernel/src/erl_epmd.erl
@@ -141,8 +141,8 @@ handle_call({register, Name, PortNo}, _From, State) ->
end;
handle_call(client_info_req, _From, State) ->
- Reply = {ok,{r4,State#state.name,State#state.port_no}},
- {reply,Reply,State};
+ Reply = {ok,{r4,State#state.name,State#state.port_no}},
+ {reply, Reply, State};
handle_call(stop, _From, State) ->
{stop, shutdown, ok, State}.
diff --git a/lib/kernel/src/error_handler.erl b/lib/kernel/src/error_handler.erl
index 5f2507fc08..17dd02acd4 100644
--- a/lib/kernel/src/error_handler.erl
+++ b/lib/kernel/src/error_handler.erl
@@ -1,19 +1,19 @@
%%
%% %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
%% 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(error_handler).
@@ -117,13 +117,13 @@ stub_function(Mod, Func, Args) ->
check_inheritance(Module, Args) ->
Attrs = erlang:get_module_info(Module, attributes),
- case lists:keysearch(extends, 1, Attrs) of
- {value,{extends,[Base]}} when is_atom(Base), Base =/= Module ->
+ case lists:keyfind(extends, 1, Attrs) of
+ {extends, [Base]} when is_atom(Base), Base =/= Module ->
%% This is just a heuristic for detecting abstract modules
%% with inheritance so they can be handled; it would be
%% much better to do it in the emulator runtime
- case lists:keysearch(abstract, 1, Attrs) of
- {value,{abstract,[true]}} ->
+ case lists:keyfind(abstract, 1, Attrs) of
+ {abstract, [true]} ->
case lists:reverse(Args) of
[M|Rs] when tuple_size(M) > 1,
element(1,M) =:= Module,
diff --git a/lib/kernel/src/file_io_server.erl b/lib/kernel/src/file_io_server.erl
index 37e803c493..3ac35a209d 100644
--- a/lib/kernel/src/file_io_server.erl
+++ b/lib/kernel/src/file_io_server.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2000-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
-module(file_io_server).
@@ -106,21 +106,21 @@ do_start(Spawn, Owner, FileName, ModeList) ->
parse_options(List) ->
parse_options(expand_encoding(List), list, latin1, []).
-parse_options([],list,Uni,Acc) ->
+parse_options([], list, Uni, Acc) ->
{list,Uni,[binary|lists:reverse(Acc)]};
-parse_options([],binary,Uni,Acc) ->
+parse_options([], binary, Uni, Acc) ->
{binary,Uni,lists:reverse(Acc)};
-parse_options([{encoding, Encoding}|T],RMode,_,Acc) ->
+parse_options([{encoding, Encoding}|T], RMode, _, Acc) ->
case valid_enc(Encoding) of
{ok, ExpandedEnc} ->
- parse_options(T,RMode,ExpandedEnc,Acc);
- {error,Reason} ->
- {error,Reason}
+ parse_options(T, RMode, ExpandedEnc, Acc);
+ {error,_Reason} = Error ->
+ Error
end;
-parse_options([binary|T],_,Uni,Acc) ->
- parse_options(T,binary,Uni,[binary|Acc]);
-parse_options([H|T],R,U,Acc) ->
- parse_options(T,R,U,[H|Acc]).
+parse_options([binary|T], _, Uni, Acc) ->
+ parse_options(T, binary, Uni, [binary|Acc]);
+parse_options([H|T], R, U, Acc) ->
+ parse_options(T, R, U, [H|Acc]).
expand_encoding([]) ->
[];
@@ -153,7 +153,6 @@ valid_enc(_Other) ->
{error,badarg}.
-
server_loop(#state{mref = Mref} = State) ->
receive
{file_request, From, ReplyAs, Request} when is_pid(From) ->
@@ -326,7 +325,6 @@ io_request(Unknown,
{error,{error,Reason},State}.
-
%% Process a list of requests as long as the results are ok.
io_request_loop([], Result) ->
@@ -342,7 +340,6 @@ io_request_loop([Request|Tail],
io_request_loop(Tail, io_request(Request, State)).
-
%% I/O request put_chars
%%
put_chars(Chars, latin1, #state{handle=Handle, unic=latin1}=State) ->
@@ -653,20 +650,14 @@ do_setopts(Opts, State) ->
end.
getopts(#state{read_mode=RM, unic=Unic} = State) ->
- Bin = {binary, case RM of
- binary ->
- true;
- _ ->
- false
- end},
+ Bin = {binary, RM =:= binary},
Uni = {encoding, Unic},
{reply,[Bin,Uni],State}.
-
%% Concatenate two binaries and convert the result to list or binary
-cat(B1, B2, binary,latin1,latin1) ->
+cat(B1, B2, binary, latin1, latin1) ->
list_to_binary([B1,B2]);
-cat(B1, B2, binary,InEncoding,OutEncoding) ->
+cat(B1, B2, binary, InEncoding, OutEncoding) ->
case unicode:characters_to_binary([B1,B2],InEncoding,OutEncoding) of
Good when is_binary(Good) ->
Good;
diff --git a/lib/kernel/src/heart.erl b/lib/kernel/src/heart.erl
index bad0950fca..e78acfc7a6 100644
--- a/lib/kernel/src/heart.erl
+++ b/lib/kernel/src/heart.erl
@@ -1,19 +1,19 @@
%%
%% %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
%% 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(heart).
@@ -61,8 +61,8 @@ start() ->
wait_for_init_ack(From) ->
receive
- {ok, From} ->
- {ok, From};
+ {ok, From} = Ok ->
+ Ok;
{no_heart, From} ->
ignore;
{Error, From} ->
@@ -119,8 +119,7 @@ wait() ->
start_portprogram() ->
check_start_heart(),
- HeartCmd = "heart -pid " ++ os:getpid() ++ " " ++
- get_heart_timeouts(),
+ HeartCmd = "heart -pid " ++ os:getpid() ++ " " ++ get_heart_timeouts(),
try open_port({spawn, HeartCmd}, [{packet, 2}]) of
Port when is_port(Port) ->
case wait_ack(Port) of
@@ -175,7 +174,7 @@ wait_ack(Port) ->
loop(Parent, Port, Cmd) ->
send_heart_beat(Port),
receive
- {From, set_cmd, NewCmd} when is_list(NewCmd), length(NewCmd) < 2047 ->
+ {From, set_cmd, NewCmd} when length(NewCmd) < 2047 ->
send_heart_cmd(Port, NewCmd),
wait_ack(Port),
From ! {heart, ok},
diff --git a/lib/kernel/src/inet_db.erl b/lib/kernel/src/inet_db.erl
index ec95620cc0..d4749b9756 100644
--- a/lib/kernel/src/inet_db.erl
+++ b/lib/kernel/src/inet_db.erl
@@ -102,14 +102,14 @@
start() ->
case gen_server:start({local, inet_db}, inet_db, [], []) of
- {ok,Pid} -> inet_config:init(), {ok,Pid};
+ {ok, _Pid}=Ok -> inet_config:init(), Ok;
Error -> Error
end.
start_link() ->
case gen_server:start_link({local, inet_db}, inet_db, [], []) of
- {ok,Pid} -> inet_config:init(), {ok,Pid};
+ {ok, _Pid}=Ok -> inet_config:init(), Ok;
Error -> Error
end.
@@ -140,7 +140,6 @@ add_hosts(File) ->
Error -> Error
end.
-
add_host(IP, Names) -> call({add_host, IP, Names}).
del_host(IP) -> call({del_host, IP}).
@@ -482,10 +481,7 @@ res_check_option_absfile(F) ->
res_check_list([], _Fun) -> true;
res_check_list([H|T], Fun) ->
- case Fun(H) of
- true -> res_check_list(T, Fun);
- false -> false
- end;
+ Fun(H) andalso res_check_list(T, Fun);
res_check_list(_, _Fun) -> false.
res_check_ns({{A,B,C,D,E,F,G,H}, Port})
@@ -497,12 +493,12 @@ res_check_ns(_) -> false.
res_check_search("") -> true;
res_check_search(Dom) -> inet_parse:visible_string(Dom).
-socks_option(server) -> db_get(socks5_server);
-socks_option(port) -> db_get(socks5_port);
-socks_option(methods) -> db_get(socks5_methods);
-socks_option(noproxy) -> db_get(socks5_noproxy).
+socks_option(server) -> db_get(socks5_server);
+socks_option(port) -> db_get(socks5_port);
+socks_option(methods) -> db_get(socks5_methods);
+socks_option(noproxy) -> db_get(socks5_noproxy).
-gethostname() -> db_get(hostname).
+gethostname() -> db_get(hostname).
res_update_conf() ->
res_update(res_resolv_conf, res_resolv_conf_tm, res_resolv_conf_info,
@@ -591,15 +587,13 @@ getbyname(Name, Type) ->
getbysearch(Name, Dot, [Dom | Ds], Type, _) ->
case hostent_by_domain(Name ++ Dot ++ Dom, Type) of
- {ok, HEnt} -> {ok, HEnt};
- Error ->
- getbysearch(Name, Dot, Ds, Type, Error)
+ {ok, _HEnt}=Ok -> Ok;
+ Error -> getbysearch(Name, Dot, Ds, Type, Error)
end;
getbysearch(_Name, _Dot, [], _Type, Error) ->
Error.
-
%%
%% get_searchlist
%%
@@ -610,7 +604,6 @@ get_searchlist() ->
end.
-
make_hostent(Name, Addrs, Aliases, ?S_A) ->
#hostent {
h_name = Name,
@@ -1146,7 +1139,6 @@ handle_call(Request, From, #state{db=Db}=State) ->
{reply, error, State}
end.
-
%%----------------------------------------------------------------------
%% Func: handle_cast/2
%% Returns: {noreply, State} |
@@ -1359,16 +1351,15 @@ do_add_rr(RR, Db, State) ->
TM = times(),
case alloc_entry(Db, CacheDb, TM) of
true ->
- cache_rr(Db, CacheDb, RR#dns_rr { tm = TM,
- cnt = TM });
+ cache_rr(Db, CacheDb, RR#dns_rr{tm = TM, cnt = TM});
_ ->
false
end.
cache_rr(_Db, Cache, RR) ->
%% delete possible old entry
- ets:match_delete(Cache, RR#dns_rr { cnt = '_', tm = '_', ttl = '_',
- bm = '_', func = '_'}),
+ ets:match_delete(Cache, RR#dns_rr{cnt = '_', tm = '_', ttl = '_',
+ bm = '_', func = '_'}),
ets:insert(Cache, RR).
times() ->
@@ -1378,9 +1369,9 @@ times() ->
%% lookup and remove old entries
do_lookup_rr(Domain, Class, Type) ->
- match_rr(#dns_rr { domain = tolower(Domain), class = Class,type = Type,
- cnt = '_', tm = '_', ttl = '_',
- bm = '_', func = '_', data = '_'}).
+ match_rr(#dns_rr{domain = tolower(Domain), class = Class,type = Type,
+ cnt = '_', tm = '_', ttl = '_',
+ bm = '_', func = '_', data = '_'}).
match_rr(RR) ->
filter_rr(ets:match_object(inet_cache, RR), times()).
@@ -1431,7 +1422,7 @@ dn_in_addr_arpa(A,B,C,D) ->
integer_to_list(A) ++ ".in-addr.arpa".
dnib(X) ->
- [ hex(X), $., hex(X bsr 4), $., hex(X bsr 8), $., hex(X bsr 12), $.].
+ [hex(X), $., hex(X bsr 4), $., hex(X bsr 8), $., hex(X bsr 12), $.].
hex(X) ->
X4 = (X band 16#f),
@@ -1526,12 +1517,7 @@ alloc_entry(CacheDb, OldSize, TM, N) ->
delete_n_oldest(CacheDb, TM, OldestTM, N) ->
DelTM = trunc((TM - OldestTM) * 0.3) + OldestTM,
- case delete_older(CacheDb, DelTM, N) of
- 0 ->
- false;
- _ ->
- true
- end.
+ delete_older(CacheDb, DelTM, N) =/= 0.
%% Delete entries with latest access time older than TM.
%% Delete max N number of entries.
diff --git a/lib/kernel/src/inet_gethost_native.erl b/lib/kernel/src/inet_gethost_native.erl
index b7b3007b99..db3e44ce6f 100644
--- a/lib/kernel/src/inet_gethost_native.erl
+++ b/lib/kernel/src/inet_gethost_native.erl
@@ -154,7 +154,7 @@ run_once() ->
{Port, {data, <<1:32, BinReply/binary>>}} ->
Pid ! {R, {ok, BinReply}}
after Timeout ->
- Pid ! {R,{error,timeout}}
+ Pid ! {R, {error, timeout}}
end.
-spec terminate(term(), pid()) -> 'ok'.
@@ -342,14 +342,14 @@ pick_client(State,RID,Clid) ->
{last, SoleClient}; % Note, not removed, the caller
% should cleanup request data
CList ->
- case lists:keysearch(Clid,1,CList) of
- {value, Client} ->
+ case lists:keyfind(Clid,1,CList) of
+ false ->
+ false;
+ Client ->
NCList = lists:keydelete(Clid,1,CList),
ets:insert(State#state.requests,
R#request{clients = NCList}),
- {more, Client};
- false ->
- false
+ {more, Client}
end
end
end.
@@ -387,8 +387,7 @@ restart_port(#state{port = Port, requests = Requests}) ->
end,
Requests),
NewPort.
-
-
+
do_open_port(Poolsize, ExtraArgs) ->
try
diff --git a/lib/kernel/src/kernel_config.erl b/lib/kernel/src/kernel_config.erl
index cdad354876..b1daf655c9 100644
--- a/lib/kernel/src/kernel_config.erl
+++ b/lib/kernel/src/kernel_config.erl
@@ -92,9 +92,9 @@ code_change(_OldVsn, State, _Extra) ->
%%-----------------------------------------------------------------
sync_nodes() ->
case catch get_sync_data() of
- {error, Reason} ->
+ {error, Reason} = Error ->
error_logger:format("~p", [Reason]),
- {error, Reason};
+ Error;
{infinity, MandatoryNodes, OptionalNodes} ->
case wait_nodes(MandatoryNodes, OptionalNodes) of
ok ->
diff --git a/lib/kernel/src/rpc.erl b/lib/kernel/src/rpc.erl
index 43a987f313..e09acb5024 100644
--- a/lib/kernel/src/rpc.erl
+++ b/lib/kernel/src/rpc.erl
@@ -56,7 +56,7 @@
-export([safe_multi_server_call/2,safe_multi_server_call/3]).
%% gen_server exports
--export([init/1,handle_call/3,handle_cast/2,handle_info/2,
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
%% Internals
@@ -73,12 +73,12 @@
-spec start() -> {'ok', pid()} | 'ignore' | {'error', term()}.
start() ->
- gen_server:start({local,?NAME},?MODULE,[],[]).
+ gen_server:start({local,?NAME}, ?MODULE, [], []).
-spec start_link() -> {'ok', pid()} | 'ignore' | {'error', term()}.
start_link() ->
- gen_server:start_link({local,?NAME},?MODULE,[],[]).
+ gen_server:start_link({local,?NAME}, ?MODULE, [], []).
-spec stop() -> term().
@@ -121,12 +121,11 @@ handle_call(_, _To, S) ->
-spec handle_cast(term(), state()) -> {'noreply', state()}.
handle_cast({cast, Mod, Fun, Args, Gleader}, S) ->
- spawn(
- fun() ->
- set_group_leader(Gleader),
- apply(Mod, Fun, Args)
- end),
- {noreply, S};
+ spawn(fun() ->
+ set_group_leader(Gleader),
+ apply(Mod, Fun, Args)
+ end),
+ {noreply, S};
handle_cast(_, S) ->
{noreply, S}. % Ignore !
@@ -163,7 +162,7 @@ handle_info({From, {sbcast, Name, Msg}}, S) ->
_ ->
From ! {?NAME, node(), node()}
end,
- {noreply,S};
+ {noreply, S};
handle_info({From, {send, Name, Msg}}, S) ->
case catch Name ! {From, Msg} of %% use catch to get the printout
{'EXIT', _} ->
@@ -171,12 +170,12 @@ handle_info({From, {send, Name, Msg}}, S) ->
_ ->
ok %% It's up to Name to respond !!!!!
end,
- {noreply,S};
+ {noreply, S};
handle_info({From, {call,Mod,Fun,Args,Gleader}}, S) ->
%% Special for hidden C node's, uugh ...
handle_call_call(Mod, Fun, Args, Gleader, {From,?NAME}, S);
handle_info(_, S) ->
- {noreply,S}.
+ {noreply, S}.
-spec terminate(term(), state()) -> 'ok'.
@@ -231,7 +230,7 @@ proxy_user() ->
case whereis(rex_proxy_user) of
Pid when is_pid(Pid) -> Pid;
undefined ->
- Pid = spawn(fun()-> proxy_user_loop() end),
+ Pid = spawn(fun() -> proxy_user_loop() end),
try register(rex_proxy_user,Pid) of
true -> Pid
catch error:_ -> % spawn race, kill and try again
diff --git a/lib/kernel/src/standard_error.erl b/lib/kernel/src/standard_error.erl
index 98a44d1ee9..e41dcd01fc 100644
--- a/lib/kernel/src/standard_error.erl
+++ b/lib/kernel/src/standard_error.erl
@@ -24,8 +24,6 @@
-define(NAME, standard_error).
-define(PROCNAME_SUP, standard_error_sup).
-%% Internal exports
--export([server/1, server/2]).
%% Defines for control ops
-define(CTRL_OP_GET_WINSIZE,100).
@@ -54,18 +52,11 @@ init([]) ->
{error,no_stderror}
end.
-
start_port(PortSettings) ->
- Id = spawn(?MODULE,server,[{fd,2,2},PortSettings]),
- register(?NAME,Id),
+ Id = spawn(fun () -> server({fd,2,2}, PortSettings) end),
+ register(?NAME, Id),
Id.
-
-server(Pid) when is_pid(Pid) ->
- process_flag(trap_exit, true),
- link(Pid),
- run(Pid).
-
server(PortName,PortSettings) ->
process_flag(trap_exit, true),
Port = open_port(PortName,PortSettings),
@@ -88,17 +79,15 @@ server_loop(Port) ->
server_loop(Port)
end.
-
get_fd_geometry(Port) ->
case (catch port_control(Port,?CTRL_OP_GET_WINSIZE,[])) of
- List when is_list(List), length(List) =:= 8 ->
+ List when length(List) =:= 8 ->
<<W:32/native,H:32/native>> = list_to_binary(List),
{W,H};
_ ->
error
end.
-
%% NewSaveBuffer = io_request(Request, FromPid, ReplyAs, Port, SaveBuffer)
do_io_request(Req, From, ReplyAs, Port) ->
@@ -227,12 +216,7 @@ do_setopts(Opts, _Port) ->
{ok,ok}.
getopts(_Port) ->
- Uni = {unicode, case get(unicode) of
- true ->
- true;
- _ ->
- false
- end},
+ Uni = {unicode, get(unicode) =:= true},
{ok,[Uni]}.
wrap_characters_to_binary(Chars,From,To) ->
diff --git a/lib/kernel/src/user.erl b/lib/kernel/src/user.erl
index 17dc5a56a2..88f32df20b 100644
--- a/lib/kernel/src/user.erl
+++ b/lib/kernel/src/user.erl
@@ -26,9 +26,6 @@
-define(NAME, user).
-%% Internal exports
--export([server/1, server/2]).
-
%% Defines for control ops
-define(CTRL_OP_GET_WINSIZE,100).
@@ -43,7 +40,7 @@ start([Mod,Fun|Args]) ->
%% Mod,Fun,Args should return a pid. That process is supposed to act
%% as the io port.
Pid = apply(Mod, Fun, Args), % This better work!
- Id = spawn(?MODULE, server, [Pid]),
+ Id = spawn(fun() -> server(Pid) end),
register(?NAME, Id),
Id.
@@ -52,8 +49,8 @@ start_out() ->
start_port([out,binary]).
start_port(PortSettings) ->
- Id = spawn(?MODULE,server,[{fd,0,1},PortSettings]),
- register(?NAME,Id),
+ Id = spawn(fun() -> server({fd,0,1}, PortSettings) end),
+ register(?NAME, Id),
Id.
%% Return the pid of the shell process.
@@ -72,7 +69,6 @@ interfaces(User) ->
[]
end.
-
server(Pid) when is_pid(Pid) ->
process_flag(trap_exit, true),
link(Pid),
@@ -104,7 +100,7 @@ catch_loop(Port, Shell, Q) ->
new_shell ->
exit(Shell, kill),
catch_loop(Port, start_new_shell());
- {unknown_exit,{Shell,Reason},_} -> % shell has exited
+ {unknown_exit,{Shell,Reason},_} -> % shell has exited
case Reason of
normal ->
put_chars("*** ", Port, []);
@@ -172,7 +168,7 @@ server_loop(Port, Q) ->
get_fd_geometry(Port) ->
case (catch port_control(Port,?CTRL_OP_GET_WINSIZE,[])) of
- List when is_list(List), length(List) =:= 8 ->
+ List when length(List) =:= 8 ->
<<W:32/native,H:32/native>> = list_to_binary(List),
{W,H};
_ ->
@@ -373,12 +369,7 @@ do_setopts(Opts, _Port, Q) ->
end.
getopts(_Port,Q) ->
- Bin = {binary, case get(read_mode) of
- binary ->
- true;
- _ ->
- false
- end},
+ Bin = {binary, get(read_mode) =:= binary},
Uni = {encoding, case get(unicode) of
true ->
unicode;
diff --git a/lib/kernel/test/code_SUITE.erl b/lib/kernel/test/code_SUITE.erl
index 37b9200942..08b6477c9d 100644
--- a/lib/kernel/test/code_SUITE.erl
+++ b/lib/kernel/test/code_SUITE.erl
@@ -543,8 +543,8 @@ add_del_path(Config) when is_list(Config) ->
?line code:del_path(Dir2),
?line PrivDir1 = code:priv_dir(dummy_app),
ok.
-
-
+
+
clash(Config) when is_list(Config) ->
DDir = ?config(data_dir,Config)++"clash/",
P = code:get_path(),
@@ -555,11 +555,11 @@ clash(Config) when is_list(Config) ->
?line true = code:del_path("."),
?line true = code:add_path(DDir++"foobar-0.1/ebin"),
?line true = code:add_path(DDir++"zork-0.8/ebin"),
- ?line test_server:capture_start(),
- ?line code:clash(),
- ?line test_server:capture_stop(),
- ?line OKMsg = test_server:capture_get(),
- ?line lists:prefix("** Found 0 name clashes in code paths", OKMsg),
+ test_server:capture_start(),
+ ?line ok = code:clash(),
+ test_server:capture_stop(),
+ ?line [OKMsg|_] = test_server:capture_get(),
+ ?line true = lists:prefix("** Found 0 name clashes", OKMsg),
?line true = code:set_path(P),
%% test clashing entries
@@ -568,13 +568,29 @@ clash(Config) when is_list(Config) ->
?line true = code:del_path("."),
?line true = code:add_path(DDir++"foobar-0.1/ebin"),
?line true = code:add_path(DDir++"foobar-0.1.ez/foobar-0.1/ebin"),
- ?line test_server:capture_start(),
- ?line code:clash(),
- ?line test_server:capture_stop(),
- ?line [ErrMsg1|_] = test_server:capture_get(),
- ?line {match, [" hides "]} = re:run(ErrMsg1, "\\*\\* .*( hides ).*",
+ test_server:capture_start(),
+ ?line ok = code:clash(),
+ test_server:capture_stop(),
+ ?line [ClashMsg|_] = test_server:capture_get(),
+ ?line {match, [" hides "]} = re:run(ClashMsg, "\\*\\* .*( hides ).*",
[{capture,all_but_first,list}]),
?line true = code:set_path(P),
+
+ %% test "Bad path can't read"
+
+ %% remove "." to prevent clash with test-server path
+ Priv = ?config(priv_dir, Config),
+ ?line true = code:del_path("."),
+ TmpEzFile = Priv++"foobar-0.tmp.ez",
+ ?line {ok, _} = file:copy(DDir++"foobar-0.1.ez", TmpEzFile),
+ ?line true = code:add_path(TmpEzFile++"/foobar-0.1/ebin"),
+ ?line ok = file:delete(TmpEzFile),
+ test_server:capture_start(),
+ ?line ok = code:clash(),
+ test_server:capture_stop(),
+ ?line [BadPathMsg|_] = test_server:capture_get(),
+ ?line true = lists:prefix("** Bad path can't read", BadPathMsg),
+ ?line true = code:set_path(P),
ok.
ext_mod_dep(suite) ->
diff --git a/lib/kernel/test/file_SUITE.erl b/lib/kernel/test/file_SUITE.erl
index d01e1f1fcf..1d170790a3 100644
--- a/lib/kernel/test/file_SUITE.erl
+++ b/lib/kernel/test/file_SUITE.erl
@@ -270,7 +270,10 @@ make_del_dir(Config) when is_list(Config) ->
%% 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 {error, eexist} = ?FILE_MODULE:del_dir('..'),
+ 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,{}]),
diff --git a/lib/kernel/test/inet_sockopt_SUITE_data/sockopt_helper.c b/lib/kernel/test/inet_sockopt_SUITE_data/sockopt_helper.c
index fb3c622909..f24c93edf5 100644
--- a/lib/kernel/test/inet_sockopt_SUITE_data/sockopt_helper.c
+++ b/lib/kernel/test/inet_sockopt_SUITE_data/sockopt_helper.c
@@ -1,4 +1,4 @@
-#if defined(VXWORKS) || defined(__OSE__)
+#if defined(VXWORKS)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/lib/kernel/test/prim_file_SUITE.erl b/lib/kernel/test/prim_file_SUITE.erl
index 860aeecbf4..6badbb5090 100644
--- a/lib/kernel/test/prim_file_SUITE.erl
+++ b/lib/kernel/test/prim_file_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2000-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
-module(prim_file_SUITE).
@@ -243,7 +243,10 @@ make_del_dir(Config, Handle, Suffix) ->
%% 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 {error, eexist} = ?PRIM_FILE_call(del_dir, Handle, [".."]),
+ 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,{}]]),
diff --git a/lib/megaco/doc/src/megaco_user.xml b/lib/megaco/doc/src/megaco_user.xml
index 6a0de29385..7332fa684d 100644
--- a/lib/megaco/doc/src/megaco_user.xml
+++ b/lib/megaco/doc/src/megaco_user.xml
@@ -471,7 +471,7 @@ protocol_version() = integer() ]]></code>
<v>transaction_result() = action_reps()</v>
<v>segment_result() = {segment_no(), last_segment(), action_reps()}</v>
<v>action_reps() = [action_reply()]</v>
- <v>failure() = {error, reason()}</v>
+ <v>failure() = {error, reason()} | {error, ReplyNo, reason()}</v>
<v>reason() = transaction_reason() | segment_reason() | user_cancel_reason() | send_reason() | other_reason()</v>
<v>transaction_reason() = error_desc()</v>
<v>segment_reason() = {segment_no(), last_segment(), error_desc()}</v>
@@ -486,6 +486,7 @@ protocol_version() = integer() ]]></code>
<v>send_failed_reason() = {send_message_failed, reason_for_send_failure()}</v>
<v>reason_for_send_failure() = term()</v>
<v>ReplyData = reply_data()</v>
+ <v>ReplyNo = integer() > 0</v>
<v>reply_data() = term()</v>
<v>Extra = term()</v>
</type>
diff --git a/lib/megaco/doc/src/notes.xml b/lib/megaco/doc/src/notes.xml
index 65bf0345f5..6e1356b55d 100644
--- a/lib/megaco/doc/src/notes.xml
+++ b/lib/megaco/doc/src/notes.xml
@@ -36,6 +36,59 @@
section is the version number of Megaco.</p>
<section>
+ <title>Megaco 3.14.1</title>
+
+ <p>Version 3.14.1 supports code replacement in runtime from/to
+ version 3.14, 3.13, 3.12 and 3.11.3.</p>
+
+ <section>
+ <title>Improvements and new features</title>
+
+<!--
+ <p>-</p>
+-->
+
+ <list type="bulleted">
+ <item>
+ <p>A minor compiler related performance improvement. </p>
+ <p>Own Id: OTP-8561</p>
+ </item>
+
+ </list>
+
+ </section>
+
+ <section>
+ <title>Fixed bugs and malfunctions</title>
+ <p>-</p>
+
+<!--
+ <list type="bulleted">
+ <item>
+ <p>Callbacks, when the callback module is unknown (undefined),
+ results in warning messages. </p>
+ <p>A raise condition scenario. As part of a cancelation operation,
+ replies with waiting acknowledgements is cancelled. This includes
+ informing the user (via a call to the handle_trans_ack callback
+ function). It is possible that at this point the connection data
+ has been removed, which makes it impossible for megaco to
+ perform this operation, resulting in the warning message. The
+ solution is to also store the callback module with the other
+ reply information, to be used when cleaning up after a
+ cancelation. </p>
+ <p>Own Id: OTP-8328</p>
+ <p>Aux Id: Seq 11384</p>
+ </item>
+
+ </list>
+-->
+
+ </section>
+
+ </section> <!-- 3.14.1 -->
+
+
+ <section>
<title>Megaco 3.14</title>
<p>Version 3.14 supports code replacement in runtime from/to
diff --git a/lib/megaco/src/app/megaco.appup.src b/lib/megaco/src/app/megaco.appup.src
index 4f781478ef..5df31f2923 100644
--- a/lib/megaco/src/app/megaco.appup.src
+++ b/lib/megaco/src/app/megaco.appup.src
@@ -124,10 +124,18 @@
%% |
%% v
%% 3.14
+%% |
+%% v
+%% 3.14.1
%%
%%
{"%VSN%",
[
+ {"3.14",
+ [
+ {update, megaco_config, soft, soft_purge, soft_purge, []}
+ ]
+ },
{"3.13",
[
{load_module, megaco_messenger, soft_purge, soft_purge, []},
@@ -163,6 +171,11 @@
}
],
[
+ {"3.14",
+ [
+ {update, megaco_config, soft, soft_purge, soft_purge, []}
+ ]
+ },
{"3.13",
[
{load_module, megaco_messenger, soft_purge, soft_purge, []},
diff --git a/lib/megaco/src/engine/megaco_config.erl b/lib/megaco/src/engine/megaco_config.erl
index 1c7a141be7..0445f10838 100644
--- a/lib/megaco/src/engine/megaco_config.erl
+++ b/lib/megaco/src/engine/megaco_config.erl
@@ -224,149 +224,278 @@ update_user_info(UserMid, orig_pending_limit, Val) ->
update_user_info(UserMid, Item, Val) ->
call({update_user_info, UserMid, Item, Val}).
-conn_info(CH, Item)
- when is_record(CH, megaco_conn_handle) andalso (Item /= cancel) ->
- case Item of
- conn_handle ->
- CH;
- mid ->
- CH#megaco_conn_handle.local_mid;
- local_mid ->
- CH#megaco_conn_handle.local_mid;
- remote_mid ->
- CH#megaco_conn_handle.remote_mid;
- conn_data ->
- case lookup_local_conn(CH) of
- [] ->
- exit({no_such_connection, CH});
- [ConnData] ->
- ConnData
- end;
- _ ->
- case lookup_local_conn(CH) of
- [] ->
- exit({no_such_connection, CH});
- [ConnData] ->
- conn_info(ConnData, Item)
- end
+
+conn_info(Data, Item) ->
+ %% The purpose of this is a compiler optimization...
+ %% Args are processed from left to right.
+ do_conn_info(Item, Data).
+
+do_conn_info(mid = _Item, #megaco_conn_handle{local_mid = Mid}) ->
+ Mid;
+do_conn_info(local_mid = _Item, #megaco_conn_handle{local_mid = LMid}) ->
+ LMid;
+do_conn_info(remote_mid = _Item, #megaco_conn_handle{remote_mid = RMid}) ->
+ RMid;
+do_conn_info(conn_handle = _Item, CH) when is_record(CH, megaco_conn_handle) ->
+ CH;
+do_conn_info(conn_data = _Item, CH) when is_record(CH, megaco_conn_handle) ->
+ case lookup_local_conn(CH) of
+ [] ->
+ exit({no_such_connection, CH});
+ [ConnData] ->
+ ConnData
+ end;
+do_conn_info(Item, CH) when is_record(CH, megaco_conn_handle) ->
+ case lookup_local_conn(CH) of
+ [] ->
+ exit({no_such_connection, CH});
+ [ConnData] ->
+ do_conn_info(Item, ConnData)
end;
-conn_info(#conn_data{conn_handle = CH}, cancel) ->
+
+do_conn_info(cancel = _Item, #conn_data{conn_handle = CH}) ->
+ %% To minimise raise-condition propabillity,
+ %% we always look in the table instead of
+ %% in the record for this one
+ ets:lookup_element(megaco_local_conn, CH, #conn_data.cancel);
+do_conn_info(cancel = _Item, CH) when is_record(CH, megaco_conn_handle) ->
%% To minimise raise-condition propabillity,
%% we always look in the table instead of
%% in the record for this one
ets:lookup_element(megaco_local_conn, CH, #conn_data.cancel);
-conn_info(CD, Item) when is_record(CD, conn_data) ->
- case Item of
- all ->
- Tags0 = record_info(fields, conn_data),
- Tags1 = replace(serial, trans_id, Tags0),
- Tags = [mid, local_mid, remote_mid] ++
- replace(max_serial, max_trans_id, Tags1),
- [{Tag, conn_info(CD,Tag)} || Tag <- Tags,
- Tag /= conn_data,
- Tag /= trans_sender,
- Tag /= cancel];
- conn_data -> CD;
- conn_handle -> CD#conn_data.conn_handle;
- mid -> (CD#conn_data.conn_handle)#megaco_conn_handle.local_mid;
- local_mid -> (CD#conn_data.conn_handle)#megaco_conn_handle.local_mid;
- remote_mid -> (CD#conn_data.conn_handle)#megaco_conn_handle.remote_mid;
- trans_id -> CH = CD#conn_data.conn_handle,
- LocalMid = CH#megaco_conn_handle.local_mid,
- Item2 = {LocalMid, trans_id_counter},
- case (catch ets:lookup(megaco_config, Item2)) of
- {'EXIT', _} ->
- undefined_serial;
- [] ->
- user_info(LocalMid, min_trans_id);
- [{_, Serial}] ->
- Max = CD#conn_data.max_serial,
- if
- ((Max =:= infinity) andalso
- is_integer(Serial) andalso
- (Serial < 4294967295)) ->
- Serial + 1;
- (Max =:= infinity) andalso
- is_integer(Serial) andalso
- (Serial =:= 4294967295) ->
- user_info(LocalMid,
- min_trans_id);
- Serial < Max ->
- Serial + 1;
- Serial =:= Max ->
- user_info(LocalMid,
- min_trans_id);
- Serial =:= 4294967295 ->
- user_info(LocalMid,
- min_trans_id);
- true ->
- undefined_serial
- end
- end;
- max_trans_id -> CD#conn_data.max_serial;
- request_timer -> CD#conn_data.request_timer;
- long_request_timer -> CD#conn_data.long_request_timer;
-
- auto_ack -> CD#conn_data.auto_ack;
-
- trans_ack -> CD#conn_data.trans_ack;
- trans_ack_maxcount -> CD#conn_data.trans_ack_maxcount;
-
- trans_req -> CD#conn_data.trans_req;
- trans_req_maxcount -> CD#conn_data.trans_req_maxcount;
- trans_req_maxsize -> CD#conn_data.trans_req_maxsize;
-
- trans_timer -> CD#conn_data.trans_timer;
-
- pending_timer -> CD#conn_data.pending_timer;
- orig_pending_limit -> CD#conn_data.sent_pending_limit;
- sent_pending_limit -> CD#conn_data.sent_pending_limit;
- recv_pending_limit -> CD#conn_data.recv_pending_limit;
- reply_timer -> CD#conn_data.reply_timer;
- control_pid -> CD#conn_data.control_pid;
- monitor_ref -> CD#conn_data.monitor_ref;
- send_mod -> CD#conn_data.send_mod;
- send_handle -> CD#conn_data.send_handle;
- encoding_mod -> CD#conn_data.encoding_mod;
- encoding_config -> CD#conn_data.encoding_config;
- protocol_version -> CD#conn_data.protocol_version;
- auth_data -> CD#conn_data.auth_data;
- user_mod -> CD#conn_data.user_mod;
- user_args -> CD#conn_data.user_args;
- reply_action -> CD#conn_data.reply_action;
- reply_data -> CD#conn_data.reply_data;
- threaded -> CD#conn_data.threaded;
- strict_version -> CD#conn_data.strict_version;
- long_request_resend -> CD#conn_data.long_request_resend;
- call_proxy_gc_timeout -> CD#conn_data.call_proxy_gc_timeout;
- cancel -> CD#conn_data.cancel;
- resend_indication -> CD#conn_data.resend_indication;
- segment_reply_ind -> CD#conn_data.segment_reply_ind;
- segment_recv_acc -> CD#conn_data.segment_recv_acc;
- segment_recv_timer -> CD#conn_data.segment_recv_timer;
- segment_send -> CD#conn_data.segment_send;
- segment_send_timer -> CD#conn_data.segment_send_timer;
- max_pdu_size -> CD#conn_data.max_pdu_size;
- request_keep_alive_timeout -> CD#conn_data.request_keep_alive_timeout;
- receive_handle ->
- LocalMid = (CD#conn_data.conn_handle)#megaco_conn_handle.local_mid,
- #megaco_receive_handle{local_mid = LocalMid,
- encoding_mod = CD#conn_data.encoding_mod,
- encoding_config = CD#conn_data.encoding_config,
- send_mod = CD#conn_data.send_mod};
- _ ->
- exit({no_such_item, Item})
+do_conn_info(all = _Item,
+ #conn_data{conn_handle = CH,
+ serial = TransId,
+ max_serial = MaxTransId,
+ request_timer = ReqTmr,
+ long_request_timer = LongReqTmr,
+ auto_ack = AutoAck,
+ trans_ack = TransAck,
+ trans_ack_maxcount = TransAckMaxCount,
+ trans_req = TransReq,
+ trans_req_maxcount = TransReqMaxCount,
+ trans_req_maxsize = TransReqMaxSz,
+ trans_timer = TransTmr,
+ %% trans_sender,
+ pending_timer = PendingTmr,
+ sent_pending_limit = SentPendingLimit,
+ recv_pending_limit = RecvPendingLimit,
+ reply_timer = ReplyTmr,
+ control_pid = CtrlPid,
+ monitor_ref = MonRef,
+ send_mod = SendMod,
+ send_handle = SendHandle,
+ encoding_mod = EncodingMod,
+ encoding_config = EncodingConf,
+ protocol_version = ProtoVersion,
+ auth_data = AuthData,
+ user_mod = UserMod,
+ user_args = UserArgs,
+ reply_action = ReplyAction,
+ reply_data = ReplyData,
+ threaded = Threaded,
+ strict_version = StrictVersion,
+ long_request_resend = LongReqResend,
+ call_proxy_gc_timeout = CallProxyGCTimeout,
+ %% cancel,
+ resend_indication = ResendInd,
+ segment_reply_ind = SegReplyInd,
+ segment_recv_acc = SegRecvAcc,
+ segment_recv_timer = SegRecvTmr,
+ segment_send = SegSend,
+ segment_send_timer = SegSendTmr,
+ max_pdu_size = MaxPduSz,
+ request_keep_alive_timeout = RequestKeepAliveTmr}) ->
+ [{conn_handle, CH},
+ {trans_id, TransId},
+ {max_trans_id, MaxTransId},
+ {request_timer, ReqTmr},
+ {long_request_timer, LongReqTmr},
+ {mid, CH#megaco_conn_handle.local_mid},
+ {local_mid, CH#megaco_conn_handle.local_mid},
+ {remote_mid, CH#megaco_conn_handle.remote_mid},
+ {auto_ack, AutoAck},
+ {trans_ack, TransAck},
+ {trans_ack_maxcount, TransAckMaxCount},
+ {trans_req, TransReq},
+ {trans_req_maxcount, TransReqMaxCount},
+ {trans_req_maxsize, TransReqMaxSz},
+ {trans_timer, TransTmr},
+ {pending_timer, PendingTmr},
+ {sent_pending_limit, SentPendingLimit},
+ {recv_pending_limit, RecvPendingLimit},
+ {reply_timer, ReplyTmr},
+ {control_pid, CtrlPid},
+ {monitor_ref, MonRef},
+ {send_mod, SendMod},
+ {send_handle, SendHandle},
+ {encoding_mod, EncodingMod},
+ {encoding_config, EncodingConf},
+ {protocol_version, ProtoVersion},
+ {auth_data, AuthData},
+ {user_mod, UserMod},
+ {user_args, UserArgs},
+ {reply_action, ReplyAction},
+ {reply_data, ReplyData},
+ {threaded, Threaded},
+ {strict_version, StrictVersion},
+ {long_request_resend, LongReqResend},
+ {call_proxy_gc_timeout, CallProxyGCTimeout},
+ {resend_indication, ResendInd},
+ {segment_reply_ind, SegReplyInd},
+ {segment_recv_acc, SegRecvAcc},
+ {segment_recv_timer, SegRecvTmr},
+ {segment_send, SegSend},
+ {segment_send_timer, SegSendTmr},
+ {max_pdu_size, MaxPduSz},
+ {request_keep_alive_timeout, RequestKeepAliveTmr}];
+
+do_conn_info(conn_data = _Item, CD) ->
+ CD;
+do_conn_info(conn_handle = _Item, #conn_data{conn_handle = Val}) ->
+ Val;
+do_conn_info(mid = _Item,
+ #conn_data{conn_handle = #megaco_conn_handle{local_mid = Val}}) ->
+ Val;
+do_conn_info(local_mid = _Item,
+ #conn_data{conn_handle = #megaco_conn_handle{local_mid = Val}}) ->
+ Val;
+do_conn_info(remote_mid = _Item,
+ #conn_data{conn_handle = #megaco_conn_handle{remote_mid = Val}}) ->
+ Val;
+do_conn_info(trans_id = _Item,
+ #conn_data{conn_handle = #megaco_conn_handle{local_mid = LMid},
+ max_serial = Max}) ->
+ Item2 = {LMid, trans_id_counter},
+ case (catch ets:lookup(megaco_config, Item2)) of
+ {'EXIT', _} ->
+ undefined_serial;
+ [] ->
+ user_info(LMid, min_trans_id);
+ [{_, Serial}] ->
+ if
+ ((Max =:= infinity) andalso
+ is_integer(Serial) andalso
+ (Serial < 4294967295)) ->
+ Serial + 1;
+ ((Max =:= infinity) andalso
+ is_integer(Serial) andalso
+ (Serial =:= 4294967295)) ->
+ user_info(LMid, min_trans_id);
+ Serial < Max ->
+ Serial + 1;
+ Serial =:= Max ->
+ user_info(LMid, min_trans_id);
+ Serial =:= 4294967295 ->
+ user_info(LMid, min_trans_id);
+ true ->
+ undefined_serial
+ end
end;
-conn_info(BadHandle, _Item) ->
- {error, {no_such_connection, BadHandle}}.
-
-replace(_, _, []) ->
- [];
-replace(Item, WithItem, [Item|List]) ->
- [WithItem|List];
-replace(Item, WithItem, [OtherItem|List]) ->
- [OtherItem | replace(Item, WithItem, List)].
+do_conn_info(max_trans_id = _Item, #conn_data{max_serial = Val}) ->
+ Val;
+do_conn_info(request_timer = _Item, #conn_data{request_timer = Val}) ->
+ Val;
+do_conn_info(long_request_timer = _Item, #conn_data{long_request_timer = Val}) ->
+ Val;
+do_conn_info(auto_ack = _Item, #conn_data{auto_ack = Val}) ->
+ Val;
+do_conn_info(trans_ack = _Item, #conn_data{trans_ack = Val}) ->
+ Val;
+do_conn_info(trans_ack_maxcount = _Item, #conn_data{trans_ack_maxcount = Val}) ->
+ Val;
+do_conn_info(trans_req = _Item, #conn_data{trans_req = Val}) ->
+ Val;
+do_conn_info(trans_req_maxcount = _Item, #conn_data{trans_req_maxcount = Val}) ->
+ Val;
+do_conn_info(trans_req_maxsize = _Item, #conn_data{trans_req_maxsize = Val}) ->
+ Val;
+do_conn_info(trans_timer = _Item, #conn_data{trans_timer = Val}) ->
+ Val;
+do_conn_info(pending_timer = _Item, #conn_data{pending_timer = Val}) ->
+ Val;
+do_conn_info(orig_pending_limit = _Item, #conn_data{sent_pending_limit = Val}) ->
+ Val;
+do_conn_info(sent_pending_limit = _Item, #conn_data{sent_pending_limit = Val}) ->
+ Val;
+do_conn_info(recv_pending_limit = _Item, #conn_data{recv_pending_limit = Val}) ->
+ Val;
+do_conn_info(reply_timer = _Item, #conn_data{reply_timer = Val}) ->
+ Val;
+do_conn_info(control_pid = _Item, #conn_data{control_pid = Val}) ->
+ Val;
+do_conn_info(send_mod = _Item, #conn_data{send_mod = Val}) ->
+ Val;
+do_conn_info(send_handle = _Item, #conn_data{send_handle = Val}) ->
+ Val;
+do_conn_info(encoding_mod = _Item, #conn_data{encoding_mod = Val}) ->
+ Val;
+do_conn_info(encoding_config = _Item, #conn_data{encoding_config = Val}) ->
+ Val;
+do_conn_info(protocol_version = _Item, #conn_data{protocol_version = Val}) ->
+ Val;
+do_conn_info(auth_data = _Item, #conn_data{auth_data = Val}) ->
+ Val;
+do_conn_info(user_mod = _Item, #conn_data{user_mod = Val}) ->
+ Val;
+do_conn_info(user_args = _Item, #conn_data{user_args = Val}) ->
+ Val;
+do_conn_info(reply_action = _Item, #conn_data{reply_action = Val}) ->
+ Val;
+do_conn_info(reply_data = _Item, #conn_data{reply_data = Val}) ->
+ Val;
+do_conn_info(threaded = _Item, #conn_data{threaded = Val}) ->
+ Val;
+do_conn_info(strict_version = _Item, #conn_data{strict_version = Val}) ->
+ Val;
+do_conn_info(long_request_resend = _Item,
+ #conn_data{long_request_resend = Val}) ->
+ Val;
+do_conn_info(call_proxy_gc_timeout = _Item,
+ #conn_data{call_proxy_gc_timeout = Val}) ->
+ Val;
+do_conn_info(resend_indication = _Item, #conn_data{resend_indication = Val}) ->
+ Val;
+do_conn_info(segment_reply_ind = _Item, #conn_data{segment_reply_ind = Val}) ->
+ Val;
+do_conn_info(segment_recv_acc = _Item, #conn_data{segment_recv_acc = Val}) ->
+ Val;
+do_conn_info(segment_recv_timer = _Item,
+ #conn_data{segment_recv_timer = Val}) ->
+ Val;
+do_conn_info(segment_send = _Item, #conn_data{segment_send = Val}) ->
+ Val;
+do_conn_info(segment_send_timer = _Item,
+ #conn_data{segment_send_timer = Val}) ->
+ Val;
+do_conn_info(max_pdu_size = _Item, #conn_data{max_pdu_size = Val}) ->
+ Val;
+do_conn_info(request_keep_alive_timeout = _Item,
+ #conn_data{request_keep_alive_timeout = Val}) ->
+ Val;
+do_conn_info(receive_handle = _Item,
+ #conn_data{conn_handle = #megaco_conn_handle{local_mid = LMid},
+ encoding_mod = EM,
+ encoding_config = EC,
+ send_mod = SM}) ->
+ #megaco_receive_handle{local_mid = LMid,
+ encoding_mod = EM,
+ encoding_config = EC,
+ send_mod = SM};
+do_conn_info(Item, Data)
+ when is_record(Data, conn_data) orelse is_record(Data, megaco_conn_handle) ->
+ exit({no_such_item, Item});
+do_conn_info(_Item, BadData) ->
+ {error, {no_such_connection, BadData}}.
+
+
+%% replace(_, _, []) ->
+%% [];
+%% replace(Item, WithItem, [Item|List]) ->
+%% [WithItem|List];
+%% replace(Item, WithItem, [OtherItem|List]) ->
+%% [OtherItem | replace(Item, WithItem, List)].
update_conn_info(#conn_data{conn_handle = CH}, Item, Val) ->
diff --git a/lib/megaco/test/megaco_config_test.erl b/lib/megaco/test/megaco_config_test.erl
index 453c1b8964..9ab1a7d90d 100644
--- a/lib/megaco/test/megaco_config_test.erl
+++ b/lib/megaco/test/megaco_config_test.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2000-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -106,166 +106,197 @@ config(Config) when is_list(Config) ->
Evil = 400,
End = 500,
+ InitialCmd =
+ fun(No, Desc, Cmd, VerifyVal) ->
+ initial_command(Initial + No, Desc, Cmd, VerifyVal)
+ end,
+
+ VerifyCmd =
+ fun(M, No, Key, V) ->
+ verify_user_default_command(M, Verify + No, Key, V)
+ end,
+
+ NiceCmd =
+ fun(M, No, Key, Val) ->
+ nice_user_update_command(M, Nice + No, Key, Val)
+ end,
+
+ EvilCmd =
+ fun(M, No, Key, Val) ->
+ evil_user_update_command(M, Evil + No, Key, Val)
+ end,
+
+ %% End commands
+ ExitCmd =
+ fun(No, Desc, Cmd) ->
+ exit_command(End + No, Desc, Cmd)
+ end,
+ ErrorCmd =
+ fun(No, Desc, Cmd, MainReason, TS) ->
+ error_command(End + No, Desc, Cmd, MainReason, TS)
+ end,
+ PlainCmd =
+ fun(No, Desc, Cmd, V) ->
+ command(End + No, Desc, Cmd, V)
+ end,
+
Commands =
[
%% Initial commands
- initial_command( Initial + 0,
- "enable trace",
- fun() -> megaco:enable_trace(100, io) end, ok),
- initial_command( Initial + 1,
- "start",
- fun() -> megaco:start() end, ok),
- initial_command( Initial + 2,
- "Verify no active requests",
- fun() -> megaco:system_info(n_active_requests) end,
- 0),
- initial_command( Initial + 3,
- "Verify no active replies",
- fun() -> megaco:system_info(n_active_replies) end,
- 0),
- initial_command( Initial + 4,
- "Verify no active connections",
- fun() ->
- megaco:system_info(n_active_connections)
- end,
- 0),
- initial_command( Initial + 5,
- "Verify no connections",
- fun() -> megaco:system_info(connections) end, []),
- initial_command( Initial + 6,
- "Verify no users",
- fun() -> megaco:system_info(users) end, []),
- initial_command( Initial + 7,
- "Start user",
- fun() -> megaco:start_user(Mid, []) end, ok),
-
+ InitialCmd(0,
+ "enable trace",
+ fun() -> megaco:enable_trace(100, io) end,
+ ok),
+ InitialCmd(1,
+ "start",
+ fun() -> megaco:start() end,
+ ok),
+ InitialCmd(2,
+ "Verify no active requests",
+ fun() -> megaco:system_info(n_active_requests) end,
+ 0),
+ InitialCmd(3,
+ "Verify no active replies",
+ fun() -> megaco:system_info(n_active_replies) end,
+ 0),
+ InitialCmd(4,
+ "Verify no active connections",
+ fun() -> megaco:system_info(n_active_connections) end,
+ 0),
+ InitialCmd(5,
+ "Verify no connections",
+ fun() -> megaco:system_info(connections) end,
+ []),
+ InitialCmd(6,
+ "Verify no users",
+ fun() -> megaco:system_info(users) end,
+ []),
+ InitialCmd(7,
+ "Start user",
+ fun() -> megaco:start_user(Mid, []) end,
+ ok),
+
%% Verify user defaults
- verify_user_default_command(Mid, Verify + 1, connections, []),
- verify_user_default_command(Mid, Verify + 2, min_trans_id, 1),
- verify_user_default_command(Mid, Verify + 3, max_trans_id, infinity),
- verify_user_default_command(Mid, Verify + 4, request_timer,
- #megaco_incr_timer{}),
- verify_user_default_command(Mid, Verify + 5, long_request_timer, timer:seconds(60)),
- verify_user_default_command(Mid, Verify + 6, auto_ack, false),
- verify_user_default_command(Mid, Verify + 7, pending_timer, 30000),
- verify_user_default_command(Mid, Verify + 8, reply_timer, 30000),
- verify_user_default_command(Mid, Verify + 9, send_mod, megaco_tcp),
- verify_user_default_command(Mid, Verify + 10, encoding_mod,
- megaco_pretty_text_encoder),
- verify_user_default_command(Mid, Verify + 11, encoding_config, []),
- verify_user_default_command(Mid, Verify + 12, protocol_version, 1),
- verify_user_default_command(Mid, Verify + 13, reply_data, undefined),
- verify_user_default_command(Mid, Verify + 14, receive_handle,
- fun(H) when is_record(H, megaco_receive_handle) -> {ok, H};
- (R) -> {error, R}
- end),
+ VerifyCmd(Mid, 1, connections, []),
+ VerifyCmd(Mid, 2, min_trans_id, 1),
+ VerifyCmd(Mid, 3, max_trans_id, infinity),
+ VerifyCmd(Mid, 4, request_timer, #megaco_incr_timer{}),
+ VerifyCmd(Mid, 5, long_request_timer, timer:seconds(60)),
+ VerifyCmd(Mid, 6, auto_ack, false),
+ VerifyCmd(Mid, 7, pending_timer, 30000),
+ VerifyCmd(Mid, 8, reply_timer, 30000),
+ VerifyCmd(Mid, 9, send_mod, megaco_tcp),
+ VerifyCmd(Mid, 10, encoding_mod, megaco_pretty_text_encoder),
+ VerifyCmd(Mid, 11, encoding_config, []),
+ VerifyCmd(Mid, 12, protocol_version, 1),
+ VerifyCmd(Mid, 13, reply_data, undefined),
+ VerifyCmd(Mid, 14, receive_handle,
+ fun(H) when is_record(H, megaco_receive_handle) ->
+ {ok, H};
+ (R) ->
+ {error, R}
+ end),
%% Nice update
- nice_user_update_command(Mid, Nice + 1, min_trans_id, Int),
- nice_user_update_command(Mid, Nice + 2, max_trans_id, Int),
- nice_user_update_command(Mid, Nice + 3, max_trans_id, infinity),
- nice_user_update_command(Mid, Nice + 4, request_timer, Int),
- nice_user_update_command(Mid, Nice + 5, request_timer, infinity),
- nice_user_update_command(Mid, Nice + 6, request_timer, IT),
- nice_user_update_command(Mid, Nice + 7, long_request_timer, Int),
- nice_user_update_command(Mid, Nice + 8, long_request_timer, infinity),
- nice_user_update_command(Mid, Nice + 9, long_request_timer, IT),
- nice_user_update_command(Mid, Nice + 10, auto_ack, true),
- nice_user_update_command(Mid, Nice + 11, auto_ack, false),
- nice_user_update_command(Mid, Nice + 12, pending_timer, Int),
- nice_user_update_command(Mid, Nice + 13, pending_timer, infinity),
- nice_user_update_command(Mid, Nice + 14, pending_timer, IT),
- nice_user_update_command(Mid, Nice + 15, reply_timer, Int),
- nice_user_update_command(Mid, Nice + 16, reply_timer, infinity),
- nice_user_update_command(Mid, Nice + 17, reply_timer, IT),
- nice_user_update_command(Mid, Nice + 18, send_mod, an_atom),
- nice_user_update_command(Mid, Nice + 19, encoding_mod, an_atom),
- nice_user_update_command(Mid, Nice + 20, encoding_config, []),
- nice_user_update_command(Mid, Nice + 21, protocol_version, Int),
- nice_user_update_command(Mid, Nice + 23, reply_data, IT),
- nice_user_update_command(Mid, Nice + 23, resend_indication, true),
- nice_user_update_command(Mid, Nice + 24, resend_indication, false),
- nice_user_update_command(Mid, Nice + 25, resend_indication, flag),
+ NiceCmd(Mid, 1, min_trans_id, Int),
+ NiceCmd(Mid, 2, max_trans_id, Int),
+ NiceCmd(Mid, 3, max_trans_id, infinity),
+ NiceCmd(Mid, 4, request_timer, Int),
+ NiceCmd(Mid, 5, request_timer, infinity),
+ NiceCmd(Mid, 6, request_timer, IT),
+ NiceCmd(Mid, 7, long_request_timer, Int),
+ NiceCmd(Mid, 8, long_request_timer, infinity),
+ NiceCmd(Mid, 9, long_request_timer, IT),
+ NiceCmd(Mid, 10, auto_ack, true),
+ NiceCmd(Mid, 11, auto_ack, false),
+ NiceCmd(Mid, 12, pending_timer, Int),
+ NiceCmd(Mid, 13, pending_timer, infinity),
+ NiceCmd(Mid, 14, pending_timer, IT),
+ NiceCmd(Mid, 15, reply_timer, Int),
+ NiceCmd(Mid, 16, reply_timer, infinity),
+ NiceCmd(Mid, 17, reply_timer, IT),
+ NiceCmd(Mid, 18, send_mod, an_atom),
+ NiceCmd(Mid, 19, encoding_mod, an_atom),
+ NiceCmd(Mid, 20, encoding_config, []),
+ NiceCmd(Mid, 21, protocol_version, Int),
+ NiceCmd(Mid, 23, reply_data, IT),
+ NiceCmd(Mid, 23, resend_indication, true),
+ NiceCmd(Mid, 24, resend_indication, false),
+ NiceCmd(Mid, 25, resend_indication, flag),
%% Evil update
- evil_user_update_command(Mid, Evil + 1, min_trans_id, NonInt),
- evil_user_update_command(Mid, Evil + 2, max_trans_id, NonInt),
- evil_user_update_command(Mid, Evil + 3, max_trans_id, non_infinity),
- evil_user_update_command(Mid, Evil + 4, request_timer, NonInt),
- evil_user_update_command(Mid, Evil + 5, request_timer, non_infinity),
- evil_user_update_command(Mid, Evil + 6, request_timer, IT2),
- evil_user_update_command(Mid, Evil + 7, request_timer, IT3),
- evil_user_update_command(Mid, Evil + 8, request_timer, IT4),
- evil_user_update_command(Mid, Evil + 9, request_timer, IT5),
- evil_user_update_command(Mid, Evil + 10, long_request_timer, NonInt),
- evil_user_update_command(Mid, Evil + 11, long_request_timer, non_infinity),
- evil_user_update_command(Mid, Evil + 12, long_request_timer, IT2),
- evil_user_update_command(Mid, Evil + 13, long_request_timer, IT3),
- evil_user_update_command(Mid, Evil + 14, long_request_timer, IT4),
- evil_user_update_command(Mid, Evil + 15, long_request_timer, IT5),
- evil_user_update_command(Mid, Evil + 16, auto_ack, non_bool),
- evil_user_update_command(Mid, Evil + 17, pending_timer, NonInt),
- evil_user_update_command(Mid, Evil + 18, pending_timer, non_infinity),
- evil_user_update_command(Mid, Evil + 19, pending_timer, IT2),
- evil_user_update_command(Mid, Evil + 20, pending_timer, IT3),
- evil_user_update_command(Mid, Evil + 21, pending_timer, IT4),
- evil_user_update_command(Mid, Evil + 22, pending_timer, IT5),
- evil_user_update_command(Mid, Evil + 23, reply_timer, NonInt),
- evil_user_update_command(Mid, Evil + 24, reply_timer, non_infinity),
- evil_user_update_command(Mid, Evil + 25, reply_timer, IT2),
- evil_user_update_command(Mid, Evil + 26, reply_timer, IT3),
- evil_user_update_command(Mid, Evil + 27, reply_timer, IT4),
- evil_user_update_command(Mid, Evil + 28, reply_timer, IT5),
- evil_user_update_command(Mid, Evil + 29, send_mod, {non_atom}),
- evil_user_update_command(Mid, Evil + 30, encoding_mod, {non_atom}),
- evil_user_update_command(Mid, Evil + 31, encoding_config, non_list),
- evil_user_update_command(Mid, Evil + 32, protocol_version, NonInt),
- evil_user_update_command(Mid, Evil + 33, resend_indication, flagg),
-
-
- exit_command(End + 1,
- "Verify non-existing system info",
- fun() -> megaco:system_info(non_exist) end),
- exit_command(End + 2,
- "Verify non-existing user user info",
- fun() -> megaco:user_info(non_exist, trans_id) end),
- exit_command(End + 3, "Verify non-existing user info",
- fun() -> megaco:user_info(Mid, non_exist) end),
-
- error_command(End + 4,
- "Try updating user info for non-existing user",
- fun() ->
- megaco:update_user_info(non_exist, trans_id, 1)
- end,
- no_such_user, 2),
- error_command(End + 11,
- "Try updating non-existing user info",
- fun() ->
- megaco:update_user_info(Mid, trans_id, 4711)
- end,
- bad_user_val, 4),
- error_command(End + 12,
- "Try start already started user",
- fun() ->
- megaco:start_user(Mid, [])
- end,
- user_already_exists, 2),
-
- command(End + 13, "Verify started users",
- fun() -> megaco:system_info(users) end, [Mid]),
- command(End + 14, "Stop user", fun() -> megaco:stop_user(Mid) end, ok),
- command(End + 15, "Verify started users",
- fun() -> megaco:system_info(users) end, []),
- error_command(End + 16, "Try stop not started user",
- fun() -> megaco:stop_user(Mid) end, no_such_user, 2),
- error_command(End + 17, "Try start megaco (it's already started)",
- fun() -> megaco:start() end, already_started, 2),
- command(End + 18, "Stop megaco", fun() -> megaco:stop() end, ok),
- error_command(End + 19, "Try stop megaco (it's not running)",
- fun() -> megaco:stop() end, not_started, 2)
+ EvilCmd(Mid, 1, min_trans_id, NonInt),
+ EvilCmd(Mid, 2, max_trans_id, NonInt),
+ EvilCmd(Mid, 3, max_trans_id, non_infinity),
+ EvilCmd(Mid, 4, request_timer, NonInt),
+ EvilCmd(Mid, 5, request_timer, non_infinity),
+ EvilCmd(Mid, 6, request_timer, IT2),
+ EvilCmd(Mid, 7, request_timer, IT3),
+ EvilCmd(Mid, 8, request_timer, IT4),
+ EvilCmd(Mid, 9, request_timer, IT5),
+ EvilCmd(Mid, 10, long_request_timer, NonInt),
+ EvilCmd(Mid, 11, long_request_timer, non_infinity),
+ EvilCmd(Mid, 12, long_request_timer, IT2),
+ EvilCmd(Mid, 13, long_request_timer, IT3),
+ EvilCmd(Mid, 14, long_request_timer, IT4),
+ EvilCmd(Mid, 15, long_request_timer, IT5),
+ EvilCmd(Mid, 16, auto_ack, non_bool),
+ EvilCmd(Mid, 17, pending_timer, NonInt),
+ EvilCmd(Mid, 18, pending_timer, non_infinity),
+ EvilCmd(Mid, 19, pending_timer, IT2),
+ EvilCmd(Mid, 20, pending_timer, IT3),
+ EvilCmd(Mid, 21, pending_timer, IT4),
+ EvilCmd(Mid, 22, pending_timer, IT5),
+ EvilCmd(Mid, 23, reply_timer, NonInt),
+ EvilCmd(Mid, 24, reply_timer, non_infinity),
+ EvilCmd(Mid, 25, reply_timer, IT2),
+ EvilCmd(Mid, 26, reply_timer, IT3),
+ EvilCmd(Mid, 27, reply_timer, IT4),
+ EvilCmd(Mid, 28, reply_timer, IT5),
+ EvilCmd(Mid, 29, send_mod, {non_atom}),
+ EvilCmd(Mid, 30, encoding_mod, {non_atom}),
+ EvilCmd(Mid, 31, encoding_config, non_list),
+ EvilCmd(Mid, 32, protocol_version, NonInt),
+ EvilCmd(Mid, 33, resend_indication, flagg),
+
+
+ %% End
+ ExitCmd(1, "Verify non-existing system info",
+ fun() -> megaco:system_info(non_exist) end),
+ ExitCmd(2, "Verify non-existing user user info",
+ fun() -> megaco:user_info(non_exist, trans_id) end),
+ ExitCmd(3, "Verify non-existing user info",
+ fun() -> megaco:user_info(Mid, non_exist) end),
+
+ ErrorCmd(4, "Try updating user info for non-existing user",
+ fun() ->
+ megaco:update_user_info(non_exist, trans_id, 1)
+ end,
+ no_such_user, 2),
+ ErrorCmd(11, "Try updating non-existing user info",
+ fun() ->
+ megaco:update_user_info(Mid, trans_id, 4711)
+ end,
+ bad_user_val, 4),
+ ErrorCmd(12, "Try start already started user",
+ fun() -> megaco:start_user(Mid, []) end,
+ user_already_exists, 2),
+
+ PlainCmd(13, "Verify started users",
+ fun() -> megaco:system_info(users) end, [Mid]),
+ PlainCmd(14, "Stop user", fun() -> megaco:stop_user(Mid) end, ok),
+ PlainCmd(15, "Verify started users",
+ fun() -> megaco:system_info(users) end, []),
+ ErrorCmd(16, "Try stop not started user",
+ fun() -> megaco:stop_user(Mid) end, no_such_user, 2),
+ ErrorCmd(17, "Try start megaco (it's already started)",
+ fun() -> megaco:start() end, already_started, 2),
+ PlainCmd(18, "Stop megaco", fun() -> megaco:stop() end, ok),
+ ErrorCmd(19, "Try stop megaco (it's not running)",
+ fun() -> megaco:stop() end, not_started, 2)
],
@@ -279,7 +310,7 @@ exec([#command{id = No,
desc = Desc,
cmd = Cmd,
verify = Verify}|Commands]) ->
- io:format("Executing command ~2w: ~s: ", [No, Desc]),
+ io:format("Executing command ~3w: ~s: ", [No, Desc]),
case (catch Verify((catch Cmd()))) of
{ok, OK} ->
io:format("ok => ~p~n", [OK]),
@@ -320,7 +351,7 @@ nice_user_update_command(Mid, No, Key, Val) ->
evil_user_update_command(Mid, No, Key, Val) ->
- Desc = lists:flatten(io_lib:format("Evil: Update ~w", [Key])),
+ Desc = lists:flatten(io_lib:format("Evil - Update ~w", [Key])),
Cmd = fun() ->
case (catch megaco:user_info(Mid, Key)) of
{'EXIT', R} ->
@@ -371,14 +402,19 @@ error_command(No, Desc, Cmd, MainReason, TS) when is_function(Cmd) ->
end,
command(No, Desc, Cmd, Verify).
-command(No, Desc, Cmd, Verify) when is_integer(No) and is_list(Desc) and
- is_function(Cmd) and is_function(Verify) ->
+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) and is_list(Desc) and
- is_function(Cmd) ->
+command(No, Desc, Cmd, VerifyVal)
+ when (is_integer(No) andalso
+ is_list(Desc) andalso
+ is_function(Cmd)) ->
Verify = fun(Val) ->
case Val of
VerifyVal ->
@@ -881,6 +917,12 @@ otp_8167(Config) when is_list(Config) ->
p("connect ok: CD = ~n~p", [CD]),
CH = CD#conn_data.conn_handle,
+ p("get value for item cancel from connection: ~p", [CH]),
+ false = megaco_config:conn_info(CH, cancel),
+
+ p("get value for item cancel from connection data", []),
+ false = megaco_config:conn_info(CD, cancel),
+
p("get value for item call_proxy_gc_timeout for connection: ~p", [CH]),
10101 = megaco_config:conn_info(CH, call_proxy_gc_timeout),
diff --git a/lib/megaco/vsn.mk b/lib/megaco/vsn.mk
index 19eca6d309..34a5ac1ed2 100644
--- a/lib/megaco/vsn.mk
+++ b/lib/megaco/vsn.mk
@@ -18,11 +18,13 @@
# %CopyrightEnd%
APPLICATION = megaco
-MEGACO_VSN = 3.14
+MEGACO_VSN = 3.14.1
PRE_VSN =
APP_VSN = "$(APPLICATION)-$(MEGACO_VSN)$(PRE_VSN)"
-TICKETS = OTP-8317 OTP-8323 OTP-8328 OTP-8362 OTP-8403
+TICKETS = OTP-8561
+
+TICKETS_3_14 = OTP-8317 OTP-8323 OTP-8328 OTP-8362 OTP-8403
TICKETS_3_13 = OTP-8205 OTP-8239 OTP-8249
diff --git a/lib/public_key/src/public_key.appup.src b/lib/public_key/src/public_key.appup.src
index ee0f9a3cc1..46e5ecca33 100644
--- a/lib/public_key/src/public_key.appup.src
+++ b/lib/public_key/src/public_key.appup.src
@@ -1,18 +1,40 @@
%% -*- erlang -*-
{"%VSN%",
[
+ {"0.5",
+ [
+ {update, public_key, soft, soft_purge, soft_purge, []},
+ {update, pubkey_crypto, soft, soft_purge, soft_purge, []},
+ {update, pubkey_pem, soft, soft_purge, soft_purge, []},
+ {update, pubkey_cert, soft, soft_purge, soft_purge, []}
+ ]
+ },
{"0.4",
[
{update, public_key, soft, soft_purge, soft_purge, []},
- {update, pubkey_cert_records, soft, soft_purge, soft_purge, []}
+ {update, pubkey_cert_records, soft, soft_purge, soft_purge, []},
+ {update, pubkey_crypto, soft, soft_purge, soft_purge, []},
+ {update, pubkey_pem, soft, soft_purge, soft_purge, []},
+ {update, pubkey_cert, soft, soft_purge, soft_purge, []}
]
}
],
[
+ {"0.5",
+ [
+ {update, public_key, soft, soft_purge, soft_purge, []},
+ {update, pubkey_crypto, soft, soft_purge, soft_purge, []},
+ {update, pubkey_pem, soft, soft_purge, soft_purge, []},
+ {update, pubkey_cert, soft, soft_purge, soft_purge, []}
+ ]
+ },
{"0.4",
[
{update, public_key, soft, soft_purge, soft_purge, []},
- {update, pubkey_cert_records, soft, soft_purge, soft_purge, []}
+ {update, pubkey_cert_records, soft, soft_purge, soft_purge, []},
+ {update, pubkey_crypto, soft, soft_purge, soft_purge, []},
+ {update, pubkey_pem, soft, soft_purge, soft_purge, []},
+ {update, pubkey_cert, soft, soft_purge, soft_purge, []}
]
}
]}.
diff --git a/lib/reltool/bin/reltool.escript b/lib/reltool/bin/reltool.escript
new file mode 100644
index 0000000000..0dcd5ad1e9
--- /dev/null
+++ b/lib/reltool/bin/reltool.escript
@@ -0,0 +1,249 @@
+#!/usr/bin/env escript
+%% -*- 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%
+
+-include_lib("reltool/src/reltool.hrl").
+
+main(Args) ->
+ process_flag(trap_exit, true),
+ try
+ Tokens = scan_args(Args, [], []),
+ {Options, Actions} = parse_args(Tokens, []),
+ case invoke(Options, Actions) of
+ ok ->
+ safe_stop(0);
+ {error, ReasonString} ->
+ fatal_error(ReasonString, 2)
+ end
+ catch
+ throw:usage ->
+ usage(),
+ safe_stop(1);
+ exit:Reason ->
+ String = lists:flatten(io_lib:format("EXIT: ~p", [Reason])),
+ fatal_error(String, 3)
+ end.
+
+usage() ->
+ Usage =
+ [
+ "[Config] [--window]",
+ "[Config] --create_config [-defaults] [-derived] [ConfigFile]",
+ "[Config] --create_rel RelName [RelFile]",
+ "[Config] --create_script RelName [ScriptFile]",
+ "[Config] --create_target TargetDir",
+ "[Config] --create_target_spec [SpecFile]",
+ "[Config] --eval_target_spec Spec TargetDir RootDir"
+ ],
+ Script = script_name(),
+ String = lists:flatten([[Script, " ", U, "\n"] || U <- Usage]),
+ io:format("Erlang/OTP release management tool\n\n"
+ "~s\nConfig = ConfigFile | '{sys, [sys()]}'\n"
+ "Spec = SpecFile | '{spec, [target_spec()}']\n\n"
+ "See User's guide and Reference manual for more info.\n",
+ [String]).
+
+safe_stop(Code) ->
+ init:stop(Code),
+ timer:sleep(infinity).
+
+invoke(Options, Actions) ->
+ case Actions of
+ [] ->
+ invoke(Options, [["--window"]]);
+ [["--window"]] ->
+ start_window(Options);
+ [["--create_config" | OptArgs]] ->
+ DefArg = "-defaults",
+ DerivArg = "-derived",
+ InclDef = lists:member(DefArg, OptArgs),
+ InclDeriv = lists:member(DerivArg, OptArgs),
+ case reltool:get_config(Options, InclDef, InclDeriv) of
+ {ok, Config} ->
+ String = pretty("config", Config),
+ case OptArgs -- [DefArg, DerivArg] of
+ [] ->
+ format("~s", [String]);
+ [ConfigFile] ->
+ write_file(ConfigFile, String);
+ _ ->
+ throw(usage)
+ end;
+ {error, Reason} ->
+ {error, Reason}
+ end;
+ [["--create_rel", RelName | OptArgs]] ->
+ case reltool:get_rel(Options, RelName) of
+ {ok, Rel} ->
+ String = pretty("rel", Rel),
+ case OptArgs of
+ [] ->
+ format("~s", [String]);
+ [RelFile] ->
+ write_file(RelFile, String);
+ _ ->
+ throw(usage)
+ end;
+ {error, Reason} ->
+ {error, Reason}
+ end;
+ [["--create_script", RelName | OptArgs]] ->
+ case reltool:get_script(Options, RelName) of
+ {ok, Script} ->
+ String = pretty("script", Script),
+ case OptArgs of
+ [] ->
+ format("~s", [String]);
+ [ScriptFile] ->
+ write_file(ScriptFile, String);
+ _ ->
+ throw(usage)
+ end;
+ {error, Reason} ->
+ {error, Reason}
+ end;
+ [["--create_target", TargetDir]] ->
+ reltool:create_target(Options, TargetDir);
+ [["--create_target_spec" | OptArgs]] ->
+ case reltool:get_target_spec(Options) of
+ {ok, Script} ->
+ String = pretty("target_spec", Script),
+ case OptArgs of
+ [] ->
+ format("~s", [String]);
+ [SpecFile] ->
+ write_file(SpecFile, String);
+ _ ->
+ throw(usage)
+ end;
+ {error, Reason} ->
+ {error, Reason}
+ end;
+ [["--eval_target_spec", TargetSpec, TargetDir, RootDir]] ->
+ try
+ {ok, Tokens, _} = erl_scan:string(TargetSpec ++ ". "),
+ {ok, {spec, Spec}} = erl_parse:parse_term(Tokens),
+ reltool:eval_target_spec(Spec, TargetDir, RootDir)
+ catch
+ error:{badmatch, _} ->
+ case file:consult(TargetSpec) of
+ {ok, Spec2} ->
+ reltool:eval_target_spec(Spec2, TargetDir, RootDir);
+ {error, Reason} ->
+ Text = file:format_error(Reason),
+ {error, TargetSpec ++ ": " ++ Text}
+ end
+ end;
+ _ ->
+ throw(usage)
+ end.
+
+start_window(Options) ->
+ case reltool:start_link(Options) of
+ {ok, WinPid} ->
+ receive
+ {'EXIT', WinPid, shutdown} ->
+ ok;
+ {'EXIT', WinPid, normal} ->
+ ok;
+ {'EXIT', WinPid, Reason} ->
+ exit(Reason)
+ end;
+ {error, Reason} ->
+ {error, Reason}
+ end.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Helpers
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+script_name() ->
+ filename:basename(escript:script_name(), ".escript").
+
+fatal_error(String, Code) ->
+ io:format(standard_error, "~s: ~s\n", [script_name(), String]),
+ safe_stop(Code).
+
+write_file(File, IoList) ->
+ case file:write_file(File, IoList) of
+ ok ->
+ ok;
+ {error, Reason} ->
+ {error, file:format_error(Reason)}
+ end.
+
+format(Format, Args) ->
+ io:format(Format, Args),
+ %% Wait a while for the I/O to be processed
+ timer:sleep(timer:seconds(1)).
+
+pretty(Tag, Term) ->
+ lists:flatten(io_lib:format("%% ~s generated at ~w ~w\n~p.\n\n",
+ [Tag, date(), time(), Term])).
+
+scan_args([H | T], Single, Multi) ->
+ case H of
+ "--" ++ _ when Single =:= [] ->
+ scan_args(T, [H], Multi);
+ "--" ++ _ ->
+ scan_args(T, [H], [lists:reverse(Single) | Multi]);
+ _ ->
+ scan_args(T, [H | Single], Multi)
+ end;
+scan_args([], [], Multi) ->
+ lists:reverse(Multi);
+scan_args([], Single, Multi) ->
+ lists:reverse([lists:reverse(Single) | Multi]).
+
+parse_args([H | T] = Args, Options) ->
+ case H of
+ ["--wx_debug" | Levels] ->
+ Dbg =
+ fun(L) ->
+ case catch list_to_integer(L) of
+ {'EXIT', _} ->
+ case catch list_to_atom(L) of
+ {'EXIT', _} ->
+ exit("Illegal wx debug level: " ++ L);
+ Atom ->
+ Atom
+ end;
+ Int ->
+ Int
+ end
+ end,
+ Levels2 = lists:map(Dbg, Levels),
+ parse_args(T, [{wx_debug, Levels2} | Options]);
+ ["--" ++ _ | _] ->
+ %% No more options
+ {lists:reverse(Options), Args};
+ [Config] ->
+ try
+ {ok, Tokens, _} = erl_scan:string(Config ++ ". "),
+ {ok, {sys, _} = Sys} = erl_parse:parse_term(Tokens),
+ parse_args(T, [{config, Sys} | Options])
+ catch
+ error:{badmatch, _} ->
+ parse_args(T, [{config, Config} | Options]);
+ X:Y ->
+ io:format("\n\n~p\n\n", [{X, Y}])
+ end
+ end;
+parse_args([], Options) ->
+ {lists:reverse(Options), []}.
diff --git a/lib/reltool/doc/src/reltool.xml b/lib/reltool/doc/src/reltool.xml
index 9786928ae8..0c2b7d2a2b 100644
--- a/lib/reltool/doc/src/reltool.xml
+++ b/lib/reltool/doc/src/reltool.xml
@@ -67,14 +67,14 @@
<taglist>
- <tag><c><![CDATA[config]]></c></tag>
+ <tag><c>config</c></tag>
<item>
<p>This is the main option and it controls the configuration
of <c>reltool</c>. It can either be a <c>sys</c> tuple or
a name of a <c>file</c> containing a sys tuple.</p>
</item>
- <tag><c><![CDATA[trap_exit]]></c></tag>
+ <tag><c>trap_exit></c></tag>
<item>
<p>This option controls the error handling behavior of
<c>reltool</c>. By default the window processes traps
@@ -82,7 +82,7 @@
<c>trap_exit</c> to <c>false</c>.</p>
</item>
- <tag><c><![CDATA[wx_debug]]></c></tag>
+ <tag><c>wx_debug</c></tag>
<item>
<p>This option controls the debug level of <c>wx</c>. As its
name indicates it is only useful for debugging. See
@@ -97,27 +97,27 @@
<taglist>
- <tag><c><![CDATA[erts]]></c></tag>
+ <tag><c>erts</c></tag>
<item>
<p>Erts specific configuration. See application level options
below.</p>
</item>
- <tag><c><![CDATA[escript]]></c></tag>
+ <tag><c>escript</c></tag>
<item>
<p>Escript specific configuration. An escript has a mandatory
file name and escript level options that are described
below.</p>
</item>
- <tag><c><![CDATA[app]]></c></tag>
+ <tag><c>app</c></tag>
<item>
<p>Application specific configuration. An application has a
mandatory name and application level options that are
described below.</p>
</item>
- <tag><c><![CDATA[mod_cond]]></c></tag>
+ <tag><c>mod_cond</c></tag>
<item>
<p>This parameter controls the module inclusion policy. It
defaults to <c>all</c> which means that if an application is
@@ -134,28 +134,28 @@
system level is used as default for all applications.</p>
</item>
- <tag><c><![CDATA[incl_cond]]></c></tag>
+ <tag><c>incl_cond</c></tag>
<item>
- <p>This parameter controls the application and escript
- inclusion policy. It defaults to <c>derived</c> which means
- that the applications that not have any explicit
- <c>incl_cond</c> setting, will only be included if any other
- (explicitly or implicitly included) application uses it. The
- value <c>include</c> implies that all applications and
- escripts that that not have any explicit <c>incl_cond</c>
- setting will be included. <c>exclude</c> implies that all
- applications and escripts) that that not have any explicit
- <c>incl_cond</c> setting will be excluded.</p>
+ <p>This parameter controls the application and escript
+ inclusion policy. It defaults to <c>derived</c> which means
+ that the applications that not have any explicit
+ <c>incl_cond</c> setting, will only be included if any other
+ (explicitly or implicitly included) application uses it. The
+ value <c>include</c> implies that all applications and
+ escripts that that not have any explicit <c>incl_cond</c>
+ setting will be included. <c>exclude</c> implies that all
+ applications and escripts) that that not have any explicit
+ <c>incl_cond</c> setting will be excluded.</p>
</item>
- <tag><c><![CDATA[boot_rel]]></c></tag>
+ <tag><c>boot_rel</c></tag>
<item>
<p>A target system may have several releases but the one given
as <c>boot_rel</c> will be used as default when the system is
booting up.</p>
</item>
- <tag><c><![CDATA[rel]]></c></tag>
+ <tag><c>rel</c></tag>
<item>
<p>Release specific configuration. Each release maps to a
<c>rel</c>, <c>script</c> and <c>boot </c> file. See the
@@ -165,38 +165,38 @@
applications.</p>
</item>
- <tag><c><![CDATA[relocatable]]></c></tag>
+ <tag><c>relocatable</c></tag>
<item>
- <p>This parameter controls whether the <c>erl</c> executable
- in the target system automatically should determine where it
- is installed or if it should use a hardcoded path to the
- installation. In the latter case the target system must be
- installed with <c>reltool:install/2</c> before it can be
- used. If the system is relocatable, the file tree containing
- the target system can be moved to another location without
- re-installation. The default is <c>true</c>.</p>
+ <p>This parameter controls whether the <c>erl</c> executable
+ in the target system automatically should determine where it
+ is installed or if it should use a hardcoded path to the
+ installation. In the latter case the target system must be
+ installed with <c>reltool:install/2</c> before it can be
+ used. If the system is relocatable, the file tree containing
+ the target system can be moved to another location without
+ re-installation. The default is <c>true</c>.</p>
</item>
- <tag><c><![CDATA[profile]]></c></tag>
+ <tag><c>profile</c></tag>
<item>
- <p>The creation of the specification for a target system is
- performed in two steps. In the first step a complete
- specification is generated. It will likely contain much more
- files than you are interested in your customized target
- system. In the second step the specification will be filtered
- according to your filters. There you have the ability to
- specify filters per application as well as system wide
- filters. You can also select a <c>profile</c> for your
- system. Depending on the <c>profile</c>, different default
- filters will be used. There are three different profiles to
- choose from: <c>development</c>, <c>embedded</c> and
- <c>standalone</c>. <c>development</c> is default. The
- parameters that are affected by the <c>profile</c> are:
- <c>incl_sys_filters</c>, <c>excl_sys_filters</c>,
- <c>incl_app_filters</c> and <c>excl_app_filters</c>.</p>
+ <p>The creation of the specification for a target system is
+ performed in two steps. In the first step a complete
+ specification is generated. It will likely contain much more
+ files than you are interested in your customized target
+ system. In the second step the specification will be filtered
+ according to your filters. There you have the ability to
+ specify filters per application as well as system wide
+ filters. You can also select a <c>profile</c> for your
+ system. Depending on the <c>profile</c>, different default
+ filters will be used. There are three different profiles to
+ choose from: <c>development</c>, <c>embedded</c> and
+ <c>standalone</c>. <c>development</c> is default. The
+ parameters that are affected by the <c>profile</c> are:
+ <c>incl_sys_filters</c>, <c>excl_sys_filters</c>,
+ <c>incl_app_filters</c> and <c>excl_app_filters</c>.</p>
</item>
- <tag><c><![CDATA[app_file]]></c></tag>
+ <tag><c>app_file</c></tag>
<item>
<p>This parameter controls the default handling of the
<c>app</c> files when a target system is generated. It
@@ -213,7 +213,7 @@
and <c>strip</c>.</p>
</item>
- <tag><c><![CDATA[debug_info]]></c></tag>
+ <tag><c>debug_info</c></tag>
<item>
<p>The <c>debug_info</c> parameter controls whether the debug
information in the beam file should be kept (<c>keep</c>) or
@@ -221,7 +221,7 @@
system.</p>
</item>
- <tag><c><![CDATA[incl_sys_filters]]></c></tag>
+ <tag><c>incl_sys_filters</c></tag>
<item>
<p>This parameter normally contains a list of regular
expressions that controls which files in the system that
@@ -235,7 +235,7 @@
<c>[".*"]</c>.</p>
</item>
- <tag><c><![CDATA[excl_sys_filters]]></c></tag>
+ <tag><c>excl_sys_filters</c></tag>
<item>
<p>This parameter normally contains a list of regular
expressions that controls which files in the system that not
@@ -245,7 +245,7 @@
<c>excl_sys_filters</c>. This parameter defaults to
<c>[]</c>.</p>
</item>
- <tag><c><![CDATA[incl_app_filters]]></c></tag>
+ <tag><c>incl_app_filters</c></tag>
<item>
<p>This parameter normally contains a list of regular
expressions that controls which application specific files
@@ -256,7 +256,7 @@
parameter defaults to <c>[".*"]</c>.</p>
</item>
- <tag><c><![CDATA[excl_app_filters]]></c></tag>
+ <tag><c>excl_app_filters</c></tag>
<item>
<p>This parameter normally contains a list of regular
expressions that controls which application specific files
@@ -267,7 +267,7 @@
<c>[]</c>.</p>
</item>
- <tag><c><![CDATA[incl_archive_filters]]></c></tag>
+ <tag><c>incl_archive_filters</c></tag>
<item>
<p>This parameter normally contains a list of regular
expressions that controls which top level directories in an
@@ -280,7 +280,7 @@
parameter defaults to <c>[".*"]</c>.</p>
</item>
- <tag><c><![CDATA[excl_archive_filters]]></c></tag>
+ <tag><c>excl_archive_filters</c></tag>
<item>
<p>This parameter normally contains a list of regular
expressions that controls which top level directories in an
@@ -291,7 +291,7 @@
parameter defaults to <c>["^include$","^priv$"]</c>.</p>
</item>
- <tag><c><![CDATA[archive_opts]]></c></tag>
+ <tag><c>archive_opts</c></tag>
<item>
<p>This parameter contains a list of options that are given to
<c>zip:create/3</c> when application specific files are
@@ -307,7 +307,7 @@
supported:</p>
<taglist>
- <tag><c><![CDATA[incl_cond]]></c></tag>
+ <tag><c>incl_cond</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
@@ -318,62 +318,62 @@
supported:</p>
<taglist>
- <tag><c><![CDATA[vsn]]></c></tag>
+ <tag><c>vsn</c></tag>
<item>
<p>The version of the application. In an installed system there may
exist several versions of an application. The <c>vsn</c> parameter
controls which version of the application that will be choosen. If it
is omitted, the latest version will be choosen.</p>
</item>
- <tag><c><![CDATA[mod]]></c></tag>
+ <tag><c>mod</c></tag>
<item>
<p>Module specific configuration. A module has a mandatory
name and module level options that are described below.</p>
</item>
- <tag><c><![CDATA[mod_cond]]></c></tag>
+ <tag><c>mod_cond</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[incl_cond]]></c></tag>
+ <tag><c>incl_cond</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[app_file]]></c></tag>
+ <tag><c>app_file</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[debug_info]]></c></tag>
+ <tag><c>debug_info</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[incl_app_filters]]></c></tag>
+ <tag><c>incl_app_filters</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[excl_app_filters]]></c></tag>
+ <tag><c>excl_app_filters</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[incl_archive_filters]]></c></tag>
+ <tag><c>incl_archive_filters</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[excl_archive_filters]]></c></tag>
+ <tag><c>excl_archive_filters</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
</item>
- <tag><c><![CDATA[archive_opts]]></c></tag>
+ <tag><c>archive_opts</c></tag>
<item>
<p>The value of this parameter overrides the parameter with the
same name on system level.</p>
@@ -384,18 +384,18 @@
supported:</p>
<taglist>
- <tag><c><![CDATA[incl_cond]]></c></tag>
+ <tag><c>incl_cond</c></tag>
<item>
- <p>This parameter controls whether the module is included or not. By
- default the <c>mod_incl</c> parameter on application and system level
- will be used to control whether the module is included or not. The
- value of <c>incl_cond</c> overrides the module inclusion policy.
- <c>include</c> implies that the module is included, while
- <c>exclude</c> implies that the module not is included.
- <c>derived</c> implies that the is included if any included uses the
- module.</p>
+ <p>This parameter controls whether the module is included or not. By
+ default the <c>mod_incl</c> parameter on application and system level
+ will be used to control whether the module is included or not. The
+ value of <c>incl_cond</c> overrides the module inclusion policy.
+ <c>include</c> implies that the module is included, while
+ <c>exclude</c> implies that the module not is included.
+ <c>derived</c> implies that the is included if any included uses the
+ module.</p>
</item>
- <tag><c><![CDATA[debug_info]]></c></tag>
+ <tag><c>debug_info</c></tag>
<item>
<p>The value of this parameter overrides the parameter with
the same name on application level.</p>
@@ -477,7 +477,9 @@ mod_name() = atom()
profile() = development | embedded | standalone
re_regexp() = string()
reason() = string()
-regexps() = [re_regexp()] | {add, [re_regexp()]} | {del, [re_regexp()]}
+regexps() = [re_regexp()]
+ | {add, [re_regexp()]}
+ | {del, [re_regexp()]}
rel_file() = term()
rel_name() = string()
rel_vsn() = string()
@@ -487,7 +489,19 @@ script_file() = term()
server() = server_pid() | options()
server_pid() = pid()
target_dir() = file()
-window_pid() = pid()]]></code>
+window_pid() = pid()
+base_dir() = dir()
+base_file() = file()
+top_dir() = file()
+top_file() = file()
+target_spec() = [target_spec()]
+ | {create_dir, base_dir(), [target_spec()]}
+ | {create_dir, base_dir(), top_dir(), [target_spec()]}
+ | {archive, base_file(), [archive_opt()], [target_spec()]}
+ | {copy_file, base_file()}
+ | {copy_file, base_file(), top_file()}
+ | {write_file, base_file(), iolist()}
+ | {strip_beam_file, base_file()}]]></code>
<marker id="start"></marker>
</section>
@@ -497,9 +511,9 @@ window_pid() = pid()]]></code>
<name>create_target(Server, TargetDir) -> ok | {error, Reason}</name>
<fsummary>Create a target system</fsummary>
<type>
- <v>Server = server()</v>
+ <v>Server = server()</v>
<v>TargetDir = target_dir()</v>
- <v>Reason = reason()</v>
+ <v>Reason = reason()</v>
</type>
<desc><p>Create a target system. Gives the same result as
<c>{ok,TargetSpec}=reltool:get_target_spec(Server)</c> and
@@ -604,6 +618,17 @@ window_pid() = pid()]]></code>
</func>
<func>
+ <name>get_status(Server) -> {ok, [Warning]} | {error, Reason}</name>
+ <fsummary>Get contents of a release file</fsummary>
+ <type>
+ <v>Server = server()</v>
+ <v>Warning = string()</v>
+ <v>Reason = reason()</v>
+ </type>
+ <desc><p>Get status about the configuration</p></desc>
+ </func>
+
+ <func>
<name>get_server(WindowPid) -> {ok, ServerPid} | {error, Reason}</name>
<fsummary>Start server process with options</fsummary>
<type>
diff --git a/lib/reltool/doc/src/reltool_examples.xml b/lib/reltool/doc/src/reltool_examples.xml
index d6db246f6c..bce9413b52 100644
--- a/lib/reltool/doc/src/reltool_examples.xml
+++ b/lib/reltool/doc/src/reltool_examples.xml
@@ -249,11 +249,11 @@ Eshell V5.7.3 (abort with ^G)
<pre>
5&gt; {ok, Server} = reltool:start_server([{config, {sys, [{boot_rel, "NAME"},
{rel, "NAME", "VSN",
- [kernel, stdlib, sasl]}]}}]).
+ [sasl]}]}}]).
{ok,&lt;0.1288.0&gt;}
6&gt; reltool:get_config(Server).
{ok,{sys,[{boot_rel,"NAME"},
- {rel,"NAME","VSN",[kernel,stdlib,sasl]}]}}
+ {rel,"NAME","VSN",[sasl]}]}}
7&gt; reltool:get_rel(Server, "NAME").
{ok,{release,{"NAME","VSN"},
{erts,"5.7"},
diff --git a/lib/reltool/src/Makefile b/lib/reltool/src/Makefile
index 7fac7cbf88..4e6a112b7e 100644
--- a/lib/reltool/src/Makefile
+++ b/lib/reltool/src/Makefile
@@ -28,7 +28,6 @@ include ../vsn.mk
VSN = $(RELTOOL_VSN)
APP_VSN = "reltool-$(VSN)"
-
# ----------------------------------------------------
# Release directory specification
# ----------------------------------------------------
@@ -39,25 +38,20 @@ RELSYSDIR = $(RELEASE_PATH)/lib/reltool-$(VSN)
# Target Specs
# ----------------------------------------------------
-MODULES = \
- reltool \
- reltool_app_win \
- reltool_fgraph \
- reltool_fgraph_win \
- reltool_mod_win \
- reltool_sys_win \
- reltool_server \
- reltool_target \
- reltool_utils
-
-HRL_FILES =
-
-INTERNAL_HRL_FILES = reltool.hrl reltool_fgraph.hrl
+include files.mk
ERL_FILES = $(MODULES:%=%.erl)
TARGET_FILES= $(MODULES:%=$(EBIN)/%.$(EMULATOR))
+APP_FILE = reltool.app
+APP_SRC = $(APP_FILE).src
+APP_TARGET = $(EBIN)/$(APP_FILE)
+
+APPUP_FILE = reltool.appup
+APPUP_SRC = $(APPUP_FILE).src
+APPUP_TARGET = $(EBIN)/$(APPUP_FILE)
+
# ----------------------------------------------------
# FLAGS
# ----------------------------------------------------
@@ -69,15 +63,28 @@ ERL_COMPILE_FLAGS += +'{parse_transform,sys_pre_attributes}' \
# Targets
# ----------------------------------------------------
-debug opt: $(TARGET_FILES) $(HRL_FILES)
+debug:
+ @${MAKE} TYPE=debug opt
+
+opt: $(TARGET_FILES) $(APP_TARGET) $(APPUP_TARGET)
clean:
- rm -f $(TARGET_FILES)
+ rm -f $(TARGET_FILES) $(APP_TARGET) $(APPUP_TARGET)
rm -f core
docs:
# ----------------------------------------------------
+# Special Build Targets
+# ----------------------------------------------------
+
+$(APP_TARGET): $(APP_SRC) ../vsn.mk
+ sed -e 's;%VSN%;$(VSN);' $< > $@
+
+$(APPUP_TARGET): $(APPUP_SRC) ../vsn.mk
+ sed -e 's;%VSN%;$(VSN);' $< > $@
+
+# ----------------------------------------------------
# Dependencies
# ----------------------------------------------------
@@ -94,6 +101,7 @@ release_spec: opt
$(INSTALL_DATA) $(INTERNAL_HRL_FILES) $(ERL_FILES) $(RELSYSDIR)/src
$(INSTALL_DIR) $(RELSYSDIR)/ebin
$(INSTALL_DATA) $(TARGET_FILES) $(RELSYSDIR)/ebin
+ $(INSTALL_DATA) $(APP_TARGET) $(APPUP_TARGET) $(RELSYSDIR)/ebin
release_docs_spec:
diff --git a/lib/reltool/src/files.mk b/lib/reltool/src/files.mk
new file mode 100644
index 0000000000..99a1f1c14a
--- /dev/null
+++ b/lib/reltool/src/files.mk
@@ -0,0 +1,32 @@
+#-*-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%
+
+MODULES = \
+ reltool \
+ reltool_app_win \
+ reltool_fgraph \
+ reltool_fgraph_win \
+ reltool_mod_win \
+ reltool_sys_win \
+ reltool_server \
+ reltool_target \
+ reltool_utils
+
+HRL_FILES =
+
+INTERNAL_HRL_FILES = reltool.hrl reltool_fgraph.hrl
diff --git a/lib/reltool/src/reltool.app.src b/lib/reltool/src/reltool.app.src
index f83042c157..b80753e8fc 100644
--- a/lib/reltool/src/reltool.app.src
+++ b/lib/reltool/src/reltool.app.src
@@ -1,37 +1,38 @@
%% This is an -*- erlang -*- file.
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
+%% %CopyrightEnd%
{application, reltool,
- [{description, "Release management tool"},
- {vsn, "%VSN%"},
- {modules, [
- reltool,
- reltool_app,
- reltool_fgraph,
- reltool_fgraph_win,
- reltool_gen,
- reltool_mod,
- reltool_sys,
- reltool_server,
- reltool_utils
- ]},
- {applications, [kernel, stdlib]}
- ]
-}.
+ [{description, "Reltool the release management tool"},
+ {vsn, "%VSN%"},
+ {modules,
+ [
+ reltool_app_win,
+ reltool,
+ reltool_fgraph,
+ reltool_fgraph_win,
+ reltool_mod_win,
+ reltool_server,
+ reltool_sys_win,
+ reltool_target,
+ reltool_utils
+ ]},
+ {registered, []},
+ {applications, [stdlib, kernel]},
+ {env, []}
+ ]}.
diff --git a/lib/reltool/src/reltool.appup.src b/lib/reltool/src/reltool.appup.src
new file mode 100644
index 0000000000..c02edd2afb
--- /dev/null
+++ b/lib/reltool/src/reltool.appup.src
@@ -0,0 +1,22 @@
+%% This is an -*- erlang -*- file.
+%%
+%% %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%
+
+{"%VSN%",
+ [ ]
+}.
diff --git a/lib/reltool/src/reltool.erl b/lib/reltool/src/reltool.erl
index e6a8bca069..9dd0a24f46 100644
--- a/lib/reltool/src/reltool.erl
+++ b/lib/reltool/src/reltool.erl
@@ -20,9 +20,8 @@
%% Public
-export([
- main/1, % Escript
start/0, start/1, start_link/1, debug/0, % GUI
- start_server/1, get_server/1, stop/1,
+ start_server/1, get_server/1, get_status/1, stop/1,
get_config/1, get_config/3, get_rel/2, get_script/2,
create_target/2, get_target_spec/1, eval_target_spec/3,
install/2
@@ -32,39 +31,26 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%% Main function for escript
--spec main([escript_arg()]) -> ok.
-main(_) ->
- process_flag(trap_exit, true),
- {ok, WinPid} = start_link([]),
- receive
- {'EXIT', WinPid, shutdown} ->
- ok;
- {'EXIT', WinPid, normal} ->
- ok;
- {'EXIT', WinPid, Reason} ->
- io:format("EXIT: ~p\n", [Reason]),
- erlang:halt(1)
- end.
-
%% Start main window process
--spec start() -> {ok, window_pid()}.
+-spec start() -> {ok, window_pid()} | {error, reason()}.
start() ->
start([]).
%% Start main window process
--spec start(options()) -> {ok, window_pid() | {error, reason()}}.
+-spec start(options()) -> {ok, window_pid()} | {error, reason()}.
start(Options)when is_list(Options) ->
- {ok, WinPid} = start_link(Options),
- unlink(WinPid),
- {ok, WinPid}.
+ case start_link(Options) of
+ {ok, WinPid} ->
+ unlink(WinPid),
+ {ok, WinPid};
+ Other->
+ Other
+ end.
%% Start main window process with wx debugging enabled
--spec debug() -> {ok, window_pid()}.
+-spec debug() -> {ok, window_pid()} | {error, reason()}.
debug() ->
- {ok, WinPid} = start_link([{wx_debug, 2}]),
- unlink(WinPid),
- {ok, WinPid}.
+ start([{wx_debug, 2}]).
%% Start main window process with options
-spec start_link(options()) -> {ok, window_pid() | {error, reason()}}.
@@ -110,20 +96,48 @@ stop(Pid) when is_pid(Pid) ->
end.
%% Internal library function
--spec eval_server(server(), fun((server_pid()) -> term())) ->
+-spec eval_server(server(), boolean(), fun((server_pid()) -> term())) ->
{ok, server_pid()} | {error, reason()}.
-eval_server(Pid, Fun) when is_pid(Pid) ->
+eval_server(Pid, DisplayWarnings, Fun)
+ when is_pid(Pid) ->
Fun(Pid);
-eval_server(Options, Fun) when is_list(Options), is_function(Fun, 1) ->
- case start_server(Options) of
- {ok, Pid} ->
- Res = Fun(Pid),
- stop(Pid),
- Res;
- {error, Reason} ->
- {error, Reason}
+eval_server(Options, DisplayWarnings, Fun)
+ when is_list(Options) ->
+ TrapExit = process_flag(trap_exit, true),
+ Res = case start_server(Options) of
+ {ok, Pid} ->
+ apply_fun(Pid, DisplayWarnings, Fun);
+ {error, Reason} ->
+ {error, Reason}
+ end,
+ process_flag(trap_exit, TrapExit),
+ Res.
+
+apply_fun(Pid, false, Fun) ->
+ Res = Fun(Pid),
+ stop(Pid),
+ Res;
+apply_fun(Pid, true, Fun) ->
+ case get_status(Pid) of
+ {ok, Warnings} ->
+ [io:format("~p: ~s\n", [?APPLICATION, W]) || W <- Warnings],
+ apply_fun(Pid, false, Fun);
+ {error, Reason} ->
+ stop(Pid),
+ {error, Reason}
end.
+%% Get status about the configuration
+-type warning() :: string().
+-spec get_status(server()) ->
+ {ok, [warning()]} | {error, reason()}.
+get_status(PidOrOptions)
+ when is_pid(PidOrOptions); is_list(PidOrOptions) ->
+ eval_server(PidOrOptions, false,
+ fun(Pid) ->
+ reltool_server:get_status(Pid)
+ end).
+
%% Get reltool configuration
-spec get_config(server()) -> {ok, config()} | {error, reason()}.
get_config(PidOrOption) ->
@@ -133,7 +147,7 @@ get_config(PidOrOption) ->
{ok, config()} | {error, reason()}.
get_config(PidOrOptions, InclDef, InclDeriv)
when is_pid(PidOrOptions); is_list(PidOrOptions) ->
- eval_server(PidOrOptions,
+ eval_server(PidOrOptions, true,
fun(Pid) ->
reltool_server:get_config(Pid, InclDef, InclDeriv)
end).
@@ -142,7 +156,7 @@ get_config(PidOrOptions, InclDef, InclDeriv)
-spec get_rel(server(), rel_name()) -> {ok, rel_file()} | {error, reason()}.
get_rel(PidOrOptions, RelName)
when is_pid(PidOrOptions); is_list(PidOrOptions) ->
- eval_server(PidOrOptions,
+ eval_server(PidOrOptions, true,
fun(Pid) -> reltool_server:get_rel(Pid, RelName) end).
%% Get contents of boot script file
@@ -150,21 +164,22 @@ get_rel(PidOrOptions, RelName)
{ok, script_file()} | {error, reason()}.
get_script(PidOrOptions, RelName)
when is_pid(PidOrOptions); is_list(PidOrOptions) ->
- eval_server(PidOrOptions,
+ eval_server(PidOrOptions, true,
fun(Pid) -> reltool_server:get_script(Pid, RelName) end).
%% Generate a target system
-spec create_target(server(), target_dir()) -> ok | {error, reason()}.
create_target(PidOrOptions, TargetDir)
when is_pid(PidOrOptions); is_list(PidOrOptions) ->
- eval_server(PidOrOptions,
+ eval_server(PidOrOptions, true,
fun(Pid) -> reltool_server:gen_target(Pid, TargetDir) end).
%% Generate a target system
-spec get_target_spec(server()) -> {ok, target_spec()} | {error, reason()}.
get_target_spec(PidOrOptions)
when is_pid(PidOrOptions); is_list(PidOrOptions) ->
- eval_server(PidOrOptions, fun(Pid) -> reltool_server:gen_spec(Pid) end).
+ eval_server(PidOrOptions, true,
+ fun(Pid) -> reltool_server:gen_spec(Pid) end).
%% Generate a target system
-spec eval_target_spec(target_spec(), root_dir(), target_dir()) ->
diff --git a/lib/reltool/src/reltool.hrl b/lib/reltool/src/reltool.hrl
index 8a6a2142fd..1a34ced89d 100644
--- a/lib/reltool/src/reltool.hrl
+++ b/lib/reltool/src/reltool.hrl
@@ -17,7 +17,7 @@
%% %CopyrightEnd%
-define(APPLICATION, reltool).
--define(MISSING_APP, '*MISSING*').
+-define(MISSING_APP_NAME, '*MISSING*').
-define(MISSING_APP_TEXT, "*MISSING*").
-type file() :: string().
@@ -104,7 +104,7 @@
-type rel_file() :: term().
-type script_file() :: term().
-type reason() :: string().
--type escript_arg() :: string().
+
-type base_dir() :: dir().
-type base_file() :: file().
-type top_dir() :: file().
@@ -112,10 +112,7 @@
-type target_spec() :: [target_spec()]
| {create_dir, base_dir(), [target_spec()]}
| {create_dir, base_dir(), top_dir(), [target_spec()]}
- | {archive,
- base_file(),
- [archive_opt()],
- [target_spec()]}
+ | {archive, base_file(), [archive_opt()], [target_spec()]}
| {copy_file, base_file()}
| {copy_file, base_file(), top_file()}
| {write_file, base_file(), iolist()}
@@ -139,57 +136,58 @@
-record(mod,
{%% Static
- name :: mod_name(),
- app_name :: app_name(),
- incl_cond :: incl_cond() | undefined,
- debug_info :: debug_info() | undefined,
- is_app_mod :: boolean(),
+ name :: mod_name(),
+ app_name :: app_name(),
+ incl_cond :: incl_cond() | undefined,
+ debug_info :: debug_info() | undefined,
+ is_app_mod :: boolean(),
is_ebin_mod :: boolean(),
- uses_mods :: [mod_name()],
- exists :: boolean(),
+ uses_mods :: [mod_name()],
+ exists :: boolean(),
+
%% Dynamic
- status :: status(),
- used_by_mods :: [mod_name()],
+ status :: status(),
+ used_by_mods :: [mod_name()],
is_pre_included :: boolean() | undefined,
- is_included :: boolean() | undefined
+ is_included :: boolean() | undefined
}).
-record(app_info,
{
- description = "",
- id = "",
- vsn = "",
- modules = [],
- maxP = infinity,
- maxT = infinity,
- registered = [],
- incl_apps = [],
- applications = [],
- env = [],
- mod = undefined,
- start_phases = undefined
+ description = "" :: string(),
+ id = "" :: string(),
+ vsn = "" :: app_vsn(),
+ modules = [] :: [mod_name()],
+ maxP = infinity :: integer() | infinity,
+ maxT = infinity :: integer() | infinity,
+ registered = [] :: [atom()],
+ incl_apps = [] :: [app_name()],
+ applications = [] :: [app_name()],
+ env = [] :: [{atom(), term()}],
+ mod = undefined :: {mod_name(), [term()]} | undefined,
+ start_phases = undefined :: [{atom(), term()}] | undefined
}).
-record(app,
{%% Static info
- name :: app_name(),
- is_escript :: boolean(),
+ name :: app_name(),
+ is_escript :: boolean(),
use_selected_vsn :: boolean() | undefined,
- active_dir :: dir(),
- sorted_dirs :: [dir()],
- vsn :: app_vsn(),
- label :: app_label(),
- info :: #app_info{} | undefined,
- mods :: [#mod{}],
+ active_dir :: dir(),
+ sorted_dirs :: [dir()],
+ vsn :: app_vsn(),
+ label :: app_label(),
+ info :: #app_info{} | undefined,
+ mods :: [#mod{}],
%% Static source cond
- mod_cond :: mod_cond() | undefined,
+ mod_cond :: mod_cond() | undefined,
incl_cond :: incl_cond() | undefined,
%% Static target cond
- debug_info :: debug_info() | undefined,
- app_file :: app_file() | undefined,
- app_type :: app_type(),
+ debug_info :: debug_info() | undefined,
+ app_file :: app_file() | undefined,
+ app_type :: app_type() | undefined,
incl_app_filters :: incl_app_filters(),
excl_app_filters :: excl_app_filters(),
incl_archive_filters :: incl_archive_filters(),
@@ -197,19 +195,20 @@
archive_opts :: [archive_opt()],
%% Dynamic
- status :: status(),
- uses_mods :: [mod_name()],
- used_by_mods :: [mod_name()],
- uses_apps :: [app_name()],
- used_by_apps :: [app_name()],
+ status :: status(),
+ uses_mods :: [mod_name()],
+ used_by_mods :: [mod_name()],
+ uses_apps :: [app_name()],
+ used_by_apps :: [app_name()],
is_pre_included :: boolean(),
- is_included :: boolean()
+ is_included :: boolean(),
+ rels :: [rel_name()]
}).
-record(rel_app,
{
- name :: app_name(),
- app_type :: app_type(),
+ name :: app_name(),
+ app_type :: app_type(),
incl_apps :: [incl_app()]
}).
@@ -231,21 +230,22 @@
apps :: [#app{}],
%% Target cond
- boot_rel :: boot_rel(),
- rels :: [#rel{}],
- emu_name :: emu_name(),
- profile :: profile(),
- incl_sys_filters :: incl_sys_filters(),
- excl_sys_filters :: excl_sys_filters(),
- incl_app_filters :: incl_app_filters(),
- excl_app_filters :: excl_app_filters(),
+ boot_rel :: boot_rel(),
+ rels :: [#rel{}],
+ emu_name :: emu_name(),
+ profile :: profile(),
+ incl_sys_filters :: incl_sys_filters(),
+ excl_sys_filters :: excl_sys_filters(),
+ incl_app_filters :: incl_app_filters(),
+ excl_app_filters :: excl_app_filters(),
incl_archive_filters :: incl_archive_filters(),
excl_archive_filters :: excl_archive_filters(),
- archive_opts :: [archive_opt()],
- relocatable :: boolean(),
- app_type :: app_type(),
- app_file :: app_file(),
- debug_info :: debug_info()
+ archive_opts :: [archive_opt()],
+ relocatable :: boolean(),
+ rel_app_type :: app_type(),
+ embedded_app_type :: app_type() | undefined,
+ app_file :: app_file(),
+ debug_info :: debug_info()
}).
-record(regexp, {source, compiled}).
@@ -268,7 +268,8 @@
-define(DEFAULT_EMU_NAME, "beam").
-define(DEFAULT_PROFILE, development).
-define(DEFAULT_RELOCATABLE, true).
--define(DEFAULT_APP_TYPE, permanent).
+-define(DEFAULT_REL_APP_TYPE, permanent).
+-define(DEFAULT_EMBEDDED_APP_TYPE, undefined).
-define(DEFAULT_APP_FILE, keep).
-define(DEFAULT_DEBUG_INFO, keep).
@@ -282,22 +283,23 @@
-define(DEFAULT_EXCL_APP_FILTERS, []).
-define(EMBEDDED_INCL_SYS_FILTERS, ["^bin",
- "^erts",
- "^lib",
- "^releases"]).
+ "^erts",
+ "^lib",
+ "^releases"]).
-define(EMBEDDED_EXCL_SYS_FILTERS,
["^bin/(erlc|dialyzer|typer)(|\\.exe)\$",
"^erts.*/bin/(erlc|dialyzer|typer)(|\\.exe)\$",
"^erts.*/bin/.*(debug|pdb)"]).
-define(EMBEDDED_INCL_APP_FILTERS, ["^ebin",
- "^priv",
- "^include"]).
+ "^include",
+ "^priv"]).
-define(EMBEDDED_EXCL_APP_FILTERS, []).
+-define(EMBEDDED_APP_TYPE, load).
-define(STANDALONE_INCL_SYS_FILTERS, ["^bin/(erl|epmd)(|\\.exe|\\.ini)\$",
- "^bin/start(|_clean).boot\$",
- "^erts.*/bin",
- "^lib\$"]).
+ "^bin/start(|_clean).boot\$",
+ "^erts.*/bin",
+ "^lib\$"]).
-define(STANDALONE_EXCL_SYS_FILTERS,
["^erts.*/bin/(erlc|dialyzer|typer)(|\\.exe)\$",
"^erts.*/bin/(start|escript|to_erl|run_erl)(|\\.exe)\$",
diff --git a/lib/reltool/src/reltool_mod_win.erl b/lib/reltool/src/reltool_mod_win.erl
index c2544cc2d8..f68c61fd6f 100644
--- a/lib/reltool/src/reltool_mod_win.erl
+++ b/lib/reltool/src/reltool_mod_win.erl
@@ -514,7 +514,7 @@ select_image(Xref, ModName) ->
{ok, M} = reltool_server:get_mod(Xref, ModName),
Image =
case M#mod.is_included of
- _ when M#mod.app_name =:= ?MISSING_APP -> ?ERR_IMAGE;
+ _ when M#mod.app_name =:= ?MISSING_APP_NAME -> ?ERR_IMAGE;
true -> ?TICK_IMAGE;
false -> ?WARN_IMAGE;
undefined -> ?ERR_IMAGE
@@ -674,7 +674,7 @@ do_goto_function(#state{active_page = P} = S, [FunName]) ->
find_regexp_forward(S, "^" ++ FunName ++ "(");
do_goto_function(S, [ModStr, FunStr]) ->
case reltool_server:get_mod(S#state.xref_pid, list_to_atom(ModStr)) of
- {ok, Mod} when Mod#mod.app_name =/= ?MISSING_APP ->
+ {ok, Mod} when Mod#mod.app_name =/= ?MISSING_APP_NAME ->
S2 = create_code_page(S#state{mod = Mod}, ModStr),
find_regexp_forward(S2, "^" ++ FunStr ++ "(");
{ok, _} ->
diff --git a/lib/reltool/src/reltool_server.erl b/lib/reltool/src/reltool_server.erl
index a7064f7651..039ad56aa8 100644
--- a/lib/reltool/src/reltool_server.erl
+++ b/lib/reltool/src/reltool_server.erl
@@ -132,19 +132,20 @@ init(Options) ->
end.
do_init(Options) ->
- case parse_options(Options) of
- {#state{parent_pid = ParentPid, common = C, sys = Sys} = S, Status} ->
- %% process_flag(trap_exit, (S#state.common)#common.trap_exit),
- proc_lib:init_ack(ParentPid,
- {ok, self(), C, Sys#sys{apps = undefined}}),
- {S2, Status2} = refresh(S, true, Status),
- {S3, Status3} = analyse(S2#state{old_sys = S2#state.sys}, Status2),
- case Status3 of
- {ok, _Warnings} ->
- loop(S3#state{status = Status3, old_status = {ok, []}});
- {error, Reason} ->
- exit(Reason)
- end
+ {S, Status} = parse_options(Options),
+ #state{parent_pid = ParentPid, common = C, sys = Sys} = S,
+
+ %% process_flag(trap_exit, (S#state.common)#common.trap_exit),
+ proc_lib:init_ack(ParentPid,
+ {ok, self(), C, Sys#sys{apps = undefined}}),
+ {S2, Status2} = refresh(S, true, Status),
+ {S3, Status3} =
+ analyse(S2#state{old_sys = S2#state.sys}, Status2),
+ case Status3 of
+ {ok, _Warnings} -> % BUGBUG: handle warnings
+ loop(S3#state{status = Status3, old_status = {ok, []}});
+ {error, Reason} ->
+ exit(Reason)
end.
parse_options(Opts) ->
@@ -161,33 +162,28 @@ parse_options(Opts) ->
rels = reltool_utils:default_rels(),
emu_name = ?DEFAULT_EMU_NAME,
profile = ?DEFAULT_PROFILE,
- incl_sys_filters =
- reltool_utils:decode_regexps(incl_sys_filters,
- ?DEFAULT_INCL_SYS_FILTERS,
- []),
- excl_sys_filters =
- reltool_utils:decode_regexps(excl_sys_filters,
- ?DEFAULT_EXCL_SYS_FILTERS,
- []),
- incl_app_filters =
- reltool_utils:decode_regexps(incl_app_filters,
- ?DEFAULT_INCL_APP_FILTERS,
- []),
- excl_app_filters =
- reltool_utils:decode_regexps(excl_app_filters,
- ?DEFAULT_EXCL_APP_FILTERS,
- []),
+ incl_sys_filters = dec_re(incl_sys_filters,
+ ?DEFAULT_INCL_SYS_FILTERS,
+ []),
+ excl_sys_filters = dec_re(excl_sys_filters,
+ ?DEFAULT_EXCL_SYS_FILTERS,
+ []),
+ incl_app_filters = dec_re(incl_app_filters,
+ ?DEFAULT_INCL_APP_FILTERS,
+ []),
+ excl_app_filters = dec_re(excl_app_filters,
+ ?DEFAULT_EXCL_APP_FILTERS,
+ []),
relocatable = ?DEFAULT_RELOCATABLE,
- app_type = ?DEFAULT_APP_TYPE,
+ rel_app_type = ?DEFAULT_REL_APP_TYPE,
+ embedded_app_type = ?DEFAULT_EMBEDDED_APP_TYPE,
app_file = ?DEFAULT_APP_FILE,
- incl_archive_filters =
- reltool_utils:decode_regexps(incl_archive_filters,
- ?DEFAULT_INCL_ARCHIVE_FILTERS,
- []),
- excl_archive_filters =
- reltool_utils:decode_regexps(excl_archive_filters,
- ?DEFAULT_EXCL_ARCHIVE_FILTERS,
- []),
+ incl_archive_filters = dec_re(incl_archive_filters,
+ ?DEFAULT_INCL_ARCHIVE_FILTERS,
+ []),
+ excl_archive_filters = dec_re(excl_archive_filters,
+ ?DEFAULT_EXCL_ARCHIVE_FILTERS,
+ []),
archive_opts = ?DEFAULT_ARCHIVE_OPTS,
debug_info = ?DEFAULT_DEBUG_INFO},
C2 = #common{sys_debug = [],
@@ -199,6 +195,9 @@ parse_options(Opts) ->
S = #state{options = Opts},
parse_options(Opts, S, C2, Sys, {ok, []}).
+dec_re(Key, Regexps, Old) ->
+ reltool_utils:decode_regexps(Key, Regexps, Old).
+
parse_options([{Key, Val} | KeyVals], S, C, Sys, Status) ->
case Key of
parent ->
@@ -261,6 +260,7 @@ loop(#state{common = C, sys = Sys} = S) ->
{ok, _Warnings} ->
S5#state{status = Status3, old_status = S#state.status};
{error, _} ->
+ %% Keep old state
S
end,
reltool_utils:reply(ReplyTo, Ref, Status3),
@@ -277,9 +277,9 @@ loop(#state{common = C, sys = Sys} = S) ->
Reply =
case lists:keysearch(RelName, #rel.name, Sys#sys.rels) of
{value, Rel} ->
- {ok, reltool_target:gen_rel(Rel, Sys)};
+ reltool_target:gen_rel(Rel, Sys);
false ->
- {error, "No such release"}
+ {error, "No such release: " ++ RelName}
end,
reltool_utils:reply(ReplyTo, Ref, Reply),
?MODULE:loop(S);
@@ -292,7 +292,7 @@ loop(#state{common = C, sys = Sys} = S) ->
Vars = [],
reltool_target:gen_script(Rel, Sys, PathFlag, Vars);
false ->
- {error, "No such release"}
+ {error, "No such release: " ++ RelName}
end,
reltool_utils:reply(ReplyTo, Ref, Reply),
?MODULE:loop(S);
@@ -302,7 +302,7 @@ loop(#state{common = C, sys = Sys} = S) ->
[M] ->
{ok, M};
[] ->
- {ok, missing_mod(ModName, ?MISSING_APP)}
+ {ok, missing_mod(ModName, ?MISSING_APP_NAME)}
end,
reltool_utils:reply(ReplyTo, Ref, Reply),
?MODULE:loop(S);
@@ -312,7 +312,8 @@ loop(#state{common = C, sys = Sys} = S) ->
{value, App} ->
{ok, App};
false ->
- {error, enoent}
+ {error, "No such application: " ++
+ atom_to_list(AppName)}
end,
reltool_utils:reply(ReplyTo, Ref, Reply),
?MODULE:loop(S);
@@ -327,6 +328,7 @@ loop(#state{common = C, sys = Sys} = S) ->
reltool_utils:reply(ReplyTo, Ref, {ok, App2, Warnings}),
?MODULE:loop(S3);
{error, Reason} ->
+ %% Keep old state
reltool_utils:reply(ReplyTo, Ref, {error, Reason}),
?MODULE:loop(S)
end;
@@ -372,16 +374,20 @@ loop(#state{common = C, sys = Sys} = S) ->
(Sys2#sys.lib_dirs =/= Sys#sys.lib_dirs) orelse
(Sys2#sys.escripts =/= Sys#sys.escripts),
{S3, Status} = refresh(S2, Force, {ok, []}),
- {S4, Status2} = analyse(S3#state{old_sys = S#state.sys}, Status),
- S6 =
- case Status2 of
- {ok, _Warnings} ->
- S4#state{status = Status2, old_status = S#state.status};
- {error, _} ->
- S
- end,
- reltool_utils:reply(ReplyTo, Ref, Status2),
- ?MODULE:loop(S6);
+ {S4, Status2} =
+ analyse(S3#state{old_sys = S#state.sys}, Status),
+ {S5, Status3} =
+ case Status2 of
+ {ok, _Warnings} -> % BUGBUG: handle warnings
+ {S4#state{status = Status2,
+ old_status = S#state.status},
+ Status2};
+ {error, _} ->
+ %% Keep old state
+ {S, Status2}
+ end,
+ reltool_utils:reply(ReplyTo, Ref, Status3),
+ ?MODULE:loop(S5);
{call, ReplyTo, Ref, get_status} ->
reltool_utils:reply(ReplyTo, Ref, S#state.status),
?MODULE:loop(S);
@@ -427,15 +433,24 @@ do_set_app(#state{sys = Sys} = S, App, Status) ->
Sys2 = Sys#sys{apps = Apps2, escripts = Escripts},
{S#state{sys = Sys2}, Status2}.
-analyse(#state{common = C, sys = #sys{apps = Apps0} = Sys} = S, Status) ->
- Apps = lists:keydelete(?MISSING_APP, #app.name, Apps0),
+analyse(#state{common = C,
+ sys = #sys{apps = Apps0, rels = Rels} = Sys} = S,
+ Status) ->
+ Apps = lists:keydelete(?MISSING_APP_NAME, #app.name, Apps0),
ets:delete_all_objects(C#common.app_tab),
ets:delete_all_objects(C#common.mod_tab),
ets:delete_all_objects(C#common.mod_used_by_tab),
- MissingApp = default_app(?MISSING_APP, "missing"),
+ MissingApp = default_app(?MISSING_APP_NAME, "missing"),
ets:insert(C#common.app_tab, MissingApp),
- Apps2 = lists:map(fun(App) -> app_init_is_included(C, Sys, App) end, Apps),
+ {RevRelApps, Status2} = apps_in_rels(Rels, Apps, Status),
+ RelApps2 = lists:reverse(RevRelApps),
+ {Apps2, Status3} =
+ lists:mapfoldl(fun(App, Acc) ->
+ app_init_is_included(C, Sys, App, RelApps2, Acc)
+ end,
+ Status2,
+ Apps),
Apps3 =
case app_propagate_is_included(C, Sys, Apps2, []) of
[] ->
@@ -452,17 +467,59 @@ analyse(#state{common = C, sys = #sys{apps = Apps0} = Sys} = S, Status) ->
app_propagate_is_used_by(C, Apps3),
Apps4 = read_apps(C, Sys, Apps3, []),
%% io:format("Missing app: ~p\n",
- %% [lists:keysearch(?MISSING_APP, #app.name, Apps4)]),
+ %% [lists:keysearch(?MISSING_APP_NAME, #app.name, Apps4)]),
Sys2 = Sys#sys{apps = Apps4},
- try
- Status2 = verify_config(Sys2, Status),
- {S#state{sys = Sys2}, Status2}
- catch
- throw:{error, Status3} ->
- {S, Status3}
+
+ case verify_config(RelApps2, Sys2, Status3) of
+ {ok, _Warnings} = Status4 ->
+ {S#state{sys = Sys2}, Status4};
+ {error, _} = Status4 ->
+ {S, Status4}
end.
-app_init_is_included(C, Sys, #app{mods = Mods} = A) ->
+apps_in_rels(Rels, Apps, Status) ->
+ lists:foldl(fun(Rel, {RelApps, S}) ->
+ {MoreRelApps, S2} = apps_in_rel(Rel, Apps, S),
+ {MoreRelApps ++ RelApps, S2}
+ end,
+ {[], Status},
+ Rels).
+
+apps_in_rel(#rel{name = RelName, rel_apps = RelApps}, Apps, Status) ->
+ Mandatory = [{RelName, kernel}, {RelName, stdlib}],
+ Other = [{RelName, AppName} ||
+ RA <- RelApps,
+ AppName <- [RA#rel_app.name | RA#rel_app.incl_apps],
+ not lists:keymember(AppName, 2, Mandatory)],
+ more_apps_in_rels(Mandatory ++ Other, Apps, [], Status).
+
+more_apps_in_rels([{RelName, AppName} = RA | RelApps], Apps, Acc, Status) ->
+ case lists:member(RA, Acc) of
+ true ->
+ more_apps_in_rels(RelApps, Apps, Acc, Status);
+ false ->
+ case lists:keysearch(AppName, #app.name, Apps) of
+ {value, #app{info = #app_info{applications = InfoApps}}} ->
+ Extra = [{RelName, N} || N <- InfoApps],
+ {Acc2, Status2} =
+ more_apps_in_rels(Extra, Apps, [RA | Acc], Status),
+ more_apps_in_rels(RelApps, Apps, Acc2, Status2);
+ false ->
+ Text = lists:concat(["Release ", RelName,
+ " uses non existing application ",
+ AppName]),
+ Status2 = reltool_utils:return_first_error(Status, Text),
+ more_apps_in_rels(RelApps, Apps, Acc, Status2)
+ end
+ end;
+more_apps_in_rels([], _Apps, Acc, Status) ->
+ {Acc, Status}.
+
+app_init_is_included(C,
+ Sys,
+ #app{name = AppName, mods = Mods} = A,
+ RelApps,
+ Status) ->
AppCond =
case A#app.incl_cond of
undefined -> Sys#sys.incl_cond;
@@ -473,24 +530,37 @@ app_init_is_included(C, Sys, #app{mods = Mods} = A) ->
undefined -> Sys#sys.mod_cond;
_ -> A#app.mod_cond
end,
- IsIncl =
- case AppCond of
- include -> true;
- exclude -> false;
- derived -> undefined
+ Rels = [RelName || {RelName, AN} <- RelApps, AN =:= AppName],
+ {Default, IsPreIncl, IsIncl, Status2} =
+ case {AppCond, Rels} of
+ {include, _} ->
+ {undefined, true, true, Status};
+ {exclude, []} ->
+ {undefined, false, false, Status};
+ {exclude, [RelName | _]} -> % App is included in at least one rel
+ Text = lists:concat(["Application ", AppName, " is used "
+ "in release ", RelName, " and cannot "
+ "be excluded"]),
+ TmpStatus = reltool_utils:return_first_error(Status, Text),
+ {undefined, false, false, TmpStatus};
+ {derived, []} ->
+ {undefined, undefined, undefined, Status};
+ {derived, [_ | _]} -> % App is included in at least one rel
+ {true, undefined, true, Status}
end,
- A2 = A#app{is_pre_included = IsIncl, is_included = IsIncl},
+ A2 = A#app{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,
- undefined)
+ Default)
end,
Mods),
- %%app_mod_init_is_included(C, AppName, Info, ModCond, AppCond),
- A2.
+ {A2, Status2}.
mod_init_is_included(C, M, ModCond, AppCond, Default) ->
%% print(M#mod.name, hipe, "incl_cond -> ~p\n", [AppCond]),
@@ -635,7 +705,7 @@ mod_mark_is_included(C, Sys, UsedByName, [ModName | ModNames], Acc) ->
Acc2)
end;
[] ->
- M = missing_mod(ModName, ?MISSING_APP),
+ M = missing_mod(ModName, ?MISSING_APP_NAME),
M2 = M#mod{is_included = true},
ets:insert(C#common.mod_tab, M2),
ets:insert(C#common.mod_used_by_tab, {UsedByName, ModName}),
@@ -646,7 +716,7 @@ mod_mark_is_included(_C, _Sys, _UsedByName, [], Acc) ->
Acc.
app_propagate_is_used_by(C, [#app{mods = Mods, name = Name} | Apps]) ->
- case Name =:= ?MISSING_APP of
+ case Name =:= ?MISSING_APP_NAME of
true -> ok;
false -> ok
end,
@@ -672,8 +742,6 @@ mod_propagate_is_used_by(_C, []) ->
read_apps(C, Sys, [#app{mods = Mods, is_included = IsIncl} = A | Apps], Acc) ->
{Mods2, IsIncl2} = read_apps(C, Sys, A, Mods, [], IsIncl),
- %% reltool_utils:print(A#app.name, stdlib, "Mods2: ~p\n",
- %% [[M#mod.status || M <- Mods2]]),
Status =
case lists:keysearch(missing, #mod.status, Mods2) of
{value, _} -> missing;
@@ -736,9 +804,7 @@ filter_app(A) ->
Mods = [M#mod{is_app_mod = undefined,
is_ebin_mod = undefined,
uses_mods = undefined,
- exists = false,
- is_pre_included = undefined,
- is_included = undefined} ||
+ exists = false} ||
M <- A#app.mods,
M#mod.incl_cond =/= undefined],
if
@@ -747,8 +813,7 @@ filter_app(A) ->
label = undefined,
info = undefined,
mods = [],
- uses_mods = undefined,
- is_included = undefined}};
+ uses_mods = undefined}};
Mods =:= [],
A#app.mod_cond =:= undefined,
A#app.incl_cond =:= undefined,
@@ -778,8 +843,7 @@ filter_app(A) ->
label = undefined,
info = undefined,
mods = Mods,
- uses_mods = undefined,
- is_included = undefined}}
+ uses_mods = undefined}}
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -816,16 +880,16 @@ refresh_app(#app{name = AppName,
end,
%% Add non-existing modules
+ AppInfoMods = AppInfo#app_info.modules,
AppModNames =
case AppInfo#app_info.mod of
{StartModName, _} ->
- case lists:member(StartModName,
- AppInfo#app_info.modules) of
- true -> AppInfo#app_info.modules;
- false -> [StartModName | AppInfo#app_info.modules]
+ case lists:member(StartModName, AppInfoMods) of
+ true -> AppInfoMods;
+ false -> [StartModName | AppInfoMods]
end;
undefined ->
- AppInfo#app_info.modules
+ AppInfoMods
end,
MissingMods = add_missing_mods(AppName, EbinMods, AppModNames),
@@ -862,11 +926,15 @@ read_app_info(AppFileOrBin, AppFile, AppName, DefaultVsn, Status) ->
parse_app_info(AppFile, Info, AI, Status);
{ok, _BadApp} ->
Text = lists:concat([AppName,
- ": Illegal contents in app file ", AppFile]),
+ ": Illegal contents in app file ", AppFile,
+ ", application tuple with arity 3 expected."]),
{missing_app_info(DefaultVsn),
reltool_utils:add_warning(Status, Text)};
- {error, Text} when Text =:= EnoentText->
- {missing_app_info(DefaultVsn), Status};
+ {error, Text} when Text =:= EnoentText ->
+ Text2 = lists:concat([AppName,
+ ": Missing app file ", AppFile, "."]),
+ {missing_app_info(DefaultVsn),
+ reltool_utils:add_warning(Status, Text2)};
{error, Text} ->
Text2 = lists:concat([AppName,
": Cannot parse app file ",
@@ -1045,7 +1113,7 @@ do_get_config(S, InclDef, InclDeriv) ->
false -> shrink_sys(S);
true -> S
end,
- {ok, reltool_target:gen_config(S2#state.sys, InclDef)}.
+ reltool_target:gen_config(S2#state.sys, InclDef).
do_save_config(S, Filename, InclDef, InclDeriv) ->
{ok, Config} = do_get_config(S, InclDef, InclDeriv),
@@ -1072,6 +1140,7 @@ do_load_config(S, SysConfig) ->
{ok, _Warnings2} ->
S3#state{status = Status3, old_status = S#state.status};
{error, _} ->
+ %% Keep old state
S
end,
{S4, Status3};
@@ -1093,29 +1162,36 @@ read_config(OldSys, Filename, Status) when is_list(Filename) ->
{error, Reason} ->
Text = file:format_error(Reason),
{OldSys,
- reltool_utils:return_first_error(Status, "File access: " ++
- Text)}
+ reltool_utils:return_first_error(Status,
+ "Illegal config file " ++
+ Filename ++ ": " ++ Text)}
end;
read_config(OldSys, {sys, KeyVals}, Status) ->
{NewSys, Status2} =
- try
- decode(OldSys#sys{apps = [], rels = []}, KeyVals, Status)
- catch
- throw:{error, Text} ->
- {OldSys, reltool_utils:return_first_error(Status, Text)}
- end,
- Apps = [A#app{mods = lists:sort(A#app.mods)} || A <- NewSys#sys.apps],
- case NewSys#sys.rels of
- [] -> Rels = reltool_utils:default_rels();
- Rels -> ok
- end,
- NewSys2 = NewSys#sys{apps = lists:sort(Apps), rels = lists:sort(Rels)},
- case lists:keysearch(NewSys2#sys.boot_rel, #rel.name, NewSys2#sys.rels) of
- {value, _} ->
- {NewSys2, Status2};
- false ->
- Text2 = "Missing rel: " ++ NewSys2#sys.boot_rel,
- {OldSys, reltool_utils:return_first_error(Status2, Text2)}
+ decode(OldSys#sys{apps = [], rels = []}, KeyVals, Status),
+ case Status2 of
+ {ok, _Warnings} -> % BUGBUG: handle warnings
+ Apps = [A#app{mods = lists:sort(A#app.mods)} ||
+ A <- NewSys#sys.apps],
+ case NewSys#sys.rels of
+ [] -> Rels = reltool_utils:default_rels();
+ Rels -> ok
+ end,
+ NewSys2 = NewSys#sys{apps = lists:sort(Apps),
+ rels = lists:sort(Rels)},
+ case lists:keysearch(NewSys2#sys.boot_rel,
+ #rel.name,
+ NewSys2#sys.rels) of
+ {value, _} ->
+ {NewSys2, Status2};
+ false ->
+ Text2 = lists:concat(["Release " ++ NewSys2#sys.boot_rel,
+ " is mandatory (used as boot_rel)"]),
+ {OldSys, reltool_utils:return_first_error(Status2, Text2)}
+ end;
+ {error, _} ->
+ %% Keep old state
+ {OldSys, Status2}
end;
read_config(OldSys, BadConfig, Status) ->
Text = lists:flatten(io_lib:format("~p", [BadConfig])),
@@ -1160,120 +1236,96 @@ decode(#sys{} = Sys, [{Key, Val} | KeyVals], Status) ->
{Sys#sys{root_dir = Val}, Status};
lib_dirs when is_list(Val) ->
{Sys#sys{lib_dirs = Val}, Status};
- mod_cond when Val =:= all; Val =:= app;
- Val =:= ebin; Val =:= derived;
+ mod_cond when Val =:= all;
+ Val =:= app;
+ Val =:= ebin;
+ Val =:= derived;
Val =:= none ->
{Sys#sys{mod_cond = Val}, Status};
- incl_cond when Val =:= include; Val =:= exclude;
+ incl_cond when Val =:= include;
+ Val =:= exclude;
Val =:= derived ->
{Sys#sys{incl_cond = Val}, Status};
boot_rel when is_list(Val) ->
{Sys#sys{boot_rel = Val}, Status};
emu_name when is_list(Val) ->
{Sys#sys{emu_name = Val}, Status};
- profile when Val =:= development ->
- Val = ?DEFAULT_PROFILE, % assert,
- {Sys#sys{profile = Val,
- incl_sys_filters =
- reltool_utils:decode_regexps(incl_sys_filters,
- ?DEFAULT_INCL_SYS_FILTERS,
- Sys#sys.incl_sys_filters),
- excl_sys_filters =
- reltool_utils:decode_regexps(excl_sys_filters,
- ?DEFAULT_EXCL_SYS_FILTERS,
- Sys#sys.excl_sys_filters),
- incl_app_filters =
- reltool_utils:decode_regexps(incl_app_filters,
- ?DEFAULT_INCL_APP_FILTERS,
- Sys#sys.incl_app_filters),
- excl_app_filters =
- reltool_utils:decode_regexps(excl_app_filters,
- ?DEFAULT_EXCL_APP_FILTERS,
- Sys#sys.excl_app_filters)},
- Status};
- profile when Val =:= embedded ->
- {Sys#sys{profile = Val,
- incl_sys_filters =
- reltool_utils:decode_regexps(incl_sys_filters,
- ?EMBEDDED_INCL_SYS_FILTERS,
- Sys#sys.incl_sys_filters),
- excl_sys_filters =
- reltool_utils:decode_regexps(excl_sys_filters,
- ?EMBEDDED_EXCL_SYS_FILTERS,
- Sys#sys.excl_sys_filters),
- incl_app_filters =
- reltool_utils:decode_regexps(incl_app_filters,
- ?EMBEDDED_INCL_APP_FILTERS,
- Sys#sys.incl_app_filters),
- excl_app_filters =
- reltool_utils:decode_regexps(excl_app_filters,
- ?EMBEDDED_EXCL_APP_FILTERS,
- Sys#sys.excl_app_filters)},
- Status};
- profile when Val =:= standalone ->
- {Sys#sys{profile = Val,
- incl_sys_filters =
- reltool_utils:decode_regexps(incl_sys_filters,
- ?STANDALONE_INCL_SYS_FILTERS,
- Sys#sys.incl_sys_filters),
- excl_sys_filters =
- reltool_utils:decode_regexps(excl_sys_filters,
- ?STANDALONE_EXCL_SYS_FILTERS,
- Sys#sys.excl_sys_filters),
- incl_app_filters =
- reltool_utils:decode_regexps(incl_app_filters,
- ?STANDALONE_INCL_APP_FILTERS,
- Sys#sys.incl_app_filters),
- excl_app_filters =
- reltool_utils:decode_regexps(excl_app_filters,
- ?STANDALONE_EXCL_APP_FILTERS,
- Sys#sys.excl_app_filters)},
+ profile when Val =:= development;
+ Val =:= embedded;
+ Val =:= standalone ->
+ InclSys = reltool_utils:choose_default(incl_sys_filters, Val, false),
+ ExclSys = reltool_utils:choose_default(excl_sys_filters, Val, false),
+ InclApp = reltool_utils:choose_default(incl_app_filters, Val, false),
+ ExclApp = reltool_utils:choose_default(excl_app_filters, Val, false),
+ AppType = reltool_utils:choose_default(embedded_app_type, Val, false),
+ {Sys#sys{profile = Val,
+ incl_sys_filters = dec_re(incl_sys_filters,
+ InclSys,
+ Sys#sys.incl_sys_filters),
+ excl_sys_filters = dec_re(excl_sys_filters,
+ ExclSys,
+ Sys#sys.excl_sys_filters),
+ incl_app_filters = dec_re(incl_app_filters,
+ InclApp,
+ Sys#sys.incl_app_filters),
+ excl_app_filters = dec_re(excl_app_filters,
+ ExclApp,
+ Sys#sys.excl_app_filters),
+ embedded_app_type = AppType},
Status};
incl_sys_filters ->
{Sys#sys{incl_sys_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- Sys#sys.incl_sys_filters)},
+ dec_re(Key,
+ Val,
+ Sys#sys.incl_sys_filters)},
Status};
excl_sys_filters ->
{Sys#sys{excl_sys_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- Sys#sys.excl_sys_filters)},
+ dec_re(Key,
+ Val,
+ Sys#sys.excl_sys_filters)},
Status};
incl_app_filters ->
{Sys#sys{incl_app_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- Sys#sys.incl_app_filters)},
+ dec_re(Key,
+ Val,
+ Sys#sys.incl_app_filters)},
Status};
excl_app_filters ->
{Sys#sys{excl_app_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- Sys#sys.excl_app_filters)},
+ dec_re(Key,
+ Val,
+ Sys#sys.excl_app_filters)},
Status};
incl_archive_filters ->
{Sys#sys{incl_archive_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- Sys#sys.incl_archive_filters)},
+ dec_re(Key,
+ Val,
+ Sys#sys.incl_archive_filters)},
Status};
excl_archive_filters ->
{Sys#sys{excl_archive_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- Sys#sys.excl_archive_filters)},
+ dec_re(Key,
+ Val,
+ Sys#sys.excl_archive_filters)},
Status};
archive_opts when is_list(Val) ->
{Sys#sys{archive_opts = Val}, Status};
relocatable when Val =:= true; Val =:= false ->
{Sys#sys{relocatable = Val}, Status};
- app_type when Val =:= permanent;
- Val =:= transient;
- Val =:= temporary;
- Val =:= load; Val =:= none ->
- {Sys#sys{app_type = Val}, Status};
+ rel_app_type when Val =:= permanent;
+ Val =:= transient;
+ Val =:= temporary;
+ Val =:= load;
+ Val =:= none ->
+ {Sys#sys{rel_app_type = Val}, Status};
+ embedded_app_type when Val =:= permanent;
+ Val =:= transient;
+ Val =:= temporary;
+ Val =:= load;
+ Val =:= none;
+ Val =:= undefined ->
+ {Sys#sys{embedded_app_type = Val}, Status};
app_file when Val =:= keep; Val =:= strip, Val =:= all ->
{Sys#sys{app_file = Val}, Status};
debug_info when Val =:= keep; Val =:= strip ->
@@ -1303,38 +1355,39 @@ decode(#app{} = App, [{Key, Val} | KeyVals], Status) ->
Val =:= strip ->
{App#app{debug_info = Val}, Status};
app_file when Val =:= keep;
- Val =:= strip,
+ Val =:= strip;
Val =:= all ->
{App#app{app_file = Val}, Status};
app_type when Val =:= permanent;
Val =:= transient;
Val =:= temporary;
Val =:= load;
- Val =:= none ->
+ Val =:= none;
+ Val =:= undefined ->
{App#app{app_type = Val}, Status};
incl_app_filters ->
{App#app{incl_app_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- App#app.incl_app_filters)},
+ dec_re(Key,
+ Val,
+ App#app.incl_app_filters)},
Status};
excl_app_filters ->
{App#app{excl_app_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- App#app.excl_app_filters)},
+ dec_re(Key,
+ Val,
+ App#app.excl_app_filters)},
Status};
incl_archive_filters ->
{App#app{incl_archive_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- App#app.incl_archive_filters)},
+ dec_re(Key,
+ Val,
+ App#app.incl_archive_filters)},
Status};
excl_archive_filters ->
{App#app{excl_archive_filters =
- reltool_utils:decode_regexps(Key,
- Val,
- App#app.excl_archive_filters)},
+ dec_re(Key,
+ Val,
+ App#app.excl_archive_filters)},
Status};
archive_opts when is_list(Val) ->
{App#app{archive_opts = Val}, Status};
@@ -1439,54 +1492,53 @@ merge_config(OldSys, NewSys, Force, Status) ->
apps = PatchedApps},
{NewSys2, Status5}.
-verify_config(Sys, Status) ->
- case lists:keymember(Sys#sys.boot_rel, #rel.name, Sys#sys.rels) of
+verify_config(RelApps, #sys{boot_rel = BootRel, rels = Rels, apps = Apps}, Status) ->
+ case lists:keymember(BootRel, #rel.name, Rels) of
true ->
- lists:foreach(fun(Rel)-> check_rel(Rel, Sys, Status) end,
- Sys#sys.rels),
- Status;
+ Status2 = lists:foldl(fun(RA, Acc) ->
+ check_app(RA, Apps, Acc) end,
+ Status,
+ RelApps),
+ lists:foldl(fun(#rel{name = RelName}, Acc)->
+ check_rel(RelName, RelApps, Acc)
+ end,
+ Status2,
+ Rels);
false ->
- Text = lists:concat([Sys#sys.boot_rel, ": release is mandatory"]),
- Status2 = reltool_utils:return_first_error(Status, Text),
- throw({error, Status2})
+ Text = lists:concat(["Release ", BootRel,
+ " is mandatory (used as boot_rel)"]),
+ reltool_utils:return_first_error(Status, Text)
+ end.
+
+check_app({RelName, AppName}, Apps, Status) ->
+ case lists:keysearch(AppName, #app.name, Apps) of
+ {value, App} when App#app.is_pre_included ->
+ Status;
+ {value, App} when App#app.is_included ->
+ Status;
+ _ ->
+ Text = lists:concat(["Release ", RelName,
+ " uses non included application ",
+ AppName]),
+ reltool_utils:return_first_error(Status, Text)
end.
-check_rel(#rel{name = RelName, rel_apps = RelApps},
- #sys{apps = Apps},
- Status) ->
+check_rel(RelName, RelApps, Status) ->
EnsureApp =
- fun(AppName) ->
- case lists:keymember(AppName, #rel_app.name, RelApps) of
+ fun(AppName, Acc) ->
+ case lists:member({RelName, AppName}, RelApps) of
true ->
- ok;
+ Acc;
false ->
- Text = lists:concat([RelName, ": ", AppName,
- " is not included."]),
- Status2 =
- reltool_utils:return_first_error(Status, Text),
- throw({error, Status2})
- end
- end,
- EnsureApp(kernel),
- EnsureApp(stdlib),
- CheckRelApp =
- fun(#rel_app{name = AppName}) ->
- case lists:keysearch(AppName, #app.name, Apps) of
- {value, App} when App#app.is_pre_included ->
- ok;
- {value, App} when App#app.is_included ->
- ok;
- _ ->
- Text =
- lists:concat([RelName, ": uses application ",
- AppName, " that not is included."]),
- Status2 =
- reltool_utils:return_first_error(Status, Text),
- %% throw BUGBUG: add throw
- ({error, Status2})
+ Text = lists:concat(["Mandatory application ",
+ AppName,
+ " is not included in release ",
+ RelName]),
+ reltool_utils:return_first_error(Acc, Text)
end
end,
- lists:foreach(CheckRelApp, RelApps).
+ Mandatory = [kernel, stdlib],
+ lists:foldl(EnsureApp, Status, Mandatory).
patch_erts_version(RootDir, Apps, Status) ->
AppName = erts,
@@ -1507,7 +1559,7 @@ patch_erts_version(RootDir, Apps, Status) ->
{Apps, Status}
end;
false ->
- Text = "erts cannnot be found in the root directory " ++ RootDir,
+ Text = "erts cannot be found in the root directory " ++ RootDir,
Status2 = reltool_utils:return_first_error(Status, Text),
{Apps, Status2}
end.
@@ -1813,7 +1865,8 @@ default_app(Name) ->
status = missing,
uses_mods = undefined,
is_pre_included = undefined,
- is_included = undefined}.
+ is_included = undefined,
+ rels = undefined}.
%% Assume that the application are sorted
refresh_apps([Old | OldApps], [New | NewApps], Acc, Force, Status)
@@ -1842,7 +1895,7 @@ refresh_apps([Old | OldApps], [New | NewApps], Acc, Force, Status)
when New#app.name > Old#app.name ->
%% No new version. Remove the old.
Status2 =
- case Old#app.name =:= ?MISSING_APP of
+ case Old#app.name =:= ?MISSING_APP_NAME of
true ->
Status;
false ->
@@ -1860,7 +1913,7 @@ refresh_apps([], [New | NewApps], Acc, Force, Status) ->
refresh_apps([Old | OldApps], [], Acc, Force, Status) ->
%% No new version. Remove the old.
Status2 =
- case Old#app.name =:= ?MISSING_APP of
+ case Old#app.name =:= ?MISSING_APP_NAME of
true ->
Status;
false ->
diff --git a/lib/reltool/src/reltool_sys_win.erl b/lib/reltool/src/reltool_sys_win.erl
index 2e226d9147..dbb8e32aa2 100644
--- a/lib/reltool/src/reltool_sys_win.erl
+++ b/lib/reltool/src/reltool_sys_win.erl
@@ -1227,7 +1227,7 @@ create_fgraph_window(S, Title, Nodes, Links) ->
Panel = wxPanel:new(Frame, []),
Options = [{size, {lists:max([100, ?WIN_WIDTH - 100]), ?WIN_HEIGHT}}],
{Server, Fgraph} = reltool_fgraph_win:new(Panel, Options),
- Choose = fun(?MISSING_APP) -> alternate;
+ Choose = fun(?MISSING_APP_NAME) -> alternate;
(_) -> default
end,
[reltool_fgraph_win:add_node(Server, N, Choose(N)) || N <- Nodes],
diff --git a/lib/reltool/src/reltool_target.erl b/lib/reltool/src/reltool_target.erl
index e079a02f3c..dd6f75b9fc 100644
--- a/lib/reltool/src/reltool_target.erl
+++ b/lib/reltool/src/reltool_target.erl
@@ -31,7 +31,7 @@
gen_target/2,
install/2
]).
--compile(export_all).
+
-include("reltool.hrl").
-include_lib("kernel/include/file.hrl").
@@ -64,54 +64,60 @@ kernel_processes(KernelApp) ->
%% Generate the contents of a config file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-gen_config(#sys{root_dir = RootDir,
- lib_dirs = LibDirs,
- mod_cond = ModCond,
- incl_cond = AppCond,
- apps = Apps,
- boot_rel = BootRel,
- rels = Rels,
- emu_name = EmuName,
- profile = Profile,
- incl_sys_filters = InclSysFiles,
- excl_sys_filters = ExclSysFiles,
- incl_app_filters = InclAppFiles,
- excl_app_filters = ExclAppFiles,
- incl_archive_filters = InclArchiveDirs,
- excl_archive_filters = ExclArchiveDirs,
- archive_opts = ArchiveOpts,
- relocatable = Relocatable,
- app_type = AppType,
- app_file = AppFile,
- debug_info = DebugInfo},
- InclDefs) ->
+gen_config(Sys, InclDefs) ->
+ {ok, do_gen_config(Sys, InclDefs)}.
+
+do_gen_config(#sys{root_dir = RootDir,
+ lib_dirs = LibDirs,
+ mod_cond = ModCond,
+ incl_cond = AppCond,
+ apps = Apps,
+ boot_rel = BootRel,
+ rels = Rels,
+ emu_name = EmuName,
+ profile = Profile,
+ incl_sys_filters = InclSysFiles,
+ excl_sys_filters = ExclSysFiles,
+ incl_app_filters = InclAppFiles,
+ excl_app_filters = ExclAppFiles,
+ incl_archive_filters = InclArchiveDirs,
+ excl_archive_filters = ExclArchiveDirs,
+ archive_opts = ArchiveOpts,
+ relocatable = Relocatable,
+ rel_app_type = RelAppType,
+ embedded_app_type = InclAppType,
+ app_file = AppFile,
+ debug_info = DebugInfo},
+ InclDefs) ->
ErtsItems =
case lists:keysearch(erts, #app.name, Apps) of
{value, Erts} ->
- [{erts, gen_config(Erts, InclDefs)}];
+ [{erts, do_gen_config(Erts, InclDefs)}];
false ->
[]
end,
AppsItems =
- [{app, A#app.name, gen_config(A, InclDefs)}
+ [do_gen_config(A, InclDefs)
|| A <- Apps,
- A#app.name =/= ?MISSING_APP,
+ A#app.name =/= ?MISSING_APP_NAME,
A#app.name =/= erts,
- A#app.is_included =:= true,
- A#app.is_escript =/= true],
+ not A#app.is_escript],
EscriptItems = [{escript,
A#app.active_dir,
emit(incl_cond, A#app.incl_cond, undefined, InclDefs)}
- || A <- Apps, A#app.is_escript],
+ || A <- Apps, A#app.is_escript],
DefaultRels = reltool_utils:default_rels(),
RelsItems =
- case {[{rel, R#rel.name, R#rel.vsn, gen_config(R, InclDefs)} ||
- R <- Rels],
- [{rel, R#rel.name, R#rel.vsn, gen_config(R, InclDefs)} ||
- R <- DefaultRels]} of
- {RI, RI} -> [];
- {RI, _} -> RI
- end,
+ [{rel, R#rel.name, R#rel.vsn, do_gen_config(R, InclDefs)} ||
+ R <- Rels],
+ DefaultRelsItems =
+ [{rel, R#rel.name, R#rel.vsn, do_gen_config(R, InclDefs)} ||
+ R <- DefaultRels],
+ RelsItems2 =
+ case InclDefs of
+ true -> RelsItems;
+ false -> RelsItems -- DefaultRelsItems
+ end,
X = fun(List) -> [Re || #regexp{source = Re} <- List] end,
{sys,
emit(root_dir, RootDir, code:root_dir(), InclDefs) ++
@@ -120,78 +126,103 @@ gen_config(#sys{root_dir = RootDir,
emit(mod_cond, ModCond, ?DEFAULT_MOD_COND, InclDefs) ++
emit(incl_cond, AppCond, ?DEFAULT_INCL_COND, InclDefs) ++
ErtsItems ++
- AppsItems ++
+ lists:flatten(AppsItems) ++
emit(boot_rel, BootRel, ?DEFAULT_REL_NAME, InclDefs) ++
- RelsItems ++
+ RelsItems2 ++
emit(emu_name, EmuName, ?DEFAULT_EMU_NAME, InclDefs) ++
emit(relocatable, Relocatable, ?DEFAULT_RELOCATABLE, InclDefs) ++
emit(profile, Profile, ?DEFAULT_PROFILE, InclDefs) ++
- emit(incl_sys_filters, X(InclSysFiles), ?DEFAULT_INCL_SYS_FILTERS, InclDefs) ++
- emit(excl_sys_filters, X(ExclSysFiles), ?DEFAULT_EXCL_SYS_FILTERS, InclDefs) ++
- emit(incl_app_filters, X(InclAppFiles), ?DEFAULT_INCL_APP_FILTERS, InclDefs) ++
- emit(excl_app_filters, X(ExclAppFiles), ?DEFAULT_EXCL_APP_FILTERS, InclDefs) ++
+ emit(incl_sys_filters, X(InclSysFiles), reltool_utils:choose_default(incl_sys_filters, Profile, InclDefs), InclDefs) ++
+ emit(excl_sys_filters, X(ExclSysFiles), reltool_utils:choose_default(excl_sys_filters, Profile, InclDefs), InclDefs) ++
+ emit(incl_app_filters, X(InclAppFiles), reltool_utils:choose_default(incl_app_filters, Profile, InclDefs), InclDefs) ++
+ emit(excl_app_filters, X(ExclAppFiles), reltool_utils:choose_default(excl_app_filters, Profile, InclDefs), InclDefs) ++
emit(incl_archive_filters, X(InclArchiveDirs), ?DEFAULT_INCL_ARCHIVE_FILTERS, InclDefs) ++
emit(excl_archive_filters, X(ExclArchiveDirs), ?DEFAULT_EXCL_ARCHIVE_FILTERS, InclDefs) ++
emit(archive_opts, ArchiveOpts, ?DEFAULT_ARCHIVE_OPTS, InclDefs) ++
- emit(app_type, AppType, ?DEFAULT_APP_TYPE, InclDefs) ++
+ emit(rel_app_type, RelAppType, ?DEFAULT_REL_APP_TYPE, InclDefs) ++
+ emit(embedded_app_type, InclAppType, reltool_utils:choose_default(embedded_app_type, Profile, InclDefs), InclDefs) ++
emit(app_file, AppFile, ?DEFAULT_APP_FILE, InclDefs) ++
emit(debug_info, DebugInfo, ?DEFAULT_DEBUG_INFO, InclDefs)};
-gen_config(#app{name = _Name,
- mod_cond = ModCond,
- incl_cond = AppCond,
- debug_info = DebugInfo,
- app_file = AppFile,
- incl_app_filters = InclAppFiles,
- excl_app_filters = ExclAppFiles,
- incl_archive_filters = InclArchiveDirs,
- excl_archive_filters = ExclArchiveDirs,
- archive_opts = ArchiveOpts,
- use_selected_vsn = UseSelected,
- vsn = Vsn,
- mods = Mods},
- InclDefs) ->
- emit(mod_cond, ModCond, undefined, InclDefs) ++
- emit(incl_cond, AppCond, undefined, InclDefs) ++
- emit(debug_info, DebugInfo, undefined, InclDefs) ++
- emit(app_file, AppFile, undefined, InclDefs) ++
- emit(incl_app_filters, InclAppFiles, undefined, InclDefs) ++
- emit(excl_app_filters, ExclAppFiles, undefined, InclDefs) ++
- emit(incl_archive_filters, InclArchiveDirs, undefined, InclDefs) ++
- emit(excl_archive_filters, ExclArchiveDirs, undefined, InclDefs) ++
- emit(archive_opts, ArchiveOpts, undefined, InclDefs) ++
- emit(vsn, Vsn, undefined, InclDefs orelse UseSelected =/= true) ++
- [{mod, M#mod.name, gen_config(M, InclDefs)} ||
- M <- Mods,
- M#mod.is_included =:= true];
-gen_config(#mod{name = _Name,
- incl_cond = AppCond,
- debug_info = DebugInfo},
- InclDefs) ->
- emit(incl_cond, AppCond, undefined, InclDefs) ++
- emit(debug_info, DebugInfo, undefined, InclDefs);
-gen_config(#rel{name = _Name,
- vsn = _Vsn,
- rel_apps = RelApps},
- InclDefs) ->
- [gen_config(RA, InclDefs) || RA <- RelApps];
-gen_config(#rel_app{name = Name,
- app_type = Type,
- incl_apps = InclApps},
- _InclDefs) ->
+do_gen_config(#app{name = Name,
+ mod_cond = ModCond,
+ incl_cond = AppCond,
+ debug_info = DebugInfo,
+ app_file = AppFile,
+ incl_app_filters = InclAppFiles,
+ excl_app_filters = ExclAppFiles,
+ incl_archive_filters = InclArchiveDirs,
+ excl_archive_filters = ExclArchiveDirs,
+ archive_opts = ArchiveOpts,
+ use_selected_vsn = UseSelected,
+ vsn = Vsn,
+ mods = Mods,
+ is_included = IsIncl},
+ InclDefs) ->
+ AppConfig =
+ [
+ emit(mod_cond, ModCond, undefined, InclDefs),
+ emit(incl_cond, AppCond, undefined, InclDefs),
+ emit(debug_info, DebugInfo, undefined, InclDefs),
+ emit(app_file, AppFile, undefined, InclDefs),
+ emit(incl_app_filters, InclAppFiles, undefined, InclDefs),
+ emit(excl_app_filters, ExclAppFiles, undefined, InclDefs),
+ emit(incl_archive_filters, InclArchiveDirs, undefined, InclDefs),
+ emit(excl_archive_filters, ExclArchiveDirs, undefined, InclDefs),
+ emit(archive_opts, ArchiveOpts, undefined, InclDefs),
+ if
+ IsIncl, InclDefs -> [{vsn, Vsn}];
+ UseSelected -> [{vsn, Vsn}];
+ true -> []
+ end,
+ [do_gen_config(M, InclDefs) || M <- Mods]
+ ],
+ case lists:flatten(AppConfig) of
+ FlatAppConfig when FlatAppConfig =/= []; IsIncl ->
+ [{app, Name, FlatAppConfig}];
+ [] ->
+ []
+ end;
+do_gen_config(#mod{name = Name,
+ incl_cond = AppCond,
+ debug_info = DebugInfo,
+ is_included = IsIncl},
+ InclDefs) ->
+ ModConfig =
+ [
+ emit(incl_cond, AppCond, undefined, InclDefs),
+ emit(debug_info, DebugInfo, undefined, InclDefs)
+ ],
+ case lists:flatten(ModConfig) of
+ FlatModConfig when FlatModConfig =/= []; IsIncl ->
+ [{mod, Name, FlatModConfig}];
+ _ ->
+ []
+ end;
+do_gen_config(#rel{name = _Name,
+ vsn = _Vsn,
+ rel_apps = RelApps},
+ InclDefs) ->
+ [do_gen_config(RA, InclDefs) || RA <- RelApps];
+do_gen_config(#rel_app{name = Name,
+ app_type = Type,
+ incl_apps = InclApps},
+ _InclDefs) ->
case {Type, InclApps} of
{undefined, []} -> Name;
{undefined, _} -> {Name, InclApps};
{_, []} -> {Name, Type};
{_, _} -> {Name, Type, InclApps}
end;
-gen_config({Tag, Val}, InclDefs) ->
+do_gen_config({Tag, Val}, InclDefs) ->
emit(Tag, Val, undefined, InclDefs);
-gen_config([], _InclDefs) ->
+do_gen_config([], _InclDefs) ->
[];
-gen_config([H | T], InclDefs) ->
- lists:flatten([gen_config(H, InclDefs), gen_config(T, InclDefs)]).
+do_gen_config([H | T], InclDefs) ->
+ lists:flatten([do_gen_config(H, InclDefs), do_gen_config(T, InclDefs)]).
emit(Tag, Val, Default, InclDefs) ->
+ %% io:format("~p(~p):\n\t~p\n\t~p\n",
+ %% [Tag, Val =/= Default, Val, Default]),
if
Val == undefined -> [];
InclDefs -> [{Tag, Val}];
@@ -239,24 +270,127 @@ gen_app(#app{name = Name,
%% Generate the contents of a rel file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-gen_rel(#rel{name = RelName, vsn = RelVsn, rel_apps = RelApps},
- #sys{apps = Apps}) ->
- {value, Erts} = lists:keysearch(erts, #app.name, Apps),
- {release,
- {RelName, RelVsn},
- {erts, Erts#app.vsn},
- [app_to_rel(RA, Apps ) || RA <- RelApps]}.
-
-app_to_rel(#rel_app{name = Name, app_type = Type, incl_apps = InclApps},
- Apps) ->
- {value, #app{vsn = Vsn}} = lists:keysearch(Name, #app.name, Apps),
+gen_rel(Rel, Sys) ->
+ try
+ MergedApps = merge_apps(Rel, Sys),
+ {ok, do_gen_rel(Rel, Sys, MergedApps)}
+ catch
+ throw:{error, Text} ->
+ {error, Text}
+ end.
+
+do_gen_rel(#rel{name = RelName, vsn = RelVsn},
+ #sys{apps = Apps},
+ MergedApps) ->
+ ErtsName = erts,
+ case lists:keysearch(ErtsName, #app.name, Apps) of
+ {value, Erts} ->
+ {release,
+ {RelName, RelVsn},
+ {ErtsName, Erts#app.vsn},
+ [strip_rel_info(App) || App <- MergedApps]};
+ false ->
+ reltool_utils:throw_error("Mandatory application ~p is "
+ "not included",
+ [ErtsName])
+ end.
+
+strip_rel_info(#app{name = Name,
+ vsn = Vsn,
+ app_type = Type,
+ info = #app_info{incl_apps = InclApps}})
+ when Type =/= undefined ->
case {Type, InclApps} of
- {undefined, []} -> {Name, Vsn};
- {undefined, _} -> {Name, Vsn, InclApps};
+ {permanent, []} -> {Name, Vsn};
+ {permanent, _} -> {Name, Vsn, InclApps};
{_, []} -> {Name, Vsn, Type};
{_, _} -> {Name, Vsn, Type, InclApps}
end.
+merge_apps(#rel{name = RelName,
+ rel_apps = RelApps},
+ #sys{apps = Apps,
+ rel_app_type = RelAppType,
+ embedded_app_type = EmbAppType}) ->
+ Mandatory = [kernel, stdlib],
+ MergedApps = do_merge_apps(RelName, Mandatory, Apps, permanent, []),
+ MergedApps2 = do_merge_apps(RelName, RelApps, Apps, RelAppType, MergedApps),
+ Embedded =
+ [A#app.name || A <- Apps,
+ EmbAppType =/= undefined,
+ A#app.is_included,
+ A#app.name =/= erts,
+ A#app.name =/= ?MISSING_APP_NAME,
+ not lists:keymember(A#app.name, #app.name, MergedApps2)],
+ MergedApps3 = do_merge_apps(RelName, Embedded, Apps, EmbAppType, MergedApps2),
+ sort_apps(MergedApps3).
+
+do_merge_apps(RelName, [#rel_app{name = Name} = RA | RelApps], Apps, RelAppType, Acc) ->
+ case is_already_merged(Name, RelApps, Acc) of
+ true ->
+ do_merge_apps(RelName, RelApps, Apps, RelAppType, Acc);
+ false ->
+ {value, App} = lists:keysearch(Name, #app.name, Apps),
+ MergedApp = merge_app(RelName, RA, RelAppType, App),
+ MoreNames = (MergedApp#app.info)#app_info.applications,
+ Acc2 = [MergedApp | Acc],
+ do_merge_apps(RelName, MoreNames ++ RelApps, Apps, RelAppType, Acc2)
+ end;
+do_merge_apps(RelName, [Name | RelApps], Apps, RelAppType, Acc) ->
+ case is_already_merged(Name, RelApps, Acc) of
+ true ->
+ do_merge_apps(RelName, RelApps, Apps, RelAppType, Acc);
+ false ->
+ RelApp = init_rel_app(Name, Apps),
+ do_merge_apps(RelName, [RelApp | RelApps], Apps, RelAppType, Acc)
+ end;
+do_merge_apps(_RelName, [], _Apps, _RelAppType, Acc) ->
+ lists:reverse(Acc).
+
+init_rel_app(Name, Apps) ->
+ {value, App} = lists:keysearch(Name, #app.name, Apps),
+ Info = App#app.info,
+ #rel_app{name = Name,
+ app_type = undefined,
+ incl_apps = Info#app_info.incl_apps}.
+
+merge_app(RelName,
+ #rel_app{name = Name,
+ app_type = Type,
+ incl_apps = InclApps},
+ RelAppType,
+ App) ->
+ Type2 =
+ case {Type, App#app.app_type} of
+ {undefined, undefined} -> RelAppType;
+ {undefined, AppAppType} -> AppAppType;
+ {_, _} -> Type
+ end,
+ Info = App#app.info,
+ case InclApps -- Info#app_info.incl_apps of
+ [] ->
+ App#app{app_type = Type2, info = Info#app_info{incl_apps = InclApps}};
+ BadIncl ->
+ reltool_utils:throw_error("~p: These applications are "
+ "used by release ~s but are "
+ "missing as included_applications "
+ "in the app file: ~p",
+ [Name, RelName, BadIncl])
+ end.
+
+is_already_merged(Name, [Name | _], _MergedApps) ->
+ true;
+is_already_merged(Name, [#rel_app{name = Name} | _], _MergedApps) ->
+ true;
+is_already_merged(Name, [_ | RelApps], MergedApps) ->
+ is_already_merged(Name, RelApps, MergedApps);
+is_already_merged(Name, [], [#app{name = Name} | _MergedApps]) ->
+ true;
+is_already_merged(Name, [] = RelApps, [_ | MergedApps]) ->
+ is_already_merged(Name, RelApps, MergedApps);
+is_already_merged(_Name, [], []) ->
+ false.
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Generate the contents of a boot file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -270,27 +404,24 @@ gen_boot({script, {_, _}, _} = Script) ->
gen_script(Rel, Sys, PathFlag, Variables) ->
try
- do_gen_script(Rel, Sys, PathFlag, Variables)
+ MergedApps = merge_apps(Rel, Sys),
+ do_gen_script(Rel, Sys, MergedApps, PathFlag, Variables)
catch
throw:{error, Text} ->
{error, Text}
end.
-do_gen_script(#rel{name = RelName, vsn = RelVsn, rel_apps = RelApps},
- #sys{apps = Apps, app_type = DefaultType},
+do_gen_script(#rel{name = RelName, vsn = RelVsn},
+ #sys{apps = Apps},
+ MergedApps,
PathFlag,
Variables) ->
{value, Erts} = lists:keysearch(erts, #app.name, Apps),
Preloaded = [Mod#mod.name || Mod <- Erts#app.mods],
Mandatory = mandatory_modules(),
Early = Mandatory ++ Preloaded,
- MergedApps = [merge_app(RA, Apps, DefaultType) || RA <- RelApps],
- SortedApps = sort_apps(MergedApps),
- {value, KernelApp} = lists:keysearch(kernel, #app.name, SortedApps),
-
- InclApps =
- lists:append([I ||
- #app{info = #app_info{incl_apps = I}} <- SortedApps]),
+ {value, KernelApp} = lists:keysearch(kernel, #app.name, MergedApps),
+ InclApps = [I || #app{info = #app_info{incl_apps = I}} <- MergedApps],
%% Create the script
DeepList =
@@ -300,30 +431,30 @@ do_gen_script(#rel{name = RelName, vsn = RelVsn, rel_apps = RelApps},
{progress, preloaded},
%% Load mandatory modules
- {path, create_mandatory_path(SortedApps, PathFlag, Variables)},
+ {path, create_mandatory_path(MergedApps, PathFlag, Variables)},
{primLoad, lists:sort(Mandatory)},
{kernel_load_completed},
{progress, kernel_load_completed},
%% Load remaining modules
- [load_app_mods(A, Early, PathFlag, Variables) || A <- SortedApps],
+ [load_app_mods(A, Early, PathFlag, Variables) || A <- MergedApps],
{progress, modules_loaded},
%% Start kernel processes
- {path, create_path(SortedApps, PathFlag, Variables)},
+ {path, create_path(MergedApps, PathFlag, Variables)},
kernel_processes(gen_app(KernelApp)),
{progress, init_kernel_started},
%% Load applications
[{apply, {application, load, [gen_app(A)]}} ||
- A = #app{name = Name, app_type = Type} <- SortedApps,
+ A = #app{name = Name, app_type = Type} <- MergedApps,
Name =/= kernel,
Type =/= none],
{progress, applications_loaded},
%% Start applications
[{apply, {application, start_boot, [Name, Type]}} ||
- #app{name = Name, app_type = Type} <- SortedApps,
+ #app{name = Name, app_type = Type} <- MergedApps,
Type =/= none,
Type =/= load,
not lists:member(Name, InclApps)],
@@ -334,28 +465,6 @@ do_gen_script(#rel{name = RelName, vsn = RelVsn, rel_apps = RelApps},
],
{ok, {script, {RelName, RelVsn}, lists:flatten(DeepList)}}.
-merge_app(#rel_app{name = Name, app_type = Type, incl_apps = RelIncl},
- Apps,
- DefaultType) ->
- {value, App} = lists:keysearch(Name, #app.name, Apps),
- Type2 =
- case {Type, App#app.app_type} of
- {undefined, undefined} -> DefaultType;
- {undefined, AppType} -> AppType;
- {_, _} -> Type
- end,
- Info = App#app.info,
- case RelIncl -- Info#app_info.incl_apps of
- [] ->
- App#app{app_type = Type2,
- info = Info#app_info{incl_apps = RelIncl}};
- BadIncl ->
- reltool_utils:throw_error("~p: These applications are "
- "missing as included_applications "
- "in the app file: ~p\n",
- [Name, BadIncl])
- end.
-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load_app_mods(#app{mods = Mods} = App, Mand, PathFlag, Variables) ->
@@ -438,13 +547,13 @@ sort_apps([], [], [], _) ->
[];
sort_apps([], Missing, [], _) ->
%% this has already been checked before, but as we have the info...
- reltool_utils:throw_error("Undefined applications: ~p\n",
+ reltool_utils:throw_error("Undefined applications: ~p",
[make_set(Missing)]);
sort_apps([], [], Circular, _) ->
- reltool_utils:throw_error("Circular dependencies: ~p\n",
+ reltool_utils:throw_error("Circular dependencies: ~p",
[make_set(Circular)]);
sort_apps([], Missing, Circular, _) ->
- reltool_utils:throw_error("Circular dependencies: ~p\n"
+ reltool_utils:throw_error("Circular dependencies: ~p"
"Undefined applications: ~p\n",
[make_set(Circular), make_set(Missing)]).
@@ -603,14 +712,15 @@ gen_rel_files(Sys, TargetDir) ->
spec_rel_files(#sys{rels = Rels} = Sys) ->
lists:append([do_spec_rel_files(R, Sys) || R <- Rels]).
-do_spec_rel_files(#rel{name = Name} = Rel, Sys) ->
- RelFile = Name ++ ".rel",
- ScriptFile = Name ++ ".script",
- BootFile = Name ++ ".boot",
- GenRel = gen_rel(Rel, Sys),
+do_spec_rel_files(#rel{name = RelName} = Rel, Sys) ->
+ RelFile = RelName ++ ".rel",
+ ScriptFile = RelName ++ ".script",
+ BootFile = RelName ++ ".boot",
+ MergedApps = merge_apps(Rel, Sys),
+ GenRel = do_gen_rel(Rel, Sys, MergedApps),
PathFlag = true,
Variables = [],
- {ok, Script} = do_gen_script(Rel, Sys, PathFlag, Variables),
+ {ok, Script} = do_gen_script(Rel, Sys, MergedApps, PathFlag, Variables),
{ok, BootBin} = gen_boot(Script),
Date = date(),
Time = time(),
@@ -665,8 +775,6 @@ do_gen_spec(#sys{root_dir = RootDir,
{create_dir,BootVsn, RelFiles}]},
{create_dir, "bin", BinFiles}
] ++ SysFiles2,
- %% io:format("InclRegexps2: ~p\n", [InclRegexps2]),
- %% io:format("ExclRegexps2: ~p\n", [ExclRegexps2]),
SysFiles4 = filter_spec(SysFiles3, InclRegexps2, ExclRegexps2),
SysFiles5 = SysFiles4 ++ [{create_dir, "lib", LibFiles}],
check_sys(["bin", "erts", "lib"], SysFiles5),
@@ -678,23 +786,25 @@ strip_sys_files(Relocatable, SysFiles, Apps, ExclRegexps) ->
true ->
ExtraExcl = ["^erts.*/bin/.*src\$"],
reltool_utils:decode_regexps(excl_sys_filters,
- {add, ExtraExcl}, ExclRegexps);
+ {add, ExtraExcl},
+ ExclRegexps);
false ->
ExclRegexps
end,
{value, Erts} = lists:keysearch(erts, #app.name, Apps),
FilterErts =
fun(Spec) ->
- File = element(2, Spec),
- case lists:prefix("erts", File) of
- true ->
- if
- File =:= Erts#app.label ->
- replace_dyn_erl(Relocatable, Spec);
- true ->
- false
- end;
- false ->
+ File = element(2, Spec),
+ case File of
+ "erts" ->
+ reltool_utils:throw_error("This system is not installed. "
+ "The directory ~s is missing.",
+ [Erts#app.label]);
+ _ when File =:= Erts#app.label ->
+ replace_dyn_erl(Relocatable, Spec);
+ "erts-" ++ _ ->
+ false;
+ _ ->
true
end
end,
@@ -707,7 +817,8 @@ strip_sys_files(Relocatable, SysFiles, Apps, ExclRegexps) ->
replace_dyn_erl(false, _ErtsSpec) ->
true;
replace_dyn_erl(true, {create_dir, ErtsDir, ErtsFiles}) ->
- [{create_dir, _, BinFiles}] = safe_lookup_spec("bin", ErtsFiles),
+ [{create_dir, _, BinFiles}] =
+ safe_lookup_spec("bin", ErtsFiles),
case lookup_spec("dyn_erl", BinFiles) of
[] ->
case lookup_spec("erl.ini", BinFiles) of
@@ -759,20 +870,31 @@ spec_bin_files(Sys, AllSysFiles, StrippedSysFiles, RelFiles, InclRegexps) ->
GoodNames = [F || {copy_file, F} <- OldBinFiles,
not lists:suffix(".boot", F),
not lists:suffix(".script", F)],
- BinFiles2 = [Map(S) || S <- BinFiles, lists:member(element(2, S), GoodNames)],
+ BinFiles2 = [Map(S) || S <- BinFiles,
+ lists:member(element(2, S), GoodNames)],
BootFiles = [F || F <- RelFiles, lists:suffix(".boot", element(2, F))],
- [{write_file, _, BootRel}] = safe_lookup_spec(Sys#sys.boot_rel ++ ".boot", BootFiles),
- BootFiles2 = lists:keystore("start.boot", 2, BootFiles, {write_file, "start.boot", BootRel}),
- MakeRegexp = fun(File) -> "^bin/" ++ element(2, File) ++ "(|.escript)\$" end,
+ [{write_file, _, BootRel}] =
+ safe_lookup_spec(Sys#sys.boot_rel ++ ".boot", BootFiles),
+ BootFiles2 = lists:keystore("start.boot",
+ 2,
+ BootFiles,
+ {write_file, "start.boot", BootRel}),
+ MakeRegexp =
+ fun(File) -> "^bin/" ++ element(2, File) ++ "(|.escript)\$" end,
ExtraIncl = lists:map(MakeRegexp, Escripts),
- InclRegexps2 = reltool_utils:decode_regexps(incl_sys_filters, {add, ExtraIncl}, InclRegexps),
+ InclRegexps2 = reltool_utils:decode_regexps(incl_sys_filters,
+ {add, ExtraIncl},
+ InclRegexps),
{InclRegexps2, Escripts ++ BinFiles2 ++ BootFiles2}.
spec_escripts(#sys{apps = Apps}, ErtsBin, BinFiles) ->
- Filter = fun(#app{is_escript = IsEscript, is_included = IsIncl,
- is_pre_included = IsPre, name = Name, active_dir = File}) ->
+ Filter = fun(#app{is_escript = IsEscript,
+ is_included = IsIncl,
+ is_pre_included = IsPre,
+ name = Name,
+ active_dir = File}) ->
if
- Name =:= ?MISSING_APP ->
+ Name =:= ?MISSING_APP_NAME ->
false;
not IsEscript ->
false;
@@ -796,7 +918,6 @@ check_sys(Mandatory, SysFiles) ->
lists:foreach(fun(M) -> do_check_sys(M, SysFiles) end, Mandatory).
do_check_sys(Prefix, Specs) ->
- %%io:format("Prefix: ~p\n", [Prefix]),
case lookup_spec(Prefix, Specs) of
[] ->
reltool_utils:throw_error("Mandatory system directory ~s "
@@ -820,6 +941,7 @@ lookup_spec(Prefix, Specs) ->
safe_lookup_spec(Prefix, Specs) ->
case lookup_spec(Prefix, Specs) of
[] ->
+ %% io:format("lookup fail ~s:\n\t~p\n", [Prefix, Specs]),
reltool_utils:throw_error("Mandatory system file ~s is "
"not included", [Prefix]);
Match ->
@@ -834,7 +956,7 @@ spec_lib_files(#sys{apps = Apps} = Sys) ->
Filter = fun(#app{is_escript = IsEscript, is_included = IsIncl,
is_pre_included = IsPre, name = Name}) ->
if
- Name =:= ?MISSING_APP ->
+ Name =:= ?MISSING_APP_NAME ->
false;
IsEscript ->
false;
@@ -863,10 +985,10 @@ check_apps([], _) ->
spec_app(#app{name = Name,
mods = Mods,
active_dir = SourceDir,
- incl_app_filters = AppInclRegexps,
- excl_app_filters = AppExclRegexps} = App,
- #sys{incl_app_filters = SysInclRegexps,
- excl_app_filters = SysExclRegexps,
+ incl_app_filters = AppInclRegexps,
+ excl_app_filters = AppExclRegexps} = App,
+ #sys{incl_app_filters = SysInclRegexps,
+ excl_app_filters = SysExclRegexps,
debug_info = SysDebugInfo} = Sys) ->
%% List files recursively
{create_dir, _, AppFiles} = spec_dir(SourceDir),
@@ -942,13 +1064,13 @@ spec_dir(Dir) ->
Base,
[spec_dir(filename:join([Dir, F])) || F <- Files]};
error ->
- reltool_utils:throw_error("list dir ~s failed\n", [Dir])
+ reltool_utils:throw_error("list dir ~s failed", [Dir])
end;
{ok, #file_info{type = regular}} ->
%% Plain file
{copy_file, Base};
_ ->
- reltool_utils:throw_error("read file info ~s failed\n", [Dir])
+ reltool_utils:throw_error("read file info ~s failed", [Dir])
end.
spec_mod(Mod, DebugInfo) ->
@@ -1082,7 +1204,7 @@ do_eval_spec({archive, Archive, Options, Files},
{ok, _} ->
ok;
{error, Reason} ->
- reltool_utils:throw_error("create archive ~s: ~p\n",
+ reltool_utils:throw_error("create archive ~s failed: ~p",
[ArchiveFile, Reason])
end;
do_eval_spec({copy_file, File}, _OrigSourceDir, SourceDir, TargetDir) ->
@@ -1216,18 +1338,7 @@ opt_join(Path, File) ->
filename:join([Path, File]).
match(String, InclRegexps, ExclRegexps) ->
- %%case
- match(String, InclRegexps) andalso not match(String, ExclRegexps).
-%% of
-%% true ->
-%% true;
-%% false ->
-%% io:format("no match: ~p\n"
-%% " incl: ~p\n"
-%% " excl: ~p\n",
-%% [String, InclRegexps, ExclRegexps]),
-%% false
-%% end.
+ match(String, InclRegexps) andalso not match(String, ExclRegexps).
%% Match at least one regexp
match(_String, []) ->
@@ -1284,7 +1395,7 @@ do_install(RelName, TargetDir) ->
ok = release_handler:create_RELEASES(TargetDir2, RelFile),
ok;
_ ->
- reltool_utils:throw_error("~s: Illegal syntax.\n", [DataFile])
+ reltool_utils:throw_error("~s: Illegal data file syntax", [DataFile])
end.
subst_src_scripts(Scripts, SrcDir, DestDir, Vars, Opts) ->
diff --git a/lib/reltool/src/reltool_utils.erl b/lib/reltool/src/reltool_utils.erl
index 403fa574c5..39d057d994 100644
--- a/lib/reltool/src/reltool_utils.erl
+++ b/lib/reltool/src/reltool_utils.erl
@@ -19,7 +19,30 @@
-module(reltool_utils).
%% Public
--compile([export_all]).
+-export([root_dir/0, erl_libs/0, lib_dirs/1,
+ split_app_name/1, prim_consult/1,
+ default_rels/0, choose_default/3,
+
+ assign_image_list/1, get_latest_resize/1,
+ mod_conds/0, list_to_mod_cond/1, mod_cond_to_index/1,
+ incl_conds/0, list_to_incl_cond/1, incl_cond_to_index/1, elem_to_index/2,
+ app_dir_test/2, split_app_dir/1,
+ get_item/1, get_items/1, get_selected_items/3,
+ select_items/3, select_item/2,
+
+ safe_keysearch/5, print/4, return_first_error/2, add_warning/2,
+
+ create_dir/1, list_dir/1, read_file_info/1,
+ write_file_info/2, read_file/1, write_file/2,
+ recursive_delete/1, delete/2, recursive_copy_file/2, copy_file/2,
+
+ throw_error/2,
+
+ decode_regexps/3,
+ default_val/2,
+ escript_foldl/3,
+
+ call/2, cast/2, reply/3]).
-include_lib("kernel/include/file.hrl").
-include_lib("wx/include/wx.hrl").
@@ -103,18 +126,46 @@ prim_parse(Tokens, Acc) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
default_rels() ->
- Kernel = #rel_app{name = kernel, incl_apps = []},
- Stdlib = #rel_app{name = stdlib, incl_apps = []},
- Sasl = #rel_app{name = sasl, incl_apps = []},
+ %%Kernel = #rel_app{name = kernel, incl_apps = []},
+ %%Stdlib = #rel_app{name = stdlib, incl_apps = []},
+ Sasl = #rel_app{name = sasl, incl_apps = []},
[
#rel{name = ?DEFAULT_REL_NAME,
vsn = "1.0",
- rel_apps = [Kernel, Stdlib]},
+ rel_apps = []},
+ %%rel_apps = [Kernel, Stdlib]},
#rel{name = "start_sasl",
vsn = "1.0",
- rel_apps = [Kernel, Sasl, Stdlib]}
+ rel_apps = [Sasl]}
+ %%rel_apps = [Kernel, Sasl, Stdlib]}
].
+choose_default(Tag, Profile, InclDefs)
+ when Profile =:= ?DEFAULT_PROFILE; InclDefs ->
+ case Tag of
+ incl_sys_filters -> ?DEFAULT_INCL_SYS_FILTERS;
+ excl_sys_filters -> ?DEFAULT_EXCL_SYS_FILTERS;
+ incl_app_filters -> ?DEFAULT_INCL_APP_FILTERS;
+ excl_app_filters -> ?DEFAULT_EXCL_APP_FILTERS;
+ embedded_app_type -> ?DEFAULT_EMBEDDED_APP_TYPE
+ end;
+choose_default(Tag, standalone, _InclDefs) ->
+ case Tag of
+ incl_sys_filters -> ?STANDALONE_INCL_SYS_FILTERS;
+ excl_sys_filters -> ?STANDALONE_EXCL_SYS_FILTERS;
+ incl_app_filters -> ?STANDALONE_INCL_APP_FILTERS;
+ excl_app_filters -> ?STANDALONE_EXCL_APP_FILTERS;
+ embedded_app_type -> ?DEFAULT_EMBEDDED_APP_TYPE
+ end;
+choose_default(Tag, embedded, _InclDefs) ->
+ case Tag of
+ incl_sys_filters -> ?EMBEDDED_INCL_SYS_FILTERS;
+ excl_sys_filters -> ?EMBEDDED_EXCL_SYS_FILTERS;
+ incl_app_filters -> ?EMBEDDED_INCL_APP_FILTERS;
+ excl_app_filters -> ?EMBEDDED_EXCL_APP_FILTERS;
+ embedded_app_type -> ?EMBEDDED_APP_TYPE
+ end.
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
assign_image_list(ListCtrl) ->
@@ -379,7 +430,7 @@ create_dir(Dir) ->
ok;
{error, Reason} ->
Text = file:format_error(Reason),
- throw_error("create dir ~s: ~s\n", [Dir, Text])
+ throw_error("create dir ~s: ~s", [Dir, Text])
end.
list_dir(Dir) ->
@@ -388,7 +439,7 @@ list_dir(Dir) ->
Files;
error ->
Text = file:format_error(enoent),
- throw_error("list dir ~s: ~s\n", [Dir, Text])
+ throw_error("list dir ~s: ~s", [Dir, Text])
end.
read_file_info(File) ->
@@ -397,7 +448,7 @@ read_file_info(File) ->
Info;
{error, Reason} ->
Text = file:format_error(Reason),
- throw_error("read file info ~s: ~s\n", [File, Text])
+ throw_error("read file info ~s: ~s", [File, Text])
end.
write_file_info(File, Info) ->
@@ -406,7 +457,7 @@ write_file_info(File, Info) ->
ok;
{error, Reason} ->
Text = file:format_error(Reason),
- throw_error("write file info ~s: ~s\n", [File, Text])
+ throw_error("write file info ~s: ~s", [File, Text])
end.
read_file(File) ->
@@ -415,7 +466,7 @@ read_file(File) ->
Bin;
{error, Reason} ->
Text = file:format_error(Reason),
- throw_error("read file ~s: ~s\n", [File, Text])
+ throw_error("read file ~s: ~s", [File, Text])
end.
write_file(File, IoList) ->
@@ -424,7 +475,7 @@ write_file(File, IoList) ->
ok;
{error, Reason} ->
Text = file:format_error(Reason),
- throw_error("write file ~s: ~s\n", [File, Text])
+ throw_error("write file ~s: ~s", [File, Text])
end.
recursive_delete(Dir) ->
@@ -560,7 +611,12 @@ escript_foldl(Fun, Acc, File) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
call(Name, Msg) when is_atom(Name) ->
- call(whereis(Name), Msg);
+ case whereis(Name) of
+ undefined ->
+ {error, {noproc, Name}};
+ Pid ->
+ call(Pid, Msg)
+ end;
call(Pid, Msg) when is_pid(Pid) ->
Ref = erlang:monitor(process, Pid),
Pid ! {call, self(), Ref, Msg},
diff --git a/lib/reltool/test/Makefile b/lib/reltool/test/Makefile
index 00d2add3e5..34781ae720 100644
--- a/lib/reltool/test/Makefile
+++ b/lib/reltool/test/Makefile
@@ -1,19 +1,19 @@
#
# %CopyrightBegin%
-#
-# Copyright Ericsson AB 2009. All Rights Reserved.
-#
+#
+# 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%
include $(ERL_TOP)/make/target.mk
@@ -25,6 +25,7 @@ include $(ERL_TOP)/make/$(TARGET)/otp.mk
MODULES= \
rtt \
+ reltool_app_SUITE \
reltool_wx_SUITE \
reltool_server_SUITE \
reltool_test_lib
diff --git a/lib/reltool/test/reltool_app_SUITE.erl b/lib/reltool/test/reltool_app_SUITE.erl
new file mode 100644
index 0000000000..f8433f73d0
--- /dev/null
+++ b/lib/reltool/test/reltool_app_SUITE.erl
@@ -0,0 +1,291 @@
+%%
+%% %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 application specifics of the Reltool application
+%%----------------------------------------------------------------------
+-module(reltool_app_SUITE).
+
+-compile(export_all).
+
+-include("reltool_test_lib.hrl").
+
+
+t() -> reltool_test_lib:t(?MODULE).
+t(Case) -> reltool_test_lib:t({?MODULE, Case}).
+
+%% Test server callbacks
+init_per_suite(Config) ->
+ Config2 = reltool_test_lib:init_per_suite(Config),
+ case is_app(reltool) of
+ {ok, AppFile} ->
+ %% io:format("AppFile: ~n~p~n", [AppFile]),
+ [{app_file, AppFile} | Config2];
+ {error, Reason} ->
+ fail(Reason)
+ end.
+
+end_per_suite(Config) ->
+ reltool_test_lib:end_per_suite(Config).
+
+init_per_testcase(Case, Config) ->
+ Config2 =
+ case Case of
+ undef_funcs ->
+ [{tc_timeout, timer:minutes(10)} | Config];
+ _ ->
+ Config
+ end,
+ reltool_test_lib:init_per_testcase(Case, Config2).
+
+end_per_testcase(Func,Config) ->
+ reltool_test_lib:end_per_testcase(Func,Config).
+
+fin_per_testcase(Case, Config) ->
+ reltool_test_lib:end_per_testcase(Case, Config).
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+all() ->
+ all(suite).
+
+all(suite) ->
+ [
+ fields,
+ modules,
+ export_all,
+ app_depend,
+ undef_funcs
+ ].
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+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, {LineNo, Mod, Code}} ->
+ IoList = lists:concat([File, ":", LineNo, ": ",
+ Mod:format_error(Code)]),
+ {error, list_to_atom(lists:flatten(IoList))}
+ end.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+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(reltool),
+ case missing_modules(Mods, EbinList, []) of
+ [] ->
+ ok;
+ Missing ->
+ throw({error, {missing_modules, Missing}})
+ end,
+ case extra_modules(Mods, EbinList, []) 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, [], Extra) ->
+ Extra;
+extra_modules(Mods, [Mod|Ebins], Extra) ->
+ case lists:member(Mod, Mods) of
+ true ->
+ extra_modules(Mods, Ebins, Extra);
+ false ->
+ io:format("supefluous module: ~p~n", [Mod]),
+ extra_modules(Mods, Ebins, [Mod|Extra])
+ end.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+export_all(suite) ->
+ [];
+export_all(doc) ->
+ [];
+export_all(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) ->
+ App = reltool,
+ 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),
+ {ok, XRef} = xref:start(XRefTestName),
+ ok = xref:set_default(XRef,
+ [{verbose,false},{warnings,false}]),
+ XRefName = undef_funcs_make_name(App, xref_name),
+ {ok, XRefName} = xref:add_release(XRef, Root, {name,XRefName}),
+ {ok, App} = xref:replace_application(XRef, App, EbinDir),
+ {ok, Undefs} = xref:analyze(XRef, undefined_function_calls),
+ xref:stop(XRef),
+ analyze_undefined_function_calls(Undefs, Mods, []).
+
+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
+ false ->
+ fail({not_found, Key, L});
+ {value, {Key, Value}} ->
+ Value
+ end.
diff --git a/lib/reltool/test/reltool_server_SUITE.erl b/lib/reltool/test/reltool_server_SUITE.erl
index cf951191a0..faf1bdbba2 100644
--- a/lib/reltool/test/reltool_server_SUITE.erl
+++ b/lib/reltool/test/reltool_server_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2009. All Rights Reserved.
-%%
+%%
+%% 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%
-module(reltool_server_SUITE).
@@ -26,11 +26,13 @@
-include("reltool_test_lib.hrl").
-define(NODE_NAME, '__RELTOOL__TEMPORARY_TEST__NODE__').
+-define(WORK_DIR, "reltool_work_dir").
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initialization functions.
init_per_suite(Config) ->
+ ?ignore(file:make_dir(?WORK_DIR)),
reltool_test_lib:init_per_suite(Config).
end_per_suite(Config) ->
@@ -128,8 +130,7 @@ create_release(_Config) ->
{value, {_, _, StdlibVsn}} = lists:keysearch(stdlib, 1, Apps),
Rel = {release, {RelName, RelVsn},
{erts, ErtsVsn},
- [{kernel, KernelVsn},
- {stdlib, StdlibVsn}]},
+ [{kernel, KernelVsn}, {stdlib, StdlibVsn}]},
?m({ok, Rel}, reltool:get_rel([{config, Config}], RelName)),
ok.
@@ -159,15 +160,17 @@ create_script(_Config) ->
Rel = {release,
{RelName, RelVsn},
{erts, ErtsVsn},
- [{stdlib, StdlibVsn}, {kernel, KernelVsn}]},
+ [{kernel, KernelVsn}, {stdlib, StdlibVsn}]},
?m({ok, Rel}, reltool:get_rel(Pid, RelName)),
- RelFile = RelName ++ ".rel",
- ?m(ok, file:write_file(RelFile, io_lib:format("~p.\n", [Rel]))),
+ ?m(ok, file:write_file(filename:join([?WORK_DIR, RelName ++ ".rel"]),
+ io_lib:format("~p.\n", [Rel]))),
%% Generate script file
+ {ok, Cwd} = file:get_cwd(),
+ ?m(ok, file:set_cwd(?WORK_DIR)),
?m(ok, systools:make_script(RelName, [])),
- ScriptFile = RelName ++ ".script",
- {ok, [OrigScript]} = ?msym({ok, [_]}, file:consult(ScriptFile)),
+ {ok, [OrigScript]} = ?msym({ok, [_]}, file:consult(RelName ++ ".script")),
+ ?m(ok, file:set_cwd(Cwd)),
{ok, Script} = ?msym({ok, _}, reltool:get_script(Pid, RelName)),
%% OrigScript2 = sort_script(OrigScript),
%% Script2 = sort_script(Script),
@@ -201,9 +204,10 @@ create_target(_Config) ->
]},
%% Generate target file
- TargetDir = "reltool_target_dir_development",
+ TargetDir = filename:join([?WORK_DIR, "target_development"]),
?m(ok, reltool_utils:recursive_delete(TargetDir)),
?m(ok, file:make_dir(TargetDir)),
+ ?log("SPEC: ~p\n", [reltool:get_target_spec([{config, Config}])]),
?m(ok, reltool:create_target([{config, Config}], TargetDir)),
Erl = filename:join([TargetDir, "bin", "erl"]),
@@ -234,7 +238,7 @@ create_embedded(_Config) ->
]},
%% Generate target file
- TargetDir = "reltool_target_dir_embedded",
+ TargetDir = filename:join([?WORK_DIR, "target_embedded"]),
?m(ok, reltool_utils:recursive_delete(TargetDir)),
?m(ok, file:make_dir(TargetDir)),
?m(ok, reltool:create_target([{config, Config}], TargetDir)),
@@ -264,7 +268,7 @@ create_standalone(_Config) ->
]},
%% Generate target file
- TargetDir = "reltool_target_dir_standalone",
+ TargetDir = filename:join([?WORK_DIR, "target_standalone"]),
?m(ok, reltool_utils:recursive_delete(TargetDir)),
?m(ok, file:make_dir(TargetDir)),
?m(ok, reltool:create_target([{config, Config}], TargetDir)),
@@ -290,6 +294,8 @@ create_standalone(_Config) ->
create_old_target(TestInfo) when is_atom(TestInfo) ->
reltool_test_lib:tc_info(TestInfo);
create_old_target(_Config) ->
+ ?skip("Old style of target", []),
+
%% Configure the server
RelName1 = "Just testing",
RelName2 = "Just testing with SASL",
@@ -306,7 +312,7 @@ create_old_target(_Config) ->
]},
%% Generate target file
- TargetDir = "reltool_target_dir_old",
+ TargetDir = filename:join([?WORK_DIR, "target_old_style"]),
?m(ok, reltool_utils:recursive_delete(TargetDir)),
?m(ok, file:make_dir(TargetDir)),
?m(ok, reltool:create_target([{config, Config}], TargetDir)),
diff --git a/lib/reltool/test/reltool_test_lib.erl b/lib/reltool/test/reltool_test_lib.erl
index 25978294ee..5390b0a75e 100644
--- a/lib/reltool/test/reltool_test_lib.erl
+++ b/lib/reltool/test/reltool_test_lib.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2009. All Rights Reserved.
-%%
+%%
+%% 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%
-module(reltool_test_lib).
@@ -24,9 +24,11 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init_per_suite(Config) when is_list(Config)->
+ global:register_name(reltool_global_logger, group_leader()),
incr_timetrap(Config, 5).
end_per_suite(Config) when is_list(Config)->
+ global:unregister_name(reltool_global_logger),
ok.
incr_timetrap(Config, Times) ->
@@ -130,11 +132,9 @@ wx_end_per_suite(Config) ->
init_per_testcase(_Func, Config) when is_list(Config) ->
set_kill_timer(Config),
- global:register_name(reltool_global_logger, group_leader()),
Config.
end_per_testcase(_Func, Config) when is_list(Config) ->
- global:unregister_name(reltool_global_logger),
reset_kill_timer(Config),
Config.
diff --git a/lib/reltool/test/reltool_test_lib.hrl b/lib/reltool/test/reltool_test_lib.hrl
index 93134144ea..b592ebb2f0 100644
--- a/lib/reltool/test/reltool_test_lib.hrl
+++ b/lib/reltool/test/reltool_test_lib.hrl
@@ -1,23 +1,24 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2009. All Rights Reserved.
-%%
+%%
+%% 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%
-include_lib("wx/include/wx.hrl").
+-define(flat_format(Format,Args), lists:flatten(io_lib:format(Format,Args))).
-define(log(Format,Args), reltool_test_lib:log(Format,Args,?FILE,?LINE)).
-define(warning(Format,Args), ?log("<WARNING>\n " ++ Format,Args)).
-define(error(Format,Args), reltool_test_lib:error(Format,Args,?FILE,?LINE)).
diff --git a/lib/reltool/test/rtt b/lib/reltool/test/rtt
index 2411195338..1f93396196 100755
--- a/lib/reltool/test/rtt
+++ b/lib/reltool/test/rtt
@@ -1,19 +1,19 @@
#! /bin/sh -f
# %CopyrightBegin%
-#
-# Copyright Ericsson AB 2009. All Rights Reserved.
-#
+#
+# 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%
# Usage: rtt [-cerl] <args to erlang startup script>
@@ -23,7 +23,7 @@ while [ $# -gt 0 ]; do
case "$1" in
"-cerl")
shift
- emu=cerl
+ emu="$ERL_TOP/bin/cerl"
;;
*)
break
diff --git a/lib/sasl/doc/src/notes.xml b/lib/sasl/doc/src/notes.xml
index 4c4b11d3c4..e528af2522 100644
--- a/lib/sasl/doc/src/notes.xml
+++ b/lib/sasl/doc/src/notes.xml
@@ -30,6 +30,33 @@
</header>
<p>This document describes the changes made to the SASL application.</p>
+<section><title>SASL 2.1.9.2</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>In R13B04 sys:get_status was modified to invoke
+ format_status/2 in the callback module if the module
+ exports that function. This resulted in a change to the
+ term returned from calling sys:get_status on the
+ supervisor module, since supervisor is a gen_server and
+ gen_server exports format_status. The sasl
+ release_handler_1 module had a dependency on the
+ pre-R13B04 term returned by sys:get_status when invoked
+ on a supervisor, so the R13B04 change broke that
+ dependency.</p>
+ <p>This problem has been fixed by change
+ release_handler_1 to handle both the pre-R13B04 and
+ R13B04 terms that sys:get_status can return from a
+ supervisor.</p>
+ <p>
+ Own Id: OTP-8619 Aux Id: seq11570 </p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
<section><title>SASL 2.1.9.1</title>
<section><title>Improvements and New Features</title>
diff --git a/lib/sasl/src/release_handler_1.erl b/lib/sasl/src/release_handler_1.erl
index e3e3caba99..9c0edf4e99 100644
--- a/lib/sasl/src/release_handler_1.erl
+++ b/lib/sasl/src/release_handler_1.erl
@@ -1,19 +1,19 @@
%%
%% %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
%% 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_1).
@@ -554,7 +554,13 @@ get_supervisor_module(SupPid) ->
get_supervisor_module1(SupPid) ->
{status, _Pid, {module, _Mod},
[_PDict, _SysState, _Parent, _Dbg, Misc]} = sys:get_status(SupPid),
- [_Name, State, _Type, _Time] = Misc,
+ %% supervisor Misc field changed at R13B04, handle old and new variants here
+ State = case Misc of
+ [_Name, State1, _Type, _Time] ->
+ State1;
+ [_Header, _Data, {data, [{"State", State2}]}] ->
+ State2
+ end,
%% Cannot use #supervisor_state{module = Module} = State.
{ok, element(#supervisor_state.module, State)}.
diff --git a/lib/sasl/vsn.mk b/lib/sasl/vsn.mk
index cad33a5d9c..d01a9bc4f1 100644
--- a/lib/sasl/vsn.mk
+++ b/lib/sasl/vsn.mk
@@ -1 +1 @@
-SASL_VSN = 2.1.9.1
+SASL_VSN = 2.1.9.2
diff --git a/lib/snmp/doc/src/notes.xml b/lib/snmp/doc/src/notes.xml
index 33e304abfa..eb7c9db6ba 100644
--- a/lib/snmp/doc/src/notes.xml
+++ b/lib/snmp/doc/src/notes.xml
@@ -33,6 +33,68 @@
</header>
<section>
+ <title>SNMP Development Toolkit 4.16.2</title>
+ <p>Version 4.16.2 supports code replacement in runtime from/to
+ version 4.16.1, 4.16, 4.15, 4.14 and 4.13.5.</p>
+
+ <section>
+ <title>Improvements and new features</title>
+ <!--
+ <p>-</p>
+ -->
+ <list type="bulleted">
+ <item>
+ <p>[compiler] The SMI specifies that a table row OID should be
+ named: { &lt;tableIdentifier&gt; "1" }. </p>
+ <p>A new option has been introduced,
+ <seealso marker="snmpc#compiler_opts">relaxed_row_name_assign_check</seealso>,
+ that allows for a more liberal numbering scheme</p>
+ <p>Own Id: OTP-8574</p>
+ </item>
+
+ <item>
+ <p>[agent|manager] Changes to make snmp (forward) compatible with
+ the new version of the crypto application (released in R14).
+ As of R14, crypto is implemented using NIFs. Also,
+ the API is more strict. </p>
+ <p>Own Id: OTP-8594</p>
+ </item>
+
+ </list>
+
+ </section>
+
+ <section>
+ <title>Reported Fixed Bugs and Malfunctions</title>
+ <!--
+ <p>-</p>
+ -->
+
+ <list type="bulleted">
+ <item>
+ <p>Encode/decode of Counter64 values larger than
+ 16#7fffffffffffffff (9223372036854775807) failed. </p>
+ <p>Own Id: OTP-8563</p>
+ </item>
+
+ <item>
+ <p>[compiler] Fails to compile non-contiguous BITS. </p>
+ <p>Per Hedeland</p>
+ <p>Own Id: OTP-8595</p>
+ </item>
+
+ </list>
+
+ </section>
+
+ <section>
+ <title>Incompatibilities</title>
+ <p>-</p>
+ </section>
+ </section> <!-- 4.16.2 -->
+
+
+ <section>
<title>SNMP Development Toolkit 4.16.1</title>
<p>Version 4.16.1 supports code replacement in runtime from/to
version 4.16, 4.15, 4.14 and 4.13.5.</p>
diff --git a/lib/snmp/doc/src/snmpc.xml b/lib/snmp/doc/src/snmpc.xml
index 48d63d6c91..fbd0950c69 100644
--- a/lib/snmp/doc/src/snmpc.xml
+++ b/lib/snmp/doc/src/snmpc.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2004</year><year>2009</year>
+ <year>2004</year><year>2010</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -13,12 +13,12 @@
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>snmpc</title>
@@ -47,9 +47,10 @@
<type>
<v>File = string()</v>
<v>Options = [opt()]</v>
- <v>opt() = db() | deprecated() | description() | reference() | group_check() | i() | il() | imports() | module() | module_identity() | outdir() | no_defs() | verbosity() | warnings()</v>
+ <v>opt() = db() | relaxed_row_name_assign_check() | deprecated() | description() | reference() | group_check() | i() | il() | imports() | module() | module_identity() | outdir() | no_defs() | verbosity() | warnings()</v>
<v>db() = {db, volatile|persistent|mnesia}</v>
<v>deprecated() = {deprecated, bool()}</v>
+ <v>relaxed_row_name_assign_check() = relaxed_row_name_assign_check</v>
<v>description() = description</v>
<v>reference() = reference</v>
<v>group_check() = {group_check, bool()}</v>
@@ -71,75 +72,104 @@
compiled file <c>BinFileName</c> is called
<c><![CDATA[<File>.bin]]></c>. </p>
<list type="bulleted">
- <item>The option <c>db</c> specifies which database should
- be used for the default instrumentation. Default is
- <c>volatile</c>.
+ <item>
+ <p>The option <c>db</c> specifies which database should
+ be used for the default instrumentation. </p>
+ <p>Default is <c>volatile</c>. </p>
+ </item>
+ <item>
+ <p>The option <c>deprecated</c> specifies if a deprecated
+ definition should be kept or not. If the option is
+ false the MIB compiler will ignore all deprecated
+ definitions. </p>
+ <p>Default is <c>true</c>. </p>
</item>
- <item>The option <c>deprecated</c> specifies if a deprecated
- definition should be kept or not. If the option is
- false the MIB compiler will ignore all deprecated
- definitions. Default is <c>true</c>.
+ <item>
+ <p>The option <c>relaxed_row_name_assign_check</c>, if present,
+ specifies that the row name assign check shall not be done
+ strictly according to the SMI (which allows only the value 1).
+ With this option, all values greater than zero is allowed
+ (>= 1). This means that the error will be converted to a
+ warning. </p>
+ <p>By default it is not included, but if this option is present
+ it will be. </p>
</item>
- <item>The option <c>description</c> specifies if the text
- of the DESCRIPTION field will be included or not. By default
- it is not included, but if this option is present it will
- be.
+ <item>
+ <p>The option <c>description</c> specifies if the text
+ of the DESCRIPTION field will be included or not. </p>
+ <p>By default it is not included, but if this option is
+ present it will be. </p>
</item>
- <item>The option <c>reference</c> specifies if the text
- of the REFERENCE field, when found in a table definition,
- will be included or not. By default
- it is not included, but if this option is present it will
- be. The reference text will be placed in the allocList field
- of the mib-entry record (#me{}) for the table.
+ <item>
+ <p>The option <c>reference</c> specifies if the text
+ of the REFERENCE field, when found in a table definition,
+ will be included or not. </p>
+ <p>By default it is not included, but if this option is present
+ it will be. The reference text will be placed in the allocList
+ field of the mib-entry record (#me{}) for the table. </p>
</item>
- <item>The option <c>group_check</c> specifies whether the
- mib compiler should check the OBJECT-GROUP macro and
- the NOTIFICATION-GROUP macro for correctness or not.
- Default is <c>true</c>.
+ <item>
+ <p>The option <c>group_check</c> specifies whether the
+ mib compiler should check the OBJECT-GROUP macro and
+ the NOTIFICATION-GROUP macro for correctness or not. </p>
+ <p>Default is <c>true</c>. </p>
</item>
- <item>The option <c>i</c> specifies the path to search for
- imported (compiled) MIB files. The directories should be
- strings with a trailing directory delimiter. Default is
- <c>["./"]</c>.
+ <item>
+ <p>The option <c>i</c> specifies the path to search for
+ imported (compiled) MIB files. The directories should be
+ strings with a trailing directory delimiter. </p>
+ <p>Default is <c>["./"]</c>. </p>
</item>
- <item>The option <c>il</c> (include_lib) also specifies a
- list of directories to search for imported MIBs. It
- assumes that the first element in the directory name
- corresponds to an OTP application. The compiler will find
- the current installed version. For example, the value
- ["snmp/mibs/"] will be replaced by ["snmp-3.1.1/mibs/"]
- (or what the current version may be in the system). The
- current directory and the <c><![CDATA[<snmp-home>/priv/mibs/]]></c>
- are always listed last in the include path.
+ <item>
+ <p>The option <c>il</c> (include_lib) also specifies a
+ list of directories to search for imported MIBs. It
+ assumes that the first element in the directory name
+ corresponds to an OTP application. The compiler will find
+ the current installed version. For example, the value
+ ["snmp/mibs/"] will be replaced by ["snmp-3.1.1/mibs/"]
+ (or what the current version may be in the system). The
+ current directory and the
+ <c><![CDATA[<snmp-home>/priv/mibs/]]></c>
+ are always listed last in the include path. </p>
</item>
- <item>The option <c>imports</c>, if present, specifies that the
- IMPORT statement of the MIB shall be included in the compiled mib.
+ <item>
+ <p>The option <c>imports</c>, if present, specifies that
+ the IMPORT statement of the MIB shall be included in the
+ compiled mib. </p>
</item>
- <item>The option <c>module</c>, if present, specifies the
- name of a module which implements all instrumentation
- functions for the MIB. The name of all instrumentation
- functions must be the same as the corresponding managed
- object it implements.
+ <item>
+ <p>The option <c>module</c>, if present, specifies the
+ name of a module which implements all instrumentation
+ functions for the MIB. </p>
+ <p>The name of all instrumentation
+ functions must be the same as the corresponding managed
+ object it implements. </p>
</item>
- <item>The option <c>module_identity</c>, if present, specifies
- that the info part of the MODULE-IDENTITY statement of the MIB
- shall be included in the compiled mib.
+ <item>
+ <p>The option <c>module_identity</c>, if present, specifies
+ that the info part of the MODULE-IDENTITY statement of the MIB
+ shall be included in the compiled mib. </p>
</item>
- <item>The option <c>no_defs</c>, if present, specifies
- that if a managed object does not have an instrumentation
- function, the default instrumentation function should NOT
- be used, instead this is reported as an error, and the
- compilation aborts.
+ <item>
+ <p>The option <c>no_defs</c>, if present, specifies
+ that if a managed object does not have an instrumentation
+ function, the default instrumentation function should NOT
+ be used, instead this is reported as an error, and the
+ compilation aborts. </p>
</item>
- <item>The option <c>verbosity</c> specifies the verbosity of
- the SNMP mib compiler. I.e. if warning, info, log, debug
- and trace messages shall be shown. Default is <c>silence</c>.
- Note that if the option <c>warnings</c> is <c>true</c> and the
- option <c>verbosity</c> is <c>silence</c>, warning messages will
- still be shown.
+ <item>
+ <p>The option <c>verbosity</c> specifies the verbosity of
+ the SNMP mib compiler. I.e. if warning, info, log, debug
+ and trace messages shall be shown. </p>
+ <p>Default is <c>silence</c>. </p>
+ <p>Note that if the option <c>warnings</c> is <c>true</c> and the
+ option <c>verbosity</c> is <c>silence</c>, warning messages will
+ still be shown. </p>
</item>
- <item>The option <c>warnings</c> specifies whether warning
- messages should be shown. Default is <c>true</c>.
+ <item>
+ <p>The option <c>warnings</c> specifies whether warning
+ messages should be shown. </p>
+ <p>Default is <c>true</c>. </p>
</item>
</list>
<p>The MIB compiler understands both SMIv1 and SMIv2 MIBs. It
diff --git a/lib/snmp/src/agent/snmpa_usm.erl b/lib/snmp/src/agent/snmpa_usm.erl
index 12a6b996ff..b94294844b 100644
--- a/lib/snmp/src/agent/snmpa_usm.erl
+++ b/lib/snmp/src/agent/snmpa_usm.erl
@@ -560,11 +560,15 @@ encrypt(Data, PrivProtocol, PrivKey, SecLevel) ->
?vtrace("encrypt -> 3.1.4a",[]),
case (catch try_encrypt(PrivProtocol, PrivKey, Data)) of
{ok, ScopedPduData, MsgPrivParams} ->
- ?vtrace("encrypt -> encode tag",[]),
+ ?vtrace("encrypt -> encrypted - now encode tag",[]),
{snmp_pdus:enc_oct_str_tag(ScopedPduData), MsgPrivParams};
{error, Reason} ->
+ ?vtrace("encrypt -> error: "
+ "~n Reason: ~p", [Reason]),
error(Reason);
- _Error ->
+ Error ->
+ ?vtrace("encrypt -> other: "
+ "~n Error: ~p", [Error]),
error(encryptionError)
end
end.
diff --git a/lib/snmp/src/app/snmp.appup.src b/lib/snmp/src/app/snmp.appup.src
index 204de71c2e..aa3410fea3 100644
--- a/lib/snmp/src/app/snmp.appup.src
+++ b/lib/snmp/src/app/snmp.appup.src
@@ -22,14 +22,25 @@
%% ----- U p g r a d e -------------------------------------------------------
[
+ {"4.16.1",
+ [
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []}
+ ]
+ },
{"4.16",
[
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa_general_db, soft_purge, soft_purge, []},
{update, snmpm_net_if, soft, soft_purge, soft_purge, []}
]
},
{"4.15",
[
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa, soft_purge, soft_purge, [snmp_log]},
{load_module, snmp_config, soft_purge, soft_purge, []},
{load_module, snmp_log, soft_purge, soft_purge, []},
@@ -39,12 +50,15 @@
{update, snmpa_net_if, {advanced, upgrade_from_pre_4_16},
soft_purge, soft_purge, [snmpa_agent, snmp_log]},
{update, snmpa_agent, soft, soft_purge, soft_purge, []},
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
{update, snmpm_config, soft, soft_purge, soft_purge, []}
]
},
{"4.14",
[
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa, soft_purge, soft_purge, [snmp_log]},
{load_module, snmp_config, soft_purge, soft_purge, []},
{load_module, snmp_log, soft_purge, soft_purge, []},
@@ -52,6 +66,8 @@
{update, snmpa_net_if, {advanced, upgrade_from_pre_4_16},
soft_purge, soft_purge, [snmpa_agent, snmp_log]},
{update, snmpa_agent, soft, soft_purge, soft_purge, []},
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
{load_module, snmpm_user, soft_purge, soft_purge, []},
{load_module, snmpm_user_default, soft_purge, soft_purge, [snmpm_user]},
@@ -64,6 +80,7 @@
},
{"4.13.5",
[
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa_mib_data, soft_purge, soft_purge, []},
{load_module, snmpa, soft_purge, soft_purge, [snmp_log]},
{load_module, snmp_config, soft_purge, soft_purge, []},
@@ -72,6 +89,8 @@
{update, snmpa_net_if, {advanced, upgrade_from_pre_4_16},
soft_purge, soft_purge, [snmpa_agent, snmp_log]},
{update, snmpa_agent, soft, soft_purge, soft_purge, []},
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
{load_module, snmpm_user, soft_purge, soft_purge, []},
{load_module, snmpm_user_default, soft_purge, soft_purge, [snmpm_user]},
@@ -88,14 +107,25 @@
%% ------D o w n g r a d e ---------------------------------------------------
[
+ {"4.16.1",
+ [
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []}
+ ]
+ },
{"4.16",
[
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa_general_db, soft_purge, soft_purge, []},
{update, snmpm_net_if, soft, soft_purge, soft_purge, []}
]
},
{"4.15",
[
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa, soft_purge, soft_purge, [snmp_log]},
{load_module, snmp_config, soft_purge, soft_purge, []},
{load_module, snmp_log, soft_purge, soft_purge, []},
@@ -103,6 +133,8 @@
{update, snmpa_net_if, {advanced, downgrade_to_pre_4_16},
soft_purge, soft_purge, [snmpa_agent, snmp_log]},
{update, snmpa_agent, soft, soft_purge, soft_purge, []},
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
{load_module, snmpa_general_db, soft_purge, soft_purge, []},
{update, snmpm_net_if, {advanced, downgrade_to_pre_4_16},
@@ -112,6 +144,7 @@
},
{"4.14",
[
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa, soft_purge, soft_purge, [snmp_log]},
{load_module, snmp_config, soft_purge, soft_purge, []},
{load_module, snmp_log, soft_purge, soft_purge, []},
@@ -119,6 +152,8 @@
{update, snmpa_net_if, {advanced, downgrade_to_pre_4_16},
soft_purge, soft_purge, [snmpa_agent, snmp_log]},
{update, snmpa_agent, soft, soft_purge, soft_purge, []},
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
{load_module, snmpm_user, soft_purge, soft_purge, []},
{load_module, snmpm_user_default, soft_purge, soft_purge, [snmpm_user]},
@@ -131,6 +166,7 @@
},
{"4.13.5",
[
+ {load_module, snmp_pdus, soft_purge, soft_purge, []},
{load_module, snmpa_mib_data, soft_purge, soft_purge, []},
{load_module, snmp_config, soft_purge, soft_purge, []},
{load_module, snmpa, soft_purge, soft_purge, [snmp_log]},
@@ -139,6 +175,8 @@
{update, snmpa_net_if, {advanced, downgrade_to_pre_4_16},
soft_purge, soft_purge, [snmpa_agent, snmp_log]},
{update, snmpa_agent, soft, soft_purge, soft_purge, []},
+ {load_module, snmpa_usm, soft_purge, soft_purge, [snmp_usm]},
+ {load_module, snmp_usm, soft_purge, soft_purge, []},
{load_module, snmpm_user, soft_purge, soft_purge, []},
{load_module, snmpm_user_default, soft_purge, soft_purge, [snmpm_user]},
diff --git a/lib/snmp/src/compile/snmpc.erl b/lib/snmp/src/compile/snmpc.erl
index 8a1f15d4a4..a7f2cdc2bc 100644
--- a/lib/snmp/src/compile/snmpc.erl
+++ b/lib/snmp/src/compile/snmpc.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
-module(snmpc).
@@ -34,6 +34,7 @@
-include("snmpc.hrl").
-include("snmpc_lib.hrl").
+-record(dldata, {deprecated, relaxed_row_name_assign_check}).
look_at(Mib) ->
io:format("~p ~n", [snmpc_lib:look_at(Mib)]).
@@ -114,6 +115,7 @@ compile(FileName) ->
%% module_identity
%% {module, string()}
%% no_defs
+%% relaxed_row_name_assign_check
%% (hidden) {verbosity, trace|debug|log|info|silence} silence
%% (hidden) version
%% (hidden) options
@@ -201,6 +203,8 @@ get_options([imports|Opts], Formats, Args) ->
get_options(Opts, ["~n imports"|Formats], Args);
get_options([module_identity|Opts], Formats, Args) ->
get_options(Opts, ["~n module_identity"|Formats], Args);
+get_options([relaxed_row_name_assign_check|Opts], Formats, Args) ->
+ get_options(Opts, ["~n relaxed_row_name_assign_check"|Formats], Args);
get_options([_|Opts], Formats, Args) ->
get_options(Opts, Formats, Args).
@@ -284,6 +288,8 @@ check_options([imports| T]) ->
check_options(T);
check_options([module_identity| T]) ->
check_options(T);
+check_options([relaxed_row_name_assign_check| T]) ->
+ check_options(T);
check_options([{module, M} | T]) when is_atom(M) ->
check_options(T);
check_options([no_defs| T]) ->
@@ -309,6 +315,9 @@ get_description(Options) ->
get_reference(Options) ->
get_bool_option(reference, Options).
+get_relaxed_row_name_assign_check(Options) ->
+ lists:member(relaxed_row_name_assign_check, Options).
+
get_bool_option(Option, Options) ->
case lists:member(Option, Options) of
false ->
@@ -406,8 +415,12 @@ compile_parsed_data(#pdata{mib_name = MibName,
defs = Definitions}) ->
snmpc_lib:import(Imports),
update_imports(Imports),
- Deprecated = get_deprecated(get(options)),
- definitions_loop(Definitions, Deprecated),
+ Opts = get(options),
+ Deprecated = get_deprecated(Opts),
+ RelChk = get_relaxed_row_name_assign_check(Opts),
+ Data = #dldata{deprecated = Deprecated,
+ relaxed_row_name_assign_check = RelChk},
+ definitions_loop(Definitions, Data),
MibName.
update_imports(Imports) ->
@@ -436,21 +449,21 @@ update_status(Name, Status) ->
%% A deprecated object
definitions_loop([{#mc_object_type{name = ObjName, status = deprecated},
Line}|T],
- false) ->
+ #dldata{deprecated = false} = Data) ->
%% May be implemented but the compiler chooses not to.
?vinfo2("object_type ~w is deprecated => ignored", [ObjName], Line),
update_status(ObjName, deprecated),
- definitions_loop(T, false);
+ definitions_loop(T, Data);
%% A obsolete object
definitions_loop([{#mc_object_type{name = ObjName, status = obsolete},
Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("object_type ~w is obsolete => ignored", [ObjName], Line),
%% No need to implement a obsolete object
update_status(ObjName, obsolete),
ensure_macro_imported('OBJECT-TYPE', Line),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
%% Defining a table
definitions_loop([{#mc_object_type{name = NameOfTable,
@@ -475,7 +488,7 @@ definitions_loop([{#mc_object_type{name = NameOfTable,
{#mc_sequence{name = SeqName,
fields = FieldList},
Sline}|ColsEtc],
- Deprecated) ->
+ Data) ->
?vlog("defloop -> "
"[object_type(sequence_of),object_type(type,[1]),sequence]:"
"~n NameOfTable: ~p"
@@ -529,7 +542,89 @@ definitions_loop([{#mc_object_type{name = NameOfTable,
TableME#me{assocList=[{table_info,
TableInfo} | make_reference(Ref)]} |
ColMEs]),
- definitions_loop(RestObjs, Deprecated);
+ definitions_loop(RestObjs, Data);
+
+definitions_loop([{#mc_object_type{name = NameOfTable,
+ syntax = {{sequence_of, SeqName}, _},
+ max_access = Taccess,
+ kind = Kind,
+ status = Tstatus,
+ description = Desc1,
+ units = Tunits,
+ reference = Ref,
+ name_assign = Tindex},
+ Tline},
+ {#mc_object_type{name = NameOfEntry,
+ syntax = {{type, SeqName}, TEline},
+ max_access = 'not-accessible',
+ kind = {table_entry, IndexingInfo},
+ status = Estatus,
+ description = Desc2,
+ units = Eunits,
+ name_assign = {NameOfTable,[Idx]} = BadOID},
+ Eline},
+ {#mc_sequence{name = SeqName,
+ fields = FieldList},
+ Sline}|ColsEtc],
+ #dldata{relaxed_row_name_assign_check = true} = Data)
+ when is_integer(Idx) andalso (Idx > 1) ->
+ ?vlog("defloop -> "
+ "[object_type(sequence_of),object_type(type,[~w]),sequence]:"
+ "~n NameOfTable: ~p"
+ "~n SeqName: ~p"
+ "~n Taccess: ~p"
+ "~n Kind: ~p"
+ "~n Tstatus: ~p"
+ "~n Tindex: ~p"
+ "~n Tunits: ~p"
+ "~n Tline: ~p"
+ "~n NameOfEntry: ~p"
+ "~n TEline: ~p"
+ "~n IndexingInfo: ~p"
+ "~n Estatus: ~p"
+ "~n Eunits: ~p"
+ "~n Ref: ~p"
+ "~n Eline: ~p"
+ "~n FieldList: ~p"
+ "~n Sline: ~p",
+ [Idx,
+ NameOfTable,SeqName,Taccess,Kind,Tstatus,
+ Tindex,Tunits,Tline,
+ NameOfEntry,TEline,IndexingInfo,Estatus,Eunits,Ref,Eline,
+ FieldList,Sline]),
+ update_status(NameOfTable, Tstatus),
+ update_status(NameOfEntry, Estatus),
+ update_status(SeqName, undefined),
+ ensure_macro_imported('OBJECT-TYPE', Tline),
+ ?vwarning2("Bad TableEntry OID definition (~w)",
+ [BadOID], Eline),
+ test_table(NameOfTable,Taccess,Kind,Tindex,Tline),
+ {Tfather,Tsubindex} = Tindex,
+ snmpc_lib:register_oid(Tline,NameOfTable,Tfather,Tsubindex),
+ Description1 = make_description(Desc1),
+ TableME = #me{aliasname = NameOfTable,
+ entrytype = table,
+ access = 'not-accessible',
+ description = Description1,
+ units = Tunits},
+ snmpc_lib:register_oid(TEline,NameOfEntry,NameOfTable,[Idx]),
+ Description2 = make_description(Desc2),
+ TableEntryME = #me{aliasname = NameOfEntry,
+ entrytype = table_entry,
+ assocList = [{table_entry_with_sequence, SeqName}],
+ access = 'not-accessible',
+ description = Description2,
+ units = Eunits},
+ {ColMEs, RestObjs} =
+ define_cols(ColsEtc, 1, FieldList, NameOfEntry, NameOfTable, []),
+ TableInfo = snmpc_lib:make_table_info(Eline, NameOfTable,
+ IndexingInfo, ColMEs),
+ snmpc_lib:add_cdata(#cdata.mes,
+ [TableEntryME,
+ TableME#me{assocList=[{table_info,
+ TableInfo} | make_reference(Ref)]} |
+ ColMEs]),
+ definitions_loop(RestObjs, Data);
definitions_loop([{#mc_object_type{name = NameOfTable,
syntax = {{sequence_of, SeqName},_},
@@ -550,7 +645,7 @@ definitions_loop([{#mc_object_type{name = NameOfTable,
name_assign = BadOID}, Eline},
{#mc_sequence{name = SeqName,
fields = FieldList}, Sline}|ColsEtc],
- Deprecated) ->
+ Data) ->
?vlog("defloop -> "
"[object_type(sequence_of),object_type(type),sequence(fieldList)]:"
"~n NameOfTable: ~p"
@@ -605,13 +700,13 @@ definitions_loop([{#mc_object_type{name = NameOfTable,
TableME#me{assocList=[{table_info,
TableInfo} | make_reference(Ref)]} |
ColMEs]),
- definitions_loop(RestObjs, Deprecated);
+ definitions_loop(RestObjs, Data);
definitions_loop([{#mc_new_type{name = NewTypeName,
macro = Macro,
syntax = OldType,
display_hint = DisplayHint},Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> new_type:"
"~n Macro: ~p"
"~n NewTypeName: ~p"
@@ -632,7 +727,7 @@ definitions_loop([{#mc_new_type{name = NewTypeName,
imported = false,
display_hint = DisplayHint}])
end,
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
%% Plain variable
definitions_loop([{#mc_object_type{name = NewVarName,
@@ -643,7 +738,7 @@ definitions_loop([{#mc_object_type{name = NewVarName,
description = Desc1,
units = Units,
name_assign = {Parent,SubIndex}},Line} |T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> object_type (variable):"
"~n NewVarName: ~p"
"~n Type: ~p"
@@ -672,7 +767,7 @@ definitions_loop([{#mc_object_type{name = NewVarName,
VI = snmpc_lib:make_variable_info(NewME2),
snmpc_lib:add_cdata(#cdata.mes,
[NewME2#me{assocList = [{variable_info, VI}]}]),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_module_identity{name = NewVarName,
last_updated = LU,
@@ -682,7 +777,7 @@ definitions_loop([{#mc_module_identity{name = NewVarName,
revisions = Revs0,
name_assign = {Parent, SubIndex}},
Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> module-identity: "
"~n NewVarName: ~p"
"~n LU: ~p"
@@ -706,13 +801,13 @@ definitions_loop([{#mc_module_identity{name = NewVarName,
snmpc_lib:add_cdata(
#cdata.mes,
[snmpc_lib:makeInternalNode2(false, NewVarName)]),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_internal{name = NewVarName,
macro = Macro,
parent = Parent,
sub_index = SubIndex},Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> internal:"
"~n NewVarName: ~p"
"~n Macro: ~p"
@@ -724,7 +819,7 @@ definitions_loop([{#mc_internal{name = NewVarName,
snmpc_lib:add_cdata(
#cdata.mes,
[snmpc_lib:makeInternalNode2(false, NewVarName)]),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
%% A trap message
definitions_loop([{#mc_trap{name = TrapName,
@@ -732,7 +827,7 @@ definitions_loop([{#mc_trap{name = TrapName,
vars = Variables,
description = Desc1,
num = SpecificCode}, Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> trap:"
"~n TrapName: ~p"
"~n EnterPrise: ~p"
@@ -755,7 +850,7 @@ definitions_loop([{#mc_trap{name = TrapName,
lists:foreach(fun(Trap2) -> snmpc_lib:check_trap(Trap2, Trap, Line) end,
CDATA#cdata.traps),
snmpc_lib:add_cdata(#cdata.traps, [Trap]),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_object_type{name = NameOfEntry,
syntax = Type,
@@ -763,7 +858,7 @@ definitions_loop([{#mc_object_type{name = NameOfEntry,
kind = {table_entry, Index},
status = Estatus,
name_assign = SubIndex},Eline}|T],
- Deprecated) ->
+ Data) ->
?vlog("defloop -> object_type (table_entry):"
"~n NameOfEntry: ~p"
"~n Type: ~p"
@@ -777,7 +872,7 @@ definitions_loop([{#mc_object_type{name = NameOfEntry,
update_status(NameOfEntry, Estatus),
snmpc_lib:print_error("Misplaced TableEntry definition (~w)",
[NameOfEntry], Eline),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_notification{name = TrapName,
status = deprecated}, Line}|T],
@@ -790,19 +885,19 @@ definitions_loop([{#mc_notification{name = TrapName,
definitions_loop([{#mc_notification{name = TrapName,
status = obsolete}, Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> notification ~w is obsolete => ignored",
[TrapName], Line),
update_status(TrapName, obsolete),
ensure_macro_imported('NOTIFICATION-TYPE', Line),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_notification{name = TrapName,
vars = Variables,
status = Status,
description = Desc,
name_assign = {Parent, SubIndex}},Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> notification:"
"~n TrapName: ~p"
"~n Variables: ~p"
@@ -824,13 +919,13 @@ definitions_loop([{#mc_notification{name = TrapName,
oidobjects = Variables},
snmpc_lib:check_notification(Notif, Line, CDATA#cdata.traps),
snmpc_lib:add_cdata(#cdata.traps, [Notif]),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
-definitions_loop([{#mc_module_compliance{name = Name},Line}|T], Deprecated) ->
+definitions_loop([{#mc_module_compliance{name = Name},Line}|T], Data) ->
?vlog2("defloop -> module_compliance:"
"~n Name: ~p", [Name], Line),
ensure_macro_imported('MODULE-COMPLIANCE', Line),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_object_group{name = Name,
objects = GroupObjects,
@@ -838,7 +933,7 @@ definitions_loop([{#mc_object_group{name = Name,
description = Desc,
reference = Ref,
name_assign = {Parent,SubIndex}}, Line}|T],
- Deprecated) ->
+ Data) ->
?vlog2("defloop -> object_group ~p:"
"~n GroupObjects: ~p"
"~n Status: ~p"
@@ -873,7 +968,7 @@ definitions_loop([{#mc_object_group{name = Name,
{objects, GroupObjects}]},
snmpc_lib:add_cdata(#cdata.mes, [NewME]),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_notification_group{name = Name,
objects = GroupObjects,
@@ -882,7 +977,7 @@ definitions_loop([{#mc_notification_group{name = Name,
reference = Ref,
name_assign = {Parent,SubIndex}},
Line}
- |T], Deprecated) ->
+ |T], Data) ->
?vlog2("defloop -> notification_group ~p:"
"~n GroupObjects: ~p"
"~n Status: ~p"
@@ -918,13 +1013,13 @@ definitions_loop([{#mc_notification_group{name = Name,
{objects, GroupObjects}]},
snmpc_lib:add_cdata(#cdata.mes, [NewME]),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_object_type{name = NameOfTable,
syntax = {{sequence_of, SeqName},_},
status = Tstatus},Tline},
Entry, Seq|T],
- Deprecated) ->
+ Data) ->
?vlog("defloop -> object_type (sequence_of): "
"~n NameOfTable: ~p"
"~n SeqName: ~p"
@@ -956,12 +1051,12 @@ definitions_loop([{#mc_object_type{name = NameOfTable,
"Invalid TableEntry '~p' (check STATUS, Sequence name, Oid)",
[safe_elem(1,safe_elem(2,Entry))],Tline)
end,
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_object_type{name = NameOfTable,
syntax = {{sequence_of, SeqName},_},
status = Tstatus},Tline}|T],
- Deprecated) ->
+ Data) ->
?vlog("defloop -> object_type (sequence_of):"
"~n object_type: ~p"
"~n sequence_of: ~p"
@@ -969,24 +1064,24 @@ definitions_loop([{#mc_object_type{name = NameOfTable,
update_status(NameOfTable, Tstatus),
snmpc_lib:print_error("Invalid statements following table ~p.",
[NameOfTable],Tline),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
definitions_loop([{#mc_sequence{name = SeqName,
fields = _FieldList},Line}|T],
- Deprecated) ->
+ Data) ->
?vwarning2("Unexpected SEQUENCE ~w => ignoring", [SeqName], Line),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
-definitions_loop([{Obj,Line}|T], Deprecated) ->
+definitions_loop([{Obj,Line}|T], Data) ->
?vinfo2("defloop -> unknown error"
"~n Obj: ~p", [Obj], Line),
snmpc_lib:print_error("Unknown Error in MIB. "
"Can't describe the error better than this: ~999p ignored."
" Please send a trouble report to [email protected].",
[Obj], Line),
- definitions_loop(T, Deprecated);
+ definitions_loop(T, Data);
-definitions_loop([], _Deprecated) ->
+definitions_loop([], _Data) ->
?vlog("defloop -> done", []),
ok.
diff --git a/lib/snmp/src/compile/snmpc_lib.erl b/lib/snmp/src/compile/snmpc_lib.erl
index b7e84e7d6b..4e5bc69f81 100644
--- a/lib/snmp/src/compile/snmpc_lib.erl
+++ b/lib/snmp/src/compile/snmpc_lib.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -125,7 +125,8 @@ test_kibbles(Kibbles,Line) ->
test_kibbles2([],_,_) ->
ok;
-test_kibbles2([{_KibbleName,BitNo}|Ks],BitNo,Line) ->
+test_kibbles2([{_KibbleName,BitNo}|Ks],ExpectBitNo,Line)
+ when BitNo >= ExpectBitNo ->
test_kibbles2(Ks,BitNo+1,Line);
test_kibbles2([{_KibbleName,BitNo}|_Ks],ExpectBitNo,Line) ->
print_error("Expected kibble no ~p but got ~p.",[ExpectBitNo,BitNo],Line).
diff --git a/lib/snmp/src/misc/snmp_pdus.erl b/lib/snmp/src/misc/snmp_pdus.erl
index 6c80fc3876..dc8900c8cd 100644
--- a/lib/snmp/src/misc/snmp_pdus.erl
+++ b/lib/snmp/src/misc/snmp_pdus.erl
@@ -1,19 +1,19 @@
%%
%% %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
%% 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%
%%
@@ -38,7 +38,10 @@
dec_usm_security_parameters/1,
strip_encrypted_scoped_pdu_data/1,
octet_str_to_bits/1, bits_to_str/1,
- get_encoded_length/1]).
+ get_encoded_length/1,
+ enc_value/2, dec_value/1]).
+
+%% -compile(export_all).
%% Returns the number of octets required to encode Length.
get_encoded_length(Length) ->
@@ -290,12 +293,18 @@ dec_value([68 | Bytes]) ->
{Value, Rest} = dec_oct_str_notag(Bytes),
{{'Opaque', Value}, Rest};
dec_value([70 | Bytes]) ->
+ %% Counter64 is an unsigned 64 but is actually encoded as
+ %% a signed integer 64.
{Value, Rest} = dec_integer_notag(Bytes),
- if Value >= 0, Value =< 18446744073709551615 ->
- {{'Counter64', Value}, Rest};
- true ->
- exit({error, {bad_counter64, Value}})
- end;
+ Value2 =
+ if
+ (Value >= 0) andalso (Value < 16#8000000000000000) ->
+ Value;
+ (Value < 0) ->
+ 18446744073709551615 + Value + 1;
+ true ->
+ exit({error, {bad_counter64, Value}}) end,
+ {{'Counter64', Value2}, Rest};
dec_value([128,0|T]) ->
{{'NULL', noSuchObject}, T};
dec_value([129,0|T]) ->
@@ -633,6 +642,21 @@ enc_value(_Type, endOfMibView) ->
[130,0];
enc_value('NULL', _Val) ->
[5,0];
+enc_value('Counter64', Val) ->
+ Val2 =
+ if
+ Val > 16#ffffffffffffffff ->
+ exit({error, {bad_counter64, Val}});
+ Val >= 16#8000000000000000 ->
+ (Val band 16#7fffffffffffffff) - 16#8000000000000000;
+ Val >= 0 ->
+ Val;
+ true ->
+ exit({error, {bad_counter64, Val}})
+ end,
+ Bytes2 = enc_integer_notag(Val2),
+ Len2 = elength(length(Bytes2)),
+ lists:append([70 | Len2],Bytes2);
enc_value(Type, Val) ->
Bytes2 = enc_integer_notag(Val),
Len2 = elength(length(Bytes2)),
@@ -643,10 +667,7 @@ enc_val_tag('Counter32',Val) when (Val >= 0) andalso (Val =< 4294967295) ->
enc_val_tag('Unsigned32', Val) when (Val >= 0) andalso (Val =< 4294967295) ->
66;
enc_val_tag('TimeTicks', Val) when (Val >= 0) andalso (Val =< 4294967295) ->
- 67;
-enc_val_tag('Counter64', Val) when ((Val >= 0) andalso
- (Val =< 18446744073709551615)) ->
- 70.
+ 67.
%%----------------------------------------------------------------------
diff --git a/lib/snmp/src/misc/snmp_usm.erl b/lib/snmp/src/misc/snmp_usm.erl
index 19be564a8e..3508f9e1c2 100644
--- a/lib/snmp/src/misc/snmp_usm.erl
+++ b/lib/snmp/src/misc/snmp_usm.erl
@@ -198,7 +198,7 @@ des_encrypt(PrivKey, Data, SaltFun) ->
[A,B,C,D,E,F,G,H | PreIV] = PrivKey,
DesKey = [A,B,C,D,E,F,G,H],
Salt = SaltFun(),
- IV = snmp_misc:str_xor(PreIV, Salt),
+ IV = list_to_binary(snmp_misc:str_xor(PreIV, Salt)),
TailLen = (8 - (length(Data) rem 8)) rem 8,
Tail = mk_tail(TailLen),
EncData = crypto:des_cbc_encrypt(DesKey, IV, [Data,Tail]),
@@ -213,13 +213,13 @@ des_decrypt(PrivKey, MsgPrivParams, EncData)
[A,B,C,D,E,F,G,H | PreIV] = PrivKey,
DesKey = [A,B,C,D,E,F,G,H],
Salt = MsgPrivParams,
- IV = snmp_misc:str_xor(PreIV, Salt),
+ IV = list_to_binary(snmp_misc:str_xor(PreIV, Salt)),
%% Whatabout errors here??? E.g. not a mulitple of 8!
Data = binary_to_list(crypto:des_cbc_decrypt(DesKey, IV, EncData)),
Data2 = snmp_pdus:strip_encrypted_scoped_pdu_data(Data),
{ok, Data2};
des_decrypt(PrivKey, BadMsgPrivParams, EncData) ->
- ?vtrace("des_decrypt -> entry with when bad MsgPrivParams"
+ ?vtrace("des_decrypt -> entry when bad MsgPrivParams"
"~n PrivKey: ~p"
"~n BadMsgPrivParams: ~p"
"~n EncData: ~p",
@@ -232,7 +232,7 @@ aes_encrypt(PrivKey, Data, SaltFun) ->
Salt = SaltFun(),
EngineBoots = snmp_framework_mib:get_engine_boots(),
EngineTime = snmp_framework_mib:get_engine_time(),
- IV = [?i32(EngineBoots), ?i32(EngineTime) | Salt],
+ IV = list_to_binary([?i32(EngineBoots), ?i32(EngineTime) | Salt]),
EncData = crypto:aes_cfb_128_encrypt(AesKey, IV, Data),
{ok, binary_to_list(EncData), Salt}.
@@ -240,7 +240,7 @@ aes_decrypt(PrivKey, MsgPrivParams, EncData, EngineBoots, EngineTime)
when length(MsgPrivParams) =:= 8 ->
AesKey = PrivKey,
Salt = MsgPrivParams,
- IV = [?i32(EngineBoots), ?i32(EngineTime) | Salt],
+ IV = list_to_binary([?i32(EngineBoots), ?i32(EngineTime) | Salt]),
%% Whatabout errors here??? E.g. not a mulitple of 8!
Data = binary_to_list(crypto:aes_cfb_128_decrypt(AesKey, IV, EncData)),
Data2 = snmp_pdus:strip_encrypted_scoped_pdu_data(Data),
diff --git a/lib/snmp/test/modules.mk b/lib/snmp/test/modules.mk
index ff848cad1b..6a0c3e9481 100644
--- a/lib/snmp/test/modules.mk
+++ b/lib/snmp/test/modules.mk
@@ -1,20 +1,20 @@
#-*-makefile-*- ; force emacs to enter makefile-mode
# %CopyrightBegin%
-#
-# Copyright Ericsson AB 2004-2009. All Rights Reserved.
-#
+#
+# Copyright Ericsson AB 2004-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%
SUITE_MODULES = \
@@ -57,6 +57,10 @@ MODULES = \
HRL_FILES = snmp_test_lib.hrl
+# These are MIBs that aure used by the compiler test-suite.
+COMPILER_MIB_FILES = \
+ OTP8574-MIB
+
MIB_FILES = \
OLD-SNMPEA-MIB.mib \
OLD-SNMPEA-MIB-v2.mib \
diff --git a/lib/snmp/test/snmp_compiler_test.erl b/lib/snmp/test/snmp_compiler_test.erl
index 9a9127a130..ad77b01362 100644
--- a/lib/snmp/test/snmp_compiler_test.erl
+++ b/lib/snmp/test/snmp_compiler_test.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2003-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2003-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%
%%
@@ -46,7 +46,9 @@
module_identity/1,
tickets/1,
- otp_6150/1
+ otp_6150/1,
+ otp_8574/1,
+ otp_8595/1
]).
@@ -56,6 +58,7 @@
-export([
]).
+
%%----------------------------------------------------------------------
%% Macros
%%----------------------------------------------------------------------
@@ -98,7 +101,9 @@ all(suite) ->
tickets(suite) ->
[
- otp_6150
+ otp_6150,
+ otp_8574,
+ otp_8595
].
@@ -178,6 +183,54 @@ otp_6150(Config) when is_list(Config) ->
ok.
+otp_8574(suite) ->
+ [];
+otp_8574(Config) when is_list(Config) ->
+ put(tname,otp_8574),
+ p("starting with Config: ~p~n", [Config]),
+
+ Dir = ?config(comp_dir, Config),
+ MibDir = ?config(mib_dir, Config),
+ MibFile = join(MibDir, "OTP8574-MIB.mib"),
+
+ p("ensure compile fail without relaxed assign check"),
+ case snmpc:compile(MibFile, [{group_check, false}, {outdir, Dir}]) of
+ {error, compilation_failed} ->
+ p("with relaxed assign check MIB compiles with warning"),
+ case snmpc:compile(MibFile, [{group_check, false},
+ {outdir, Dir},
+ relaxed_row_name_assign_check]) of
+ {ok, _Mib} ->
+ ok;
+ {error, Reason} ->
+ p("unexpected compile failure: "
+ "~n Reason: ~p", [Reason]),
+ exit({unexpected_compile_failure, Reason})
+ end;
+
+ {ok, _} ->
+ p("unexpected compile success"),
+ exit(unexpected_compile_success)
+ end.
+
+
+otp_8595(suite) ->
+ [];
+otp_8595(Config) when is_list(Config) ->
+ put(tname,otp_8595),
+ p("starting with Config: ~p~n", [Config]),
+
+ Dir = ?config(comp_dir, Config),
+ MibDir = ?config(mib_dir, Config),
+ MibFile = join(MibDir, "OTP8595-MIB.mib"),
+ ?line {ok, Mib} =
+ snmpc:compile(MibFile, [{outdir, Dir},
+ {verbosity, trace},
+ {group_check, false}]),
+ io:format("otp_8595 -> Mib: ~n~p~n", [Mib]),
+ ok.
+
+
%%======================================================================
%% Internal functions
%%======================================================================
@@ -373,6 +426,9 @@ join(A,B) ->
%% p(F) ->
%% p(F, []).
+p(F) ->
+ p(F, []).
+
p(F, A) ->
p(get(tname), F, A).
diff --git a/lib/snmp/test/snmp_manager_config_test.erl b/lib/snmp/test/snmp_manager_config_test.erl
index fcb3d7e30c..d5dc1387f7 100644
--- a/lib/snmp/test/snmp_manager_config_test.erl
+++ b/lib/snmp/test/snmp_manager_config_test.erl
@@ -1444,10 +1444,9 @@ start_with_invalid_usm_conf_file1(Conf) when is_list(Conf) ->
p("[test 54] write usm config file with invalid auth-key (4)"),
Usm54 = setelement(4, Usm51, "[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,kalle]"),
write_usm_conf(ConfDir, [Usm54]),
- %% ?line ok = crypto:start(), %% Varf�r k�r den redan?
- ?line crypto:start(), %% Make sure it's started...
+ ?line maybe_start_crypto(), %% Make sure it's started...
?line {error, Reason54} = config_start(Opts),
- ?line ok = crypto:stop(),
+ ?line ok = maybe_stop_crypto(),
p("start failed (as expected): ~p", [Reason54]),
?line {failed_check, _, _, _, {invalid_auth_key, _}} = Reason54,
await_config_not_running(),
@@ -1492,21 +1491,35 @@ start_with_invalid_usm_conf_file1(Conf) when is_list(Conf) ->
p("[test 59] write usm config file with invalid auth-key (9)"),
Usm59 = setelement(4, Usm57, "[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,ka]"),
write_usm_conf(ConfDir, [Usm59]),
- ?line ok = crypto:start(),
+ ?line ok = maybe_start_crypto(),
?line {error, Reason59} = config_start(Opts),
- ?line ok = crypto:stop(),
+ ?line ok = maybe_stop_crypto(),
p("start failed (as expected): ~p", [Reason59]),
?line {failed_check, _, _, _, {invalid_auth_key, _}} = Reason59,
await_config_not_running(),
%% --
- p("[test 5A] write usm config file with valid auth-key when crypto not started (10)"),
- Usm5A = setelement(4, Usm57, "[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]"),
- write_usm_conf(ConfDir, [Usm5A]),
- ?line {error, Reason5A} = config_start(Opts),
- p("start failed (as expected): ~p", [Reason5A]),
- ?line {failed_check, _, _, _, {unsupported_crypto, _}} = Reason5A,
- await_config_not_running(),
+ %% <CRYPTO-MODIFICATIONS>
+ %% The crypto application do no longer need to be started
+ %% explicitly (all of it is as of R14 implemented with NIFs).
+ case (catch crypto:version()) of
+ {'EXIT', {undef, _}} ->
+ p("[test 5A] write usm config file with valid auth-key "
+ "when crypto not started (10)"),
+ Usm5A = setelement(4,
+ Usm57,
+ "[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]"),
+ write_usm_conf(ConfDir, [Usm5A]),
+ ?line {error, Reason5A} = config_start(Opts),
+ p("start failed (as expected): ~p", [Reason5A]),
+ ?line {failed_check, _, _, _, {unsupported_crypto, _}} = Reason5A,
+ await_config_not_running();
+ _ ->
+ %% This function is only present in version 2.0 or greater.
+ %% The crypto app no longer needs to be explicitly started
+ ok
+ end,
+ %% </CRYPTO-MODIFICATIONS>
%% --
p("[test 61] write usm config file with invalid priv-protocol (1)"),
@@ -1566,9 +1579,9 @@ start_with_invalid_usm_conf_file1(Conf) when is_list(Conf) ->
p("[test 74] write usm config file with invalid priv-key (4)"),
Usm74 = setelement(6, Usm71, "[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,kalle]"),
write_usm_conf(ConfDir, [Usm74]),
- ?line ok = crypto:start(),
+ ?line ok = maybe_start_crypto(),
?line {error, Reason74} = config_start(Opts),
- ?line ok = crypto:stop(),
+ ?line ok = maybe_stop_crypto(),
p("start failed (as expected): ~p", [Reason74]),
?line {failed_check, _, _, _, {invalid_priv_key, _}} = Reason74,
await_config_not_running(),
@@ -1592,15 +1605,27 @@ start_with_invalid_usm_conf_file1(Conf) when is_list(Conf) ->
await_config_not_running(),
%% --
- p("[test 77] write usm config file with valid priv-key when crypto not started (7)"),
- Usm77 = setelement(6, Usm71, "[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6]"),
- write_usm_conf(ConfDir, [Usm77]),
- ?line {error, Reason77} = config_start(Opts),
- p("start failed (as expected): ~p", [Reason77]),
- ?line {failed_check, _, _, _, {unsupported_crypto, _}} = Reason77,
- await_config_not_running(),
+ %% <CRYPTO-MODIFICATIONS>
+ %% The crypto application do no longer need to be started
+ %% explicitly (all of it is as of R14 implemented with NIFs).
+ case (catch crypto:version()) of
+ {'EXIT', {undef, _}} ->
+ p("[test 77] write usm config file with valid priv-key "
+ "when crypto not started (7)"),
+ Usm77 = setelement(6, Usm71, "[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6]"),
+ write_usm_conf(ConfDir, [Usm77]),
+ ?line {error, Reason77} = config_start(Opts),
+ p("start failed (as expected): ~p", [Reason77]),
+ ?line {failed_check, _, _, _, {unsupported_crypto, _}} = Reason77,
+ await_config_not_running();
+ _ ->
+ %% This function is only present in version 2.0 or greater.
+ %% The crypto app no longer needs to be explicitly started
+ ok
+ end,
+ %% </CRYPTO-MODIFICATIONS>
- %% --
+ %% --
p("[test 78] write usm config file with invalid usm (1)"),
write_usm_conf2(ConfDir, "{\"bmkEngine\", \"swiusmcf\"}."),
?line {error, Reason81} = config_start(Opts),
@@ -2676,6 +2701,27 @@ write_conf_file(Dir, File, Str) ->
file:close(Fd).
+maybe_start_crypto() ->
+ case (catch crypto:version()) of
+ {'EXIT', {undef, _}} ->
+ %% This is the version of crypto before the NIFs...
+ ?CRYPTO_START();
+ _ ->
+ %% No need to start this version of crypto..
+ ok
+ end.
+
+maybe_stop_crypto() ->
+ case (catch crypto:version()) of
+ {'EXIT', {undef, _}} ->
+ %% This is the version of crypto before the NIFs...
+ crypto:stop();
+ _ ->
+ %% There is nothing to stop in this version of crypto..
+ ok
+ end.
+
+
%% ------
str(X) ->
diff --git a/lib/snmp/test/snmp_pdus_test.erl b/lib/snmp/test/snmp_pdus_test.erl
index d5add50f52..6dc5b779aa 100644
--- a/lib/snmp/test/snmp_pdus_test.erl
+++ b/lib/snmp/test/snmp_pdus_test.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2003-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2003-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%
%%
@@ -37,6 +37,7 @@
all/1,
tickets/1,
otp7575/1,
+ otp8563/1,
init_per_testcase/2, fin_per_testcase/2
]).
@@ -66,6 +67,7 @@ init_per_testcase(_Case, Config) when is_list(Config) ->
fin_per_testcase(_Case, Config) when is_list(Config) ->
Config.
+
%%======================================================================
%% Test case definitions
%%======================================================================
@@ -76,7 +78,8 @@ all(suite) ->
tickets(suite) ->
[
- otp7575
+ otp7575,
+ otp8563
].
@@ -118,6 +121,55 @@ otp7575(Config) when is_list(Config) ->
ok.
+otp8563(suite) -> [];
+otp8563(doc) -> ["OTP-8563"];
+otp8563(Config) when is_list(Config) ->
+ Val1 = 16#7fffffffffffffff,
+ io:format("try encode and decode ~w~n", [Val1]),
+ Enc1 = snmp_pdus:enc_value('Counter64', Val1),
+ {{'Counter64', Val1}, []} = snmp_pdus:dec_value(Enc1),
+
+ Val2 = Val1 + 1,
+ io:format("try encode and decode ~w~n", [Val2]),
+ Enc2 = snmp_pdus:enc_value('Counter64', Val2),
+ {{'Counter64', Val2}, []} = snmp_pdus:dec_value(Enc2),
+
+ Val3 = Val2 + 1,
+ io:format("try encode and decode ~w~n", [Val3]),
+ Enc3 = snmp_pdus:enc_value('Counter64', Val3),
+ {{'Counter64', Val3}, []} = snmp_pdus:dec_value(Enc3),
+
+ Val4 = 16#fffffffffffffffe,
+ io:format("try encode and decode ~w~n", [Val4]),
+ Enc4 = snmp_pdus:enc_value('Counter64', Val4),
+ {{'Counter64', Val4}, []} = snmp_pdus:dec_value(Enc4),
+
+ Val5 = Val4 + 1,
+ io:format("try encode and decode ~w~n", [Val5]),
+ Enc5 = snmp_pdus:enc_value('Counter64', Val5),
+ {{'Counter64', Val5}, []} = snmp_pdus:dec_value(Enc5),
+
+ Val6 = 16#ffffffffffffffff + 1,
+ io:format("try and fail to encode ~w~n", [Val6]),
+ case (catch snmp_pdus:enc_value('Counter64', Val6)) of
+ {'EXIT', {error, {bad_counter64, 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('Counter64', Val7)) of
+ {'EXIT', {error, {bad_counter64, Val7}}} ->
+ ok;
+ Unexpected7 ->
+ exit({unexpected_encode_result, Unexpected7, Val7})
+ end,
+
+ ok.
+
+
%%======================================================================
%% Internal functions
%%======================================================================
diff --git a/lib/snmp/test/snmp_test_data/OLD-SNMPEA-MIB.mib b/lib/snmp/test/snmp_test_data/OLD-SNMPEA-MIB.mib
index dd90d0ab50..2ba1a6fd67 100644
--- a/lib/snmp/test/snmp_test_data/OLD-SNMPEA-MIB.mib
+++ b/lib/snmp/test/snmp_test_data/OLD-SNMPEA-MIB.mib
@@ -12,18 +12,12 @@ OLD-SNMPEA-MIB DEFINITIONS ::= BEGIN
;
-- MODULE-IDENTITY
--- LAST-UPDATED "9709220900Z"
--- ORGANIZATION "ETX/DN/S"
--- CONTACT-INFO
--- " Martin Bj�rklund
---
--- Postal: ERICSSON SOFTWARE TECHNOLOGY AB
--- ERLANG SYSTEMS
--- Box 1214
--- S-164 28 KISTA, SWEDEN
---
--- Tel: +46 8 719 20 89
--- E-mail: [email protected]"
+-- LAST-UPDATED "1004200000Z"
+-- ORGANIZATION "Erlang/OTP"
+-- CONTACT-INFO ""
+-- DESCRIPTION
+-- "Header cleanup."
+-- REVISION "1004200000Z"
-- DESCRIPTION
-- "This MIB module defines MIB objects for the SNMPEA
-- component in OTP."
diff --git a/lib/snmp/test/snmp_test_data/OTP8574-MIB.mib b/lib/snmp/test/snmp_test_data/OTP8574-MIB.mib
new file mode 100644
index 0000000000..b5e5ed1848
--- /dev/null
+++ b/lib/snmp/test/snmp_test_data/OTP8574-MIB.mib
@@ -0,0 +1,77 @@
+OTP8574-MIB DEFINITIONS ::= BEGIN
+
+IMPORTS
+ MODULE-IDENTITY, OBJECT-TYPE, enterprises, IpAddress FROM SNMPv2-SMI
+ RowStatus FROM SNMPv2-TC
+ ;
+
+otp8574MIB MODULE-IDENTITY
+ LAST-UPDATED "1004200000Z"
+ ORGANIZATION "Erlang/OTP"
+ CONTACT-INFO "www.erlang.org"
+ DESCRIPTION "The MIB module is used for testing a compiler feature"
+ ::= { otpSnmp 1 }
+
+ericsson OBJECT IDENTIFIER ::= { enterprises 193 }
+otp OBJECT IDENTIFIER ::= { ericsson 19 }
+otpApplications OBJECT IDENTIFIER ::= { otp 3 }
+otpSnmp OBJECT IDENTIFIER ::= { otpApplications 3 }
+
+testMIBObjects OBJECT IDENTIFIER ::= { otp8574MIB 1 }
+
+testMIBObjectGroup OBJECT IDENTIFIER ::= { testMIBObjects 1 }
+
+example-Table OBJECT-TYPE
+ SYNTAX SEQUENCE OF ExampleEntry
+ MAX-ACCESS not-accessible
+ STATUS current
+ DESCRIPTION "An example table"
+ ::= { testMIBObjectGroup 1 }
+
+example-Entry OBJECT-TYPE
+ SYNTAX ExampleEntry
+ MAX-ACCESS not-accessible
+ STATUS current
+ DESCRIPTION "Example table entry"
+ INDEX { exampleIndex }
+ ::= { example-Table 5 }
+
+ExampleEntry ::= SEQUENCE {
+ exampleIndex INTEGER,
+ exampleColumn OCTET STRING,
+ exampleNotAccessible OCTET STRING,
+ exampleRowStatus RowStatus
+}
+
+exampleIndex OBJECT-TYPE
+ SYNTAX INTEGER (1..100)
+ MAX-ACCESS read-write
+ STATUS current
+ DESCRIPTION "The index for this entry."
+ ::= { example-Entry 1 }
+
+exampleColumn OBJECT-TYPE
+ SYNTAX OCTET STRING
+ MAX-ACCESS read-write
+ STATUS current
+ DESCRIPTION
+ "Example table column"
+ ::= { example-Entry 2 }
+
+exampleNotAccessible OBJECT-TYPE
+ SYNTAX OCTET STRING
+ MAX-ACCESS not-accessible
+ STATUS current
+ DESCRIPTION
+ "Example table column"
+ ::= { example-Entry 3 }
+
+exampleRowStatus OBJECT-TYPE
+ SYNTAX RowStatus
+ MAX-ACCESS read-write
+ STATUS current
+ DESCRIPTION
+ "Example table RowStatus"
+ ::= { example-Entry 4 }
+
+END
diff --git a/lib/snmp/test/snmp_test_data/OTP8595-MIB.mib b/lib/snmp/test/snmp_test_data/OTP8595-MIB.mib
new file mode 100644
index 0000000000..23245bce37
--- /dev/null
+++ b/lib/snmp/test/snmp_test_data/OTP8595-MIB.mib
@@ -0,0 +1,45 @@
+OTP8595-MIB DEFINITIONS ::= BEGIN
+
+IMPORTS
+ MODULE-IDENTITY, OBJECT-TYPE, snmpModules, mib-2
+ FROM SNMPv2-SMI
+ DisplayString, TestAndIncr, TimeStamp, RowStatus, TruthValue,
+ TEXTUAL-CONVENTION
+ FROM SNMPv2-TC
+ MODULE-COMPLIANCE, OBJECT-GROUP, NOTIFICATION-GROUP
+ FROM SNMPv2-CONF
+ sysLocation, sysContact
+ FROM SNMPv2-MIB
+ ;
+
+otp8595MIB MODULE-IDENTITY
+ LAST-UPDATED "1004210000Z"
+ ORGANIZATION ""
+ CONTACT-INFO
+ ""
+ DESCRIPTION
+ "Test mib for OTP-8595"
+ ::= { snmpModules 1 }
+
+
+test OBJECT IDENTIFIER ::= { mib-2 15 }
+
+bits1 OBJECT-TYPE
+ SYNTAX BITS {
+ b0(0),
+ b1(1),
+ b2(2),
+ -- The following are extensions to the original set of
+ -- labels. The extensions start at an octet boundary.
+ -- So for bits 3 - 7, one MUST set them to zero on send
+ -- and one MUST ignore them on receipt.
+ b8(8),
+ b9(9)
+ }
+ MAX-ACCESS read-write
+ STATUS current
+ DESCRIPTION
+ ""
+ ::= { test 1 }
+
+END
diff --git a/lib/snmp/test/snmp_test_mgr_misc.erl b/lib/snmp/test/snmp_test_mgr_misc.erl
index e6220f9241..ef1ba0b948 100644
--- a/lib/snmp/test/snmp_test_mgr_misc.erl
+++ b/lib/snmp/test/snmp_test_mgr_misc.erl
@@ -1,19 +1,19 @@
%%
%% %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
%% 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%
%%
@@ -101,8 +101,8 @@ init_packet(Parent, SnmpMgr,
init_debug(Dbg) when is_atom(Dbg) ->
put(debug,Dbg),
- put(verbosity,silence);
- %% put(verbosity,trace);
+ %% put(verbosity, silence);
+ put(verbosity, trace);
init_debug(DbgOptions) when is_list(DbgOptions) ->
case lists:keysearch(debug, 1, DbgOptions) of
{value, {_, Dbg}} when is_atom(Dbg) ->
diff --git a/lib/snmp/vsn.mk b/lib/snmp/vsn.mk
index 50c72b33b5..2fccc733e6 100644
--- a/lib/snmp/vsn.mk
+++ b/lib/snmp/vsn.mk
@@ -17,11 +17,13 @@
#
# %CopyrightEnd%
-SNMP_VSN = 4.16.1
+SNMP_VSN = 4.16.2
PRE_VSN =
APP_VSN = "snmp-$(SNMP_VSN)$(PRE_VSN)"
-TICKETS = OTP-8480 OTP-8481
+TICKETS = OTP-8563 OTP-8574 OTP-8594 OTP-8595
+
+TICKETS_4_16_1 = OTP-8480 OTP-8481
TICKETS_4_16 = \
OTP-8395 \
diff --git a/lib/ssh/Makefile b/lib/ssh/Makefile
index 1ad69a9ca1..b8c7eebcc1 100644
--- a/lib/ssh/Makefile
+++ b/lib/ssh/Makefile
@@ -1,19 +1,19 @@
#
# %CopyrightBegin%
-#
-# Copyright Ericsson AB 2004-2009. All Rights Reserved.
-#
+#
+# Copyright Ericsson AB 2004-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%
#
diff --git a/lib/ssh/doc/src/book.xml b/lib/ssh/doc/src/book.xml
index 0375c441af..fcec1d6f70 100644
--- a/lib/ssh/doc/src/book.xml
+++ b/lib/ssh/doc/src/book.xml
@@ -4,7 +4,7 @@
<book xmlns:xi="http://www.w3.org/2001/XInclude">
<header titlestyle="normal">
<copyright>
- <year>2005</year><year>2009</year>
+ <year>2005</year><year>2010</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -13,12 +13,12 @@
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>SSH</title>
diff --git a/lib/ssh/doc/src/notes.xml b/lib/ssh/doc/src/notes.xml
index 0ce83fa5d1..67a226f726 100644
--- a/lib/ssh/doc/src/notes.xml
+++ b/lib/ssh/doc/src/notes.xml
@@ -29,7 +29,7 @@
<file>notes.xml</file>
</header>
- <section><title>Ssh 1.1.9</title>
+ <section><title>Ssh 2.0</title>
<section><title>Fixed Bugs and Malfunctions</title>
<list>
@@ -46,6 +46,8 @@
<p>The configuration parameter ip_v6_disabled is now available,
which makes it possible for the user to alter the IP version
SSH shall use.</p>
+ <p>
+ *** POTENTIAL INCOMPATIBILITY ***</p>
<p>Own Id: OTP-8535 Aux Id:</p>
</item>
<item>
@@ -57,6 +59,13 @@
message is not handled correctly.</p>
<p>Own Id: OTP-8524 Aux Id:</p>
</item>
+ <item>
+ <p>Removed deprecated modules (ssh_ssh, ssh_sshd and ssh_cm) and
+ functions (ssh_sftp:connect and ssh_sftp:stop).</p>
+ <p>
+ *** POTENTIAL INCOMPATIBILITY ***</p>
+ <p>Own Id: OTP-8596 Aux Id:</p>
+ </item>
</list>
</section>
diff --git a/lib/ssh/doc/src/ref_man.xml b/lib/ssh/doc/src/ref_man.xml
index c05c3051b0..9ab56b28ec 100644
--- a/lib/ssh/doc/src/ref_man.xml
+++ b/lib/ssh/doc/src/ref_man.xml
@@ -4,7 +4,7 @@
<application xmlns:xi="http://www.w3.org/2001/XInclude">
<header>
<copyright>
- <year>2004</year><year>2009</year>
+ <year>2004</year><year>2010</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -13,12 +13,12 @@
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>SSH Reference Manual</title>
diff --git a/lib/ssh/doc/src/ssh_sftp.xml b/lib/ssh/doc/src/ssh_sftp.xml
index 208b2b4e72..c1f75461b1 100644
--- a/lib/ssh/doc/src/ssh_sftp.xml
+++ b/lib/ssh/doc/src/ssh_sftp.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2005</year><year>2009</year>
+ <year>2005</year><year>2010</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -13,12 +13,12 @@
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>ssh_sftp</title>
diff --git a/lib/ssh/doc/src/ssh_sftpd.xml b/lib/ssh/doc/src/ssh_sftpd.xml
index c857983565..b3d64e72b4 100644
--- a/lib/ssh/doc/src/ssh_sftpd.xml
+++ b/lib/ssh/doc/src/ssh_sftpd.xml
@@ -4,7 +4,7 @@
<erlref>
<header>
<copyright>
- <year>2005</year><year>2009</year>
+ <year>2005</year><year>2010</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -13,12 +13,12 @@
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>ssh_sftpd</title>
diff --git a/lib/ssh/examples/Makefile b/lib/ssh/examples/Makefile
index cd8b3c797a..5f17542fb8 100644
--- a/lib/ssh/examples/Makefile
+++ b/lib/ssh/examples/Makefile
@@ -1,19 +1,19 @@
#
# %CopyrightBegin%
-#
-# Copyright Ericsson AB 2005-2009. All Rights Reserved.
-#
+#
+# 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%
#
diff --git a/lib/ssh/examples/ssh_sample_cli.erl b/lib/ssh/examples/ssh_sample_cli.erl
index 2505c1b759..6f3092e567 100644
--- a/lib/ssh/examples/ssh_sample_cli.erl
+++ b/lib/ssh/examples/ssh_sample_cli.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -30,19 +30,15 @@
%% our command functions
-export([cli_prime/1, cli_primes/1, cli_gcd/2, cli_lcm/2,
cli_factors/1, cli_exit/0, cli_rho/1, cli_help/0,
- cli_crash/0, cli_users/0, cli_self/0,
- cli_user/0, cli_host/0]).
-
-%% imports
--import(lists, [reverse/1, reverse/2, seq/2, prefix/2]).
--import(math, [sqrt/1]).
-
+ cli_crash/0, cli_self/0, cli_user/0, cli_host/0]).
listen(Port) ->
listen(Port, []).
listen(Port, Options) ->
- ssh_cli:listen(fun(U, H) -> start_our_shell(U, H) end, Port, Options).
+ crypto:start(),
+ ssh:start(),
+ ssh:daemon(any, Port, [{shell, fun(U, H) -> start_our_shell(U, H) end} | Options]).
%% our_routines
our_routines() ->
@@ -56,7 +52,6 @@ our_routines() ->
{"prime", cli_prime, "<int> check for primality"},
{"primes", cli_primes, "<int> print all primes up to <int>"},
{"rho", cli_rho, "<int> prime factors using rho's alg."},
- {"who", cli_users, " lists users"},
{"user", cli_user, " print name of user"},
{"host", cli_host, " print host addr"},
{"self", cli_self, " print my pid"}
@@ -85,11 +80,11 @@ our_routines() ->
common_prefix([C | R1], [C | R2], Acc) ->
common_prefix(R1, R2, [C | Acc]);
common_prefix(_, _, Acc) ->
- reverse(Acc).
+ lists:reverse(Acc).
%% longest prefix in a list, given a prefix
longest_prefix(List, Prefix) ->
- case [A || {A, _, _} <- List, prefix(Prefix, A)] of
+ case [A || {A, _, _} <- List, lists:prefix(Prefix, A)] of
[] ->
{none, List};
[S | Rest] ->
@@ -112,7 +107,7 @@ longest_prefix(List, Prefix) ->
expand([$ | _]) ->
{no, "", []};
expand(RevBefore) ->
- Before = reverse(RevBefore),
+ Before = lists:reverse(RevBefore),
case longest_prefix(our_routines(), Before) of
{prefix, P, [_]} ->
{yes, P ++ " ", []};
@@ -139,22 +134,27 @@ start_our_shell(User, Peer) ->
%%% an ordinary Read-Eval-Print-loop
our_shell_loop() ->
% Read
- Line = io:get_line({format, "CLI> ", []}),
+ Line = io:get_line("CLI> "),
% Eval
Result = eval_cli(Line),
% Print
io:format("---> ~p\n", [Result]),
case Result of
- done -> exit(normal);
- crash -> 1 / 0;
- _ -> our_shell_loop()
+ done ->
+ exit(normal);
+ crash ->
+ 1 / 0;
+ _ ->
+ our_shell_loop()
end.
%%% translate a command to a function
command_to_function(Command) ->
case lists:keysearch(Command, 1, our_routines()) of
- {value, {_, Proc, _}} -> Proc;
- false -> unknown_cli
+ {value, {_, Proc, _}} ->
+ Proc;
+ false ->
+ unknown_cli
end.
%%% evaluate a command line
@@ -209,14 +209,6 @@ cli_user() ->
cli_host() ->
get(peer_name).
-cli_users() ->
- case ssh_userauth:get_auth_users() of
- {ok, UsersPids} ->
- UsersPids; % [U || {U, _} <- UsersPids];
- E ->
- E
- end.
-
cli_self() ->
self().
@@ -243,7 +235,7 @@ cli_help() ->
%% a quite simple Sieve of Erastothenes (not tail-recursive, though)
primes(Size) ->
- era(sqrt(Size), seq(2,Size)).
+ era(math:sqrt(Size), lists:seq(2,Size)).
era(Max, [H|T]) when H =< Max ->
[H | era(Max, sieve([H|T], H))];
@@ -267,7 +259,7 @@ next_prime(Primes, P) ->
next_prime1(Primes, P) ->
P1 = P + 2,
- case divides(Primes, trunc(sqrt(P1)), P1) of
+ case divides(Primes, trunc(math:sqrt(P1)), P1) of
false -> P1;
true -> next_prime1(Primes, P1)
end.
@@ -282,7 +274,7 @@ divides([_ | R], Nsqrt, N) ->
divides(R, Nsqrt, N).
is_prime(P) ->
- lists:all(fun(A) -> P rem A =/= 0 end, primes(trunc(sqrt(P)))).
+ lists:all(fun(A) -> P rem A =/= 0 end, primes(trunc(math:sqrt(P)))).
%% Normal gcd, Euclid
gcd(R, Q) when abs(Q) < abs(R) -> gcd1(Q,R);
@@ -300,17 +292,17 @@ lcm(R, Q) ->
%%% Prime factors of a number (na�ve implementation)
factors(N) ->
- Nsqrt = trunc(sqrt(N)),
+ Nsqrt = trunc(math:sqrt(N)),
factors([], N, 2, Nsqrt, []).
factors(_Primes, N, Prime, Nsqrt, Factors) when Prime > Nsqrt ->
- reverse(Factors, [N]);
+ lists:reverse(Factors, [N]);
factors(Primes, N, Prime, Nsqrt, Factors) ->
case N rem Prime of
0 ->
%%io:format("factor ------- ~p\n", [Prime]),
N1 = N div Prime,
- factors(Primes, N1, Prime, trunc(sqrt(N1)), [Prime|Factors]);
+ factors(Primes, N1, Prime, trunc(math:sqrt(N1)), [Prime|Factors]);
_ ->
Primes1 = Primes ++ [Prime],
Prime1 = next_prime(Primes1, Prime),
diff --git a/lib/ssh/src/Makefile b/lib/ssh/src/Makefile
index 7abf06e52b..42880fa80b 100644
--- a/lib/ssh/src/Makefile
+++ b/lib/ssh/src/Makefile
@@ -1,19 +1,19 @@
#
# %CopyrightBegin%
-#
-# Copyright Ericsson AB 2004-2009. All Rights Reserved.
-#
+#
+# Copyright Ericsson AB 2004-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%
#
@@ -56,7 +56,6 @@ MODULES= \
ssh_auth\
ssh_bits \
ssh_cli \
- ssh_cm \
ssh_dsa \
ssh_file \
ssh_io \
@@ -67,8 +66,6 @@ MODULES= \
ssh_sftpd \
ssh_sftpd_file\
ssh_sftpd_file_api \
- ssh_ssh \
- ssh_sshd \
ssh_transport \
ssh_userreg \
ssh_xfer
diff --git a/lib/ssh/src/ssh.app.src b/lib/ssh/src/ssh.app.src
index 9319f39591..8a3e15841f 100644
--- a/lib/ssh/src/ssh.app.src
+++ b/lib/ssh/src/ssh.app.src
@@ -14,7 +14,6 @@
ssh_cli,
ssh_channel,
ssh_channel_sup,
- ssh_cm,
ssh_connection,
ssh_connection_handler,
ssh_connection_manager,
@@ -32,8 +31,6 @@
ssh_sftpd,
ssh_sftpd_file,
ssh_sftpd_file_api,
- ssh_ssh,
- ssh_sshd,
ssh_subsystem_sup,
ssh_sup,
ssh_system_sup,
diff --git a/lib/ssh/src/ssh.appup.src b/lib/ssh/src/ssh.appup.src
index 8f4b46051d..21f7508555 100644
--- a/lib/ssh/src/ssh.appup.src
+++ b/lib/ssh/src/ssh.appup.src
@@ -19,36 +19,8 @@
{"%VSN%",
[
- {"1.1.8", [{load_module, ssh_connection_manager, soft_purge, soft_purge, []},
- {load_module, ssh, soft_purge, soft_purge, []},
- {load_module, ssh_cli, soft_purge, soft_purge, []},
- {load_module, ssh_connection, soft_purge, soft_purge, []}]},
- {"1.1.7", [{load_module, ssh_connection_handler, soft_purge, soft_purge, []},
- {load_module, ssh_connection, soft_purge, soft_purge, []},
- {load_module, ssh, soft_purge, soft_purge, []},
- {load_module, ssh_cli, soft_purge, soft_purge, []},
- {load_module, ssh_connection_manager, soft_purge, soft_purge, []}]},
- {"1.1.6", [{restart_application, ssh}]},
- {"1.1.5", [{restart_application, ssh}]},
- {"1.1.4", [{restart_application, ssh}]},
- {"1.1.3", [{restart_application, ssh}]},
- {"1.1.2", [{restart_application, ssh}]}
],
[
- {"1.1.8", [{load_module, ssh_connection_manager, soft_purge, soft_purge, []},
- {load_module, ssh, soft_purge, soft_purge, []},
- {load_module, ssh_cli, soft_purge, soft_purge, []},
- {load_module, ssh_connection, soft_purge, soft_purge, []}]},
- {"1.1.7", [{load_module, ssh_connection_handler, soft_purge, soft_purge, []},
- {load_module, ssh_connection, soft_purge, soft_purge, []},
- {load_module, ssh, soft_purge, soft_purge, []},
- {load_module, ssh_cli, soft_purge, soft_purge, []},
- {load_module, ssh_connection_manager, soft_purge, soft_purge, []}]},
- {"1.1.6", [{restart_application, ssh}]},
- {"1.1.5", [{restart_application, ssh}]},
- {"1.1.4", [{restart_application, ssh}]},
- {"1.1.3", [{restart_application, ssh}]},
- {"1.1.2", [{restart_application, ssh}]}
]
}.
diff --git a/lib/ssh/src/ssh.hrl b/lib/ssh/src/ssh.hrl
index 0e4285295c..ac249b05e3 100644
--- a/lib/ssh/src/ssh.hrl
+++ b/lib/ssh/src/ssh.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2004-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2004-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%
%%
diff --git a/lib/ssh/src/ssh_acceptor.erl b/lib/ssh/src/ssh_acceptor.erl
index d19fee14e1..57229daa27 100644
--- a/lib/ssh/src/ssh_acceptor.erl
+++ b/lib/ssh/src/ssh_acceptor.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_acceptor_sup.erl b/lib/ssh/src/ssh_acceptor_sup.erl
index 707e3d3a5e..f37e1fe4ff 100644
--- a/lib/ssh/src/ssh_acceptor_sup.erl
+++ b/lib/ssh/src/ssh_acceptor_sup.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_app.erl b/lib/ssh/src/ssh_app.erl
index 5793d3a321..38659b1a2d 100644
--- a/lib/ssh/src/ssh_app.erl
+++ b/lib/ssh/src/ssh_app.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2004-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2004-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%
%%
diff --git a/lib/ssh/src/ssh_auth.erl b/lib/ssh/src/ssh_auth.erl
index aa74528544..9dbd95886e 100644
--- a/lib/ssh/src/ssh_auth.erl
+++ b/lib/ssh/src/ssh_auth.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_auth.hrl b/lib/ssh/src/ssh_auth.hrl
index 80c5a6819b..7d7bad4436 100644
--- a/lib/ssh/src/ssh_auth.hrl
+++ b/lib/ssh/src/ssh_auth.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_bits.erl b/lib/ssh/src/ssh_bits.erl
index 21ddc5e8fe..399581a0fd 100755
--- a/lib/ssh/src/ssh_bits.erl
+++ b/lib/ssh/src/ssh_bits.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_channel.erl b/lib/ssh/src/ssh_channel.erl
index 3d67065ee1..8a49a44a6c 100644
--- a/lib/ssh/src/ssh_channel.erl
+++ b/lib/ssh/src/ssh_channel.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_channel_sup.erl b/lib/ssh/src/ssh_channel_sup.erl
index c184fed627..0093bce9c2 100644
--- a/lib/ssh/src/ssh_channel_sup.erl
+++ b/lib/ssh/src/ssh_channel_sup.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_cm.erl b/lib/ssh/src/ssh_cm.erl
deleted file mode 100755
index c4d535df9a..0000000000
--- a/lib/ssh/src/ssh_cm.erl
+++ /dev/null
@@ -1,237 +0,0 @@
-%%
-%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-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%
-%%
-
-%%
-
-%%% Description : Backwards compatibility wrapper
-
--module(ssh_cm).
-
--include("ssh.hrl").
--include("ssh_connect.hrl").
-
-%% -define(DEFAULT_PACKET_SIZE, 32768).
-%% -define(DEFAULT_WINDOW_SIZE, 2*?DEFAULT_PACKET_SIZE).
-%%-define(DEFAULT_TIMEOUT, 5000).
-
--export([connect/1, connect/2, connect/3]).
--export([listen/2, listen/3, listen/4, stop_listener/1]).
--export([stop/1]).
-
--deprecated({connect, 1, next_major_release}).
--deprecated({connect, 2, next_major_release}).
--deprecated({connect, 3, next_major_release}).
--deprecated({listen, 2, next_major_release}).
--deprecated({listen, 3, next_major_release}).
--deprecated({listen, 4, next_major_release}).
--deprecated({stop_listener, 1, next_major_release}).
--deprecated({stop, 1, next_major_release}).
-
--export([adjust_window/3, attach/2, attach/3, detach/2,
- tcpip_forward/3, cancel_tcpip_forward/3, direct_tcpip/6,
- direct_tcpip/8, close/2, shell/2, exec/4,
- send/3, send/4,
- send_ack/3, send_ack/4, send_ack/5, send_eof/2,
- session_open/2, session_open/4, subsystem/4,
- open_pty/3, open_pty/7, open_pty/9,
- set_user_ack/4,
- setenv/5, signal/3, winch/4]).
-
--deprecated({adjust_window, 3, next_major_release}).
--deprecated({attach, 2, next_major_release}).
--deprecated({attach, 3, next_major_release}).
--deprecated({detach, 2, next_major_release}).
--deprecated({tcpip_forward, 3, next_major_release}).
--deprecated({cancel_tcpip_forward, 3, next_major_release}).
--deprecated({direct_tcpip, 6, next_major_release}).
--deprecated({direct_tcpip, 8, next_major_release}).
--deprecated({close, 2, next_major_release}).
--deprecated({shell, 2, next_major_release}).
--deprecated({exec, 4, next_major_release}).
--deprecated({send, 3, next_major_release}).
--deprecated({send, 4, next_major_release}).
--deprecated({send_ack, 3, next_major_release}).
--deprecated({send_ack, 4, next_major_release}).
--deprecated({send_ack, 5, next_major_release}).
--deprecated({send_eof, 2, next_major_release}).
--deprecated({session_open, 2, next_major_release}).
--deprecated({session_open, 4, next_major_release}).
--deprecated({subsystem, 4, next_major_release}).
--deprecated({open_pty, 3, next_major_release}).
--deprecated({open_pty, 7, next_major_release}).
--deprecated({open_pty, 9, next_major_release}).
--deprecated({set_user_ack, 4, next_major_release}).
--deprecated({setenv, 5, next_major_release}).
--deprecated({signal, 3, next_major_release}).
--deprecated({winch, 4, next_major_release}).
-
--export([info/1, info/2, recv_window/3,
- send_window/3, renegotiate/1, renegotiate/2,
- get_peer_addr/1]).
-
-%%====================================================================
-%% API
-%%====================================================================
-connect(Host) ->
- connect(Host, []).
-connect(Host, Opts) ->
- connect(Host, ?SSH_DEFAULT_PORT, Opts).
-connect(Host, Port, Opts) ->
- ssh:connect(Host, Port, Opts).
-
-listen(ChannelSpec, Port) ->
- listen(ChannelSpec, Port, []).
-listen(ChannelSpec, Port, Opts) ->
- listen(ChannelSpec, any, Port, Opts).
-listen(ChannelSpec, "localhost", Port, Opts) ->
- listen(ChannelSpec, any, Port, Opts);
-listen(_ChannelSpec, Host, Port, Opts) ->
- ssh:daemon(Host, Port, Opts).
-
-stop_listener(SysSup) ->
- ssh_system_sup:stop_listener(SysSup).
-stop(Cm) ->
- ssh:close(Cm).
-
-%% CM Client commands
-session_open(Cm, Timeout) ->
- session_open(Cm, ?DEFAULT_WINDOW_SIZE, ?DEFAULT_PACKET_SIZE, Timeout).
-
-session_open(Cm, InitialWindowSize, MaxPacketSize, Timeout) ->
- ssh_connection:session_channel(Cm, InitialWindowSize, MaxPacketSize,
- Timeout).
-
-
-setenv(Cm, Channel, Var, Value, Timeout) ->
- ssh_connection:setenv(Cm, Channel, Var, Value, Timeout).
-
-shell(Cm, Channel) ->
- ssh_connection:shell(Cm, Channel).
-
-exec(Cm, Channel, Command, Timeout) ->
- ssh_connection:exec(Cm, Channel, Command, Timeout).
-
-subsystem(Cm, Channel, SubSystem, Timeout) ->
- ssh_connection:subsystem(Cm, Channel, SubSystem, Timeout).
-
-%% Not needed for backwards compatibility for now
-attach(_Cm, _Timeout) ->
- ok.
-
-attach(_Cm, _ChannelPid, _Timeout) ->
- ok.
-
-detach(_Cm, _Timeout) ->
- ok.
-
-%% Not needed, send_ack is now call! Temp backwardcompability
-set_user_ack(_, _, _, _) ->
- ok.
-
-adjust_window(Cm, Channel, Bytes) ->
- ssh_connection:adjust_window(Cm, Channel, Bytes).
-
-close(Cm, Channel) ->
- ssh_connection:close(Cm, Channel).
-
-send_eof(Cm, Channel) ->
- ssh_connection:send_eof(Cm, Channel).
-
-send(Cm, Channel, Data) ->
- ssh_connection:send(Cm, Channel, 0, Data).
-
-send(Cm, Channel, Type, Data) ->
- ssh_connection:send(Cm, Channel, Type, Data).
-
-%% Send ack is not needed
-send_ack(Cm, Channel, Data) ->
- send_ack(Cm, Channel, 0, Data, infinity).
-
-send_ack(Cm, Channel, Type, Data) ->
- send_ack(Cm, Channel, Type, Data, infinity).
-
-send_ack(Cm, Channel, Type, Data, Timeout) ->
- ssh_connection:send(Cm, Channel, Type, Data, Timeout).
-
-%% ----------------------------------------------------------------------
-%% These functions replacers are not officially supported but proably will be
-%% when we had time to test them.
-%% ----------------------------------------------------------------------
-direct_tcpip(Cm, RemoteHost, RemotePort, OrigIP, OrigPort, Timeout) ->
- direct_tcpip(Cm, RemoteHost, RemotePort, OrigIP, OrigPort,
- ?DEFAULT_WINDOW_SIZE, ?DEFAULT_PACKET_SIZE, Timeout).
-
-direct_tcpip(Cm, RemoteIP, RemotePort, OrigIP, OrigPort,
- InitialWindowSize, MaxPacketSize, Timeout) ->
- ssh_connection:direct_tcpip(Cm, RemoteIP, RemotePort,
- OrigIP, OrigPort,
- InitialWindowSize,
- MaxPacketSize, Timeout).
-
-tcpip_forward(Cm, BindIP, BindPort) ->
- ssh_connection:tcpip_forward(Cm, BindIP, BindPort).
-
-cancel_tcpip_forward(Cm, BindIP, Port) ->
- ssh_connection:cancel_tcpip_forward(Cm, BindIP, Port).
-
-open_pty(Cm, Channel, Timeout) ->
- open_pty(Cm, Channel, os:getenv("TERM"), 80, 24, [], Timeout).
-
-open_pty(Cm, Channel, Term, Width, Height, PtyOpts, Timeout) ->
- open_pty(Cm, Channel, Term, Width, Height, 0, 0, PtyOpts, Timeout).
-
-open_pty(Cm, Channel, Term, Width, Height, PixWidth, PixHeight,
- PtyOpts, Timeout) ->
- ssh_connection:open_pty(Cm, Channel, Term,
- Width, Height, PixWidth,
- PixHeight, PtyOpts, Timeout).
-winch(Cm, Channel, Width, Height) ->
- winch(Cm, Channel, Width, Height, 0, 0).
-winch(Cm, Channel, Width, Height, PixWidth, PixHeight) ->
- ssh_connection:window_change(Cm, Channel, Width,
- Height, PixWidth, PixHeight).
-signal(Cm, Channel, Sig) ->
- ssh_connection:signal(Cm, Channel, Sig).
-
-%% ----------------------------------------------------------------------
-%% These functions replacers are not officially supported and
-%% the format of them will proably change when and
-%% if they get supported.
-%% ----------------------------------------------------------------------
-info(Cm) ->
- info(Cm, all).
-
-info(Cm, ChannelPid) ->
- ssh_connection_manager:info(Cm, ChannelPid).
-
-send_window(Cm, Channel, Timeout) ->
- ssh_connection_manager:send_window(Cm, Channel, Timeout).
-
-recv_window(Cm, Channel, Timeout) ->
- ssh_connection_manager:recv_window(Cm, Channel, Timeout).
-
-renegotiate(Cm) ->
- renegotiate(Cm, []).
-renegotiate(Cm, _Opts) ->
- %%TODO: How should this work, backwards compat?
- ssh_connection_manager:renegotiate(Cm).
-
-get_peer_addr(Cm) ->
- ssh_connection_manager:peer_addr(Cm).
-
diff --git a/lib/ssh/src/ssh_connect.hrl b/lib/ssh/src/ssh_connect.hrl
index a5a4e42cd8..57bb141c60 100755
--- a/lib/ssh/src/ssh_connect.hrl
+++ b/lib/ssh/src/ssh_connect.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_connection_controler.erl b/lib/ssh/src/ssh_connection_controler.erl
index 7960eb11c6..990541f8d6 100644
--- a/lib/ssh/src/ssh_connection_controler.erl
+++ b/lib/ssh/src/ssh_connection_controler.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
%%--------------------------------------------------------------------
diff --git a/lib/ssh/src/ssh_dsa.erl b/lib/ssh/src/ssh_dsa.erl
index ec24fbcd01..1b9a396f0c 100755
--- a/lib/ssh/src/ssh_dsa.erl
+++ b/lib/ssh/src/ssh_dsa.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_file.erl b/lib/ssh/src/ssh_file.erl
index 8a3c903e51..5572349fe7 100755
--- a/lib/ssh/src/ssh_file.erl
+++ b/lib/ssh/src/ssh_file.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_io.erl b/lib/ssh/src/ssh_io.erl
index 0e343c20b4..915fd63e4f 100755
--- a/lib/ssh/src/ssh_io.erl
+++ b/lib/ssh/src/ssh_io.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_math.erl b/lib/ssh/src/ssh_math.erl
index efe7f56979..510eb16aa6 100755
--- a/lib/ssh/src/ssh_math.erl
+++ b/lib/ssh/src/ssh_math.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_no_io.erl b/lib/ssh/src/ssh_no_io.erl
index 5f363ae6c2..2c8dd92ee2 100644
--- a/lib/ssh/src/ssh_no_io.erl
+++ b/lib/ssh/src/ssh_no_io.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_rsa.erl b/lib/ssh/src/ssh_rsa.erl
index 7c2bf9a2bf..e27cdcf7bd 100755
--- a/lib/ssh/src/ssh_rsa.erl
+++ b/lib/ssh/src/ssh_rsa.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_sftp.erl b/lib/ssh/src/ssh_sftp.erl
index cbfa208f6f..59e09fdd0f 100755
--- a/lib/ssh/src/ssh_sftp.erl
+++ b/lib/ssh/src/ssh_sftp.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -46,14 +46,6 @@
recv_window/1, list_dir/2, read_file/2, write_file/3,
recv_window/2, list_dir/3, read_file/3, write_file/4]).
-%% Deprecated
--export([connect/1, connect/2, connect/3, stop/1]).
-
--deprecated({connect, 1, next_major_release}).
--deprecated({connect, 2, next_major_release}).
--deprecated({connect, 3, next_major_release}).
--deprecated({stop, 1, next_major_release}).
-
%% ssh_channel callbacks
-export([init/1, handle_call/3, handle_msg/2, handle_ssh_msg/2, terminate/2]).
%% TODO: Should be placed elsewhere ssh_sftpd should not call functions in ssh_sftp!
@@ -1116,33 +1108,3 @@ lseek_pos(_, _, _) ->
{error, einval}.
-%%%%%% Deprecated %%%%
-connect(Cm) when is_pid(Cm) ->
- connect(Cm, []);
-connect(Host) when is_list(Host) ->
- connect(Host, []).
-connect(Cm, Opts) when is_pid(Cm) ->
- Timeout = proplists:get_value(timeout, Opts, infinity),
- case ssh_xfer:attach(Cm, []) of
- {ok, ChannelId, Cm} ->
- ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm, ChannelId,
- Timeout]);
- Error ->
- Error
- end;
-connect(Host, Opts) ->
- connect(Host, 22, Opts).
-connect(Host, Port, Opts) ->
- Timeout = proplists:get_value(timeout, Opts, infinity),
- case ssh_xfer:connect(Host, Port, proplists:delete(timeout, Opts)) of
- {ok, ChannelId, Cm} ->
- ssh_channel:start(Cm, ChannelId, ?MODULE, [Cm,
- ChannelId, Timeout]);
- Error ->
- Error
- end.
-
-
-stop(Pid) ->
- call(Pid, stop, infinity).
-
diff --git a/lib/ssh/src/ssh_sftpd.erl b/lib/ssh/src/ssh_sftpd.erl
index 10b8ede1e4..dc789092dd 100644
--- a/lib/ssh/src/ssh_sftpd.erl
+++ b/lib/ssh/src/ssh_sftpd.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_sftpd_file.erl b/lib/ssh/src/ssh_sftpd_file.erl
index f0b6bb4de5..91ba228e38 100644
--- a/lib/ssh/src/ssh_sftpd_file.erl
+++ b/lib/ssh/src/ssh_sftpd_file.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2006-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_sftpd_file_api.erl b/lib/ssh/src/ssh_sftpd_file_api.erl
index 8decfb38d9..176aa98194 100644
--- a/lib/ssh/src/ssh_sftpd_file_api.erl
+++ b/lib/ssh/src/ssh_sftpd_file_api.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2007-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_shell.erl b/lib/ssh/src/ssh_shell.erl
index f81b949119..6590486a4c 100644
--- a/lib/ssh/src/ssh_shell.erl
+++ b/lib/ssh/src/ssh_shell.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_ssh.erl b/lib/ssh/src/ssh_ssh.erl
deleted file mode 100644
index 6be8bf7a5a..0000000000
--- a/lib/ssh/src/ssh_ssh.erl
+++ /dev/null
@@ -1,65 +0,0 @@
-%%
-%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-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%
-%%
-
-%%
-
-%%% Description: THIS MODULE IS DEPRECATD AND SHOULD BE REMOVED IN R14
-
--module(ssh_ssh).
-
--export([connect/1, connect/2, connect/3]).
--deprecated({connect, 1, next_major_release}).
--deprecated({connect, 2, next_major_release}).
--deprecated({connect, 3, next_major_release}).
-
--include("ssh.hrl").
--include("ssh_connect.hrl").
-
--define(default_timeout, 10000).
-
-%%% Backwards compatibility
-connect(A) ->
- connect(A, []).
-
-connect(Host, Opts) when is_list(Host) ->
- connect(Host, 22, Opts);
-connect(CM, Opts) ->
- Timeout = proplists:get_value(connect_timeout, Opts, ?default_timeout),
- session(CM, Timeout).
-
-connect(Host, Port, Opts) ->
- case ssh:connect(Host, Port, Opts) of
- {ok, CM} ->
- session(CM, proplists:get_value(connect_timeout,
- Opts, ?default_timeout));
- Error ->
- Error
- end.
-
-session(CM, Timeout) ->
- case ssh_connection:session_channel(CM, Timeout) of
- {ok, ChannelId} ->
- Args = [{channel_cb, ssh_shell},
- {init_args,[CM, ChannelId]},
- {cm, CM}, {channel_id, ChannelId}],
- {ok, State} = ssh_channel:init([Args]),
- ssh_channel:enter_loop(State);
- Error ->
- Error
- end.
diff --git a/lib/ssh/src/ssh_sshd.erl b/lib/ssh/src/ssh_sshd.erl
deleted file mode 100644
index 4bc0469061..0000000000
--- a/lib/ssh/src/ssh_sshd.erl
+++ /dev/null
@@ -1,48 +0,0 @@
-%%
-%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-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%
-%%
-
-%%
-%% Description: This module uses the erlang shell and
-%% ssh_cli to make an erlang sshd
-
--module(ssh_sshd).
-
-%% API
--export([listen/0, listen/1, listen/2, listen/3, stop/1]).
-
--deprecated({listen, 0, next_major_release}).
--deprecated({listen, 1, next_major_release}).
--deprecated({listen, 2, next_major_release}).
--deprecated({listen, 3, next_major_release}).
--deprecated({stop, 1, next_major_release}).
-
-listen() ->
- listen(22).
-
-listen(Port) ->
- listen(Port, []).
-
-listen(Port, Opts) ->
- listen(any, Port, Opts).
-
-listen(Addr, Port, Opts) ->
- ssh:daemon(Addr, Port, Opts).
-
-stop(Pid) ->
- ssh:stop_daemon(Pid).
diff --git a/lib/ssh/src/ssh_subsystem_sup.erl b/lib/ssh/src/ssh_subsystem_sup.erl
index 17d47a91d5..d71b6bbc56 100644
--- a/lib/ssh/src/ssh_subsystem_sup.erl
+++ b/lib/ssh/src/ssh_subsystem_sup.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
%%
diff --git a/lib/ssh/src/ssh_sup.erl b/lib/ssh/src/ssh_sup.erl
index 4c46b1586b..f307d1f833 100644
--- a/lib/ssh/src/ssh_sup.erl
+++ b/lib/ssh/src/ssh_sup.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_system_sup.erl b/lib/ssh/src/ssh_system_sup.erl
index 477f60f993..40db2e4adf 100644
--- a/lib/ssh/src/ssh_system_sup.erl
+++ b/lib/ssh/src/ssh_system_sup.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_transport.erl b/lib/ssh/src/ssh_transport.erl
index 5617231c60..e79ccdda0c 100644
--- a/lib/ssh/src/ssh_transport.erl
+++ b/lib/ssh/src/ssh_transport.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2004-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2004-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%
%%
diff --git a/lib/ssh/src/ssh_transport.hrl b/lib/ssh/src/ssh_transport.hrl
index 18a23f0533..27d3e32355 100644
--- a/lib/ssh/src/ssh_transport.hrl
+++ b/lib/ssh/src/ssh_transport.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_userauth.hrl b/lib/ssh/src/ssh_userauth.hrl
index 39cc032ca5..8eb2d46ed1 100755
--- a/lib/ssh/src/ssh_userauth.hrl
+++ b/lib/ssh/src/ssh_userauth.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_userreg.erl b/lib/ssh/src/ssh_userreg.erl
index 06f4076b51..33c801f490 100644
--- a/lib/ssh/src/ssh_userreg.erl
+++ b/lib/ssh/src/ssh_userreg.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_xfer.erl b/lib/ssh/src/ssh_xfer.erl
index a347a9c095..c9631a73b1 100644
--- a/lib/ssh/src/ssh_xfer.erl
+++ b/lib/ssh/src/ssh_xfer.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/ssh_xfer.hrl b/lib/ssh/src/ssh_xfer.hrl
index f32ec5f774..4a4f1a4291 100755
--- a/lib/ssh/src/ssh_xfer.hrl
+++ b/lib/ssh/src/ssh_xfer.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2005-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/sshc_sup.erl b/lib/ssh/src/sshc_sup.erl
index 265d1a1cd6..7c29c669e4 100644
--- a/lib/ssh/src/sshc_sup.erl
+++ b/lib/ssh/src/sshc_sup.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
diff --git a/lib/ssh/src/sshd_sup.erl b/lib/ssh/src/sshd_sup.erl
index 9c9ba5958c..747906b2cf 100644
--- a/lib/ssh/src/sshd_sup.erl
+++ b/lib/ssh/src/sshd_sup.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2008-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
%%
diff --git a/lib/ssh/vsn.mk b/lib/ssh/vsn.mk
index 074826cafd..38a82ff32d 100644
--- a/lib/ssh/vsn.mk
+++ b/lib/ssh/vsn.mk
@@ -1,12 +1,13 @@
#-*-makefile-*- ; force emacs to enter makefile-mode
-SSH_VSN = 1.1.9
+SSH_VSN = 2.0
APP_VSN = "ssh-$(SSH_VSN)"
TICKETS = OTP-8524 \
OTP-8534 \
OTP-8535 \
- OTP-8550
+ OTP-8550 \
+ OTP-8596
TICKETS_1.1.8 = OTP-8356 \
OTP-8401
diff --git a/lib/ssl/doc/src/new_ssl.xml b/lib/ssl/doc/src/new_ssl.xml
index 08868a1b3c..ab6e112a35 100644
--- a/lib/ssl/doc/src/new_ssl.xml
+++ b/lib/ssl/doc/src/new_ssl.xml
@@ -581,6 +581,10 @@ end
<p> Upgrades a gen_tcp, or
equivalent, socket to a ssl socket e.i performs the
ssl server-side handshake.</p>
+ <p><note>Note that the listen socket should be in {active, false} mode
+ before telling the client that the server is ready to upgrade
+ and calling this function, otherwise the upgrade may
+ or may not succeed depending on timing.</note></p>
</desc>
</func>
diff --git a/lib/ssl/src/ssl.appup.src b/lib/ssl/src/ssl.appup.src
index fdda65021d..e8ae6846aa 100644
--- a/lib/ssl/src/ssl.appup.src
+++ b/lib/ssl/src/ssl.appup.src
@@ -9,7 +9,8 @@
{"3.10.5", [{restart_application, ssl}]},
{"3.10.6", [{restart_application, ssl}]},
{"3.10.7", [{restart_application, ssl}]},
- {"3.10.8", [{restart_application, ssl}]}
+ {"3.10.8", [{restart_application, ssl}]},
+ {"3.10.9", [{restart_application, ssl}]}
],
[
{"3.10", [{restart_application, ssl}]},
@@ -19,6 +20,7 @@
{"3.10.4", [{restart_application, ssl}]},
{"3.10.5", [{restart_application, ssl}]},
{"3.10.6", [{restart_application, ssl}]},
- {"3.10.8", [{restart_application, ssl}]}
+ {"3.10.8", [{restart_application, ssl}]},
+ {"3.10.9", [{restart_application, ssl}]}
]}.
diff --git a/lib/ssl/src/ssl.erl b/lib/ssl/src/ssl.erl
index fd9ed4a344..95cd92ee60 100644
--- a/lib/ssl/src/ssl.erl
+++ b/lib/ssl/src/ssl.erl
@@ -147,23 +147,23 @@ transport_accept(ListenSocket) ->
transport_accept(ListenSocket, infinity).
transport_accept(#sslsocket{pid = {ListenSocket, #config{cb=CbInfo, ssl=SslOpts}},
- fd = new_ssl} = SslSocket, Timeout) ->
+ fd = new_ssl}, Timeout) ->
%% The setopt could have been invoked on the listen socket
%% and options should be inherited.
EmOptions = emulated_options(),
{ok, InetValues} = inet:getopts(ListenSocket, EmOptions),
- {CbModule,_,_} = CbInfo,
+ ok = inet:setopts(ListenSocket, internal_inet_values()),
+ {CbModule,_,_, _} = CbInfo,
case CbModule:accept(ListenSocket, Timeout) of
{ok, Socket} ->
- inet:setopts(Socket, internal_inet_values()),
+ ok = inet:setopts(ListenSocket, InetValues),
{ok, Port} = inet:port(Socket),
ConnArgs = [server, "localhost", Port, Socket,
{SslOpts, socket_options(InetValues)}, self(), CbInfo],
case ssl_connection_sup:start_child(ConnArgs) of
{ok, Pid} ->
- CbModule:controlling_process(Socket, Pid),
- {ok, SslSocket#sslsocket{pid = Pid}};
+ ssl_connection:socket_control(Socket, Pid, CbModule);
{error, Reason} ->
{error, Reason}
end;
@@ -186,22 +186,9 @@ transport_accept(#sslsocket{} = ListenSocket, Timeout) ->
ssl_accept(ListenSocket) ->
ssl_accept(ListenSocket, infinity).
-ssl_accept(#sslsocket{pid = Pid, fd = new_ssl}, Timeout) ->
- gen_fsm:send_event(Pid, socket_control),
- try gen_fsm:sync_send_all_state_event(Pid, started, Timeout) of
- connected ->
- ok;
- {error, _} = Error ->
- Error
- catch
- exit:{noproc, _} ->
- {error, closed};
- exit:{timeout, _} ->
- {error, timeout};
- exit:{normal, _} ->
- {error, closed}
- end;
-
+ssl_accept(#sslsocket{fd = new_ssl} = Socket, Timeout) ->
+ ssl_connection:handshake(Socket, Timeout);
+
ssl_accept(ListenSocket, SslOptions) when is_port(ListenSocket) ->
ssl_accept(ListenSocket, SslOptions, infinity);
@@ -217,7 +204,7 @@ ssl_accept(Socket, SslOptions, Timeout) when is_port(Socket) ->
try handle_options(SslOptions ++ InetValues, server) of
{ok, #config{cb=CbInfo,ssl=SslOpts, emulated=EmOpts}} ->
{ok, Port} = inet:port(Socket),
- ssl_connection:accept(Port, Socket,
+ ssl_connection:ssl_accept(Port, Socket,
{SslOpts, EmOpts},
self(), CbInfo, Timeout)
catch
@@ -229,7 +216,7 @@ ssl_accept(Socket, SslOptions, Timeout) when is_port(Socket) ->
%%
%% Description: Close a ssl connection
%%--------------------------------------------------------------------
-close(#sslsocket{pid = {ListenSocket, #config{cb={CbMod,_, _}}}, fd = new_ssl}) ->
+close(#sslsocket{pid = {ListenSocket, #config{cb={CbMod,_, _, _}}}, fd = new_ssl}) ->
CbMod:close(ListenSocket);
close(#sslsocket{pid = Pid, fd = new_ssl}) ->
ssl_connection:close(Pid);
@@ -238,7 +225,7 @@ close(Socket = #sslsocket{}) ->
ssl_broker:close(Socket).
%%--------------------------------------------------------------------
-%% Function: send(Socket, Data) -> ok
+%% Function: send(Socket, Data) -> ok | {error, Reason}
%%
%% Description: Sends data over the ssl connection
%%--------------------------------------------------------------------
@@ -388,7 +375,7 @@ setopts(#sslsocket{} = Socket, Options) ->
%%
%% Description: Same as gen_tcp:shutdown/2
%%--------------------------------------------------------------------
-shutdown(#sslsocket{pid = {ListenSocket, #config{cb={CbMod,_, _}}}, fd = new_ssl}, How) ->
+shutdown(#sslsocket{pid = {ListenSocket, #config{cb={CbMod,_, _, _}}}, fd = new_ssl}, How) ->
CbMod:shutdown(ListenSocket, How);
shutdown(#sslsocket{pid = Pid, fd = new_ssl}, How) ->
ssl_connection:shutdown(Pid, How).
@@ -462,7 +449,7 @@ do_new_connect(Address, Port,
#config{cb=CbInfo, inet_user=UserOpts, ssl=SslOpts,
emulated=EmOpts,inet_ssl=SocketOpts},
Timeout) ->
- {CbModule, _, _} = CbInfo,
+ {CbModule, _, _, _} = CbInfo,
try CbModule:connect(Address, Port, SocketOpts, Timeout) of
{ok, Socket} ->
ssl_connection:connect(Address, Port, Socket, {SslOpts,EmOpts},
@@ -484,7 +471,7 @@ old_connect(Address, Port, Options, Timeout) ->
new_listen(Port, Options0) ->
try
{ok, Config} = handle_options(Options0, server),
- #config{cb={CbModule, _, _},inet_user=Options} = Config,
+ #config{cb={CbModule, _, _, _},inet_user=Options} = Config,
case CbModule:listen(Port, Options) of
{ok, ListenSocket} ->
{ok, #sslsocket{pid = {ListenSocket, Config}, fd = new_ssl}};
@@ -559,17 +546,18 @@ handle_options(Opts0, Role) ->
%% Server side option
reuse_session = handle_option(reuse_session, Opts, ReuseSessionFun),
reuse_sessions = handle_option(reuse_sessions, Opts, true),
+ secure_renegotiate = handle_option(secure_renegotiate, Opts, false),
renegotiate_at = handle_option(renegotiate_at, Opts, ?DEFAULT_RENEGOTIATE_AT),
debug = handle_option(debug, Opts, [])
},
- CbInfo = proplists:get_value(cb_info, Opts, {gen_tcp, tcp, tcp_closed}),
+ CbInfo = proplists:get_value(cb_info, Opts, {gen_tcp, tcp, tcp_closed, tcp_error}),
SslOptions = [versions, verify, verify_fun, validate_extensions_fun,
fail_if_no_peer_cert, verify_client_once,
depth, certfile, keyfile,
key, password, cacertfile, dhfile, ciphers,
debug, reuse_session, reuse_sessions, ssl_imp,
- cb_info, renegotiate_at],
+ cb_info, renegotiate_at, secure_renegotiate],
SockOpts = lists:foldl(fun(Key, PropList) ->
proplists:delete(Key, PropList)
@@ -640,6 +628,10 @@ validate_option(reuse_session, Value) when is_function(Value) ->
validate_option(reuse_sessions, Value) when Value == true;
Value == false ->
Value;
+
+validate_option(secure_renegotiate, Value) when Value == true;
+ Value == false ->
+ Value;
validate_option(renegotiate_at, Value) when is_integer(Value) ->
min(Value, ?DEFAULT_RENEGOTIATE_AT);
@@ -748,24 +740,34 @@ cipher_suites(Version, Ciphers0) ->
format_error({error, Reason}) ->
format_error(Reason);
+format_error(Reason) when is_list(Reason) ->
+ Reason;
format_error(closed) ->
- "Connection closed for the operation in question.";
+ "The connection is closed";
+format_error(ecacertfile) ->
+ "Own CA certificate file is invalid.";
+format_error(ecertfile) ->
+ "Own certificate file is invalid.";
+format_error(ekeyfile) ->
+ "Own private key file is invalid.";
+format_error(esslaccept) ->
+ "Server SSL handshake procedure between client and server failed.";
+format_error(esslconnect) ->
+ "Client SSL handshake procedure between client and server failed.";
+format_error({eoptions, Options}) ->
+ lists:flatten(io_lib:format("Error in options list: ~p~n", [Options]));
+
+%%%%%%%%%%%% START OLD SSL format_error %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
format_error(ebadsocket) ->
"Connection not found (internal error).";
format_error(ebadstate) ->
"Connection not in connect state (internal error).";
format_error(ebrokertype) ->
"Wrong broker type (internal error).";
-format_error(ecacertfile) ->
- "Own CA certificate file is invalid.";
-format_error(ecertfile) ->
- "Own certificate file is invalid.";
format_error(echaintoolong) ->
"The chain of certificates provided by peer is too long.";
format_error(ecipher) ->
"Own list of specified ciphers is invalid.";
-format_error(ekeyfile) ->
- "Own private key file is invalid.";
format_error(ekeymismatch) ->
"Own private key does not match own certificate.";
format_error(enoissuercert) ->
@@ -791,10 +793,6 @@ format_error(epeercertinvalid) ->
"Certificate provided by peer is invalid.";
format_error(eselfsignedcert) ->
"Certificate provided by peer is self signed.";
-format_error(esslaccept) ->
- "Server SSL handshake procedure between client and server failed.";
-format_error(esslconnect) ->
- "Client SSL handshake procedure between client and server failed.";
format_error(esslerrssl) ->
"SSL protocol failure. Typically because of a fatal alert from peer.";
format_error(ewantconnect) ->
@@ -813,6 +811,9 @@ format_error({badcast, _Cast}) ->
format_error({badinfo, _Info}) ->
"Call not recognized for current mode (active or passive) and state "
"of socket.";
+
+%%%%%%%%%%%%%%%%%% END OLD SSL format_error %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
format_error(Error) ->
case (catch inet:format_error(Error)) of
"unkknown POSIX" ++ _ ->
@@ -824,7 +825,7 @@ format_error(Error) ->
end.
no_format(Error) ->
- io_lib:format("No format string for error: \"~p\" available.", [Error]).
+ lists:flatten(io_lib:format("No format string for error: \"~p\" available.", [Error])).
%% Start old ssl port program if needed.
ensure_old_ssl_started() ->
diff --git a/lib/ssl/src/ssl_alert.erl b/lib/ssl/src/ssl_alert.erl
index d3f9c833f1..db9a883654 100644
--- a/lib/ssl/src/ssl_alert.erl
+++ b/lib/ssl/src/ssl_alert.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2007-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -38,10 +38,6 @@ reason_code(#alert{description = ?HANDSHAKE_FAILURE}, client) ->
esslconnect;
reason_code(#alert{description = ?HANDSHAKE_FAILURE}, server) ->
esslaccept;
-reason_code(#alert{description = ?CERTIFICATE_EXPIRED}, _) ->
- epeercertexpired;
-reason_code(#alert{level = ?FATAL}, _) ->
- esslerrssl;
reason_code(#alert{description = Description}, _) ->
description_txt(Description).
@@ -55,51 +51,51 @@ level_txt(?FATAL) ->
"Fatal error:".
description_txt(?CLOSE_NOTIFY) ->
- "close_notify";
+ "close notify";
description_txt(?UNEXPECTED_MESSAGE) ->
- "unexpected_message";
+ "unexpected message";
description_txt(?BAD_RECORD_MAC) ->
- "bad_record_mac";
+ "bad record mac";
description_txt(?DECRYPTION_FAILED) ->
- "decryption_failed";
+ "decryption failed";
description_txt(?RECORD_OVERFLOW) ->
- "record_overflow";
+ "record overflow";
description_txt(?DECOMPRESSION_FAILURE) ->
- "decompression_failure";
+ "decompression failure";
description_txt(?HANDSHAKE_FAILURE) ->
- "handshake_failure";
+ "handshake failure";
description_txt(?BAD_CERTIFICATE) ->
- "bad_certificate";
+ "bad certificate";
description_txt(?UNSUPPORTED_CERTIFICATE) ->
- "unsupported_certificate";
+ "unsupported certificate";
description_txt(?CERTIFICATE_REVOKED) ->
- "certificate_revoked";
+ "certificate revoked";
description_txt(?CERTIFICATE_EXPIRED) ->
- "certificate_expired";
+ "certificate expired";
description_txt(?CERTIFICATE_UNKNOWN) ->
- "certificate_unknown";
+ "certificate unknown";
description_txt(?ILLEGAL_PARAMETER) ->
- "illegal_parameter";
+ "illegal parameter";
description_txt(?UNKNOWN_CA) ->
- "unknown_ca";
+ "unknown ca";
description_txt(?ACCESS_DENIED) ->
- "access_denied";
+ "access denied";
description_txt(?DECODE_ERROR) ->
- "decode_error";
+ "decode error";
description_txt(?DECRYPT_ERROR) ->
- "decrypt_error";
+ "decrypt error";
description_txt(?EXPORT_RESTRICTION) ->
- "export_restriction";
+ "export restriction";
description_txt(?PROTOCOL_VERSION) ->
- "protocol_version";
+ "protocol version";
description_txt(?INSUFFICIENT_SECURITY) ->
- "insufficient_security";
+ "insufficient security";
description_txt(?INTERNAL_ERROR) ->
- "internal_error";
+ "internal error";
description_txt(?USER_CANCELED) ->
- "user_canceled";
+ "user canceled";
description_txt(?NO_RENEGOTIATION) ->
- "no_renegotiation".
+ "no renegotiation".
diff --git a/lib/ssl/src/ssl_cipher.hrl b/lib/ssl/src/ssl_cipher.hrl
index 4304c501b7..d282cbd780 100644
--- a/lib/ssl/src/ssl_cipher.hrl
+++ b/lib/ssl/src/ssl_cipher.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2007-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -250,4 +250,9 @@
-define(TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA, <<?BYTE(16#00), ?BYTE(16#65)>>).
-define(TLS_DHE_DSS_WITH_RC4_128_SHA, <<?BYTE(16#00), ?BYTE(16#66)>>).
+%% RFC 5746 - Not a real ciphersuite used to signal empty "renegotiation_info" extension
+%% to avoid handshake failure from old servers that do not ignore
+%% hello extension data as they should.
+-define(TLS_EMPTY_RENEGOTIATION_INFO_SCSV, <<?BYTE(16#00), ?BYTE(16#FF)>>).
+
-endif. % -ifdef(ssl_cipher).
diff --git a/lib/ssl/src/ssl_connection.erl b/lib/ssl/src/ssl_connection.erl
index 8ff001b172..a9ddc44edf 100644
--- a/lib/ssl/src/ssl_connection.erl
+++ b/lib/ssl/src/ssl_connection.erl
@@ -39,7 +39,8 @@
-include_lib("public_key/include/public_key.hrl").
%% Internal application API
--export([send/2, send/3, recv/3, connect/7, accept/6, close/1, shutdown/2,
+-export([send/2, send/3, recv/3, connect/7, ssl_accept/6, handshake/2,
+ socket_control/3, close/1, shutdown/2,
new_user/2, get_opts/2, set_opts/2, info/1, session_info/1,
peer_certificate/1, sockname/1, peername/1, renegotiation/1]).
@@ -57,6 +58,7 @@
transport_cb, % atom() - callback module
data_tag, % atom() - ex tcp.
close_tag, % atom() - ex tcp_closed
+ error_tag, % atom() - ex tcp_error
host, % string() | ipadress()
port, % integer()
socket, % socket()
@@ -101,41 +103,70 @@
%%====================================================================
%%--------------------------------------------------------------------
-%% Function:
+%% Function: send(Pid, Data) -> ok | {error, Reason}
%%
-%% Description:
+%% Description: Sends data over the ssl connection
%%--------------------------------------------------------------------
send(Pid, Data) ->
sync_send_all_state_event(Pid, {application_data, erlang:iolist_to_binary(Data)}, infinity).
send(Pid, Data, Timeout) ->
sync_send_all_state_event(Pid, {application_data, erlang:iolist_to_binary(Data)}, Timeout).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: recv(Socket, Length Timeout) -> {ok, Data} | {error, reason}
%%
-%% Description:
+%% Description: Receives data when active = false
%%--------------------------------------------------------------------
recv(Pid, Length, Timeout) ->
sync_send_all_state_event(Pid, {recv, Length}, Timeout).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: : connect(Host, Port, Socket, Options,
+%% User, CbInfo, Timeout) -> {ok, Socket}
%%
-%% Description:
+%% Description: Connect to a ssl server.
%%--------------------------------------------------------------------
connect(Host, Port, Socket, Options, User, CbInfo, Timeout) ->
start_fsm(client, Host, Port, Socket, Options, User, CbInfo,
Timeout).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: accept(Port, Socket, Opts, User,
+%% CbInfo, Timeout) -> {ok, Socket} | {error, Reason}
%%
-%% Description:
+%% Description: Performs accept on a ssl listen socket. e.i. performs
+%% ssl handshake.
%%--------------------------------------------------------------------
-accept(Port, Socket, Opts, User, CbInfo, Timeout) ->
+ssl_accept(Port, Socket, Opts, User, CbInfo, Timeout) ->
start_fsm(server, "localhost", Port, Socket, Opts, User,
CbInfo, Timeout).
+
%%--------------------------------------------------------------------
-%% Function:
+%% Function: handshake(SslSocket, Timeout) -> ok | {error, Reason}
+%%
+%% Description: Starts ssl handshake.
+%%--------------------------------------------------------------------
+handshake(#sslsocket{pid = Pid}, Timeout) ->
+ case sync_send_all_state_event(Pid, start, Timeout) of
+ connected ->
+ ok;
+ Error ->
+ Error
+ end.
+%--------------------------------------------------------------------
+%% Function: socket_control(Pid) -> {ok, SslSocket} | {error, Reason}
%%
-%% Description:
+%% Description: Set the ssl process to own the accept socket
+%%--------------------------------------------------------------------
+socket_control(Socket, Pid, CbModule) ->
+ case CbModule:controlling_process(Socket, Pid) of
+ ok ->
+ {ok, sslsocket(Pid)};
+ {error, Reason} ->
+ {error, Reason}
+ end.
+
+%%--------------------------------------------------------------------
+%% Function: close() -> ok
+%%
+%% Description: Close a ssl connection
%%--------------------------------------------------------------------
close(ConnectionPid) ->
case sync_send_all_state_event(ConnectionPid, close) of
@@ -146,80 +177,81 @@ close(ConnectionPid) ->
end.
%%--------------------------------------------------------------------
-%% Function:
+%% Function: shutdown(Socket, How) -> ok | {error, Reason}
%%
-%% Description:
+%% Description: Same as gen_tcp:shutdown/2
%%--------------------------------------------------------------------
shutdown(ConnectionPid, How) ->
sync_send_all_state_event(ConnectionPid, {shutdown, How}).
-
%%--------------------------------------------------------------------
-%% Function:
+%% Function: new_user(ConnectionPid, User) -> ok | {error, Reason}
%%
-%% Description:
+%% Description: Changes process that receives the messages when active = true
+%% or once.
%%--------------------------------------------------------------------
new_user(ConnectionPid, User) ->
sync_send_all_state_event(ConnectionPid, {new_user, User}).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: sockname(ConnectionPid) -> {ok, {Address, Port}} | {error, Reason}
%%
-%% Description:
+%% Description: Same as inet:sockname/1
%%--------------------------------------------------------------------
sockname(ConnectionPid) ->
sync_send_all_state_event(ConnectionPid, sockname).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: peername(ConnectionPid) -> {ok, {Address, Port}} | {error, Reason}
%%
-%% Description:
+%% Description: Same as inet:peername/1
%%--------------------------------------------------------------------
peername(ConnectionPid) ->
sync_send_all_state_event(ConnectionPid, peername).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: get_opts(ConnectionPid, OptTags) -> {ok, Options} | {error, Reason}
%%
-%% Description:
+%% Description: Same as inet:getopts/2
%%--------------------------------------------------------------------
get_opts({ListenSocket, {_SslOpts, SockOpts}, _}, OptTags) ->
get_socket_opts(ListenSocket, OptTags, SockOpts, []);
get_opts(ConnectionPid, OptTags) ->
sync_send_all_state_event(ConnectionPid, {get_opts, OptTags}).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: setopts(Socket, Options) -> ok | {error, Reason}
%%
-%% Description:
+%% Description: Same as inet:setopts/2
%%--------------------------------------------------------------------
set_opts(ConnectionPid, Options) ->
sync_send_all_state_event(ConnectionPid, {set_opts, Options}).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: info(ConnectionPid) -> {ok, {Protocol, CipherSuite}} |
+%% {error, Reason}
%%
-%% Description:
+%% Description: Returns ssl protocol and cipher used for the connection
%%--------------------------------------------------------------------
info(ConnectionPid) ->
sync_send_all_state_event(ConnectionPid, info).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: session_info(ConnectionPid) -> {ok, PropList} | {error, Reason}
%%
-%% Description:
+%% Description: Returns info about the ssl session
%%--------------------------------------------------------------------
session_info(ConnectionPid) ->
sync_send_all_state_event(ConnectionPid, session_info).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: peercert(ConnectionPid) -> {ok, Cert} | {error, Reason}
%%
-%% Description:
+%% Description: Returns the peer cert
%%--------------------------------------------------------------------
peer_certificate(ConnectionPid) ->
sync_send_all_state_event(ConnectionPid, peer_certificate).
%%--------------------------------------------------------------------
-%% Function:
+%% Function: renegotiation(ConnectionPid) -> ok | {error, Reason}
%%
-%% Description:
+%% Description: Starts a renegotiation of the ssl session.
%%--------------------------------------------------------------------
renegotiation(ConnectionPid) ->
sync_send_all_state_event(ConnectionPid, renegotiate).
@@ -269,7 +301,7 @@ init([Role, Host, Port, Socket, {SSLOpts, _} = Options,
throw:Error ->
{stop, Error}
end.
-
+
%%--------------------------------------------------------------------
%% Function:
%% state_name(Event, State) -> {next_state, NextStateName, NextState}|
@@ -282,32 +314,38 @@ init([Role, Host, Port, Socket, {SSLOpts, _} = Options,
%% using gen_fsm:send_event/2, the instance of this function with the
%% same name as the current state name StateName is called to handle
%% the event. It is also called if a timeout occurs.
+%%
%%--------------------------------------------------------------------
-hello(socket_control, #state{host = Host, port = Port, role = client,
- ssl_options = SslOpts,
- transport_cb = Transport, socket = Socket,
- connection_states = ConnectionStates}
+hello(start, #state{host = Host, port = Port, role = client,
+ ssl_options = SslOpts,
+ transport_cb = Transport, socket = Socket,
+ connection_states = ConnectionStates,
+ renegotiation = {Renegotiation, _}}
= State0) ->
Hello = ssl_handshake:client_hello(Host, Port,
- ConnectionStates, SslOpts),
+ ConnectionStates, SslOpts, Renegotiation),
+
Version = Hello#client_hello.client_version,
Hashes0 = ssl_handshake:init_hashes(),
{BinMsg, CS2, Hashes1} =
encode_handshake(Hello, Version, ConnectionStates, Hashes0),
Transport:send(Socket, BinMsg),
- State = State0#state{connection_states = CS2,
+ State1 = State0#state{connection_states = CS2,
negotiated_version = Version, %% Requested version
session =
#session{session_id = Hello#client_hello.session_id,
is_resumable = false},
tls_handshake_hashes = Hashes1},
- {next_state, hello, next_record(State)};
+ {Record, State} = next_record(State1),
+ next_state(hello, Record, State);
-hello(socket_control, #state{role = server} = State) ->
- {next_state, hello, next_record(State)};
+hello(start, #state{role = server} = State0) ->
+ {Record, State} = next_record(State0),
+ next_state(hello, Record, State);
-hello(#hello_request{}, #state{role = client} = State) ->
- {next_state, hello, State};
+hello(#hello_request{}, #state{role = client} = State0) ->
+ {Record, State} = next_record(State0),
+ next_state(hello, Record, State);
hello(#server_hello{cipher_suite = CipherSuite,
compression_method = Compression} = Hello,
@@ -316,54 +354,60 @@ hello(#server_hello{cipher_suite = CipherSuite,
role = client,
negotiated_version = ReqVersion,
host = Host, port = Port,
+ renegotiation = {Renegotiation, _},
+ ssl_options = SslOptions,
session_cache = Cache,
session_cache_cb = CacheCb} = State0) ->
- {Version, NewId, ConnectionStates1} =
- ssl_handshake:hello(Hello, ConnectionStates0),
-
- {KeyAlgorithm, _, _, _} =
- ssl_cipher:suite_definition(CipherSuite),
-
- PremasterSecret = make_premaster_secret(ReqVersion, KeyAlgorithm),
-
- State = State0#state{key_algorithm = KeyAlgorithm,
- negotiated_version = Version,
- connection_states = ConnectionStates1,
- premaster_secret = PremasterSecret},
-
- case ssl_session:is_new(OldId, NewId) of
- true ->
- Session = Session0#session{session_id = NewId,
- cipher_suite = CipherSuite,
+ case ssl_handshake:hello(Hello, SslOptions, ConnectionStates0, Renegotiation) of
+ {Version, NewId, ConnectionStates1} ->
+ {KeyAlgorithm, _, _, _} =
+ ssl_cipher:suite_definition(CipherSuite),
+
+ PremasterSecret = make_premaster_secret(ReqVersion, KeyAlgorithm),
+
+ State1 = State0#state{key_algorithm = KeyAlgorithm,
+ negotiated_version = Version,
+ connection_states = ConnectionStates1,
+ premaster_secret = PremasterSecret},
+
+ case ssl_session:is_new(OldId, NewId) of
+ true ->
+ Session = Session0#session{session_id = NewId,
+ cipher_suite = CipherSuite,
compression_method = Compression},
- {next_state, certify,
- next_record(State#state{session = Session})};
- false ->
- Session = CacheCb:lookup(Cache, {{Host, Port}, NewId}),
- case ssl_handshake:master_secret(Version, Session,
- ConnectionStates1, client) of
- {_, ConnectionStates2} ->
- {next_state, abbreviated,
- next_record(State#state{
- connection_states = ConnectionStates2,
- session = Session})};
- #alert{} = Alert ->
- handle_own_alert(Alert, Version, hello, State),
- {stop, normal, State}
- end
+ {Record, State} = next_record(State1#state{session = Session}),
+ next_state(certify, Record, State);
+ false ->
+ Session = CacheCb:lookup(Cache, {{Host, Port}, NewId}),
+ case ssl_handshake:master_secret(Version, Session,
+ ConnectionStates1, client) of
+ {_, ConnectionStates2} ->
+ {Record, State} =
+ next_record(State1#state{
+ connection_states = ConnectionStates2,
+ session = Session}),
+ next_state(abbreviated, Record, State);
+ #alert{} = Alert ->
+ handle_own_alert(Alert, Version, hello, State1),
+ {stop, normal, State1}
+ end
+ end;
+ #alert{} = Alert ->
+ handle_own_alert(Alert, ReqVersion, hello, State0),
+ {stop, normal, State0}
end;
hello(Hello = #client_hello{client_version = ClientVersion},
State = #state{connection_states = ConnectionStates0,
port = Port, session = Session0,
- session_cache = Cache,
+ renegotiation = {Renegotiation, _},
+ session_cache = Cache,
session_cache_cb = CacheCb,
ssl_options = SslOpts}) ->
- case ssl_handshake:hello(Hello, {Port, SslOpts,
- Session0, Cache, CacheCb,
- ConnectionStates0}) of
+ case ssl_handshake:hello(Hello, SslOpts, {Port, Session0, Cache, CacheCb,
+ ConnectionStates0}, Renegotiation) of
{Version, {Type, Session}, ConnectionStates} ->
do_server_hello(Type, State#state{connection_states =
ConnectionStates,
@@ -372,50 +416,59 @@ hello(Hello = #client_hello{client_version = ClientVersion},
#alert{} = Alert ->
handle_own_alert(Alert, ClientVersion, hello, State),
{stop, normal, State}
- end.
+ end;
-abbreviated(socket_control, #state{role = server} = State) ->
- {next_state, abbreviated, State};
-abbreviated(#hello_request{}, State) ->
- {next_state, certify, State};
+hello(Msg, State) ->
+ handle_unexpected_message(Msg, hello, State).
-abbreviated(Finished = #finished{},
+abbreviated(#hello_request{}, State0) ->
+ {Record, State} = next_record(State0),
+ next_state(hello, Record, State);
+
+abbreviated(Finished = #finished{verify_data = Data},
#state{role = server,
negotiated_version = Version,
tls_handshake_hashes = Hashes,
- session = #session{master_secret = MasterSecret}} =
- State0) ->
+ session = #session{master_secret = MasterSecret},
+ connection_states = ConnectionStates0} =
+ State) ->
case ssl_handshake:verify_connection(Version, Finished, client,
MasterSecret, Hashes) of
- verified ->
- State = ack_connection(State0),
- next_state_connection(State);
+ verified ->
+ ConnectionStates = ssl_record:set_client_verify_data(current_both, Data, ConnectionStates0),
+ next_state_connection(abbreviated,
+ ack_connection(State#state{connection_states = ConnectionStates}));
#alert{} = Alert ->
- handle_own_alert(Alert, Version, abbreviated, State0),
- {stop, normal, State0}
+ handle_own_alert(Alert, Version, abbreviated, State),
+ {stop, normal, State}
end;
-abbreviated(Finished = #finished{},
+abbreviated(Finished = #finished{verify_data = Data},
#state{role = client, tls_handshake_hashes = Hashes0,
session = #session{master_secret = MasterSecret},
- negotiated_version = Version} = State0) ->
+ negotiated_version = Version,
+ connection_states = ConnectionStates0} = State) ->
case ssl_handshake:verify_connection(Version, Finished, server,
MasterSecret, Hashes0) of
verified ->
- {ConnectionStates, Hashes} = finalize_client_handshake(State0),
- State = ack_connection(State0),
- next_state_connection(State#state{tls_handshake_hashes = Hashes,
- connection_states =
- ConnectionStates});
+ ConnectionStates1 = ssl_record:set_server_verify_data(current_read, Data, ConnectionStates0),
+ {ConnectionStates, Hashes} =
+ finalize_handshake(State#state{connection_states = ConnectionStates1}, abbreviated),
+ next_state_connection(abbreviated,
+ ack_connection(State#state{tls_handshake_hashes = Hashes,
+ connection_states =
+ ConnectionStates}));
#alert{} = Alert ->
- handle_own_alert(Alert, Version, abbreviated, State0),
- {stop, normal, State0}
- end.
+ handle_own_alert(Alert, Version, abbreviated, State),
+ {stop, normal, State}
+ end;
-certify(socket_control, #state{role = server} = State) ->
- {next_state, certify, State};
-certify(#hello_request{}, State) ->
- {next_state, certify, State};
+abbreviated(Msg, State) ->
+ handle_unexpected_message(Msg, abbreviated, State).
+
+certify(#hello_request{}, State0) ->
+ {Record, State} = next_record(State0),
+ next_state(hello, Record, State);
certify(#certificate{asn1_certificates = []},
#state{role = server, negotiated_version = Version,
@@ -430,9 +483,9 @@ certify(#certificate{asn1_certificates = []},
#state{role = server,
ssl_options = #ssl_options{verify = verify_peer,
fail_if_no_peer_cert = false}} =
- State) ->
- {next_state, certify,
- next_record(State#state{client_certificate_requested = false})};
+ State0) ->
+ {Record, State} = next_record(State0#state{client_certificate_requested = false}),
+ next_state(certify, Record, State);
certify(#certificate{} = Cert,
#state{negotiated_version = Version,
@@ -456,8 +509,9 @@ certify(#server_key_exchange{} = KeyExchangeMsg,
key_algorithm = Alg} = State0)
when Alg == dhe_dss; Alg == dhe_rsa ->%%Not imp:Alg == dh_anon;Alg == krb5 ->
case handle_server_key(KeyExchangeMsg, State0) of
- #state{} = State ->
- {next_state, certify, next_record(State)};
+ #state{} = State1 ->
+ {Record, State} = next_record(State1),
+ next_state(certify, Record, State);
#alert{} = Alert ->
handle_own_alert(Alert, Version, certify_server_keyexchange,
State0),
@@ -472,10 +526,9 @@ certify(#server_key_exchange{},
handle_own_alert(Alert, Version, certify_server_key_exchange, State),
{stop, normal, State};
-certify(#certificate_request{}, State) ->
- NewState = State#state{client_certificate_requested = true},
- {next_state, certify, next_record(NewState)};
-
+certify(#certificate_request{}, State0) ->
+ {Record, State} = next_record(State0#state{client_certificate_requested = true}),
+ next_state(certify, Record, State);
%% Master secret was determined with help of server-key exchange msg
certify(#server_hello_done{},
@@ -540,9 +593,10 @@ certify(#client_key_exchange{exchange_keys
ConnectionStates0, server) of
{MasterSecret, ConnectionStates} ->
Session = Session0#session{master_secret = MasterSecret},
- State = State0#state{connection_states = ConnectionStates,
+ State1 = State0#state{connection_states = ConnectionStates,
session = Session},
- {next_state, cipher, next_record(State)};
+ {Record, State} = next_record(State1),
+ next_state(cipher, Record, State);
#alert{} = Alert ->
handle_own_alert(Alert, Version,
certify_client_key_exchange, State0),
@@ -574,21 +628,25 @@ certify(#client_key_exchange{exchange_keys = #client_diffie_hellman_public{
case ssl_handshake:master_secret(Version, PremasterSecret,
ConnectionStates0, Role) of
{MasterSecret, ConnectionStates} ->
- State = State0#state{session =
+ State1 = State0#state{session =
Session#session{master_secret
= MasterSecret},
connection_states = ConnectionStates},
- {next_state, cipher, next_record(State)};
+
+ {Record, State} = next_record(State1),
+ next_state(cipher, Record, State);
#alert{} = Alert ->
handle_own_alert(Alert, Version,
certify_client_key_exchange, State0),
{stop, normal, State0}
- end.
+ end;
+
+certify(Msg, State) ->
+ handle_unexpected_message(Msg, certify, State).
-cipher(socket_control, #state{role = server} = State) ->
- {next_state, cipher, State};
-cipher(#hello_request{}, State) ->
- {next_state, cipher, State};
+cipher(#hello_request{}, State0) ->
+ {Record, State} = next_record(State0),
+ next_state(hello, Record, State);
cipher(#certificate_verify{signature = Signature},
#state{role = server,
@@ -597,71 +655,83 @@ cipher(#certificate_verify{signature = Signature},
session = #session{master_secret = MasterSecret},
key_algorithm = Algorithm,
tls_handshake_hashes = Hashes
- } = State) ->
+ } = State0) ->
case ssl_handshake:certificate_verify(Signature, PublicKeyInfo,
Version, MasterSecret,
Algorithm, Hashes) of
valid ->
- {next_state, cipher, next_record(State)};
+ {Record, State} = next_record(State0),
+ next_state(cipher, Record, State);
#alert{} = Alert ->
- handle_own_alert(Alert, Version, cipher, State),
- {stop, normal, State}
+ handle_own_alert(Alert, Version, cipher, State0),
+ {stop, normal, State0}
end;
-cipher(#finished{} = Finished,
+cipher(#finished{verify_data = Data} = Finished,
#state{negotiated_version = Version,
host = Host,
port = Port,
role = Role,
session = #session{master_secret = MasterSecret}
= Session0,
- tls_handshake_hashes = Hashes} = State0) ->
+ tls_handshake_hashes = Hashes0,
+ connection_states = ConnectionStates0} = State) ->
case ssl_handshake:verify_connection(Version, Finished,
opposite_role(Role),
- MasterSecret, Hashes) of
+ MasterSecret, Hashes0) of
verified ->
- State = ack_connection(State0),
Session = register_session(Role, Host, Port, Session0),
case Role of
client ->
- next_state_connection(State#state{session = Session});
+ ConnectionStates = ssl_record:set_server_verify_data(current_both, Data, ConnectionStates0),
+ next_state_connection(cipher, ack_connection(State#state{session = Session,
+ connection_states = ConnectionStates}));
server ->
- {NewConnectionStates, NewHashes} =
- finalize_server_handshake(State#state{
- session = Session}),
- next_state_connection(State#state{connection_states =
- NewConnectionStates,
- session = Session,
- tls_handshake_hashes =
- NewHashes})
+ ConnectionStates1 = ssl_record:set_client_verify_data(current_read, Data, ConnectionStates0),
+ {ConnectionStates, Hashes} =
+ finalize_handshake(State#state{
+ connection_states = ConnectionStates1,
+ session = Session}, cipher),
+ next_state_connection(cipher, ack_connection(State#state{connection_states =
+ ConnectionStates,
+ session = Session,
+ tls_handshake_hashes =
+ Hashes}))
end;
#alert{} = Alert ->
- handle_own_alert(Alert, Version, cipher, State0),
- {stop, normal, State0}
- end.
+ handle_own_alert(Alert, Version, cipher, State),
+ {stop, normal, State}
+ end;
+
+cipher(Msg, State) ->
+ handle_unexpected_message(Msg, cipher, State).
-connection(socket_control, #state{role = server} = State) ->
- {next_state, connection, State};
-connection(#hello_request{}, State = #state{host = Host, port = Port,
- socket = Socket,
- ssl_options = SslOpts,
- negotiated_version = Version,
- transport_cb = Transport,
- connection_states = ConnectionStates0,
- tls_handshake_hashes = Hashes0}) ->
+connection(#hello_request{}, #state{host = Host, port = Port,
+ socket = Socket,
+ ssl_options = SslOpts,
+ negotiated_version = Version,
+ transport_cb = Transport,
+ connection_states = ConnectionStates0,
+ renegotiation = {Renegotiation, _},
+ tls_handshake_hashes = Hashes0} = State0) ->
+
Hello = ssl_handshake:client_hello(Host, Port,
- ConnectionStates0, SslOpts),
+ ConnectionStates0, SslOpts, Renegotiation),
+
{BinMsg, ConnectionStates1, Hashes1} =
encode_handshake(Hello, Version, ConnectionStates0, Hashes0),
Transport:send(Socket, BinMsg),
- {next_state, hello, next_record(State#state{connection_states =
- ConnectionStates1,
- tls_handshake_hashes = Hashes1})};
+ {Record, State} = next_record(State0#state{connection_states =
+ ConnectionStates1,
+ tls_handshake_hashes = Hashes1}),
+ next_state(hello, Record, State);
connection(#client_hello{} = Hello, #state{role = server} = State) ->
- hello(Hello, State).
+ hello(Hello, State);
+connection(Msg, State) ->
+ handle_unexpected_message(Msg, connection, State).
%%--------------------------------------------------------------------
%% Function:
%% handle_event(Event, StateName, State) -> {next_state, NextStateName,
@@ -673,110 +743,8 @@ connection(#client_hello{} = Hello, #state{role = server} = State) ->
%% gen_fsm:send_all_state_event/2, this function is called to handle
%% the event.
%%--------------------------------------------------------------------
-handle_event(#ssl_tls{type = ?HANDSHAKE, fragment = Data},
- StateName,
- State0 = #state{key_algorithm = KeyAlg,
- tls_handshake_buffer = Buf0,
- negotiated_version = Version}) ->
- Handle =
- fun({#hello_request{} = Packet, _}, {next_state, connection = SName, State}) ->
- %% This message should not be included in handshake
- %% message hashes. Starts new handshake (renegotiation)
- Hs0 = ssl_handshake:init_hashes(),
- ?MODULE:SName(Packet, State#state{tls_handshake_hashes=Hs0,
- renegotiation = {true, peer}});
- ({#hello_request{} = Packet, _}, {next_state, SName, State}) ->
- %% This message should not be included in handshake
- %% message hashes. Already in negotiation so it will be ignored!
- ?MODULE:SName(Packet, State);
- ({#client_hello{} = Packet, Raw}, {next_state, connection = SName, State}) ->
- Hs0 = ssl_handshake:init_hashes(),
- Hs1 = ssl_handshake:update_hashes(Hs0, Raw),
- ?MODULE:SName(Packet, State#state{tls_handshake_hashes=Hs1,
- renegotiation = {true, peer}});
- ({Packet, Raw}, {next_state, SName, State = #state{tls_handshake_hashes=Hs0}}) ->
- Hs1 = ssl_handshake:update_hashes(Hs0, Raw),
- ?MODULE:SName(Packet, State#state{tls_handshake_hashes=Hs1});
- (_, StopState) -> StopState
- end,
- try
- {Packets, Buf} = ssl_handshake:get_tls_handshake(Data,Buf0, KeyAlg,Version),
- Start = {next_state, StateName, State0#state{tls_handshake_buffer = Buf}},
- lists:foldl(Handle, Start, Packets)
- catch throw:#alert{} = Alert ->
- handle_own_alert(Alert, Version, StateName, State0),
- {stop, normal, State0}
- end;
-
-handle_event(#ssl_tls{type = ?APPLICATION_DATA, fragment = Data},
- StateName, State0) ->
- case application_data(Data, State0) of
- Stop = {stop,_,_} ->
- Stop;
- State ->
- {next_state, StateName, State}
- end;
-
-handle_event(#ssl_tls{type = ?CHANGE_CIPHER_SPEC, fragment = <<1>>} =
- _ChangeCipher,
- StateName,
- State = #state{connection_states = ConnectionStates0}) ->
- ?DBG_TERM(_ChangeCipher),
- ConnectionStates1 =
- ssl_record:activate_pending_connection_state(ConnectionStates0, read),
- {next_state, StateName,
- next_record(State#state{connection_states = ConnectionStates1})};
-
-handle_event(#ssl_tls{type = ?ALERT, fragment = Data}, StateName, State) ->
- Alerts = decode_alerts(Data),
- ?DBG_TERM(Alerts),
- [alert_event(A) || A <- Alerts],
- {next_state, StateName, State};
-
-handle_event(#alert{level = ?FATAL} = Alert, connection,
- #state{from = From, user_application = {_Mon, Pid},
- log_alert = Log,
- host = Host, port = Port, session = Session,
- role = Role, socket_options = Opts} = State) ->
- invalidate_session(Role, Host, Port, Session),
- log_alert(Log, connection, Alert),
- alert_user(Opts#socket_options.active, Pid, From, Alert, Role),
- {stop, normal, State};
-handle_event(#alert{level = ?WARNING, description = ?CLOSE_NOTIFY} = Alert,
- connection, #state{from = From,
- role = Role,
- user_application = {_Mon, Pid},
- socket_options = Opts} = State) ->
- alert_user(Opts#socket_options.active, Pid, From, Alert, Role),
- {stop, normal, State};
-
-handle_event(#alert{level = ?FATAL} = Alert, StateName,
- #state{from = From, host = Host, port = Port, session = Session,
- log_alert = Log, role = Role} = State) ->
- invalidate_session(Role, Host, Port, Session),
- log_alert(Log, StateName, Alert),
- alert_user(From, Alert, Role),
- {stop, normal, State};
-handle_event(#alert{level = ?WARNING, description = ?CLOSE_NOTIFY} = Alert,
- _, #state{from = From, role = Role} = State) ->
- alert_user(From, Alert, Role),
- {stop, normal, State};
-
-handle_event(#alert{level = ?WARNING, description = ?NO_RENEGOTIATION} = Alert, StateName,
- #state{log_alert = Log, renegotiation = {true, internal}} = State) ->
- log_alert(Log, StateName, Alert),
- {stop, normal, State};
-
-handle_event(#alert{level = ?WARNING, description = ?NO_RENEGOTIATION} = Alert, StateName,
- #state{log_alert = Log, renegotiation = {true, From}} = State) ->
- log_alert(Log, StateName, Alert),
- gen_fsm:reply(From, {error, renegotiation_rejected}),
- {next_state, connection, next_record(State)};
-
-handle_event(#alert{level = ?WARNING, description = ?USER_CANCELED} = Alert, StateName,
- #state{log_alert = Log} = State) ->
- log_alert(Log, StateName, Alert),
- {next_state, StateName, next_record(State)}.
+handle_event(_Event, StateName, State) ->
+ {next_state, StateName, State}.
%%--------------------------------------------------------------------
%% Function:
@@ -830,27 +798,41 @@ handle_sync_event({application_data, Data}, From, StateName,
#state{send_queue = Queue} = State) ->
%% In renegotiation priorities handshake, send data when handshake is finished
{next_state, StateName, State#state{send_queue = queue:in({From, Data}, Queue)}};
-handle_sync_event(started, From, StateName, State) ->
+
+handle_sync_event(start, From, hello, State) ->
+ hello(start, State#state{from = From});
+
+%% The two clauses below could happen if a server upgrades a socket in
+%% active mode. Note that in this case we are lucky that
+%% controlling_process has been evalueated before receiving handshake
+%% messages from client. The server should put the socket in passive
+%% mode before telling the client that it is willing to upgrade
+%% and before calling ssl:ssl_accept/2. These clauses are
+%% here to make sure it is the users problem and not owers if
+%% they upgrade a active socket.
+handle_sync_event(start, _, connection, State) ->
+ {reply, connected, connection, State};
+handle_sync_event(start, From, StateName, State) ->
{next_state, StateName, State#state{from = From}};
-handle_sync_event(close, From, _StateName, State) ->
- {stop, normal, ok, State#state{from = From}};
+handle_sync_event(close, _, _StateName, State) ->
+ {stop, normal, ok, State};
-handle_sync_event({shutdown, How}, From, StateName,
+handle_sync_event({shutdown, How}, _, StateName,
#state{transport_cb = CbModule,
socket = Socket} = State) ->
case CbModule:shutdown(Socket, How) of
ok ->
{reply, ok, StateName, State};
Error ->
- {stop, normal, Error, State#state{from = From}}
+ {stop, normal, Error, State}
end;
handle_sync_event({recv, N}, From, connection = StateName, State0) ->
passive_receive(State0#state{bytes_to_read = N, from = From}, StateName);
%% Doing renegotiate wait with handling request until renegotiate is
-%% finished. Will be handled by next_state_connection/1.
+%% finished. Will be handled by next_state_connection/2.
handle_sync_event({recv, N}, From, StateName, State) ->
{next_state, StateName, State#state{bytes_to_read = N, from = From,
recv_during_renegotiation = true}};
@@ -888,7 +870,13 @@ handle_sync_event({set_opts, Opts0}, _From, StateName,
{reply, ok, StateName, State1};
Buffer =:= <<>>, Opts1#socket_options.active =:= false ->
%% Need data, set active once
- {reply, ok, StateName, next_record_if_active(State1)};
+ {Record, State2} = next_record_if_active(State1),
+ case next_state(StateName, Record, State2) of
+ {next_state, StateName, State} ->
+ {reply, ok, StateName, State};
+ {stop, Reason, State} ->
+ {stop, Reason, State}
+ end;
Buffer =:= <<>> ->
%% Active once already set
{reply, ok, StateName, State1};
@@ -896,10 +884,15 @@ handle_sync_event({set_opts, Opts0}, _From, StateName,
case application_data(<<>>, State1) of
Stop = {stop,_,_} ->
Stop;
- State ->
- {reply, ok, StateName, State}
+ {Record, State2} ->
+ case next_state(StateName, Record, State2) of
+ {next_state, StateName, State} ->
+ {reply, ok, StateName, State};
+ {stop, Reason, State} ->
+ {stop, Reason, State}
+ end
end
- end;
+ end;
handle_sync_event(renegotiate, From, connection, State) ->
renegotiate(State#state{renegotiation = {true, From}});
@@ -939,20 +932,15 @@ handle_sync_event(peer_certificate, _, StateName,
%%--------------------------------------------------------------------
%% raw data from TCP, unpack records
-handle_info({Protocol, _, Data}, StateName, State =
+handle_info({Protocol, _, Data}, StateName,
#state{data_tag = Protocol,
- negotiated_version = Version,
- tls_record_buffer = Buf0,
- tls_cipher_texts = CT0}) ->
- case ssl_record:get_tls_records(Data, Buf0) of
- {Records, Buf1} ->
- CT1 = CT0 ++ Records,
- {next_state, StateName,
- next_record(State#state{tls_record_buffer = Buf1,
- tls_cipher_texts = CT1})};
+ negotiated_version = Version} = State0) ->
+ case next_tls_record(Data, State0) of
+ {Record, State} ->
+ next_state(StateName, Record, State);
#alert{} = Alert ->
- handle_own_alert(Alert, Version, StateName, State),
- {stop, normal, State}
+ handle_own_alert(Alert, Version, StateName, State0),
+ {stop, normal, State0}
end;
handle_info({CloseTag, Socket}, _StateName,
@@ -973,13 +961,28 @@ handle_info({CloseTag, Socket}, _StateName,
?ALERT_REC(?WARNING, ?CLOSE_NOTIFY), Role),
{stop, normal, State};
+handle_info({ErrorTag, Socket, econnaborted}, StateName,
+ #state{socket = Socket, from = User, role = Role,
+ error_tag = ErrorTag} = State) when StateName =/= connection ->
+ alert_user(User, ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE), Role),
+ {stop, normal, State};
+
+handle_info({ErrorTag, Socket, Reason}, _,
+ #state{socket = Socket, from = User,
+ role = Role, error_tag = ErrorTag} = State) ->
+ Report = io_lib:format("SSL: Socket error: ~p ~n", [Reason]),
+ error_logger:info_report(Report),
+ alert_user(User, ?ALERT_REC(?FATAL, ?CLOSE_NOTIFY), Role),
+ {stop, normal, State};
+
handle_info({'DOWN', MonitorRef, _, _, _}, _,
State = #state{user_application={MonitorRef,_Pid}}) ->
{stop, normal, State};
-handle_info(A, StateName, State) ->
- io:format("SSL: Bad info (state ~w): ~w\n", [StateName, A]),
- {stop, bad_info, State}.
+handle_info(Msg, StateName, State) ->
+ Report = io_lib:format("SSL: Got unexpected info: ~p ~n", [Msg]),
+ error_logger:info_report(Report),
+ {next_state, StateName, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, StateName, State) -> void()
@@ -998,12 +1001,14 @@ terminate(_Reason, connection, #state{negotiated_version = Version,
{BinAlert, _} = encode_alert(?ALERT_REC(?WARNING,?CLOSE_NOTIFY),
Version, ConnectionStates),
Transport:send(Socket, BinAlert),
+ workaround_transport_delivery_problems(Socket, Transport),
Transport:close(Socket);
terminate(_Reason, _StateName, #state{transport_cb = Transport,
socket = Socket, send_queue = SendQueue,
renegotiation = Renegotiate}) ->
notify_senders(SendQueue),
notify_renegotiater(Renegotiate),
+ workaround_transport_delivery_problems(Socket, Transport),
Transport:close(Socket).
%%--------------------------------------------------------------------
@@ -1017,18 +1022,21 @@ code_change(_OldVsn, StateName, State, _Extra) ->
%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
-start_fsm(Role, Host, Port, Socket, Opts, User, {CbModule, _,_} = CbInfo,
+start_fsm(Role, Host, Port, Socket, Opts, User, {CbModule, _,_, _} = CbInfo,
Timeout) ->
case ssl_connection_sup:start_child([Role, Host, Port, Socket,
Opts, User, CbInfo]) of
{ok, Pid} ->
- CbModule:controlling_process(Socket, Pid),
- send_event(Pid, socket_control),
- case sync_send_all_state_event(Pid, started, Timeout) of
- connected ->
- {ok, sslsocket(Pid)};
- {error, Reason} ->
- {error, Reason}
+ case socket_control(Socket, Pid, CbModule) of
+ {ok, SslSocket} ->
+ case handshake(SslSocket, Timeout) of
+ ok ->
+ {ok, SslSocket};
+ {error, Reason} ->
+ {error, Reason}
+ end;
+ {error, Reason} ->
+ {error, Reason}
end;
{error, Reason} ->
{error, Reason}
@@ -1128,15 +1136,8 @@ init_diffie_hellman(DHParamFile, server) ->
?DEFAULT_DIFFIE_HELLMAN_PARAMS
end.
-send_event(FsmPid, Event) ->
- gen_fsm:send_event(FsmPid, Event).
-
-
-send_all_state_event(FsmPid, Event) ->
- gen_fsm:send_all_state_event(FsmPid, Event).
-
sync_send_all_state_event(FsmPid, Event) ->
- sync_send_all_state_event(FsmPid, Event, ?DEFAULT_TIMEOUT).
+ sync_send_all_state_event(FsmPid, Event, infinity).
sync_send_all_state_event(FsmPid, Event, Timeout) ->
try gen_fsm:sync_send_all_state_event(FsmPid, Event, Timeout)
@@ -1149,19 +1150,16 @@ sync_send_all_state_event(FsmPid, Event, Timeout) ->
{error, closed}
end.
-%% Events: #alert{}
-alert_event(Alert) ->
- send_all_state_event(self(), Alert).
-
%% We do currently not support cipher suites that use fixed DH.
%% If we want to implement that we should add a code
%% here to extract DH parameters form cert.
handle_peer_cert(PeerCert, PublicKeyInfo,
#state{session = Session} = State0) ->
- State = State0#state{session =
+ State1 = State0#state{session =
Session#session{peer_certificate = PeerCert},
public_key_info = PublicKeyInfo},
- {next_state, certify, next_record(State)}.
+ {Record, State} = next_record(State1),
+ next_state(certify, Record, State).
certify_client(#state{client_certificate_requested = true, role = client,
connection_states = ConnectionStates0,
@@ -1208,31 +1206,34 @@ verify_client_cert(#state{client_certificate_requested = false} = State) ->
do_server_hello(Type, #state{negotiated_version = Version,
session = Session,
- connection_states = ConnectionStates0}
+ connection_states = ConnectionStates0,
+ renegotiation = {Renegotiation, _}}
= State0) when is_atom(Type) ->
ServerHello =
ssl_handshake:server_hello(Session#session.session_id, Version,
- ConnectionStates0),
- State = server_hello(ServerHello, State0),
+ ConnectionStates0, Renegotiation),
+ State1 = server_hello(ServerHello, State0),
case Type of
new ->
- do_server_hello(ServerHello, State);
+ do_server_hello(ServerHello, State1);
resumed ->
+ ConnectionStates1 = State1#state.connection_states,
case ssl_handshake:master_secret(Version, Session,
- ConnectionStates0, server) of
- {_, ConnectionStates1} ->
- State1 = State#state{connection_states=ConnectionStates1,
- session = Session},
+ ConnectionStates1, server) of
+ {_, ConnectionStates2} ->
+ State2 = State1#state{connection_states=ConnectionStates2,
+ session = Session},
{ConnectionStates, Hashes} =
- finalize_server_handshake(State1),
- Resumed = State1#state{connection_states =
- ConnectionStates,
- tls_handshake_hashes = Hashes},
- {next_state, abbreviated, next_record(Resumed)};
+ finalize_handshake(State2, abbreviated),
+ State3 = State2#state{connection_states =
+ ConnectionStates,
+ tls_handshake_hashes = Hashes},
+ {Record, State} = next_record(State3),
+ next_state(abbreviated, Record, State);
#alert{} = Alert ->
- handle_own_alert(Alert, Version, hello, State),
- {stop, normal, State}
+ handle_own_alert(Alert, Version, hello, State1),
+ {stop, normal, State1}
end
end;
@@ -1243,12 +1244,13 @@ do_server_hello(#server_hello{cipher_suite = CipherSuite,
negotiated_version = Version} = State0) ->
try server_certify_and_key_exchange(State0) of
#state{} = State1 ->
- State = server_hello_done(State1),
+ State2 = server_hello_done(State1),
Session =
Session0#session{session_id = SessionId,
cipher_suite = CipherSuite,
compression_method = Compression},
- {next_state, certify, State#state{session = Session}}
+ {Record, State} = next_record(State2#state{session = Session}),
+ next_state(certify, Record, State)
catch
#alert{} = Alert ->
handle_own_alert(Alert, Version, hello, State0),
@@ -1259,16 +1261,16 @@ client_certify_and_key_exchange(#state{negotiated_version = Version} =
State0) ->
try do_client_certify_and_key_exchange(State0) of
State1 = #state{} ->
- {ConnectionStates, Hashes} = finalize_client_handshake(State1),
- State = State1#state{connection_states = ConnectionStates,
+ {ConnectionStates, Hashes} = finalize_handshake(State1, certify),
+ State2 = State1#state{connection_states = ConnectionStates,
%% Reinitialize
client_certificate_requested = false,
tls_handshake_hashes = Hashes},
- {next_state, cipher, next_record(State)}
-
+ {Record, State} = next_record(State2),
+ next_state(cipher, Record, State)
catch
#alert{} = Alert ->
- handle_own_alert(Alert, Version, certify_foo, State0),
+ handle_own_alert(Alert, Version, client_certify_and_key_exchange, State0),
{stop, normal, State0}
end.
@@ -1301,17 +1303,16 @@ server_hello_done(#state{transport_cb = Transport,
socket = Socket,
negotiated_version = Version,
connection_states = ConnectionStates,
- tls_handshake_hashes = Hashes} = State0) ->
+ tls_handshake_hashes = Hashes} = State) ->
HelloDone = ssl_handshake:server_hello_done(),
-
+
{BinHelloDone, NewConnectionStates, NewHashes} =
encode_handshake(HelloDone, Version, ConnectionStates, Hashes),
Transport:send(Socket, BinHelloDone),
- State = State0#state{connection_states = NewConnectionStates,
- tls_handshake_hashes = NewHashes},
- next_record(State).
-
+ State#state{connection_states = NewConnectionStates,
+ tls_handshake_hashes = NewHashes}.
+
certify_server(#state{transport_cb = Transport,
socket = Socket,
negotiated_version = Version,
@@ -1471,45 +1472,44 @@ request_client_cert(#state{ssl_options = #ssl_options{verify = verify_none}} =
State) ->
State.
-finalize_client_handshake(#state{connection_states = ConnectionStates0}
- = State) ->
- ConnectionStates1 =
- cipher_protocol(State#state{connection_states =
- ConnectionStates0}),
- ConnectionStates2 =
- ssl_record:activate_pending_connection_state(ConnectionStates1,
+finalize_handshake(State, StateName) ->
+ ConnectionStates0 = cipher_protocol(State),
+ ConnectionStates =
+ ssl_record:activate_pending_connection_state(ConnectionStates0,
write),
- finished(State#state{connection_states = ConnectionStates2}).
+ finished(State#state{connection_states = ConnectionStates}, StateName).
-
-finalize_server_handshake(State) ->
- ConnectionStates0 = cipher_protocol(State),
- ConnectionStates =
- ssl_record:activate_pending_connection_state(ConnectionStates0,
- write),
- finished(State#state{connection_states = ConnectionStates}).
-
-cipher_protocol(#state{connection_states = ConnectionStates,
+cipher_protocol(#state{connection_states = ConnectionStates0,
socket = Socket,
negotiated_version = Version,
transport_cb = Transport}) ->
- {BinChangeCipher, NewConnectionStates} =
+ {BinChangeCipher, ConnectionStates} =
encode_change_cipher(#change_cipher_spec{},
- Version, ConnectionStates),
+ Version, ConnectionStates0),
Transport:send(Socket, BinChangeCipher),
- NewConnectionStates.
+ ConnectionStates.
finished(#state{role = Role, socket = Socket, negotiated_version = Version,
transport_cb = Transport,
session = Session,
- connection_states = ConnectionStates,
- tls_handshake_hashes = Hashes}) ->
+ connection_states = ConnectionStates0,
+ tls_handshake_hashes = Hashes0}, StateName) ->
MasterSecret = Session#session.master_secret,
- Finished = ssl_handshake:finished(Version, Role, MasterSecret, Hashes),
- {BinFinished, NewConnectionStates, NewHashes} =
- encode_handshake(Finished, Version, ConnectionStates, Hashes),
+ Finished = ssl_handshake:finished(Version, Role, MasterSecret, Hashes0),
+ ConnectionStates1 = save_verify_data(Role, Finished, ConnectionStates0, StateName),
+ {BinFinished, ConnectionStates, Hashes} =
+ encode_handshake(Finished, Version, ConnectionStates1, Hashes0),
Transport:send(Socket, BinFinished),
- {NewConnectionStates, NewHashes}.
+ {ConnectionStates, Hashes}.
+
+save_verify_data(client, #finished{verify_data = Data}, ConnectionStates, certify) ->
+ ssl_record:set_client_verify_data(current_write, Data, ConnectionStates);
+save_verify_data(server, #finished{verify_data = Data}, ConnectionStates, cipher) ->
+ ssl_record:set_server_verify_data(current_both, Data, ConnectionStates);
+save_verify_data(client, #finished{verify_data = Data}, ConnectionStates, abbreviated) ->
+ ssl_record:set_client_verify_data(current_both, Data, ConnectionStates);
+save_verify_data(server, #finished{verify_data = Data}, ConnectionStates, abbreviated) ->
+ ssl_record:set_server_verify_data(current_write, Data, ConnectionStates).
handle_server_key(
#server_key_exchange{params =
@@ -1622,14 +1622,14 @@ decode_alerts(<<>>, Acc) ->
passive_receive(State0 = #state{user_data_buffer = Buffer}, StateName) ->
case Buffer of
<<>> ->
- State = next_record(State0),
- {next_state, StateName, State};
+ {Record, State} = next_record(State0),
+ next_state(StateName, Record, State);
_ ->
case application_data(<<>>, State0) of
Stop = {stop, _, _} ->
Stop;
- State ->
- {next_state, StateName, State}
+ {Record, State} ->
+ next_state(StateName, Record, State)
end
end.
@@ -1654,12 +1654,12 @@ application_data(Data, #state{user_application = {_Mon, Pid},
socket_options = SocketOpt
},
if
- SocketOpt#socket_options.active =:= false ->
- State; %% Passive mode, wait for active once or recv
- Buffer =:= <<>> -> %% Active and empty, get more data
- next_record(State);
- true -> %% We have more data
- application_data(<<>>, State)
+ SocketOpt#socket_options.active =:= false; Buffer =:= <<>> ->
+ %% Passive mode, wait for active once or recv
+ %% Active and empty, get more data
+ next_record_if_active(State);
+ true -> %% We have more data
+ application_data(<<>>, State)
end;
{error,_Reason} -> %% Invalid packet in packet mode
deliver_packet_error(SOpts, Buffer1, Pid, From),
@@ -1727,25 +1727,38 @@ deliver_app_data(SOpts = #socket_options{active=Active, packet=Type},
SO
end.
-format_reply(#socket_options{active=false, mode=Mode, header=Header}, Data) ->
- {ok, format_reply(Mode, Header, Data)};
-format_reply(#socket_options{active=_, mode=Mode, header=Header}, Data) ->
- {ssl, sslsocket(), format_reply(Mode, Header, Data)}.
+format_reply(#socket_options{active = false, mode = Mode, packet = Packet,
+ header = Header}, Data) ->
+ {ok, format_reply(Mode, Packet, Header, Data)};
+format_reply(#socket_options{active = _, mode = Mode, packet = Packet,
+ header = Header}, Data) ->
+ {ssl, sslsocket(), format_reply(Mode, Packet, Header, Data)}.
-deliver_packet_error(SO= #socket_options{active=Active}, Data, Pid, From) ->
+deliver_packet_error(SO= #socket_options{active = Active}, Data, Pid, From) ->
send_or_reply(Active, Pid, From, format_packet_error(SO, Data)).
-format_packet_error(#socket_options{active=false, mode=Mode}, Data) ->
- {error, {invalid_packet, format_reply(Mode, raw, Data)}};
-format_packet_error(#socket_options{active=_, mode=Mode}, Data) ->
- {ssl_error, sslsocket(), {invalid_packet, format_reply(Mode, raw, Data)}}.
-
-format_reply(list, _, Data) -> binary_to_list(Data);
-format_reply(binary, 0, Data) -> Data;
-format_reply(binary, raw, Data) -> Data;
-format_reply(binary, N, Data) -> % Header mode
- <<Header:N/binary, Rest/binary>> = Data,
- [binary_to_list(Header), Rest].
+format_packet_error(#socket_options{active = false, mode = Mode}, Data) ->
+ {error, {invalid_packet, format_reply(Mode, raw, 0, Data)}};
+format_packet_error(#socket_options{active = _, mode = Mode}, Data) ->
+ {ssl_error, sslsocket(), {invalid_packet, format_reply(Mode, raw, 0, Data)}}.
+
+format_reply(binary, _, N, Data) when N > 0 -> % Header mode
+ header(N, Data);
+format_reply(binary, _, _, Data) -> Data;
+format_reply(list, Packet, _, Data) when is_integer(Packet); Packet == raw ->
+ binary_to_list(Data);
+format_reply(list, _,_, Data) ->
+ Data.
+
+header(0, <<>>) ->
+ <<>>;
+header(_, <<>>) ->
+ [];
+header(0, Binary) ->
+ Binary;
+header(N, Binary) ->
+ <<?BYTE(ByteN), NewBinary/binary>> = Binary,
+ [ByteN | header(N-1, NewBinary)].
%% tcp_closed
send_or_reply(false, _Pid, undefined, _Data) ->
@@ -1766,40 +1779,111 @@ opposite_role(server) ->
send_user(Pid, Msg) ->
Pid ! Msg.
+next_state(Next, no_record, State) ->
+ {next_state, Next, State};
+
+next_state(Next, #ssl_tls{type = ?ALERT, fragment = EncAlerts}, State) ->
+ Alerts = decode_alerts(EncAlerts),
+ handle_alerts(Alerts, {next_state, Next, State});
+
+next_state(StateName, #ssl_tls{type = ?HANDSHAKE, fragment = Data},
+ State0 = #state{key_algorithm = KeyAlg,
+ tls_handshake_buffer = Buf0,
+ negotiated_version = Version}) ->
+ Handle =
+ fun({#hello_request{} = Packet, _}, {next_state, connection = SName, State}) ->
+ %% This message should not be included in handshake
+ %% message hashes. Starts new handshake (renegotiation)
+ Hs0 = ssl_handshake:init_hashes(),
+ ?MODULE:SName(Packet, State#state{tls_handshake_hashes=Hs0,
+ renegotiation = {true, peer}});
+ ({#hello_request{} = Packet, _}, {next_state, SName, State}) ->
+ %% This message should not be included in handshake
+ %% message hashes. Already in negotiation so it will be ignored!
+ ?MODULE:SName(Packet, State);
+ ({#client_hello{} = Packet, Raw}, {next_state, connection = SName, State}) ->
+ Hs0 = ssl_handshake:init_hashes(),
+ Hs1 = ssl_handshake:update_hashes(Hs0, Raw),
+ ?MODULE:SName(Packet, State#state{tls_handshake_hashes=Hs1,
+ renegotiation = {true, peer}});
+ ({Packet, Raw}, {next_state, SName, State = #state{tls_handshake_hashes=Hs0}}) ->
+ Hs1 = ssl_handshake:update_hashes(Hs0, Raw),
+ ?MODULE:SName(Packet, State#state{tls_handshake_hashes=Hs1});
+ (_, StopState) -> StopState
+ end,
+ try
+ {Packets, Buf} = ssl_handshake:get_tls_handshake(Data,Buf0, KeyAlg,Version),
+ Start = {next_state, StateName, State0#state{tls_handshake_buffer = Buf}},
+ lists:foldl(Handle, Start, Packets)
+ catch throw:#alert{} = Alert ->
+ handle_own_alert(Alert, Version, StateName, State0),
+ {stop, normal, State0}
+ end;
+
+next_state(StateName, #ssl_tls{type = ?APPLICATION_DATA, fragment = Data}, State0) ->
+ case application_data(Data, State0) of
+ Stop = {stop,_,_} ->
+ Stop;
+ {Record, State} ->
+ next_state(StateName, Record, State)
+ end;
+next_state(StateName, #ssl_tls{type = ?CHANGE_CIPHER_SPEC, fragment = <<1>>} =
+ _ChangeCipher,
+ #state{connection_states = ConnectionStates0} = State0) ->
+ ?DBG_TERM(_ChangeCipher),
+ ConnectionStates1 =
+ ssl_record:activate_pending_connection_state(ConnectionStates0, read),
+ {Record, State} = next_record(State0#state{connection_states = ConnectionStates1}),
+ next_state(StateName, Record, State);
+next_state(StateName, #ssl_tls{type = _Unknown}, State0) ->
+ %% Ignore unknown type
+ {Record, State} = next_record(State0),
+ next_state(StateName, Record, State).
+
+next_tls_record(Data, #state{tls_record_buffer = Buf0,
+ tls_cipher_texts = CT0} = State0) ->
+ case ssl_record:get_tls_records(Data, Buf0) of
+ {Records, Buf1} ->
+ CT1 = CT0 ++ Records,
+ next_record(State0#state{tls_record_buffer = Buf1,
+ tls_cipher_texts = CT1});
+ #alert{} = Alert ->
+ Alert
+ end.
+
next_record(#state{tls_cipher_texts = [], socket = Socket} = State) ->
inet:setopts(Socket, [{active,once}]),
- State;
+ {no_record, State};
next_record(#state{tls_cipher_texts = [CT | Rest],
connection_states = ConnStates0} = State) ->
{Plain, ConnStates} = ssl_record:decode_cipher_text(CT, ConnStates0),
- gen_fsm:send_all_state_event(self(), Plain),
- State#state{tls_cipher_texts = Rest, connection_states = ConnStates}.
-
+ {Plain, State#state{tls_cipher_texts = Rest, connection_states = ConnStates}}.
next_record_if_active(State =
#state{socket_options =
#socket_options{active = false}}) ->
- State;
+ {no_record ,State};
next_record_if_active(State) ->
next_record(State).
-next_state_connection(#state{send_queue = Queue0,
- negotiated_version = Version,
- socket = Socket,
- transport_cb = Transport,
- connection_states = ConnectionStates0,
- ssl_options = #ssl_options{renegotiate_at = RenegotiateAt}
- } = State) ->
+next_state_connection(StateName, #state{send_queue = Queue0,
+ negotiated_version = Version,
+ socket = Socket,
+ transport_cb = Transport,
+ connection_states = ConnectionStates0,
+ ssl_options = #ssl_options{renegotiate_at = RenegotiateAt}
+ } = State) ->
%% Send queued up data
case queue:out(Queue0) of
{{value, {From, Data}}, Queue} ->
case encode_data(Data, Version, ConnectionStates0, RenegotiateAt) of
{Msgs, [], ConnectionStates} ->
Result = Transport:send(Socket, Msgs),
- gen_fsm:reply(From, Result),
- next_state_connection(State#state{connection_states = ConnectionStates,
- send_queue = Queue});
+ gen_fsm:reply(From, Result),
+ next_state_connection(StateName,
+ State#state{connection_states = ConnectionStates,
+ send_queue = Queue});
%% This is unlikely to happen. User configuration of the
%% undocumented test option renegotiation_at can make it more likely.
{Msgs, RestData, ConnectionStates} ->
@@ -1822,9 +1906,9 @@ next_state_is_connection(State =
#socket_options{active = false}}) ->
passive_receive(State#state{recv_during_renegotiation = false}, connection);
-next_state_is_connection(State) ->
- {next_state, connection, next_record_if_active(State)}.
-
+next_state_is_connection(State0) ->
+ {Record, State} = next_record_if_active(State0),
+ next_state(connection, Record, State).
register_session(_, _, _, #session{is_resumable = true} = Session) ->
Session; %% Already registered
@@ -1843,7 +1927,7 @@ invalidate_session(server, _, Port, Session) ->
ssl_manager:invalidate_session(Port, Session).
initial_state(Role, Host, Port, Socket, {SSLOptions, SocketOptions}, User,
- {CbModule, DataTag, CloseTag}) ->
+ {CbModule, DataTag, CloseTag, ErrorTag}) ->
ConnectionStates = ssl_record:init_connection_states(Role),
SessionCacheCb = case application:get_env(ssl, session_cb) of
@@ -1863,6 +1947,7 @@ initial_state(Role, Host, Port, Socket, {SSLOptions, SocketOptions}, User,
transport_cb = CbModule,
data_tag = DataTag,
close_tag = CloseTag,
+ error_tag = ErrorTag,
role = Role,
host = Host,
port = Port,
@@ -1934,10 +2019,71 @@ set_socket_opts(Socket, [{active, Active}| Opts], SockOpts, Other) ->
set_socket_opts(Socket, [Opt | Opts], SockOpts, Other) ->
set_socket_opts(Socket, Opts, SockOpts, [Opt | Other]).
+handle_alerts([], Result) ->
+ Result;
+handle_alerts(_, {stop, _, _} = Stop) ->
+ %% If it is a fatal alert immediately close
+ Stop;
+handle_alerts([Alert | Alerts], {next_state, StateName, State}) ->
+ handle_alerts(Alerts, handle_alert(Alert, StateName, State)).
+
+handle_alert(#alert{level = ?FATAL} = Alert, connection,
+ #state{from = From, user_application = {_Mon, Pid},
+ log_alert = Log,
+ host = Host, port = Port, session = Session,
+ role = Role, socket_options = Opts} = State) ->
+ invalidate_session(Role, Host, Port, Session),
+ log_alert(Log, connection, Alert),
+ alert_user(Opts#socket_options.active, Pid, From, Alert, Role),
+ {stop, normal, State};
+
+handle_alert(#alert{level = ?WARNING, description = ?CLOSE_NOTIFY} = Alert,
+ connection, #state{from = From,
+ role = Role,
+ user_application = {_Mon, Pid},
+ socket_options = Opts} = State) ->
+ alert_user(Opts#socket_options.active, Pid, From, Alert, Role),
+ {stop, normal, State};
+
+handle_alert(#alert{level = ?FATAL} = Alert, StateName,
+ #state{from = From, host = Host, port = Port, session = Session,
+ log_alert = Log, role = Role} = State) ->
+ invalidate_session(Role, Host, Port, Session),
+ log_alert(Log, StateName, Alert),
+ alert_user(From, Alert, Role),
+ {stop, normal, State};
+handle_alert(#alert{level = ?WARNING, description = ?CLOSE_NOTIFY} = Alert,
+ _, #state{from = From, role = Role} = State) ->
+ alert_user(From, Alert, Role),
+ {stop, normal, State};
+
+handle_alert(#alert{level = ?WARNING, description = ?NO_RENEGOTIATION} = Alert, StateName,
+ #state{log_alert = Log, renegotiation = {true, internal}, from = From,
+ role = Role} = State) ->
+ log_alert(Log, StateName, Alert),
+ alert_user(From, Alert, Role),
+ {stop, normal, State};
+
+handle_alert(#alert{level = ?WARNING, description = ?NO_RENEGOTIATION} = Alert, StateName,
+ #state{log_alert = Log, renegotiation = {true, From}} = State0) ->
+ log_alert(Log, StateName, Alert),
+ gen_fsm:reply(From, {error, renegotiation_rejected}),
+ {Record, State} = next_record(State0),
+ next_state(connection, Record, State);
+
+handle_alert(#alert{level = ?WARNING, description = ?USER_CANCELED} = Alert, StateName,
+ #state{log_alert = Log} = State0) ->
+ log_alert(Log, StateName, Alert),
+ {Record, State} = next_record(State0),
+ next_state(StateName, Record, State).
+
alert_user(From, Alert, Role) ->
alert_user(false, no_pid, From, Alert, Role).
alert_user(false = Active, Pid, From, Alert, Role) ->
+ %% If there is an outstanding ssl_accept | recv
+ %% From will be defined and send_or_reply will
+ %% send the appropriate error message.
ReasonCode = ssl_alert:reason_code(Alert, Role),
send_or_reply(Active, Pid, From, {error, ReasonCode});
alert_user(Active, Pid, From, Alert, Role) ->
@@ -1965,7 +2111,7 @@ handle_own_alert(Alert, Version, StateName,
log_alert = Log}) ->
try %% Try to tell the other side
{BinMsg, _} =
- encode_alert(Alert, Version, ConnectionStates),
+ encode_alert(Alert, Version, ConnectionStates),
Transport:send(Socket, BinMsg)
catch _:_ -> %% Can crash if we are in a uninitialized state
ignore
@@ -1976,6 +2122,12 @@ handle_own_alert(Alert, Version, StateName,
catch _:_ ->
ok
end.
+
+handle_unexpected_message(_Msg, StateName, #state{negotiated_version = Version} = State) ->
+ Alert = ?ALERT_REC(?FATAL,?UNEXPECTED_MESSAGE),
+ handle_own_alert(Alert, Version, StateName, State),
+ {stop, normal, State}.
+
make_premaster_secret({MajVer, MinVer}, Alg) when Alg == rsa;
Alg == dh_dss;
Alg == dh_rsa ->
@@ -1996,9 +2148,12 @@ ack_connection(#state{renegotiation = {true, Initiater}} = State)
ack_connection(#state{renegotiation = {true, From}} = State) ->
gen_fsm:reply(From, ok),
State#state{renegotiation = undefined};
-ack_connection(#state{renegotiation = {false, first}, from = From} = State) ->
+ack_connection(#state{renegotiation = {false, first},
+ from = From} = State) when From =/= undefined ->
gen_fsm:reply(From, connected),
- State#state{renegotiation = undefined}.
+ State#state{renegotiation = undefined};
+ack_connection(State) ->
+ State.
renegotiate(#state{role = client} = State) ->
%% Handle same way as if server requested
@@ -2009,16 +2164,18 @@ renegotiate(#state{role = server,
socket = Socket,
transport_cb = Transport,
negotiated_version = Version,
- connection_states = ConnectionStates0} = State) ->
+ connection_states = ConnectionStates0} = State0) ->
HelloRequest = ssl_handshake:hello_request(),
Frag = ssl_handshake:encode_handshake(HelloRequest, Version, undefined),
Hs0 = ssl_handshake:init_hashes(),
{BinMsg, ConnectionStates} =
ssl_record:encode_handshake(Frag, Version, ConnectionStates0),
Transport:send(Socket, BinMsg),
- {next_state, hello, next_record(State#state{connection_states =
- ConnectionStates,
- tls_handshake_hashes = Hs0})}.
+ {Record, State} = next_record(State0#state{connection_states =
+ ConnectionStates,
+ tls_handshake_hashes = Hs0}),
+ next_state(hello, Record, State).
+
notify_senders(SendQueue) ->
lists:foreach(fun({From, _}) ->
gen_fsm:reply(From, {error, closed})
@@ -2028,3 +2185,8 @@ notify_renegotiater({true, From}) when not is_atom(From) ->
gen_fsm:reply(From, {error, closed});
notify_renegotiater(_) ->
ok.
+
+workaround_transport_delivery_problems(Socket, Transport) ->
+ inet:setopts(Socket, [{active, false}]),
+ Transport:shutdown(Socket, write),
+ Transport:recv(Socket, 0).
diff --git a/lib/ssl/src/ssl_handshake.erl b/lib/ssl/src/ssl_handshake.erl
index 9f5ac7106a..f0413c4d31 100644
--- a/lib/ssl/src/ssl_handshake.erl
+++ b/lib/ssl/src/ssl_handshake.erl
@@ -31,7 +31,7 @@
-include("ssl_debug.hrl").
-include_lib("public_key/include/public_key.hrl").
--export([master_secret/4, client_hello/4, server_hello/3, hello/2,
+-export([master_secret/4, client_hello/5, server_hello/4, hello/4,
hello_request/0, certify/7, certificate/3,
client_certificate_verify/6,
certificate_verify/6, certificate_request/2,
@@ -57,7 +57,7 @@
%%--------------------------------------------------------------------
client_hello(Host, Port, ConnectionStates, #ssl_options{versions = Versions,
ciphers = Ciphers}
- = SslOpts) ->
+ = SslOpts, Renegotiation) ->
Fun = fun(Version) ->
ssl_record:protocol_version(Version)
@@ -70,22 +70,25 @@ client_hello(Host, Port, ConnectionStates, #ssl_options{versions = Versions,
#client_hello{session_id = Id,
client_version = Version,
- cipher_suites = Ciphers,
+ cipher_suites = cipher_suites(Ciphers, Renegotiation),
compression_methods = ssl_record:compressions(),
- random = SecParams#security_parameters.client_random
+ random = SecParams#security_parameters.client_random,
+ renegotiation_info =
+ renegotiation_info(client, ConnectionStates, Renegotiation)
}.
%%--------------------------------------------------------------------
-%% Function: server_hello(Host, Port, SessionId,
-%% Version, ConnectionStates) -> #server_hello{}
+%% Function: server_hello(SessionId, Version,
+%% ConnectionStates, Renegotiation) -> #server_hello{}
%% SessionId
%% Version
-%% ConnectionStates
+%% ConnectionStates
+%% Renegotiation
%%
%%
%% Description: Creates a server hello message.
%%--------------------------------------------------------------------
-server_hello(SessionId, Version, ConnectionStates) ->
+server_hello(SessionId, Version, ConnectionStates, Renegotiation) ->
Pending = ssl_record:pending_connection_state(ConnectionStates, read),
SecParams = Pending#connection_state.security_parameters,
#server_hello{server_version = Version,
@@ -93,7 +96,9 @@ server_hello(SessionId, Version, ConnectionStates) ->
compression_method =
SecParams#security_parameters.compression_algorithm,
random = SecParams#security_parameters.server_random,
- session_id = SessionId
+ session_id = SessionId,
+ renegotiation_info =
+ renegotiation_info(server, ConnectionStates, Renegotiation)
}.
%%--------------------------------------------------------------------
@@ -106,27 +111,41 @@ hello_request() ->
#hello_request{}.
%%--------------------------------------------------------------------
-%% Function: hello(Hello, Info) ->
+%% Function: hello(Hello, Info, Renegotiation) ->
%% {Version, Id, NewConnectionStates} |
%% #alert{}
%%
%% Hello = #client_hello{} | #server_hello{}
-%% Info = ConnectionStates | {Port, Session, ConnectionStates}
+%% Info = ConnectionStates | {Port, #ssl_options{}, Session,
+%% Cahce, CahceCb, ConnectionStates}
%% ConnectionStates = #connection_states{}
+%% Renegotiation = boolean()
%%
%% Description: Handles a recieved hello message
%%--------------------------------------------------------------------
hello(#server_hello{cipher_suite = CipherSuite, server_version = Version,
compression_method = Compression, random = Random,
- session_id = SessionId}, ConnectionStates) ->
- NewConnectionStates =
- hello_pending_connection_states(client, CipherSuite, Random,
- Compression, ConnectionStates),
- {Version, SessionId, NewConnectionStates};
-
-hello(#client_hello{client_version = ClientVersion, random = Random} = Hello,
- {Port, #ssl_options{versions = Versions} = SslOpts,
- Session0, Cache, CacheCb, ConnectionStates0}) ->
+ session_id = SessionId, renegotiation_info = Info},
+ #ssl_options{secure_renegotiate = SecureRenegotation},
+ ConnectionStates0, Renegotiation) ->
+
+ case handle_renegotiation_info(client, Info, ConnectionStates0,
+ Renegotiation, SecureRenegotation, []) of
+ {ok, ConnectionStates1} ->
+ ConnectionStates =
+ hello_pending_connection_states(client, CipherSuite, Random,
+ Compression, ConnectionStates1),
+ {Version, SessionId, ConnectionStates};
+ #alert{} = Alert ->
+ Alert
+ end;
+
+hello(#client_hello{client_version = ClientVersion, random = Random,
+ cipher_suites = CipherSuites,
+ renegotiation_info = Info} = Hello,
+ #ssl_options{versions = Versions,
+ secure_renegotiate = SecureRenegotation} = SslOpts,
+ {Port, Session0, Cache, CacheCb, ConnectionStates0}, Renegotiation) ->
Version = select_version(ClientVersion, Versions),
case ssl_record:is_acceptable_version(Version) of
true ->
@@ -138,13 +157,20 @@ hello(#client_hello{client_version = ClientVersion, random = Random} = Hello,
no_suite ->
?ALERT_REC(?FATAL, ?INSUFFICIENT_SECURITY);
_ ->
- ConnectionStates =
- hello_pending_connection_states(server,
- CipherSuite,
- Random,
- Compression,
- ConnectionStates0),
- {Version, {Type, Session}, ConnectionStates}
+ case handle_renegotiation_info(server, Info, ConnectionStates0,
+ Renegotiation, SecureRenegotation,
+ CipherSuites) of
+ {ok, ConnectionStates1} ->
+ ConnectionStates =
+ hello_pending_connection_states(server,
+ CipherSuite,
+ Random,
+ Compression,
+ ConnectionStates1),
+ {Version, {Type, Session}, ConnectionStates};
+ #alert{} = Alert ->
+ Alert
+ end
end;
false ->
?ALERT_REC(?FATAL, ?PROTOCOL_VERSION)
@@ -525,7 +551,109 @@ select_session(Hello, Port, Session, Version,
false ->
{resumed, CacheCb:lookup(Cache, {Port, SessionId})}
end.
-
+
+
+cipher_suites(Suites, false) ->
+ [?TLS_EMPTY_RENEGOTIATION_INFO_SCSV | Suites];
+cipher_suites(Suites, true) ->
+ Suites.
+
+renegotiation_info(client, _, false) ->
+ #renegotiation_info{renegotiated_connection = undefined};
+renegotiation_info(server, ConnectionStates, false) ->
+ CS = ssl_record:current_connection_state(ConnectionStates, read),
+ case CS#connection_state.secure_renegotiation of
+ true ->
+ #renegotiation_info{renegotiated_connection = ?byte(0)};
+ false ->
+ #renegotiation_info{renegotiated_connection = undefined}
+ end;
+renegotiation_info(client, ConnectionStates, true) ->
+ CS = ssl_record:current_connection_state(ConnectionStates, read),
+ case CS#connection_state.secure_renegotiation of
+ true ->
+ Data = CS#connection_state.client_verify_data,
+ #renegotiation_info{renegotiated_connection = Data};
+ false ->
+ #renegotiation_info{renegotiated_connection = undefined}
+ end;
+
+renegotiation_info(server, ConnectionStates, true) ->
+ CS = ssl_record:current_connection_state(ConnectionStates, read),
+ case CS#connection_state.secure_renegotiation of
+ true ->
+ CData = CS#connection_state.client_verify_data,
+ SData =CS#connection_state.server_verify_data,
+ #renegotiation_info{renegotiated_connection = <<CData/binary, SData/binary>>};
+ false ->
+ #renegotiation_info{renegotiated_connection = undefined}
+ end.
+
+handle_renegotiation_info(_, #renegotiation_info{renegotiated_connection = ?byte(0)},
+ ConnectionStates, false, _, _) ->
+ {ok, ssl_record:set_renegotiation_flag(true, ConnectionStates)};
+
+handle_renegotiation_info(server, undefined, ConnectionStates, _, _, CipherSuites) ->
+ case is_member(?TLS_EMPTY_RENEGOTIATION_INFO_SCSV, CipherSuites) of
+ true ->
+ {ok, ssl_record:set_renegotiation_flag(true, ConnectionStates)};
+ false ->
+ {ok, ssl_record:set_renegotiation_flag(false, ConnectionStates)}
+ end;
+
+handle_renegotiation_info(_, undefined, ConnectionStates, false, _, _) ->
+ {ok, ssl_record:set_renegotiation_flag(false, ConnectionStates)};
+
+handle_renegotiation_info(client, #renegotiation_info{renegotiated_connection = ClientServerVerify},
+ ConnectionStates, true, _, _) ->
+ CS = ssl_record:current_connection_state(ConnectionStates, read),
+ CData = CS#connection_state.client_verify_data,
+ SData = CS#connection_state.server_verify_data,
+ case <<CData/binary, SData/binary>> == ClientServerVerify of
+ true ->
+ {ok, ConnectionStates};
+ false ->
+ ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE)
+ end;
+handle_renegotiation_info(server, #renegotiation_info{renegotiated_connection = ClientVerify},
+ ConnectionStates, true, _, CipherSuites) ->
+
+ case is_member(?TLS_EMPTY_RENEGOTIATION_INFO_SCSV, CipherSuites) of
+ true ->
+ ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE);
+ false ->
+ CS = ssl_record:current_connection_state(ConnectionStates, read),
+ Data = CS#connection_state.client_verify_data,
+ case Data == ClientVerify of
+ true ->
+ {ok, ConnectionStates};
+ false ->
+ ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE)
+ end
+ end;
+
+handle_renegotiation_info(client, undefined, ConnectionStates, true, SecureRenegotation, _) ->
+ handle_renegotiation_info(ConnectionStates, SecureRenegotation);
+
+handle_renegotiation_info(server, undefined, ConnectionStates, true, SecureRenegotation, CipherSuites) ->
+ case is_member(?TLS_EMPTY_RENEGOTIATION_INFO_SCSV, CipherSuites) of
+ true ->
+ ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE);
+ false ->
+ handle_renegotiation_info(ConnectionStates, SecureRenegotation)
+ end.
+
+handle_renegotiation_info(ConnectionStates, SecureRenegotation) ->
+ CS = ssl_record:current_connection_state(ConnectionStates, read),
+ case {SecureRenegotation, CS#connection_state.secure_renegotiation} of
+ {_, true} ->
+ ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE);
+ {true, false} ->
+ ?ALERT_REC(?FATAL, ?NO_RENEGOTIATION);
+ {false, false} ->
+ {ok, ConnectionStates}
+ end.
+
%% Update pending connection states with parameters exchanged via
%% hello messages
%% NOTE : Role is the role of the receiver of the hello message
@@ -636,31 +764,52 @@ dec_hs(?CLIENT_HELLO, <<?BYTE(Major), ?BYTE(Minor),
random = ssl_ssl2:client_random(ChallengeData, CDLength),
session_id = 0,
cipher_suites = from_3bytes(CipherSuites),
- compression_methods = [?NULL]
+ compression_methods = [?NULL],
+ renegotiation_info = undefined
};
dec_hs(?CLIENT_HELLO, <<?BYTE(Major), ?BYTE(Minor), Random:32/binary,
?BYTE(SID_length), Session_ID:SID_length/binary,
?UINT16(Cs_length), CipherSuites:Cs_length/binary,
?BYTE(Cm_length), Comp_methods:Cm_length/binary,
- _FutureCompatData/binary>>,
+ Extensions/binary>>,
_, _) ->
+
+ RenegotiationInfo = proplists:get_value(renegotiation_info, dec_hello_extensions(Extensions),
+ undefined),
#client_hello{
client_version = {Major,Minor},
random = Random,
session_id = Session_ID,
cipher_suites = from_2bytes(CipherSuites),
- compression_methods = Comp_methods
+ compression_methods = Comp_methods,
+ renegotiation_info = RenegotiationInfo
};
+
dec_hs(?SERVER_HELLO, <<?BYTE(Major), ?BYTE(Minor), Random:32/binary,
?BYTE(SID_length), Session_ID:SID_length/binary,
- Cipher_suite:2/binary, ?BYTE(Comp_method)>>, _, _) ->
+ Cipher_suite:2/binary, ?BYTE(Comp_method)>>, _, _) ->
#server_hello{
server_version = {Major,Minor},
random = Random,
session_id = Session_ID,
cipher_suite = Cipher_suite,
- compression_method = Comp_method
- };
+ compression_method = Comp_method,
+ renegotiation_info = undefined};
+
+dec_hs(?SERVER_HELLO, <<?BYTE(Major), ?BYTE(Minor), Random:32/binary,
+ ?BYTE(SID_length), Session_ID:SID_length/binary,
+ Cipher_suite:2/binary, ?BYTE(Comp_method),
+ ?UINT16(ExtLen), Extensions:ExtLen/binary>>, _, _) ->
+
+ RenegotiationInfo = proplists:get_value(renegotiation_info, dec_hello_extensions(Extensions, []),
+ undefined),
+ #server_hello{
+ server_version = {Major,Minor},
+ random = Random,
+ session_id = Session_ID,
+ cipher_suite = Cipher_suite,
+ compression_method = Comp_method,
+ renegotiation_info = RenegotiationInfo};
dec_hs(?CERTIFICATE, <<?UINT24(ACLen), ASN1Certs:ACLen/binary>>, _, _) ->
#certificate{asn1_certificates = certs_to_list(ASN1Certs)};
dec_hs(?SERVER_KEY_EXCHANGE, <<?UINT16(ModLen), Mod:ModLen/binary,
@@ -707,6 +856,32 @@ dec_hs(?FINISHED, VerifyData, _, _) ->
dec_hs(_, _, _, _) ->
throw(?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE)).
+dec_hello_extensions(<<>>) ->
+ [];
+dec_hello_extensions(<<?UINT16(ExtLen), Extensions:ExtLen/binary>>) ->
+ dec_hello_extensions(Extensions, []);
+dec_hello_extensions(_) ->
+ [].
+
+dec_hello_extensions(<<>>, Acc) ->
+ Acc;
+dec_hello_extensions(<<?UINT16(?RENEGOTIATION_EXT), ?UINT16(Len), Info:Len/binary, Rest/binary>>, Acc) ->
+ RenegotiateInfo = case Len of
+ 1 -> % Initial handshake
+ Info; % should be <<0>> will be matched in handle_renegotiation_info
+ _ ->
+ VerifyLen = Len - 1,
+ <<?BYTE(VerifyLen), VerifyInfo/binary>> = Info,
+ VerifyInfo
+ end,
+ dec_hello_extensions(Rest, [{renegotiation_info,
+ #renegotiation_info{renegotiated_connection = RenegotiateInfo}} | Acc]);
+dec_hello_extensions(<<?UINT16(_), ?UINT16(Len), _Unknown:Len, Rest/binary>>, Acc) ->
+ dec_hello_extensions(Rest, Acc);
+%% Need this clause?
+dec_hello_extensions(_, Acc) ->
+ Acc.
+
encrypted_premaster_secret(Secret, RSAPublicKey) ->
try
PreMasterSecret = public_key:encrypt_public(Secret, RSAPublicKey,
@@ -743,31 +918,36 @@ certs_from_list(ACList) ->
enc_hs(#hello_request{}, _Version, _) ->
{?HELLO_REQUEST, <<>>};
-enc_hs(#client_hello{
- client_version = {Major, Minor},
- random = Random,
- session_id = SessionID,
- cipher_suites = CipherSuites,
- compression_methods = CompMethods}, _Version, _) ->
+enc_hs(#client_hello{client_version = {Major, Minor},
+ random = Random,
+ session_id = SessionID,
+ cipher_suites = CipherSuites,
+ compression_methods = CompMethods,
+ renegotiation_info = RenegotiationInfo}, _Version, _) ->
SIDLength = byte_size(SessionID),
BinCompMethods = list_to_binary(CompMethods),
CmLength = byte_size(BinCompMethods),
BinCipherSuites = list_to_binary(CipherSuites),
CsLength = byte_size(BinCipherSuites),
+ Extensions = hello_extensions(RenegotiationInfo),
+ ExtensionsBin = enc_hello_extensions(Extensions),
{?CLIENT_HELLO, <<?BYTE(Major), ?BYTE(Minor), Random:32/binary,
?BYTE(SIDLength), SessionID/binary,
?UINT16(CsLength), BinCipherSuites/binary,
- ?BYTE(CmLength), BinCompMethods/binary>>};
-enc_hs(#server_hello{
- server_version = {Major, Minor},
- random = Random,
- session_id = Session_ID,
- cipher_suite = Cipher_suite,
- compression_method = Comp_method}, _Version, _) ->
+ ?BYTE(CmLength), BinCompMethods/binary, ExtensionsBin/binary>>};
+
+enc_hs(#server_hello{server_version = {Major, Minor},
+ random = Random,
+ session_id = Session_ID,
+ cipher_suite = Cipher_suite,
+ compression_method = Comp_method,
+ renegotiation_info = RenegotiationInfo}, _Version, _) ->
SID_length = byte_size(Session_ID),
+ Extensions = hello_extensions(RenegotiationInfo),
+ ExtensionsBin = enc_hello_extensions(Extensions),
{?SERVER_HELLO, <<?BYTE(Major), ?BYTE(Minor), Random:32/binary,
?BYTE(SID_length), Session_ID/binary,
- Cipher_suite/binary, ?BYTE(Comp_method)>>};
+ Cipher_suite/binary, ?BYTE(Comp_method), ExtensionsBin/binary>>};
enc_hs(#certificate{asn1_certificates = ASN1CertList}, _Version, _) ->
ASN1Certs = certs_from_list(ASN1CertList),
ACLen = erlang:iolist_size(ASN1Certs),
@@ -826,6 +1006,29 @@ enc_bin_sig(BinSig) ->
Size = byte_size(BinSig),
<<?UINT16(Size), BinSig/binary>>.
+%% Renegotiation info, only current extension
+hello_extensions(#renegotiation_info{renegotiated_connection = undefined}) ->
+ [];
+hello_extensions(#renegotiation_info{} = Info) ->
+ [Info].
+
+enc_hello_extensions(Extensions) ->
+ enc_hello_extensions(Extensions, <<>>).
+enc_hello_extensions([], <<>>) ->
+ <<>>;
+enc_hello_extensions([], Acc) ->
+ Size = byte_size(Acc),
+ <<?UINT16(Size), Acc/binary>>;
+
+enc_hello_extensions([#renegotiation_info{renegotiated_connection = ?byte(0) = Info} | Rest], Acc) ->
+ Len = byte_size(Info),
+ enc_hello_extensions(Rest, <<?UINT16(?RENEGOTIATION_EXT), ?UINT16(Len), Info/binary, Acc/binary>>);
+
+enc_hello_extensions([#renegotiation_info{renegotiated_connection = Info} | Rest], Acc) ->
+ InfoLen = byte_size(Info),
+ Len = InfoLen +1,
+ enc_hello_extensions(Rest, <<?UINT16(?RENEGOTIATION_EXT), ?UINT16(Len), ?BYTE(InfoLen), Info/binary, Acc/binary>>).
+
init_hashes() ->
T = {crypto:md5_init(), crypto:sha_init()},
{T, T}.
diff --git a/lib/ssl/src/ssl_handshake.hrl b/lib/ssl/src/ssl_handshake.hrl
index 889d39f2af..74fba3786c 100644
--- a/lib/ssl/src/ssl_handshake.hrl
+++ b/lib/ssl/src/ssl_handshake.hrl
@@ -81,7 +81,8 @@
random,
session_id, % opaque SessionID<0..32>
cipher_suites, % cipher_suites<2..2^16-1>
- compression_methods % compression_methods<1..2^8-1>
+ compression_methods, % compression_methods<1..2^8-1>,
+ renegotiation_info
}).
-record(server_hello, {
@@ -89,7 +90,8 @@
random,
session_id, % opaque SessionID<0..32>
cipher_suite, % cipher_suites
- compression_method % compression_method
+ compression_method, % compression_method
+ renegotiation_info
}).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -195,6 +197,15 @@
verify_data %opaque verify_data[12]
}).
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Renegotiation info RFC 5746 section 3.2
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+-define(RENEGOTIATION_EXT, 16#ff01).
+
+-record(renegotiation_info,{
+ renegotiated_connection
+ }).
+
-endif. % -ifdef(ssl_handshake).
diff --git a/lib/ssl/src/ssl_internal.hrl b/lib/ssl/src/ssl_internal.hrl
index 8d19abfe1e..fdc0c33750 100644
--- a/lib/ssl/src/ssl_internal.hrl
+++ b/lib/ssl/src/ssl_internal.hrl
@@ -75,6 +75,7 @@
%% will be reused if possible.
reuse_sessions, % boolean()
renegotiate_at,
+ secure_renegotiate,
debug %
}).
diff --git a/lib/ssl/src/ssl_record.erl b/lib/ssl/src/ssl_record.erl
index da48f049f6..f9f915f13d 100644
--- a/lib/ssl/src/ssl_record.erl
+++ b/lib/ssl/src/ssl_record.erl
@@ -38,7 +38,10 @@
set_mac_secret/4,
set_master_secret/2,
activate_pending_connection_state/2,
- set_pending_cipher_state/4]).
+ set_pending_cipher_state/4,
+ set_renegotiation_flag/2,
+ set_client_verify_data/3,
+ set_server_verify_data/3]).
%% Handling of incoming data
-export([get_tls_records/2]).
@@ -175,6 +178,98 @@ set_master_secret(MasterSecret,
master_secret = MasterSecret}},
States#connection_states{pending_read = Read1, pending_write = Write1}.
+%%--------------------------------------------------------------------
+%% Function: set_renegotiation_flag(Flag, States) ->
+%% #connection_states{}
+%% Flag = boolean()
+%% States = #connection_states{}
+%%
+%% Set master_secret in pending connection states
+%%--------------------------------------------------------------------
+set_renegotiation_flag(Flag, #connection_states{
+ current_read = CurrentRead0,
+ current_write = CurrentWrite0,
+ pending_read = PendingRead0,
+ pending_write = PendingWrite0}
+ = ConnectionStates) ->
+ CurrentRead = CurrentRead0#connection_state{secure_renegotiation = Flag},
+ CurrentWrite = CurrentWrite0#connection_state{secure_renegotiation = Flag},
+ PendingRead = PendingRead0#connection_state{secure_renegotiation = Flag},
+ PendingWrite = PendingWrite0#connection_state{secure_renegotiation = Flag},
+ ConnectionStates#connection_states{current_read = CurrentRead,
+ current_write = CurrentWrite,
+ pending_read = PendingRead,
+ pending_write = PendingWrite}.
+
+%%--------------------------------------------------------------------
+%% Function: set_client_verify_data(State, Data, States) ->
+%% #connection_states{}
+%% State = atom()
+%% Data = binary()
+%% States = #connection_states{}
+%%
+%% Set verify data in connection states.
+%%--------------------------------------------------------------------
+set_client_verify_data(current_read, Data,
+ #connection_states{current_read = CurrentRead0,
+ pending_write = PendingWrite0}
+ = ConnectionStates) ->
+ CurrentRead = CurrentRead0#connection_state{client_verify_data = Data},
+ PendingWrite = PendingWrite0#connection_state{client_verify_data = Data},
+ ConnectionStates#connection_states{current_read = CurrentRead,
+ pending_write = PendingWrite};
+set_client_verify_data(current_write, Data,
+ #connection_states{pending_read = PendingRead0,
+ current_write = CurrentWrite0}
+ = ConnectionStates) ->
+ PendingRead = PendingRead0#connection_state{client_verify_data = Data},
+ CurrentWrite = CurrentWrite0#connection_state{client_verify_data = Data},
+ ConnectionStates#connection_states{pending_read = PendingRead,
+ current_write = CurrentWrite};
+set_client_verify_data(current_both, Data,
+ #connection_states{current_read = CurrentRead0,
+ current_write = CurrentWrite0}
+ = ConnectionStates) ->
+ CurrentRead = CurrentRead0#connection_state{client_verify_data = Data},
+ CurrentWrite = CurrentWrite0#connection_state{client_verify_data = Data},
+ ConnectionStates#connection_states{current_read = CurrentRead,
+ current_write = CurrentWrite}.
+
+%%--------------------------------------------------------------------
+%% Function: set_server_verify_data(State, Data, States) ->
+%% #connection_states{}
+%% State = atom()
+%% Data = binary()
+%% States = #connection_states{}
+%%
+%% Set verify data in pending connection states.
+%%--------------------------------------------------------------------
+set_server_verify_data(current_write, Data,
+ #connection_states{pending_read = PendingRead0,
+ current_write = CurrentWrite0}
+ = ConnectionStates) ->
+ PendingRead = PendingRead0#connection_state{server_verify_data = Data},
+ CurrentWrite = CurrentWrite0#connection_state{server_verify_data = Data},
+ ConnectionStates#connection_states{pending_read = PendingRead,
+ current_write = CurrentWrite};
+
+set_server_verify_data(current_read, Data,
+ #connection_states{current_read = CurrentRead0,
+ pending_write = PendingWrite0}
+ = ConnectionStates) ->
+ CurrentRead = CurrentRead0#connection_state{server_verify_data = Data},
+ PendingWrite = PendingWrite0#connection_state{server_verify_data = Data},
+ ConnectionStates#connection_states{current_read = CurrentRead,
+ pending_write = PendingWrite};
+
+set_server_verify_data(current_both, Data,
+ #connection_states{current_read = CurrentRead0,
+ current_write = CurrentWrite0}
+ = ConnectionStates) ->
+ CurrentRead = CurrentRead0#connection_state{server_verify_data = Data},
+ CurrentWrite = CurrentWrite0#connection_state{server_verify_data = Data},
+ ConnectionStates#connection_states{current_read = CurrentRead,
+ current_write = CurrentWrite}.
%%--------------------------------------------------------------------
%% Function: activate_pending_connection_state(States, Type) ->
@@ -191,7 +286,9 @@ activate_pending_connection_state(States =
NewCurrent = Pending#connection_state{sequence_number = 0},
SecParams = Pending#connection_state.security_parameters,
ConnectionEnd = SecParams#security_parameters.connection_end,
- NewPending = empty_connection_state(ConnectionEnd),
+ EmptyPending = empty_connection_state(ConnectionEnd),
+ SecureRenegotation = NewCurrent#connection_state.secure_renegotiation,
+ NewPending = EmptyPending#connection_state{secure_renegotiation = SecureRenegotation},
States#connection_states{current_read = NewCurrent,
pending_read = NewPending
};
@@ -202,7 +299,9 @@ activate_pending_connection_state(States =
NewCurrent = Pending#connection_state{sequence_number = 0},
SecParams = Pending#connection_state.security_parameters,
ConnectionEnd = SecParams#security_parameters.connection_end,
- NewPending = empty_connection_state(ConnectionEnd),
+ EmptyPending = empty_connection_state(ConnectionEnd),
+ SecureRenegotation = NewCurrent#connection_state.secure_renegotiation,
+ NewPending = EmptyPending#connection_state{secure_renegotiation = SecureRenegotation},
States#connection_states{current_write = NewCurrent,
pending_write = NewPending
}.
diff --git a/lib/ssl/src/ssl_record.hrl b/lib/ssl/src/ssl_record.hrl
index 362b7039d4..5fb0070b91 100644
--- a/lib/ssl/src/ssl_record.hrl
+++ b/lib/ssl/src/ssl_record.hrl
@@ -60,7 +60,11 @@
compression_state,
cipher_state,
mac_secret,
- sequence_number
+ sequence_number,
+ %% RFC 5746
+ secure_renegotiation,
+ client_verify_data,
+ server_verify_data
}).
-define(MAX_SEQENCE_NUMBER, 18446744073709552000). %% math:pow(2, 64) - 1 = 1.8446744073709552e19
diff --git a/lib/ssl/test/ssl.cover b/lib/ssl/test/ssl.cover
index 138bf96b9d..e8daa363c5 100644
--- a/lib/ssl/test/ssl.cover
+++ b/lib/ssl/test/ssl.cover
@@ -3,5 +3,17 @@
'PKIX1Explicit88',
'PKIX1Implicit88',
'PKIXAttributeCertificate',
- 'SSL-PKIX']}.
+ 'SSL-PKIX',
+ ssl_pem,
+ ssl_pkix,
+ ssl_base64,
+ ssl_broker,
+ ssl_broker_int,
+ ssl_broker_sup,
+ ssl_debug,
+ ssl_server,
+ ssl_prim,
+ inet_ssl_dist,
+ 'OTP-PKIX'
+ ]}.
diff --git a/lib/ssl/test/ssl_basic_SUITE.erl b/lib/ssl/test/ssl_basic_SUITE.erl
index 7f33efd7e1..9afcbd9113 100644
--- a/lib/ssl/test/ssl_basic_SUITE.erl
+++ b/lib/ssl/test/ssl_basic_SUITE.erl
@@ -152,6 +152,7 @@ all(doc) ->
all(suite) ->
[app, connection_info, controlling_process, controller_dies,
+ client_closes_socket,
peercert, connect_dist,
peername, sockname, socket_options, misc_ssl_options, versions, cipher_suites,
upgrade, upgrade_with_timeout, tcp_connect,
@@ -170,7 +171,8 @@ all(suite) ->
client_verify_none_active, client_verify_none_active_once
%%, session_cache_process_list, session_cache_process_mnesia
,reuse_session, reuse_session_expired, server_does_not_want_to_reuse_session,
- client_renegotiate, server_renegotiate,
+ client_renegotiate, server_renegotiate, client_renegotiate_reused_session,
+ server_renegotiate_reused_session,
client_no_wrap_sequence_number, server_no_wrap_sequence_number,
extended_key_usage, validate_extensions_fun
].
@@ -322,6 +324,10 @@ controller_dies(Config) when is_list(Config) ->
Connect = fun(Pid) ->
{ok, Socket} = ssl:connect(Hostname, Port,
[{reuseaddr,true},{ssl_imp,new}]),
+ %% Make sure server finishes and verification
+ %% and is in coonection state before
+ %% killing client
+ test_server:sleep(?SLEEP),
Pid ! {self(), connected, Socket},
receive die_nice -> normal end
end,
@@ -393,6 +399,36 @@ get_close(Pid, Where) ->
end.
%%--------------------------------------------------------------------
+client_closes_socket(doc) ->
+ ["Test what happens when client closes socket before handshake is compleated"];
+client_closes_socket(suite) -> [];
+client_closes_socket(Config) when is_list(Config) ->
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+ TcpOpts = [binary, {reuseaddr, true}],
+
+ Server = ssl_test_lib:start_upgrade_server_error([{node, ServerNode}, {port, 0},
+ {from, self()},
+ {tcp_options, TcpOpts},
+ {ssl_options, ServerOpts}]),
+ Port = ssl_test_lib:inet_port(Server),
+
+ Connect = fun() ->
+ {ok, _Socket} = rpc:call(ClientNode, gen_tcp, connect,
+ [Hostname, Port, TcpOpts]),
+ %% Make sure that ssl_accept is called before
+ %% client process ends and closes socket.
+ test_server:sleep(?SLEEP)
+ end,
+
+ _Client = spawn_link(Connect),
+
+ ssl_test_lib:check_result(Server, {error,closed}),
+
+ ssl_test_lib:close(Server).
+
+%%--------------------------------------------------------------------
+
peercert(doc) ->
[""];
@@ -630,7 +666,7 @@ misc_ssl_options(Config) when is_list(Config) ->
{password, []},
{reuse_session, fun(_,_,_,_) -> true end},
{debug, []},
- {cb_info, {gen_tcp, tcp, tcp_closed}}],
+ {cb_info, {gen_tcp, tcp, tcp_closed, tcp_error}}],
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
@@ -796,11 +832,12 @@ upgrade(Config) when is_list(Config) ->
TcpOpts = [binary, {reuseaddr, true}],
Server = ssl_test_lib:start_upgrade_server([{node, ServerNode}, {port, 0},
- {from, self()},
- {mfa, {?MODULE,
- upgrade_result, []}},
- {tcp_options, TcpOpts},
- {ssl_options, ServerOpts}]),
+ {from, self()},
+ {mfa, {?MODULE,
+ upgrade_result, []}},
+ {tcp_options,
+ [{active, false} | TcpOpts]},
+ {ssl_options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_upgrade_client([{node, ClientNode},
{port, Port},
@@ -819,6 +856,7 @@ upgrade(Config) when is_list(Config) ->
ssl_test_lib:close(Client).
upgrade_result(Socket) ->
+ ssl:setopts(Socket, [{active, true}]),
ok = ssl:send(Socket, "Hello world"),
%% Make sure binary is inherited from tcp socket and that we do
%% not get the list default!
@@ -845,7 +883,8 @@ upgrade_with_timeout(Config) when is_list(Config) ->
{timeout, 5000},
{mfa, {?MODULE,
upgrade_result, []}},
- {tcp_options, TcpOpts},
+ {tcp_options,
+ [{active, false} | TcpOpts]},
{ssl_options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_upgrade_client([{node, ClientNode},
@@ -1884,7 +1923,6 @@ server_require_peer_cert_fail(Config) when is_list(Config) ->
Server = ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
- {mfa, {?MODULE, no_result, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
@@ -1892,7 +1930,6 @@ server_require_peer_cert_fail(Config) when is_list(Config) ->
Client = ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
- {mfa, {?MODULE, no_result, []}},
{options, [{active, false} | BadClientOpts]}]),
ssl_test_lib:check_result(Server, {error, esslaccept},
@@ -2076,6 +2113,76 @@ server_renegotiate(Config) when is_list(Config) ->
ok.
%%--------------------------------------------------------------------
+client_renegotiate_reused_session(doc) ->
+ ["Test ssl:renegotiate/1 on client when the ssl session will be reused."];
+
+client_renegotiate_reused_session(suite) ->
+ [];
+
+client_renegotiate_reused_session(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ ServerOpts = ?config(server_opts, Config),
+ ClientOpts = ?config(client_opts, Config),
+
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = "From erlang to erlang",
+
+ Server =
+ ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, erlang_ssl_receive, [Data]}},
+ {options, ServerOpts}]),
+ Port = ssl_test_lib:inet_port(Server),
+
+ Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE,
+ renegotiate_reuse_session, [Data]}},
+ {options, [{reuse_sessions, true} | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Client, ok, Server, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client),
+ process_flag(trap_exit, false),
+ ok.
+%%--------------------------------------------------------------------
+server_renegotiate_reused_session(doc) ->
+ ["Test ssl:renegotiate/1 on server when the ssl session will be reused."];
+
+server_renegotiate_reused_session(suite) ->
+ [];
+
+server_renegotiate_reused_session(Config) when is_list(Config) ->
+ process_flag(trap_exit, true),
+ ServerOpts = ?config(server_opts, Config),
+ ClientOpts = ?config(client_opts, Config),
+
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = "From erlang to erlang",
+
+ Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE,
+ renegotiate_reuse_session, [Data]}},
+ {options, ServerOpts}]),
+ Port = ssl_test_lib:inet_port(Server),
+
+ Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, erlang_ssl_receive, [Data]}},
+ {options, [{reuse_sessions, true} | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client),
+ ok.
+
+%%--------------------------------------------------------------------
client_no_wrap_sequence_number(doc) ->
["Test that erlang client will renegotiate session when",
"max sequence number celing is about to be reached. Although"
@@ -2278,14 +2385,14 @@ renegotiate(Socket, Data) ->
case Result of
ok ->
ok;
- %% It is not an error in erlang ssl
- %% if peer rejects renegotiation.
- %% Connection will stay up
- {error, renegotiation_rejected} ->
- ok;
Other ->
Other
end.
+
+renegotiate_reuse_session(Socket, Data) ->
+ %% Make sure session is registerd
+ test_server:sleep(?SLEEP),
+ renegotiate(Socket, Data).
session_cache_process_list(doc) ->
["Test reuse of sessions (short handshake)"];
diff --git a/lib/ssl/test/ssl_packet_SUITE.erl b/lib/ssl/test/ssl_packet_SUITE.erl
index 1bcb9a657b..a019e660e9 100644
--- a/lib/ssl/test/ssl_packet_SUITE.erl
+++ b/lib/ssl/test/ssl_packet_SUITE.erl
@@ -42,7 +42,6 @@
-define(MANY, 1000).
-define(SOME, 50).
-
%% Test server callback functions
%%--------------------------------------------------------------------
%% Function: init_per_suite(Config) -> Config
@@ -144,9 +143,20 @@ all(suite) ->
packet_wait_passive, packet_wait_active,
packet_baddata_passive, packet_baddata_active,
packet_size_passive, packet_size_active,
- packet_erl_decode,
+ packet_cdr_decode,
packet_http_decode,
- packet_http_bin_decode_multi
+ packet_http_decode_list,
+ packet_http_bin_decode_multi,
+ packet_line_decode,
+ packet_asn1_decode,
+ packet_tpkt_decode,
+ %packet_fcgi_decode,
+ packet_sunrm_decode,
+ header_decode_one_byte,
+ header_decode_two_bytes,
+ header_decode_two_bytes_one_sent,
+ header_decode_two_bytes_two_sent
+
].
%% Test cases starts here.
@@ -503,7 +513,8 @@ packet_raw_active_once_many_small(Config) when is_list(Config) ->
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
- {mfa, {?MODULE, active_once_raw, [Data, ?MANY]}},
+ {mfa, {?MODULE, active_once_raw,
+ [Data, ?MANY]}},
{options, [{active, once},
{packet, raw} |
ClientOpts]}]),
@@ -535,7 +546,8 @@ packet_raw_active_once_some_big(Config) when is_list(Config) ->
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
- {mfa, {?MODULE, active_once_raw, [Data, ?SOME]}},
+ {mfa, {?MODULE, active_once_raw,
+ [Data, ?SOME]}},
{options, [{active, once},
{packet, raw} |
ClientOpts]}]),
@@ -1191,7 +1203,8 @@ packet_send_to_large(Config) when is_list(Config) ->
{mfa, {?MODULE, active_packet, [Data, 1]}},
{options, [{active, true} | ClientOpts]}]),
- ssl_test_lib:check_result(Server, {error, {badarg, {packet_to_large, 300, 255}}}),
+ ssl_test_lib:check_result(Server, {error, {badarg,
+ {packet_to_large, 300, 255}}}),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
@@ -1216,7 +1229,8 @@ packet_wait_active(Config) when is_list(Config) ->
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
- {mfa, {?MODULE, send_incomplete ,[Data, ?SOME]}},
+ {mfa, {?MODULE, send_incomplete,
+ [Data, ?SOME]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
@@ -1251,7 +1265,8 @@ packet_wait_passive(Config) when is_list(Config) ->
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
- {mfa, {?MODULE, send_incomplete ,[Data, ?SOME]}},
+ {mfa, {?MODULE, send_incomplete,
+ [Data, ?SOME]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
@@ -1293,7 +1308,8 @@ packet_baddata_active(Config) when is_list(Config) ->
{packet, cdr} |
ClientOpts]}]),
receive
- {Client, {other, {ssl_error, _Socket, {invalid_packet, _}},{error,closed},1}} -> ok;
+ {Client, {other, {ssl_error, _Socket,
+ {invalid_packet, _}},{error,closed},1}} -> ok;
Unexpected ->
test_server:fail({unexpected, Unexpected})
end,
@@ -1338,8 +1354,11 @@ packet_baddata_passive(Config) when is_list(Config) ->
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
+
packet_size_active(doc) ->
- ["Test that if a packet of size larger than packet_size arrives error msg is sent and socket is closed"];
+ ["Test that if a packet of size larger than
+ packet_size arrives error msg is sent and socket is closed"];
+
packet_size_active(suite) ->
[];
@@ -1363,7 +1382,8 @@ packet_size_active(Config) when is_list(Config) ->
{packet, 4}, {packet_size, 10} |
ClientOpts]}]),
receive
- {Client, {other, {ssl_error, _Socket, {invalid_packet, _}},{error,closed},1}} -> ok;
+ {Client, {other, {ssl_error, _Socket,
+ {invalid_packet, _}},{error,closed},1}} -> ok;
Unexpected ->
test_server:fail({unexpected, Unexpected})
end,
@@ -1371,10 +1391,11 @@ packet_size_active(Config) when is_list(Config) ->
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
+
packet_size_passive(doc) ->
- ["Test that if a packet of size larger than packet_size arrives error msg is sent and socket is closed"];
-packet_size_passive(suite) ->
- [];
+ ["Test that if a packet of size larger
+ than packet_size arrives error msg is sent and socket is closed"];
+packet_size_passive(suite) -> [];
packet_size_passive(Config) when is_list(Config) ->
ClientOpts = ?config(client_opts, Config),
@@ -1391,7 +1412,8 @@ packet_size_passive(Config) when is_list(Config) ->
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
- {mfa, {?MODULE, passive_recv_packet, [Data, 1]}},
+ {mfa, {?MODULE, passive_recv_packet,
+ [Data, 1]}},
{options, [{active, false},
{packet, 4}, {packet_size, 30} |
ClientOpts]}]),
@@ -1405,14 +1427,11 @@ packet_size_passive(Config) when is_list(Config) ->
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
-packet_erl_decode(doc) ->
- ["Test that packets of sent to erlang:decode_packet works, i.e. currently"
- "asn1 | cdr | sunrm | fcgi | tpkt | line | http | http_bin"
- ];
-packet_erl_decode(suite) ->
+packet_cdr_decode(doc) ->
+ ["Test setting the packet option {packet, cdr}"];
+packet_cdr_decode(suite) ->
[];
-
-packet_erl_decode(Config) when is_list(Config) ->
+packet_cdr_decode(Config) when is_list(Config) ->
ClientOpts = ?config(client_opts, Config),
ServerOpts = ?config(server_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
@@ -1423,54 +1442,28 @@ packet_erl_decode(Config) when is_list(Config) ->
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
- {mfa, {?MODULE, server_packet_decode ,[Data]}},
- {options, [{active, true}, binary, {packet, cdr}|ServerOpts]}]),
+ {mfa, {?MODULE, server_packet_decode,
+ [Data]}},
+ {options, [{active, true}, binary,
+ {packet, cdr}|ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
- {mfa, {?MODULE, client_packet_decode, [Data]}},
- {options, [{active, true}, binary | ClientOpts]}]),
+ {mfa, {?MODULE, client_packet_decode,
+ [Data]}},
+ {options, [{active, true}, {packet, cdr},
+ binary | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
-
-server_packet_decode(Socket, CDR) ->
- receive
- {ssl, Socket, CDR} -> ok;
- Other1 -> exit({?LINE, Other1})
- end,
- ok = ssl:send(Socket, CDR),
- receive
- {ssl, Socket, CDR} -> ok;
- Other2 -> exit({?LINE, Other2})
- end,
- ok = ssl:send(Socket, CDR),
- ok.
-
-client_packet_decode(Socket, CDR) ->
- <<P1:10/binary, P2/binary>> = CDR,
- ok = ssl:send(Socket, P1),
- ok = ssl:send(Socket, P2),
- receive
- {ssl, Socket, CDR} -> ok;
- Other1 -> exit({?LINE, Other1})
- end,
- ssl:setopts(Socket, [{packet, cdr}]),
- ok = ssl:send(Socket, CDR),
- receive
- {ssl, Socket, CDR} -> ok;
- Other2 -> exit({?LINE, Other2})
- end,
- ok.
-
%%--------------------------------------------------------------------
packet_http_decode(doc) ->
- ["Test setting the packet option {packet, http}"];
+ ["Test setting the packet option {packet, http} {mode, binary}"];
packet_http_decode(suite) ->
[];
@@ -1489,16 +1482,19 @@ packet_http_decode(Config) when is_list(Config) ->
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
- {mfa, {?MODULE, server_http_decode, [Response]}},
- {options, [{active, true}, binary, {packet, http} |
- ServerOpts]}]),
+ {mfa, {?MODULE, server_http_decode,
+ [Response]}},
+ {options, [{active, true}, binary,
+ {packet, http} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
- {mfa, {?MODULE, client_http_decode, [Request]}},
- {options, [{active, true}, binary, {packet, http} |
+ {mfa, {?MODULE, client_http_decode,
+ [Request]}},
+ {options, [{active, true}, binary,
+ {packet, http} |
ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
@@ -1550,6 +1546,65 @@ client_http_decode(Socket, HttpRequest) ->
ok.
%%--------------------------------------------------------------------
+packet_http_decode_list(doc) ->
+ ["Test setting the packet option {packet, http}, {mode, list}"];
+packet_http_decode_list(suite) ->
+ [];
+packet_http_decode_list(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Request = "GET / HTTP/1.1\r\n"
+ "host: www.example.com\r\n"
+ "user-agent: HttpTester\r\n"
+ "\r\n",
+ Response = "HTTP/1.1 200 OK\r\n"
+ "\r\n"
+ "Hello!",
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_http_decode,
+ [Response]}},
+ {options, [{active, true}, binary,
+ {packet, http} |
+ ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_http_decode_list,
+ [Request]}},
+ {options, [{active, true}, list,
+ {packet, http} |
+ ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
+
+client_http_decode_list(Socket, HttpRequest) ->
+ ok = ssl:send(Socket, HttpRequest),
+ receive
+ {ssl, Socket, {http_response, {1,1}, 200, "OK"}} -> ok;
+ Other1 -> exit({?LINE, Other1})
+ end,
+ receive
+ {ssl, Socket, http_eoh} -> ok;
+ Other2 -> exit({?LINE, Other2})
+ end,
+ ok = ssl:setopts(Socket, [{packet, 0}]),
+ receive
+ {ssl, Socket, "Hello!"} -> ok;
+ Other3 -> exit({?LINE, Other3})
+ end,
+ ok.
+
+%%--------------------------------------------------------------------
packet_http_bin_decode_multi(doc) ->
["Test setting the packet option {packet, http_bin} with multiple requests"];
packet_http_bin_decode_multi(suite) ->
@@ -1571,16 +1626,20 @@ packet_http_bin_decode_multi(Config) when is_list(Config) ->
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
- {mfa, {?MODULE, server_http_bin_decode, [Response, NumMsgs]}},
- {options, [{active, true}, binary, {packet, http_bin} |
+ {mfa, {?MODULE, server_http_bin_decode,
+ [Response, NumMsgs]}},
+ {options, [{active, true}, binary,
+ {packet, http_bin} |
ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
- {mfa, {?MODULE, client_http_bin_decode, [Request, NumMsgs]}},
- {options, [{active, true}, binary, {packet, http_bin} |
+ {mfa, {?MODULE, client_http_bin_decode,
+ [Request, NumMsgs]}},
+ {options, [{active, true}, binary,
+ {packet, http_bin} |
ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
@@ -1635,6 +1694,344 @@ client_http_bin_decode(Socket, HttpRequest, Count) when Count > 0 ->
client_http_bin_decode(Socket, HttpRequest, Count - 1);
client_http_bin_decode(_, _, _) ->
ok.
+%%--------------------------------------------------------------------
+packet_line_decode(doc) ->
+ ["Test setting the packet option {packet, line}"];
+packet_line_decode(suite) ->
+ [];
+packet_line_decode(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = list_to_binary(lists:flatten(io_lib:format("Line ends here.~n"
+ "Now it is a new line.~n",
+ []))),
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_line_packet_decode,
+ [Data]}},
+ {options, [{active, true}, binary,
+ {packet, line}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_line_packet_decode,
+ [Data]}},
+ {options, [{active, true},
+ {packet, line},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
+
+server_line_packet_decode(Socket, Lines) ->
+ receive
+ {ssl, Socket, <<"Line ends here.\n">>} -> ok;
+ Other1 -> exit({?LINE, Other1})
+ end,
+ receive
+ {ssl, Socket, <<"Now it is a new line.\n">>} -> ok;
+ Other2 -> exit({?LINE, Other2})
+ end,
+ ok = ssl:send(Socket, Lines).
+
+client_line_packet_decode(Socket, Lines) ->
+ <<P1:10/binary, P2/binary>> = Lines,
+ ok = ssl:send(Socket, P1),
+ ok = ssl:send(Socket, P2),
+ receive
+ {ssl, Socket, <<"Line ends here.\n">>} -> ok;
+ Other1 -> exit({?LINE, Other1})
+ end,
+ receive
+ {ssl, Socket, <<"Now it is a new line.\n">>} -> ok;
+ Other2 -> exit({?LINE, Other2})
+ end.
+
+%%--------------------------------------------------------------------
+
+packet_asn1_decode(doc) ->
+ ["Test setting the packet option {packet, asn1}"];
+packet_asn1_decode(suite) ->
+ [];
+packet_asn1_decode(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ File = proplists:get_value(certfile, ServerOpts),
+
+ %% A valid asn1 BER packet (DER is stricter BER)
+ {ok,[{cert, Data, _}]} = public_key:pem_to_der(File),
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_packet_decode,
+ [Data]}},
+ {options, [{active, true}, binary,
+ {packet, asn1}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_packet_decode,
+ [Data]}},
+ {options, [{active, true}, {packet, asn1},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
+%%--------------------------------------------------------------------
+packet_tpkt_decode(doc) ->
+ ["Test setting the packet option {packet, tpkt}"];
+packet_tpkt_decode(suite) ->
+ [];
+packet_tpkt_decode(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = list_to_binary(add_tpkt_header("TPKT data")),
+
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_packet_decode,
+ [Data]}},
+ {options, [{active, true}, binary,
+ {packet, tpkt}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_packet_decode,
+ [Data]}},
+ {options, [{active, true}, {packet, tpkt},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
+%%--------------------------------------------------------------------
+
+%% packet_fcgi_decode(doc) ->
+%% ["Test setting the packet option {packet, fcgi}"];
+%% packet_fcgi_decode(suite) ->
+%% [];
+%% packet_fcgi_decode(Config) when is_list(Config) ->
+%% ClientOpts = ?config(client_opts, Config),
+%% ServerOpts = ?config(server_opts, Config),
+%% {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+%% Data = ...
+
+%% Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+%% {from, self()},
+%% {mfa, {?MODULE, server_packet_decode,
+%% [Data0, Data1]}},
+%% {options, [{active, true}, binary,
+%% {packet, fcgi}|ServerOpts]}]),
+
+%% Port = ssl_test_lib:inet_port(Server),
+%% Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+%% {host, Hostname},
+%% {from, self()},
+%% {mfa, {?MODULE, client_packet_decode,
+%% [Data0, Data1]}},
+%% {options, [{active, true}, {packet, fcgi},
+%% binary | ClientOpts]}]),
+
+%% ssl_test_lib:check_result(Server, ok, Client, ok),
+
+%% ssl_test_lib:close(Server),
+%% ssl_test_lib:close(Client).
+
+
+%%--------------------------------------------------------------------
+
+packet_sunrm_decode(doc) ->
+ ["Test setting the packet option {packet, sunrm}"];
+packet_sunrm_decode(suite) ->
+ [];
+packet_sunrm_decode(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = <<11:32, "Hello world">>,
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_packet_decode,
+ [Data]}},
+ {options, [{active, true}, binary,
+ {packet, sunrm}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_packet_decode,
+ [Data]}},
+ {options, [{active, true}, {packet, sunrm},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+%%--------------------------------------------------------------------
+
+header_decode_one_byte(doc) ->
+ ["Test setting the packet option {header, 1}"];
+header_decode_one_byte(suite) ->
+ [];
+header_decode_one_byte(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = <<11:8, "Hello world">>,
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_header_decode,
+ [Data, [11 | <<"Hello world">>]]}},
+ {options, [{active, true}, binary,
+ {header,1}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_header_decode,
+ [Data, [11 | <<"Hello world">> ]]}},
+ {options, [{active, true}, {header, 1},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
+%%--------------------------------------------------------------------
+
+header_decode_two_bytes(doc) ->
+ ["Test setting the packet option {header, 2}"];
+header_decode_two_bytes(suite) ->
+ [];
+header_decode_two_bytes(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = <<11:8, "Hello world">>,
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_header_decode,
+ [Data, [11, $H | <<"ello world">> ]]}},
+ {options, [{active, true}, binary,
+ {header,2}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_header_decode,
+ [Data, [11, $H | <<"ello world">> ]]}},
+ {options, [{active, true}, {header, 2},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
+
+%%--------------------------------------------------------------------
+
+header_decode_two_bytes_two_sent(doc) ->
+ ["Test setting the packet option {header, 2} and sending on byte"];
+header_decode_two_bytes_two_sent(suite) ->
+ [];
+header_decode_two_bytes_two_sent(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = <<"He">>,
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_header_decode,
+ [Data, [$H, $e | <<>> ]]}},
+ {options, [{active, true}, binary,
+ {header,2}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_header_decode,
+ [Data, [$H, $e | <<>> ]]}},
+ {options, [{active, true}, {header, 2},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
+
+%%--------------------------------------------------------------------
+
+header_decode_two_bytes_one_sent(doc) ->
+ ["Test setting the packet option {header, 2} and sending on byte"];
+header_decode_two_bytes_one_sent(suite) ->
+ [];
+header_decode_two_bytes_one_sent(Config) when is_list(Config) ->
+ ClientOpts = ?config(client_opts, Config),
+ ServerOpts = ?config(server_opts, Config),
+ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
+
+ Data = <<"H">>,
+
+ Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
+ {from, self()},
+ {mfa, {?MODULE, server_header_decode,
+ [Data, "H"]}},
+ {options, [{active, true}, binary,
+ {header,2}|ServerOpts]}]),
+
+ Port = ssl_test_lib:inet_port(Server),
+ Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {?MODULE, client_header_decode,
+ [Data, "H"]}},
+ {options, [{active, true}, {header, 2},
+ binary | ClientOpts]}]),
+
+ ssl_test_lib:check_result(Server, ok, Client, ok),
+
+ ssl_test_lib:close(Server),
+ ssl_test_lib:close(Client).
+
%%--------------------------------------------------------------------
%% Internal functions
@@ -1744,3 +2141,61 @@ active_packet(Socket, Data, N) ->
assert_packet_opt(Socket, Type) ->
{ok, [{packet, Type}]} = ssl:getopts(Socket, [packet]).
+
+server_packet_decode(Socket, Packet) ->
+ receive
+ {ssl, Socket, Packet} -> ok;
+ Other1 -> exit({?LINE, Other1})
+ end,
+ ok = ssl:send(Socket, Packet),
+ receive
+ {ssl, Socket, Packet} -> ok;
+ Other2 -> exit({?LINE, Other2})
+ end,
+ ok = ssl:send(Socket, Packet).
+
+client_packet_decode(Socket, Packet) ->
+ <<P1:10/binary, P2/binary>> = Packet,
+ ok = ssl:send(Socket, P1),
+ ok = ssl:send(Socket, P2),
+ receive
+ {ssl, Socket, Packet} -> ok;
+ Other1 -> exit({?LINE, Other1})
+ end,
+ ok = ssl:send(Socket, Packet),
+ receive
+ {ssl, Socket, Packet} -> ok;
+ Other2 -> exit({?LINE, Other2})
+ end.
+
+server_header_decode(Socket, Packet, Result) ->
+ receive
+ {ssl, Socket, Result} -> ok;
+ Other1 -> exit({?LINE, Other1})
+ end,
+ ok = ssl:send(Socket, Packet),
+ receive
+ {ssl, Socket, Result} -> ok;
+ Other2 -> exit({?LINE, Other2})
+ end,
+ ok = ssl:send(Socket, Packet).
+
+client_header_decode(Socket, Packet, Result) ->
+ ok = ssl:send(Socket, Packet),
+ receive
+ {ssl, Socket, Result} -> ok;
+ Other1 -> exit({?LINE, Other1})
+ end,
+ ok = ssl:send(Socket, Packet),
+ receive
+ {ssl, Socket, Result} -> ok;
+ Other2 -> exit({?LINE, Other2})
+ end.
+
+add_tpkt_header(Data) when is_binary(Data) ->
+ L = size(Data) + 4,
+ [3, 0, ((L) bsr 8) band 16#ff, (L) band 16#ff ,Data];
+add_tpkt_header(IOList) when is_list(IOList) ->
+ Binary = list_to_binary(IOList),
+ L = size(Binary) + 4,
+ [3, 0, ((L) bsr 8) band 16#ff, (L) band 16#ff , Binary].
diff --git a/lib/ssl/test/ssl_test_lib.erl b/lib/ssl/test/ssl_test_lib.erl
index 00c5350ad0..46b6eb401d 100644
--- a/lib/ssl/test/ssl_test_lib.erl
+++ b/lib/ssl/test/ssl_test_lib.erl
@@ -394,6 +394,41 @@ run_upgrade_client(Opts) ->
ok = rpc:call(Node, ssl, close, [SslSocket])
end.
+start_upgrade_server_error(Args) ->
+ Result = spawn_link(?MODULE, run_upgrade_server_error, [Args]),
+ receive
+ {listen, up} ->
+ Result
+ end.
+
+run_upgrade_server_error(Opts) ->
+ Node = proplists:get_value(node, Opts),
+ Port = proplists:get_value(port, Opts),
+ TimeOut = proplists:get_value(timeout, Opts, infinity),
+ TcpOptions = proplists:get_value(tcp_options, Opts),
+ SslOptions = proplists:get_value(ssl_options, Opts),
+ Pid = proplists:get_value(from, Opts),
+
+ test_server:format("gen_tcp:listen(~p, ~p)~n", [Port, TcpOptions]),
+ {ok, ListenSocket} = rpc:call(Node, gen_tcp, listen, [Port, TcpOptions]),
+ Pid ! {listen, up},
+ send_selected_port(Pid, Port, ListenSocket),
+ test_server:format("gen_tcp:accept(~p)~n", [ListenSocket]),
+ {ok, AcceptSocket} = rpc:call(Node, gen_tcp, accept, [ListenSocket]),
+ Error = case TimeOut of
+ infinity ->
+ test_server:format("ssl:ssl_accept(~p, ~p)~n",
+ [AcceptSocket, SslOptions]),
+ rpc:call(Node, ssl, ssl_accept,
+ [AcceptSocket, SslOptions]);
+ _ ->
+ test_server:format("ssl:ssl_accept(~p, ~p, ~p)~n",
+ [AcceptSocket, SslOptions, TimeOut]),
+ rpc:call(Node, ssl, ssl_accept,
+ [AcceptSocket, SslOptions, TimeOut])
+ end,
+ Pid ! {self(), Error}.
+
start_server_error(Args) ->
Result = spawn_link(?MODULE, run_server_error, [Args]),
receive
diff --git a/lib/ssl/test/ssl_to_openssl_SUITE.erl b/lib/ssl/test/ssl_to_openssl_SUITE.erl
index cbf0447bf0..03466aec6f 100644
--- a/lib/ssl/test/ssl_to_openssl_SUITE.erl
+++ b/lib/ssl/test/ssl_to_openssl_SUITE.erl
@@ -81,11 +81,20 @@ end_per_suite(_Config) ->
%% variable, but should NOT alter/remove any existing entries.
%% Description: Initialization before each test case
%%--------------------------------------------------------------------
-init_per_testcase(_TestCase, Config0) ->
+init_per_testcase(TestCase, Config0) ->
Config = lists:keydelete(watchdog, 1, Config0),
Dog = ssl_test_lib:timetrap(?TIMEOUT),
- [{watchdog, Dog} | Config].
+ special_init(TestCase, [{watchdog, Dog} | Config]).
+special_init(TestCase, Config)
+ when TestCase == erlang_client_openssl_server_renegotiate;
+ TestCase == erlang_client_openssl_server_no_wrap_sequence_number;
+ TestCase == erlang_server_openssl_client_no_wrap_sequence_number ->
+ check_sane_openssl_renegotaite(Config);
+
+special_init(_, Config) ->
+ Config.
+
%%--------------------------------------------------------------------
%% Function: end_per_testcase(TestCase, Config) -> _
%% Case - atom()
@@ -297,12 +306,8 @@ erlang_client_openssl_server_renegotiate(Config) when is_list(Config) ->
test_server:sleep(?SLEEP),
port_command(OpensslPort, OpenSslData),
- %%ssl_test_lib:check_result(Client, ok),
- %% Currently allow test case to not fail
- %% if server requires secure renegotiation from RFC-5746
- %% This should be removed as soon as we have implemented it.
- ssl_test_lib:check_result_ignore_renegotiation_reject(Client, ok),
-
+ ssl_test_lib:check_result(Client, ok),
+
%% Clean close down! Server needs to be closed first !!
close_port(OpensslPort),
@@ -350,11 +355,7 @@ erlang_client_openssl_server_no_wrap_sequence_number(Config) when is_list(Config
{options, [{reuse_sessions, false},
{renegotiate_at, N} | ClientOpts]}]),
- %%ssl_test_lib:check_result(Client, ok),
- %% Currently allow test case to not fail
- %% if server requires secure renegotiation from RFC-5746
- %% This should be removed as soon as we have implemented it.
- ssl_test_lib:check_result_ignore_renegotiation_reject(Client, ok),
+ ssl_test_lib:check_result(Client, ok),
%% Clean close down! Server needs to be closed first !!
close_port(OpensslPort),
@@ -958,7 +959,7 @@ erlang_client_bad_openssl_server(Config) when is_list(Config) ->
wait_for_openssl_server(),
- Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
+ Client0 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, server_sent_garbage, []}},
@@ -970,11 +971,22 @@ erlang_client_bad_openssl_server(Config) when is_list(Config) ->
test_server:sleep(?SLEEP),
- Client ! server_sent_garbage,
-
- ssl_test_lib:check_result(Client, true),
-
- ssl_test_lib:close(Client),
+ Client0 ! server_sent_garbage,
+
+ ssl_test_lib:check_result(Client0, true),
+
+ ssl_test_lib:close(Client0),
+
+ %% Make sure openssl does not hang and leave zombie process
+ Client1 = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
+ {host, Hostname},
+ {from, self()},
+ {mfa, {ssl_test_lib, no_result_msg, []}},
+ {options,
+ [{versions, [tlsv1]} | ClientOpts]}]),
+
+ ssl_test_lib:close(Client1),
+
%% Clean close down!
close_port(OpensslPort),
process_flag(trap_exit, false),
@@ -1055,6 +1067,7 @@ server_sent_garbage(Socket) ->
receive
server_sent_garbage ->
{error, closed} == ssl:send(Socket, "data")
+
end.
wait_for_openssl_server() ->
@@ -1068,3 +1081,10 @@ wait_for_openssl_server() ->
test_server:sleep(?SLEEP)
end.
+check_sane_openssl_renegotaite(Config) ->
+ case os:cmd("openssl version") of
+ "OpenSSL 0.9.8l" ++ _ ->
+ {skip, "Known renegotiation bug in OppenSSL"};
+ _ ->
+ Config
+ end.
diff --git a/lib/ssl/vsn.mk b/lib/ssl/vsn.mk
index 337ea4b380..e3db7008e3 100644
--- a/lib/ssl/vsn.mk
+++ b/lib/ssl/vsn.mk
@@ -17,14 +17,18 @@
# %CopyrightEnd%
#
-SSL_VSN = 3.11
-
-TICKETS = OTP-8517 \
- OTP-7046 \
- OTP-8557 \
- OTP-8560 \
- OTP-8545 \
- OTP-8554
+SSL_VSN = 3.11.1
+
+TICKETS = OTP-8588 \
+ OTP-8568 \
+ OTP-7049
+
+#TICKETS_3.11 = OTP-8517 \
+# OTP-7046 \
+# OTP-8557 \
+# OTP-8560 \
+# OTP-8545 \
+# OTP-8554
#TICKETS_3.10.9 = OTP-8510
diff --git a/lib/stdlib/doc/src/erl_scan.xml b/lib/stdlib/doc/src/erl_scan.xml
index 4175146c3c..1199c34f0f 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>2009</year>
+ <year>1996</year><year>2010</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -13,12 +13,12 @@
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>erl_scan</title>
@@ -103,7 +103,7 @@ attributes() = line() | list() | tuple()</code>
Info, atom()}</c>,
<c>{char, Info, integer()}</c>, <c>{comment, Info,
string()}</c>, <c>{float, Info, float()}</c>, <c>{integer,
- Info, integer()}</c>, <c>{var, Info, atom()}</c>,
+ Info, integer()}</c>, <c>{var, Info, atom()}</c>,
and <c>{white_space, Info, string()}</c>.</p>
<p>The valid options are:</p>
<taglist>
@@ -149,7 +149,8 @@ attributes() = line() | list() | tuple()</code>
<v>StartLocation = EndLocation = location()</v>
<v>Options = Option | [Option]</v>
<v>Option = {reserved_word_fun,reserved_word_fun()}
- | return_comments | return_white_spaces | return</v>
+ | return_comments | return_white_spaces | return
+ | text</v>
</type>
<desc>
<p>This is the re-entrant scanner which scans characters until
@@ -173,7 +174,7 @@ attributes() = line() | list() | tuple()</code>
<tag><c>{error, ErrorInfo, EndLocation}</c></tag>
<item>
<p>An error occurred. <c>LeftOverChars</c> is the remaining
- characters of the input data,
+ characters of the input data,
starting from <c>EndLocation</c>.</p>
</item>
</taglist>
@@ -278,7 +279,7 @@ attributes() = line() | list() | tuple()</code>
<item><p>The token's symbol.</p>
</item>
<tag><c>{text, string()}</c></tag>
- <item><p>The token's text..</p>
+ <item><p>The token's text.</p>
</item>
</taglist>
</desc>
@@ -315,7 +316,7 @@ attributes() = line() | list() | tuple()</code>
<type>
<v>Attributes = attributes()</v>
<v>AttributeItemSpec = AttributeItem | [AttributeItem]</v>
- <v>AttributesInfo = AttributeInfoTuple | undefined
+ <v>AttributesInfo = AttributeInfoTuple | undefined
| [AttributeInfoTuple]</v>
<v>AttributeInfoTuple = {AttributeItem, Info}</v>
<v>AttributeItem = atom()</v>
@@ -352,7 +353,7 @@ attributes() = line() | list() | tuple()</code>
just the line if the column unknown.</p>
</item>
<tag><c>{text, string()}</c></tag>
- <item><p>The token's text..</p>
+ <item><p>The token's text.</p>
</item>
</taglist>
</desc>
diff --git a/lib/stdlib/src/erl_parse.yrl b/lib/stdlib/src/erl_parse.yrl
index 786319d79c..69807aad83 100644
--- a/lib/stdlib/src/erl_parse.yrl
+++ b/lib/stdlib/src/erl_parse.yrl
@@ -30,9 +30,8 @@ expr_600 expr_700 expr_800 expr_900
expr_max
list tail
list_comprehension lc_expr lc_exprs
-binary_comprehension
+binary_comprehension
tuple
-atom1
%struct
record_expr record_tuple record_field record_fields
if_expr if_clause if_clauses case_expr cr_clause cr_clauses receive_expr
@@ -55,7 +54,7 @@ char integer float atom string var
'(' ')' ',' '->' ':-' '{' '}' '[' ']' '|' '||' '<-' ';' ':' '#' '.'
'after' 'begin' 'case' 'try' 'catch' 'end' 'fun' 'if' 'of' 'receive' 'when'
-'andalso' 'orelse' 'query' 'spec'
+'andalso' 'orelse' 'query'
'bnot' 'not'
'*' '/' 'div' 'rem' 'band' 'and'
'+' '-' 'bor' 'bxor' 'bsl' 'bsr' 'or' 'xor'
@@ -63,6 +62,7 @@ char integer float atom string var
'==' '/=' '=<' '<' '>=' '>' '=:=' '=/=' '<='
'<<' '>>'
'!' '=' '::'
+'spec' % helper
dot.
Expect 2.
@@ -77,19 +77,16 @@ attribute -> '-' atom attr_val : build_attribute('$2', '$3').
attribute -> '-' atom typed_attr_val : build_typed_attribute('$2','$3').
attribute -> '-' atom '(' typed_attr_val ')' : build_typed_attribute('$2','$4').
attribute -> '-' 'spec' type_spec : build_type_spec('$2', '$3').
-
-atom1 -> 'spec' : {atom, ?line('$1'), 'spec'}.
-atom1 -> atom : '$1'.
type_spec -> spec_fun type_sigs : {'$1', '$2'}.
type_spec -> '(' spec_fun type_sigs ')' : {'$2', '$3'}.
-spec_fun -> atom1 : '$1'.
-spec_fun -> atom1 ':' atom1 : {'$1', '$3'}.
+spec_fun -> atom : '$1'.
+spec_fun -> atom ':' atom : {'$1', '$3'}.
%% The following two are retained only for backwards compatibility;
%% they are not part of the EEP syntax and should be removed.
-spec_fun -> atom1 '/' integer '::' : {'$1', '$3'}.
-spec_fun -> atom1 ':' atom1 '/' integer '::' : {'$1', '$3', '$5'}.
+spec_fun -> atom '/' integer '::' : {'$1', '$3'}.
+spec_fun -> atom ':' atom '/' integer '::' : {'$1', '$3', '$5'}.
typed_attr_val -> expr ',' typed_record_fields : {typed_record, '$1', '$3'}.
typed_attr_val -> expr '::' top_type : {type_def, '$1', '$3'}.
@@ -107,13 +104,13 @@ type_sigs -> type_sig : ['$1'].
type_sigs -> type_sig ';' type_sigs : ['$1'|'$3'].
type_sig -> fun_type : '$1'.
-type_sig -> fun_type 'when' type_guards : {type, ?line('$1'), bounded_fun,
+type_sig -> fun_type 'when' type_guards : {type, ?line('$1'), bounded_fun,
['$1','$3']}.
type_guards -> type_guard : ['$1'].
type_guards -> type_guard ',' type_guards : ['$1'|'$3'].
-type_guard -> atom1 '(' top_types ')' : {type, ?line('$1'), constraint,
+type_guard -> atom '(' top_types ')' : {type, ?line('$1'), constraint,
['$1', '$3']}.
top_types -> top_type : ['$1'].
@@ -127,53 +124,53 @@ top_type_100 -> type '|' top_type_100 : lift_unions('$1','$3').
type -> '(' top_type ')' : {paren_type, ?line('$2'), ['$2']}.
type -> var : '$1'.
-type -> atom1 : '$1'.
-type -> atom1 '(' ')' : build_gen_type('$1').
-type -> atom1 '(' top_types ')' : {type, ?line('$1'),
+type -> atom : '$1'.
+type -> atom '(' ')' : build_gen_type('$1').
+type -> atom '(' top_types ')' : {type, ?line('$1'),
normalise('$1'), '$3'}.
-type -> atom1 ':' atom1 '(' ')' : {remote_type, ?line('$1'),
+type -> atom ':' atom '(' ')' : {remote_type, ?line('$1'),
['$1', '$3', []]}.
-type -> atom1 ':' atom1 '(' top_types ')' : {remote_type, ?line('$1'),
+type -> atom ':' atom '(' top_types ')' : {remote_type, ?line('$1'),
['$1', '$3', '$5']}.
type -> '[' ']' : {type, ?line('$1'), nil, []}.
type -> '[' top_type ']' : {type, ?line('$1'), list, ['$2']}.
-type -> '[' top_type ',' '.' '.' '.' ']' : {type, ?line('$1'),
+type -> '[' top_type ',' '.' '.' '.' ']' : {type, ?line('$1'),
nonempty_list, ['$2']}.
type -> '{' '}' : {type, ?line('$1'), tuple, []}.
type -> '{' top_types '}' : {type, ?line('$1'), tuple, '$2'}.
-type -> '#' atom1 '{' '}' : {type, ?line('$1'), record, ['$2']}.
-type -> '#' atom1 '{' field_types '}' : {type, ?line('$1'),
+type -> '#' atom '{' '}' : {type, ?line('$1'), record, ['$2']}.
+type -> '#' atom '{' field_types '}' : {type, ?line('$1'),
record, ['$2'|'$4']}.
type -> binary_type : '$1'.
type -> int_type : '$1'.
-type -> int_type '.' '.' int_type : {type, ?line('$1'), range,
+type -> int_type '.' '.' int_type : {type, ?line('$1'), range,
['$1', '$4']}.
type -> 'fun' '(' ')' : {type, ?line('$1'), 'fun', []}.
type -> 'fun' '(' fun_type_100 ')' : '$3'.
int_type -> integer : '$1'.
-int_type -> '-' integer : abstract(-normalise('$2'),
+int_type -> '-' integer : abstract(-normalise('$2'),
?line('$2')).
-fun_type_100 -> '(' '.' '.' '.' ')' '->' top_type
+fun_type_100 -> '(' '.' '.' '.' ')' '->' top_type
: {type, ?line('$1'), 'fun',
[{type, ?line('$1'), any}, '$7']}.
fun_type_100 -> fun_type : '$1'.
fun_type -> '(' ')' '->' top_type : {type, ?line('$1'), 'fun',
[{type, ?line('$1'), product, []}, '$4']}.
-fun_type -> '(' top_types ')' '->' top_type
+fun_type -> '(' top_types ')' '->' top_type
: {type, ?line('$1'), 'fun',
[{type, ?line('$1'), product, '$2'},'$5']}.
field_types -> field_type : ['$1'].
field_types -> field_type ',' field_types : ['$1'|'$3'].
-field_type -> atom1 '::' top_type : {type, ?line('$1'), field_type,
+field_type -> atom '::' top_type : {type, ?line('$1'), field_type,
['$1', '$3']}.
-binary_type -> '<<' '>>' : {type, ?line('$1'),binary,
- [abstract(0, ?line('$1')),
+binary_type -> '<<' '>>' : {type, ?line('$1'),binary,
+ [abstract(0, ?line('$1')),
abstract(0, ?line('$1'))]}.
binary_type -> '<<' bin_base_type '>>' : {type, ?line('$1'),binary,
['$2', abstract(0, ?line('$1'))]}.
@@ -195,7 +192,7 @@ function -> function_clauses : build_function('$1').
function_clauses -> function_clause : ['$1'].
function_clauses -> function_clause ';' function_clauses : ['$1'|'$3'].
-function_clause -> atom1 clause_args clause_guard clause_body :
+function_clause -> atom clause_args clause_guard clause_body :
{clause,?line('$1'),element(3, '$1'),'$2','$3','$4'}.
@@ -248,9 +245,9 @@ expr_800 -> expr_900 ':' expr_max :
{remote,?line('$2'),'$1','$3'}.
expr_800 -> expr_900 : '$1'.
-expr_900 -> '.' atom1 :
+expr_900 -> '.' atom :
{record_field,?line('$1'),{atom,?line('$1'),''},'$2'}.
-expr_900 -> expr_900 '.' atom1 :
+expr_900 -> expr_900 '.' atom :
{record_field,?line('$2'),'$1','$3'}.
expr_900 -> expr_max : '$1'.
@@ -301,8 +298,8 @@ opt_bit_type_list -> '$empty' : default.
bit_type_list -> bit_type '-' bit_type_list : ['$1' | '$3'].
bit_type_list -> bit_type : ['$1'].
-bit_type -> atom1 : element(3,'$1').
-bit_type -> atom1 ':' integer : { element(3,'$1'), element(3,'$3') }.
+bit_type -> atom : element(3,'$1').
+bit_type -> atom ':' integer : { element(3,'$1'), element(3,'$3') }.
bit_size_expr -> expr_max : '$1'.
@@ -322,7 +319,7 @@ tuple -> '{' '}' : {tuple,?line('$1'),[]}.
tuple -> '{' exprs '}' : {tuple,?line('$1'),'$2'}.
-%%struct -> atom1 tuple :
+%%struct -> atom tuple :
%% {struct,?line('$1'),element(3, '$1'),element(3, '$2')}.
@@ -330,13 +327,17 @@ tuple -> '{' exprs '}' : {tuple,?line('$1'),'$2'}.
%% N.B. Field names are returned as the complete object, even if they are
%% always atoms for the moment, this might change in the future.
-record_expr -> '#' atom1 '.' atom1 :
+record_expr -> '#' atom '.' atom :
{record_index,?line('$1'),element(3, '$2'),'$4'}.
-record_expr -> '#' atom1 record_tuple :
+record_expr -> '#' atom record_tuple :
{record,?line('$1'),element(3, '$2'),'$3'}.
-record_expr -> expr_max '#' atom1 '.' atom1 :
+record_expr -> expr_max '#' atom '.' atom :
{record_field,?line('$2'),'$1',element(3, '$3'),'$5'}.
-record_expr -> expr_max '#' atom1 record_tuple :
+record_expr -> expr_max '#' atom record_tuple :
+ {record,?line('$2'),'$1',element(3, '$3'),'$4'}.
+record_expr -> record_expr '#' atom '.' atom :
+ {record_field,?line('$2'),'$1',element(3, '$3'),'$5'}.
+record_expr -> record_expr '#' atom record_tuple :
{record,?line('$2'),'$1',element(3, '$3'),'$4'}.
record_tuple -> '{' '}' : [].
@@ -346,7 +347,7 @@ record_fields -> record_field : ['$1'].
record_fields -> record_field ',' record_fields : ['$1' | '$3'].
record_field -> var '=' expr : {record_field,?line('$1'),'$1','$3'}.
-record_field -> atom1 '=' expr : {record_field,?line('$1'),'$1','$3'}.
+record_field -> atom '=' expr : {record_field,?line('$1'),'$1','$3'}.
%% N.B. This is called from expr_700.
@@ -380,9 +381,9 @@ receive_expr -> 'receive' cr_clauses 'after' expr clause_body 'end' :
{'receive',?line('$1'),'$2','$4','$5'}.
-fun_expr -> 'fun' atom1 '/' integer :
+fun_expr -> 'fun' atom '/' integer :
{'fun',?line('$1'),{function,element(3, '$2'),element(3, '$4')}}.
-fun_expr -> 'fun' atom1 ':' atom1 '/' integer :
+fun_expr -> 'fun' atom ':' atom '/' integer :
{'fun',?line('$1'),{function,element(3, '$2'),element(3, '$4'),element(3,'$6')}}.
fun_expr -> 'fun' fun_clauses 'end' :
build_fun(?line('$1'), '$2').
@@ -412,7 +413,7 @@ try_clauses -> try_clause ';' try_clauses : ['$1' | '$3'].
try_clause -> expr clause_guard clause_body :
L = ?line('$1'),
{clause,L,[{tuple,L,[{atom,L,throw},'$1',{var,L,'_'}]}],'$2','$3'}.
-try_clause -> atom1 ':' expr clause_guard clause_body :
+try_clause -> atom ':' expr clause_guard clause_body :
L = ?line('$1'),
{clause,L,[{tuple,L,['$1','$3',{var,L,'_'}]}],'$4','$5'}.
try_clause -> var ':' expr clause_guard clause_body :
@@ -436,7 +437,7 @@ guard -> exprs ';' guard : ['$1'|'$3'].
atomic -> char : '$1'.
atomic -> integer : '$1'.
atomic -> float : '$1'.
-atomic -> atom1 : '$1'.
+atomic -> atom : '$1'.
atomic -> strings : '$1'.
strings -> string : '$1'.
@@ -481,7 +482,7 @@ rule -> rule_clauses : build_rule('$1').
rule_clauses -> rule_clause : ['$1'].
rule_clauses -> rule_clause ';' rule_clauses : ['$1'|'$3'].
-rule_clause -> atom1 clause_args clause_guard rule_body :
+rule_clause -> atom clause_args clause_guard rule_body :
{clause,?line('$1'),element(3, '$1'),'$2','$3','$4'}.
rule_body -> ':-' lc_exprs: '$2'.
@@ -503,8 +504,8 @@ Erlang code.
%% mkop(Op, Arg) -> {op,Line,Op,Arg}.
%% mkop(Left, Op, Right) -> {op,Line,Op,Left,Right}.
--define(mkop2(L, OpPos, R),
- begin
+-define(mkop2(L, OpPos, R),
+ begin
{Op,Pos} = OpPos,
{op,Pos,Op,L,R}
end).
@@ -522,6 +523,8 @@ Erlang code.
%% These really suck and are only here until Calle gets multiple
%% entry points working.
+parse_form([{'-',L1},{atom,L2,spec}|Tokens]) ->
+ parse([{'-',L1},{'spec',L2}|Tokens]);
parse_form(Tokens) ->
parse(Tokens).
@@ -548,7 +551,7 @@ parse_term(Tokens) ->
-type attributes() :: 'export' | 'file' | 'import' | 'module'
| 'opaque' | 'record' | 'type'.
-build_typed_attribute({atom,La,record},
+build_typed_attribute({atom,La,record},
{typed_record, {atom,_Ln,RecordName}, RecTuple}) ->
{attribute,La,record,{RecordName,record_tuple(RecTuple)}};
build_typed_attribute({atom,La,Attr},
@@ -571,7 +574,7 @@ build_typed_attribute({atom,La,Attr},_) ->
build_type_spec({spec,La}, {SpecFun, TypeSpecs}) ->
NewSpecFun =
case SpecFun of
- {atom, _, Fun} ->
+ {atom, _, Fun} ->
{Fun, find_arity_from_specs(TypeSpecs)};
{{atom,_, Mod}, {atom,_, Fun}} ->
{Mod,Fun,find_arity_from_specs(TypeSpecs)};
@@ -705,7 +708,7 @@ attribute_farity(Other) -> Other.
attribute_farity_list(Args) ->
[attribute_farity(A) || A <- Args].
-
+
-spec error_bad_decl(integer(), attributes()) -> no_return().
error_bad_decl(L, S) ->
@@ -728,17 +731,17 @@ record_fields([{match,_Lm,{atom,La,A},Expr}|Fields]) ->
[{record_field,La,{atom,La,A},Expr}|record_fields(Fields)];
record_fields([{typed,Expr,TypeInfo}|Fields]) ->
[Field] = record_fields([Expr]),
- TypeInfo1 =
+ TypeInfo1 =
case Expr of
{match, _, _, _} -> TypeInfo; %% If we have an initializer.
- {atom, La, _} ->
+ {atom, La, _} ->
case has_undefined(TypeInfo) of
false ->
lift_unions(abstract(undefined, La), TypeInfo);
true ->
TypeInfo
end
- end,
+ end,
[{typed_record_field,Field,TypeInfo1}|record_fields(Fields)];
record_fields([Other|_Fields]) ->
ret_err(?line(Other), "bad record field");
diff --git a/lib/stdlib/src/erl_scan.erl b/lib/stdlib/src/erl_scan.erl
index 52ec81a78b..1013d54bdc 100644
--- a/lib/stdlib/src/erl_scan.erl
+++ b/lib/stdlib/src/erl_scan.erl
@@ -1,19 +1,19 @@
%%
%% %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
%% 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%
%%
@@ -48,7 +48,7 @@
-module(erl_scan).
-%%% External exports
+%%% External exports
-export([string/1,string/2,string/3,tokens/3,tokens/4,
format_error/1,reserved_word/1,
@@ -98,41 +98,41 @@
-spec format_error(Error :: term()) -> string().
format_error({string,Quote,Head}) ->
lists:flatten(["unterminated " ++ string_thing(Quote) ++
- " starting with " ++
+ " starting with " ++
io_lib:write_unicode_string(Head, Quote)]);
-format_error({illegal,Type}) ->
+format_error({illegal,Type}) ->
lists:flatten(io_lib:fwrite("illegal ~w", [Type]));
format_error(char) -> "unterminated character";
-format_error({base,Base}) ->
+format_error({base,Base}) ->
lists:flatten(io_lib:fwrite("illegal base '~w'", [Base]));
-format_error(Other) ->
+format_error(Other) ->
lists:flatten(io_lib:write(Other)).
--type string_return() :: {'ok', tokens(), location()}
+-type string_return() :: {'ok', tokens(), location()}
| {'error', error_info(), location()}.
-spec string(String :: string()) -> string_return().
string(String) ->
string(String, 1, []).
--spec string(String :: string(), StartLocation :: location()) ->
+-spec string(String :: string(), StartLocation :: location()) ->
string_return().
string(String, StartLocation) ->
string(String, StartLocation, []).
--spec string(String :: string(), StartLocation :: location(),
+-spec string(String :: string(), StartLocation :: location(),
Options :: options()) -> string_return().
string(String, Line, Options) when ?STRING(String), ?ALINE(Line) ->
string1(String, options(Options), Line, no_col, []);
string(String, {Line,Column}, Options) when ?STRING(String),
- ?ALINE(Line),
+ ?ALINE(Line),
?COLUMN(Column) ->
string1(String, options(Options), Line, Column, []).
-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(),
+-opaque return_cont() :: {string(), column(), tokens(), line(),
#erl_scan{}, cont_fun(), any()}.
-type cont() :: return_cont() | [].
-type tokens_result() :: {'ok', tokens(), location()}
@@ -141,13 +141,13 @@ string(String, {Line,Column}, Options) when ?STRING(String),
-type tokens_return() :: {'done', tokens_result(), char_spec()}
| {'more', return_cont()}.
--spec tokens(Cont :: cont(), CharSpec :: char_spec(),
+-spec tokens(Cont :: cont(), CharSpec :: char_spec(),
StartLocation :: location()) -> tokens_return().
tokens(Cont, CharSpec, StartLocation) ->
tokens(Cont, CharSpec, StartLocation, []).
--spec tokens(Cont :: cont(), CharSpec :: char_spec(),
- StartLocation :: location(), Options :: options()) ->
+-spec tokens(Cont :: cont(), CharSpec :: char_spec(),
+ StartLocation :: location(), Options :: options()) ->
tokens_return().
tokens([], CharSpec, Line, Options) when ?ALINE(Line) ->
tokens1(CharSpec, options(Options), Line, no_col, [], fun scan/6, []);
@@ -157,15 +157,15 @@ tokens([], CharSpec, {Line,Column}, Options) when ?ALINE(Line),
tokens({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'
+-type attribute_item() :: 'column' | 'length' | 'line'
| 'location' | 'text'.
-type info_location() :: location() | term().
--type attribute_info() :: {'column', column()}| {'length', pos_integer()}
- | {'line', info_line()}
+-type attribute_info() :: {'column', column()}| {'length', pos_integer()}
+ | {'line', info_line()}
| {'location', info_location()}
| {'text', string()}.
-type token_item() :: 'category' | 'symbol' | attribute_item().
--type token_info() :: {'category', category()} | {'symbol', symbol()}
+-type token_info() :: {'category', category()} | {'symbol', symbol()}
| attribute_info().
-spec token_info(token()) -> [token_info()].
@@ -214,7 +214,7 @@ attributes_info(Attrs, [A|As]) when is_atom(A) ->
AttributeInfo when is_tuple(AttributeInfo) ->
[AttributeInfo|attributes_info(Attrs, As)]
end;
-attributes_info({Line,Column}, column=Item) when ?ALINE(Line),
+attributes_info({Line,Column}, column=Item) when ?ALINE(Line),
?COLUMN(Column) ->
{Item,Column};
attributes_info(Line, column) when ?ALINE(Line) ->
@@ -230,12 +230,12 @@ attributes_info(Attrs, length=Item) ->
end;
attributes_info(Line, line=Item) when ?ALINE(Line) ->
{Item,Line};
-attributes_info({Line,Column}, line=Item) when ?ALINE(Line),
+attributes_info({Line,Column}, line=Item) when ?ALINE(Line),
?COLUMN(Column) ->
{Item,Line};
attributes_info(Attrs, line=Item) ->
attr_info(Attrs, Item);
-attributes_info({Line,Column}=Location, location=Item) when ?ALINE(Line),
+attributes_info({Line,Column}=Location, location=Item) when ?ALINE(Line),
?COLUMN(Column) ->
{Item,Location};
attributes_info(Line, location=Item) when ?ALINE(Line) ->
@@ -289,11 +289,11 @@ string_thing(_) -> "string".
options(Opts0) when is_list(Opts0) ->
Opts = lists:foldr(fun expand_opt/2, [], Opts0),
- [RW_fun] =
+ [RW_fun] =
case opts(Opts, [reserved_word_fun], []) of
badarg ->
erlang:error(badarg, [Opts0]);
- R ->
+ R ->
R
end,
Comment = proplists:get_bool(return_comments, Opts),
@@ -336,7 +336,7 @@ attr_info(Attrs, Item) ->
case catch lists:keysearch(Item, 1, Attrs) of
{value,{Item,Value}} ->
{Item,Value};
- false ->
+ false ->
undefined;
_ ->
erlang:error(badarg, [Attrs, Item])
@@ -591,12 +591,12 @@ scan_atom(Cs0, St, Line, Col, Toks, Ncs0) ->
case catch list_to_atom(Wcs) of
Name when is_atom(Name) ->
case (St#erl_scan.resword_fun)(Name) of
- true ->
+ true ->
tok2(Cs, St, Line, Col, Toks, Wcs, Name);
- false ->
+ false ->
tok3(Cs, St, Line, Col, Toks, atom, Wcs, Name)
end;
- _Error ->
+ _Error ->
Ncol = incr_column(Col, length(Wcs)),
scan_error({illegal,atom}, Line, Col, Line, Ncol, Cs)
end
@@ -610,7 +610,7 @@ scan_variable(Cs0, St, Line, Col, Toks, Ncs0) ->
case catch list_to_atom(Wcs) of
Name when is_atom(Name) ->
tok3(Cs, St, Line, Col, Toks, var, Wcs, Name);
- _Error ->
+ _Error ->
Ncol = incr_column(Col, length(Wcs)),
scan_error({illegal,var}, Line, Col, Line, Ncol, Cs)
end
@@ -690,7 +690,7 @@ scan_nl_spcs([]=Cs, _St, Line, Col, Toks, N) ->
{more,{Cs,Col,Toks,Line,N,fun scan_nl_spcs/6}};
scan_nl_spcs(Cs, St, Line, Col, Toks, N) ->
newline_end(Cs, St, Line, Col, Toks, N, nl_spcs(N)).
-
+
scan_nl_tabs([$\t|Cs], St, Line, Col, Toks, N) when N < 11 ->
scan_nl_tabs(Cs, St, Line, Col, Toks, N+1);
scan_nl_tabs([]=Cs, _St, Line, Col, Toks, N) ->
@@ -701,7 +701,7 @@ scan_nl_tabs(Cs, St, Line, Col, Toks, N) ->
%% Note: returning {more,Cont} is meaningless here; one could just as
%% well return several tokens. But since tokens() scans up to a full
%% stop anyway, nothing is gained by not collecting all white spaces.
-scan_nl_white_space([$\n|Cs], #erl_scan{text = false}=St, Line, no_col=Col,
+scan_nl_white_space([$\n|Cs], #erl_scan{text = false}=St, Line, no_col=Col,
Toks0, Ncs) ->
Toks = [{white_space,Line,lists:reverse(Ncs)}|Toks0],
scan_newline(Cs, St, Line+1, Col, Toks);
@@ -714,7 +714,7 @@ scan_nl_white_space([C|Cs], St, Line, Col, Toks, Ncs) when ?WHITE_SPACE(C) ->
scan_nl_white_space(Cs, St, Line, Col, Toks, [C|Ncs]);
scan_nl_white_space([]=Cs, _St, Line, Col, Toks, Ncs) ->
{more,{Cs,Col,Toks,Line,Ncs,fun scan_nl_white_space/6}};
-scan_nl_white_space(Cs, #erl_scan{text = false}=St, Line, no_col=Col,
+scan_nl_white_space(Cs, #erl_scan{text = false}=St, Line, no_col=Col,
Toks, Ncs) ->
scan1(Cs, St, Line+1, Col, [{white_space,Line,lists:reverse(Ncs)}|Toks]);
scan_nl_white_space(Cs, St, Line, Col, Toks, Ncs0) ->
@@ -723,7 +723,7 @@ scan_nl_white_space(Cs, St, Line, Col, Toks, Ncs0) ->
Token = {white_space,Attrs,Ncs},
scan1(Cs, St, Line+1, new_column(Col, length(Ncs)), [Token|Toks]).
-newline_end(Cs, #erl_scan{text = false}=St, Line, no_col=Col,
+newline_end(Cs, #erl_scan{text = false}=St, Line, no_col=Col,
Toks, _N, Ncs) ->
scan1(Cs, St, Line+1, Col, [{white_space,Line,Ncs}|Toks]);
newline_end(Cs, St, Line, Col, Toks, N, Ncs) ->
@@ -789,7 +789,7 @@ scan_char([$\\|Cs]=Cs0, St, Line, Col, Toks) ->
Ntoks = [{char,Attrs,Val}|Toks],
scan1(Ncs, St, Line, Ncol, Ntoks)
end;
-scan_char([$\n=C|Cs], St, Line, Col, Toks) ->
+scan_char([$\n=C|Cs], St, Line, Col, Toks) ->
Attrs = attributes(Line, Col, St, [$$,C]),
scan1(Cs, St, Line+1, new_column(Col, 1), [{char,Attrs,C}|Toks]);
scan_char([C|Cs], St, Line, Col, Toks) when ?CHAR(C) ->
@@ -896,7 +896,7 @@ scan_string_no_col([Q|Cs], Line, Col, Q, Wcs, Uni) ->
{Cs,Line,Col,_DontCare=[],lists:reverse(Wcs),Uni};
scan_string_no_col([$\n=C|Cs], Line, Col, Q, Wcs, Uni) ->
scan_string_no_col(Cs, Line+1, Col, Q, [C|Wcs], Uni);
-scan_string_no_col([C|Cs], Line, Col, Q, Wcs, Uni) when C =/= $\\,
+scan_string_no_col([C|Cs], Line, Col, Q, Wcs, Uni) when C =/= $\\,
?CHAR(C), ?UNI255(C) ->
scan_string_no_col(Cs, Line, Col, Q, [C|Wcs], Uni);
scan_string_no_col(Cs, Line, Col, Q, Wcs, Uni) ->
@@ -909,7 +909,7 @@ scan_string_col([Q|Cs], Line, Col, Q, Wcs0, Uni) ->
{Cs,Line,Col+1,Str,Wcs,Uni};
scan_string_col([$\n=C|Cs], Line, _xCol, Q, Wcs, Uni) ->
scan_string_col(Cs, Line+1, 1, Q, [C|Wcs], Uni);
-scan_string_col([C|Cs], Line, Col, Q, Wcs, Uni) when C =/= $\\,
+scan_string_col([C|Cs], Line, Col, Q, Wcs, Uni) when C =/= $\\,
?CHAR(C), ?UNI255(C) ->
scan_string_col(Cs, Line, Col+1, Q, [C|Wcs], Uni);
scan_string_col(Cs, Line, Col, Q, Wcs, Uni) ->
@@ -970,8 +970,8 @@ scan_string1(eof, Line, Col, _Q, _Str, Wcs, _Uni) ->
{error,Line,Col,lists:reverse(Wcs),eof}.
-define(OCT(C), C >= $0, C =< $7).
--define(HEX(C), C >= $0 andalso C =< $9 orelse
- C >= $A andalso C =< $F orelse
+-define(HEX(C), C >= $0 andalso C =< $9 orelse
+ C >= $A andalso C =< $F orelse
C >= $a andalso C =< $f).
%% \<1-3> octal digits
@@ -1086,7 +1086,7 @@ scan_number(Cs, St, Line, Col, Toks, Ncs0) ->
Ncol = incr_column(Col, length(Ncs)),
scan_error({illegal,integer}, Line, Col, Line, Ncol, Cs)
end.
-
+
scan_based_int([C|Cs], St, Line, Col, Toks, {B,Ncs,Bcs})
when ?DIGIT(C), C < $0+B ->
scan_based_int(Cs, St, Line, Col, Toks, {B,[C|Ncs],Bcs});
@@ -1262,7 +1262,7 @@ nl_tabs(8) -> "\n\t\t\t\t\t\t\t";
nl_tabs(9) -> "\n\t\t\t\t\t\t\t\t";
nl_tabs(10) -> "\n\t\t\t\t\t\t\t\t\t";
nl_tabs(11) -> "\n\t\t\t\t\t\t\t\t\t\t".
-
+
tabs(1) -> "\t";
tabs(2) -> "\t\t";
tabs(3) -> "\t\t\t";
@@ -1303,5 +1303,4 @@ reserved_word('bsl') -> true;
reserved_word('bsr') -> true;
reserved_word('or') -> true;
reserved_word('xor') -> true;
-reserved_word('spec') -> true;
reserved_word(_) -> false.
diff --git a/lib/stdlib/src/ets.erl b/lib/stdlib/src/ets.erl
index ef9c8f0cfb..d7b5dbc636 100644
--- a/lib/stdlib/src/ets.erl
+++ b/lib/stdlib/src/ets.erl
@@ -230,7 +230,7 @@ from_dets(EtsTable, DetsTable) ->
erlang:error(Unexpected,[EtsTable,DetsTable])
end.
--spec to_dets(tab(), dets:tab_name()) -> dets:tabname().
+-spec to_dets(tab(), dets:tab_name()) -> dets:tab_name().
to_dets(EtsTable, DetsTable) ->
case (catch dets:from_ets(DetsTable, EtsTable)) of
diff --git a/lib/stdlib/src/lists.erl b/lib/stdlib/src/lists.erl
index e1f8d1c200..857eda8161 100644
--- a/lib/stdlib/src/lists.erl
+++ b/lib/stdlib/src/lists.erl
@@ -1,19 +1,19 @@
%%
%% %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
%% 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(lists).
@@ -25,7 +25,7 @@
unzip/1, unzip3/1, zip/2, zip3/3, zipwith/3, zipwith3/4,
sort/1, merge/1, merge/2, rmerge/2, merge3/3, rmerge3/3,
usort/1, umerge/1, umerge3/3, umerge/2, rumerge3/3, rumerge/2,
- concat/1, flatten/1, flatten/2, flat_length/1, flatlength/1,
+ concat/1, flatten/1, flatten/2, flatlength/1,
keydelete/3, keyreplace/4, keytake/3, keystore/4,
keysort/2, keymerge/3, rkeymerge/3, rukeymerge/3,
ukeysort/2, ukeymerge/3, keymap/3]).
@@ -40,8 +40,6 @@
mapfoldl/3,mapfoldr/3,foreach/2,takewhile/2,dropwhile/2,splitwith/2,
split/2]).
--deprecated([flat_length/1]).
-
%% member(X, L) -> (true | false)
%% test if X is a member of the list L
%% Now a BIF!
@@ -436,13 +434,6 @@ do_flatten([H|T], Tail) ->
do_flatten([], Tail) ->
Tail.
-%% flat_length(List) (undocumented can be removed later)
-%% Calculate the length of a list of lists.
-
--spec flat_length([_]) -> non_neg_integer().
-
-flat_length(List) -> flatlength(List).
-
%% flatlength(List)
%% Calculate the length of a list of lists.
diff --git a/lib/stdlib/src/otp_internal.erl b/lib/stdlib/src/otp_internal.erl
index 7ea7de8d58..f3cfd78d54 100644
--- a/lib/stdlib/src/otp_internal.erl
+++ b/lib/stdlib/src/otp_internal.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1999-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 1999-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(otp_internal).
@@ -236,98 +236,116 @@ obsolete_1(erlang, fault, 2) ->
obsolete_1(file, rawopen, 2) ->
{removed, "deprecated (will be removed in R13B); use file:open/2 with the raw option"};
-obsolete_1(httpd, start, 0) -> {deprecated,{inets,start,[2,3]},"R14B"};
-obsolete_1(httpd, start, 1) -> {deprecated,{inets,start,[2,3]},"R14B"};
-obsolete_1(httpd, start_link, 1) -> {deprecated,{inets,start,[2,3]},"R14B"};
-obsolete_1(httpd, start_child, 0) -> {deprecated,{inets,start,[2,3]},"R14B"};
-obsolete_1(httpd, start_child, 1) -> {deprecated,{inets,start,[2,3]},"R14B"};
-obsolete_1(httpd, stop, 0) -> {deprecated,{inets,stop,2},"R14B"};
-obsolete_1(httpd, stop, 1) -> {deprecated,{inets,stop,2},"R14B"};
-obsolete_1(httpd, stop, 2) -> {deprecated,{inets,stop,2},"R14B"};
-obsolete_1(httpd, stop_child, 0) -> {deprecated,{inets,stop,2},"R14B"};
-obsolete_1(httpd, stop_child, 1) -> {deprecated,{inets,stop,2},"R14B"};
-obsolete_1(httpd, stop_child, 2) -> {deprecated,{inets,stop,2},"R14B"};
-obsolete_1(httpd, restart, 0) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, restart, 1) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, restart, 2) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, block, 0) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, block, 1) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, block, 2) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, block, 3) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, block, 4) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, unblock, 0) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, unblock, 1) -> {deprecated,{httpd,reload_config,2},"R14B"};
-obsolete_1(httpd, unblock, 2) -> {deprecated,{httpd,reload_config,2},"R14B"};
+obsolete_1(http, request, 1) -> {deprecated,{httpc,request,1},"R15B"};
+obsolete_1(http, request, 2) -> {deprecated,{httpc,request,2},"R15B"};
+obsolete_1(http, request, 4) -> {deprecated,{httpc,request,4},"R15B"};
+obsolete_1(http, request, 5) -> {deprecated,{httpc,request,5},"R15B"};
+obsolete_1(http, cancel_request, 1) -> {deprecated,{httpc,cancel_request,1},"R15B"};
+obsolete_1(http, cancel_request, 2) -> {deprecated,{httpc,cancel_request,2},"R15B"};
+obsolete_1(http, set_option, 2) -> {deprecated,{httpc,set_option,2},"R15B"};
+obsolete_1(http, set_option, 3) -> {deprecated,{httpc,set_option,3},"R15B"};
+obsolete_1(http, set_options, 1) -> {deprecated,{httpc,set_options,1},"R15B"};
+obsolete_1(http, set_options, 2) -> {deprecated,{httpc,set_options,2},"R15B"};
+obsolete_1(http, verify_cookies, 2) -> {deprecated,{httpc,verify_cookies,2},"R15B"};
+obsolete_1(http, verify_cookies, 3) -> {deprecated,{httpc,verify_cookies,3},"R15B"};
+obsolete_1(http, cookie_header, 1) -> {deprecated,{httpc,cookie_header,1},"R15B"};
+obsolete_1(http, cookie_header, 2) -> {deprecated,{httpc,cookie_header,2},"R15B"};
+obsolete_1(http, stream_next, 1) -> {deprecated,{httpc,stream_next,1},"R15B"};
+obsolete_1(http, default_profile, 0) -> {deprecated,{httpc,default_profile,0},"R15B"};
+
+obsolete_1(httpd, start, 0) -> {removed,{inets,start,[2,3]},"R14B"};
+obsolete_1(httpd, start, 1) -> {removed,{inets,start,[2,3]},"R14B"};
+obsolete_1(httpd, start_link, 0) -> {removed,{inets,start,[2,3]},"R14B"};
+obsolete_1(httpd, start_link, 1) -> {removed,{inets,start,[2,3]},"R14B"};
+obsolete_1(httpd, start_child, 0) -> {removed,{inets,start,[2,3]},"R14B"};
+obsolete_1(httpd, start_child, 1) -> {removed,{inets,start,[2,3]},"R14B"};
+obsolete_1(httpd, stop, 0) -> {removed,{inets,stop,2},"R14B"};
+obsolete_1(httpd, stop, 1) -> {removed,{inets,stop,2},"R14B"};
+obsolete_1(httpd, stop, 2) -> {removed,{inets,stop,2},"R14B"};
+obsolete_1(httpd, stop_child, 0) -> {removed,{inets,stop,2},"R14B"};
+obsolete_1(httpd, stop_child, 1) -> {removed,{inets,stop,2},"R14B"};
+obsolete_1(httpd, stop_child, 2) -> {removed,{inets,stop,2},"R14B"};
+obsolete_1(httpd, restart, 0) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, restart, 1) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, restart, 2) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, block, 0) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, block, 1) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, block, 2) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, block, 3) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, block, 4) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, unblock, 0) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, unblock, 1) -> {removed,{httpd,reload_config,2},"R14B"};
+obsolete_1(httpd, unblock, 2) -> {removed,{httpd,reload_config,2},"R14B"};
obsolete_1(httpd_util, key1search, 2) -> {removed,{proplists,get_value,2},"R13B"};
obsolete_1(httpd_util, key1search, 3) -> {removed,{proplists,get_value,3},"R13B"};
-obsolete_1(ftp, open, 3) -> {deprecated,{inets,start,[2,3]},"R14B"};
-obsolete_1(ftp, force_active, 1) -> {deprecated,{inets,start,[2,3]},"R14B"};
+obsolete_1(ftp, open, 3) -> {removed,{inets,start,[2,3]},"R14B"};
+obsolete_1(ftp, force_active, 1) -> {removed,{inets,start,[2,3]},"R14B"};
%% Added in R12B-4.
obsolete_1(ssh_cm, connect, A) when 1 =< A, A =< 3 ->
- {deprecated,{ssh,connect,A},"R14B"};
+ {removed,{ssh,connect,A},"R14B"};
obsolete_1(ssh_cm, listen, A) when 2 =< A, A =< 4 ->
- {deprecated,{ssh,daemon,A},"R14B"};
+ {removed,{ssh,daemon,A},"R14B"};
obsolete_1(ssh_cm, stop_listener, 1) ->
- {deprecated,{ssh,stop_listener,[1,2]},"R14B"};
+ {removed,{ssh,stop_listener,[1,2]},"R14B"};
obsolete_1(ssh_cm, session_open, A) when A =:= 2; A =:= 4 ->
- {deprecated,{ssh_connection,session_channel,A},"R14B"};
+ {removed,{ssh_connection,session_channel,A},"R14B"};
obsolete_1(ssh_cm, direct_tcpip, A) when A =:= 6; A =:= 8 ->
- {deprecated,{ssh_connection,direct_tcpip,A}};
+ {removed,{ssh_connection,direct_tcpip,A}};
obsolete_1(ssh_cm, tcpip_forward, 3) ->
- {deprecated,{ssh_connection,tcpip_forward,3},"R14B"};
+ {removed,{ssh_connection,tcpip_forward,3},"R14B"};
obsolete_1(ssh_cm, cancel_tcpip_forward, 3) ->
- {deprecated,{ssh_connection,cancel_tcpip_forward,3},"R14B"};
+ {removed,{ssh_connection,cancel_tcpip_forward,3},"R14B"};
obsolete_1(ssh_cm, open_pty, A) when A =:= 3; A =:= 7; A =:= 9 ->
- {deprecated,{ssh_connection,open_pty,A},"R14"};
+ {removed,{ssh_connection,open_pty,A},"R14"};
obsolete_1(ssh_cm, setenv, 5) ->
- {deprecated,{ssh_connection,setenv,5},"R14B"};
+ {removed,{ssh_connection,setenv,5},"R14B"};
obsolete_1(ssh_cm, shell, 2) ->
- {deprecated,{ssh_connection,shell,2},"R14B"};
+ {removed,{ssh_connection,shell,2},"R14B"};
obsolete_1(ssh_cm, exec, 4) ->
- {deprecated,{ssh_connection,exec,4},"R14B"};
+ {removed,{ssh_connection,exec,4},"R14B"};
obsolete_1(ssh_cm, subsystem, 4) ->
- {deprecated,{ssh_connection,subsystem,4},"R14B"};
+ {removed,{ssh_connection,subsystem,4},"R14B"};
obsolete_1(ssh_cm, winch, A) when A =:= 4; A =:= 6 ->
- {deprecated,{ssh_connection,window_change,A},"R14B"};
+ {removed,{ssh_connection,window_change,A},"R14B"};
obsolete_1(ssh_cm, signal, 3) ->
- {deprecated,{ssh_connection,signal,3},"R14B"};
+ {removed,{ssh_connection,signal,3},"R14B"};
obsolete_1(ssh_cm, attach, A) when A =:= 2; A =:= 3 ->
- {deprecated,{ssh,attach,A}};
+ {removed,{ssh,attach,A}};
obsolete_1(ssh_cm, detach, 2) ->
- {deprecated,"no longer useful; will be removed in R14B"};
+ {removed,"no longer useful; will be removed in R14B"};
obsolete_1(ssh_cm, set_user_ack, 4) ->
- {deprecated,"no longer useful; will be removed in R14B"};
+ {removed,"no longer useful; will be removed in R14B"};
obsolete_1(ssh_cm, adjust_window, 3) ->
- {deprecated,{ssh_connection,adjust_window,3},"R14B"};
+ {removed,{ssh_connection,adjust_window,3},"R14B"};
obsolete_1(ssh_cm, close, 2) ->
- {deprecated,{ssh_connection,close,2},"R14B"};
+ {removed,{ssh_connection,close,2},"R14B"};
obsolete_1(ssh_cm, stop, 1) ->
- {deprecated,{ssh,close,1},"R14B"};
+ {removed,{ssh,close,1},"R14B"};
obsolete_1(ssh_cm, send_eof, 2) ->
- {deprecated,{ssh_connection,send_eof,2},"R14B"};
+ {removed,{ssh_connection,send_eof,2},"R14B"};
obsolete_1(ssh_cm, send, A) when A =:= 3; A =:= 4 ->
- {deprecated,{ssh_connection,send,A},"R14B"};
+ {removed,{ssh_connection,send,A},"R14B"};
obsolete_1(ssh_cm, send_ack, A) when 3 =< A, A =< 5 ->
- {deprecated,{ssh_connection,send,[3,4]},"R14B"};
+ {removed,{ssh_connection,send,[3,4]},"R14B"};
obsolete_1(ssh_ssh, connect, A) when 1 =< A, A =< 3 ->
- {deprecated,{ssh,shell,A},"R14B"};
+ {removed,{ssh,shell,A},"R14B"};
obsolete_1(ssh_sshd, listen, A) when 0 =< A, A =< 3 ->
- {deprecated,{ssh,daemon,[1,2,3]},"R14"};
+ {removed,{ssh,daemon,[1,2,3]},"R14"};
obsolete_1(ssh_sshd, stop, 1) ->
- {deprecated,{ssh,stop_listener,1}};
+ {removed,{ssh,stop_listener,1}};
%% Added in R13A.
obsolete_1(regexp, _, _) ->
{deprecated, "the regexp module is deprecated (will be removed in R15A); use the re module instead"};
obsolete_1(lists, flat_length, 1) ->
- {deprecated,{lists,flatlength,1},"R14"};
+ {removed,{lists,flatlength,1},"R14"};
obsolete_1(ssh_sftp, connect, A) when 1 =< A, A =< 3 ->
- {deprecated,{ssh_sftp,start_channel,A},"R14B"};
+ {removed,{ssh_sftp,start_channel,A},"R14B"};
obsolete_1(ssh_sftp, stop, 1) ->
- {deprecated,{ssh_sftp,stop_channel,1},"R14B"};
+ {removed,{ssh_sftp,stop_channel,1},"R14B"};
%% Added in R13B01.
obsolete_1(ssl_pkix, decode_cert_file, A) when A =:= 1; A =:= 2 ->
@@ -337,7 +355,7 @@ obsolete_1(ssl_pkix, decode_cert, A) when A =:= 1; A =:= 2 ->
%% Added in R13B04.
obsolete_1(erlang, concat_binary, 1) ->
- {deprecated,{erlang,list_to_binary,1},"R14B"};
+ {deprecated,{erlang,list_to_binary,1},"R15B"};
obsolete_1(_, _, _) ->
no.
diff --git a/lib/stdlib/test/erl_pp_SUITE.erl b/lib/stdlib/test/erl_pp_SUITE.erl
index 92a54108aa..66730b7b94 100644
--- a/lib/stdlib/test/erl_pp_SUITE.erl
+++ b/lib/stdlib/test/erl_pp_SUITE.erl
@@ -46,7 +46,7 @@
neg_indent/1,
tickets/1,
otp_6321/1, otp_6911/1, otp_6914/1, otp_8150/1, otp_8238/1,
- otp_8473/1, otp_8522/1]).
+ otp_8473/1, otp_8522/1, otp_8567/1]).
%% Internal export.
-export([ehook/6]).
@@ -150,15 +150,15 @@ recs(Config) when is_list(Config) ->
(A#r1.a)#r.a > 3 -> 3
end(#r1{a = #r{a = 4}}),
7 = fun(A) when record(A#r3.a, r1) -> 7 end(#r3{}),
- [#r1{a = 2,b = 1}] =
+ [#r1{a = 2,b = 1}] =
fun() ->
- [A || A <- [#r1{a = 1, b = 3},
- #r2{a = 2,b = 1},
+ [A || A <- [#r1{a = 1, b = 3},
+ #r2{a = 2,b = 1},
#r1{a = 2, b = 1}],
- A#r1.a >
+ A#r1.a >
A#r1.b]
end(),
- {[_],b} =
+ {[_],b} =
fun(L) ->
%% A is checked only once:
R1 = [{A,B} || A <- L, A#r1.a, B <- L, A#r1.b],
@@ -177,7 +177,7 @@ recs(Config) when is_list(Config) ->
end(#r1{a = 2}),
%% The test done twice (an effect of doing the test as soon as possible).
- 3 = fun(A) when A#r1.a > 3,
+ 3 = fun(A) when A#r1.a > 3,
record(A, r1) -> 3
end(#r1{a = 5}),
@@ -251,18 +251,18 @@ recs(Config) when is_list(Config) ->
ok
end(),
- both = fun(A) when A#r.a, A#r.b -> both
+ both = fun(A) when A#r.a, A#r.b -> both
end(#r{a = true, b = true}),
ok = fun() ->
- F = fun(A, B) when ((A#r1.a) orelse (B#r2.a))
+ F = fun(A, B) when ((A#r1.a) orelse (B#r2.a))
or (B#r2.b) or (A#r1.b) ->
true;
(_, _) -> false
end,
- true = F(#r1{a = false, b = false},
+ true = F(#r1{a = false, b = false},
#r2{a = false, b = true}),
- false = F(#r1{a = true, b = true},
+ false = F(#r1{a = true, b = true},
#r1{a = false, b = true}),
ok
end(),
@@ -273,7 +273,7 @@ recs(Config) when is_list(Config) ->
<<"-record(r1, {a, b = foo:bar(kljlfjsdlf, kjlksdjf)}).
-record(r2, {c = #r1{}, d = #r1{a = bar:foo(kljklsjdf)}}).
- t() ->
+ t() ->
R = #r2{},
R#r2{c = R, d = #r1{}}.">>}
],
@@ -304,10 +304,10 @@ try_catch(Config) when is_list(Config) ->
{try_6,
<<"t() -> try 1=2 catch throw:{badmatch,2} -> 3 end.">>},
{try_7,
- <<"t() -> try 1=2 of 3 -> 4
+ <<"t() -> try 1=2 of 3 -> 4
catch error:{badmatch,2} -> 5 end.">>},
{try_8,
- <<"t() -> try 1=2
+ <<"t() -> try 1=2
catch error:{badmatch,2} -> 3
after put(try_catch, 4) end.">>},
{try_9,
@@ -371,7 +371,7 @@ receive_after(Config) when is_list(Config) ->
{X,Y};
Z ->
Z
- after
+ after
foo:bar() ->
{3,4}
end.">>}
@@ -429,7 +429,7 @@ head_tail(Config) when is_list(Config) ->
{list_4,
<<"t() -> [a].">>},
{list_5,
- <<"t() ->
+ <<"t() ->
[foo:bar(lkjljlskdfj, klsdajflds, sdafkljsdlfkjdas, kjlsdadjl),
bar:foo(kljlkjsdf, lkjsdlfj, [kljsfj, sdfdsfsad])].">>}
],
@@ -462,7 +462,7 @@ cond1(Config) when is_list(Config) ->
" true ->\n"
" {x,y}\n"
"end" = CChars,
-% ?line ok = pp_expr(<<"cond
+% ?line ok = pp_expr(<<"cond
% {foo,bar} ->
% [a,b];
% true ->
@@ -544,7 +544,7 @@ old_mnemosyne_syntax(Config) when is_list(Config) ->
" X <- table(tab),\n"
" X.foo = bar\n"
" ]\n"
- "end" =
+ "end" =
lists:flatten(erl_pp:expr(Q)),
R = {rule,12,sales,2,
@@ -559,7 +559,7 @@ old_mnemosyne_syntax(Config) when is_list(Config) ->
{atom,14,sales}}]}]},
?line "sales(E, employee) :-\n"
" E <- table(employee),\n"
- " E.salary = sales.\n" =
+ " E.salary = sales.\n" =
lists:flatten(erl_pp:form(R)),
ok.
@@ -660,7 +660,7 @@ hook(Config) when is_list(Config) ->
?line "INVALID-FORM:{foo,bar}:" = lists:flatten(erl_pp:expr({foo,bar})),
- %% A list (as before R6), not a list of lists.
+ %% A list (as before R6), not a list of lists.
G = [{op,1,'>',{atom,1,a},{foo,{atom,1,b}}}], % not a proper guard
GChars = lists:flatten(erl_pp:guard(G, H)),
G2 = [{op,1,'>',{atom,1,a},
@@ -677,23 +677,23 @@ hook(Config) when is_list(Config) ->
%% Note: no leading spaces before "begin".
Block = {block,0,[{match,0,{var,0,'A'},{integer,0,3}},
{atom,0,true}]},
- ?line "begin\n A =" ++ _ =
+ ?line "begin\n A =" ++ _ =
lists:flatten(erl_pp:expr(Block, 17, none)),
%% Special...
- ?line true =
+ ?line true =
"{some,value}" =:= lists:flatten(erl_pp:expr({value,0,{some,value}})),
%% Silly...
?line true =
- "if true -> 0 end" =:=
+ "if true -> 0 end" =:=
flat_expr({'if',0,[{clause,0,[],[],[{atom,0,0}]}]}),
%% More compatibility: before R6
OldIf = {'if',0,[{clause,0,[],[{atom,0,true}],[{atom,0,b}]}]},
NewIf = {'if',0,[{clause,0,[],[[{atom,0,true}]],[{atom,0,b}]}]},
OldIfChars = lists:flatten(erl_pp:expr(OldIf)),
- NewIfChars = lists:flatten(erl_pp:expr(NewIf)),
+ NewIfChars = lists:flatten(erl_pp:expr(NewIf)),
?line true = OldIfChars =:= NewIfChars,
ok.
@@ -706,7 +706,7 @@ remove_indentation(S) ->
ehook(HE, I, P, H, foo, bar) ->
hook(HE, I, P, H).
-hook({foo,E}, I, P, H) ->
+hook({foo,E}, I, P, H) ->
erl_pp:expr({call,0,{atom,0,foo},[E]}, I, P, H).
neg_indent(suite) ->
@@ -722,14 +722,14 @@ neg_indent(Config) when is_list(Config) ->
end">>),
?line ok = pp_expr(
<<"fun() ->
- F = fun(A, B) when ((A#r1.a) orelse (B#r2.a))
+ F = fun(A, B) when ((A#r1.a) orelse (B#r2.a))
or (B#r2.b) or (A#r1.b) ->
true;
(_, _) -> false
end,
- true = F(#r1{a = false, b = false},
+ true = F(#r1{a = false, b = false},
#r2{a = false, b = true}),
- false = F(#r1{a = true, b = true},
+ false = F(#r1{a = true, b = true},
#r1{a = false, b = true}),
ok
end()">>),
@@ -764,7 +764,8 @@ neg_indent(Config) when is_list(Config) ->
ok.
tickets(suite) ->
- [otp_6321, otp_6911, otp_6914, otp_8150, otp_8238, otp_8473, otp_8522].
+ [otp_6321, otp_6911, otp_6914, otp_8150, otp_8238, otp_8473, otp_8522,
+ otp_8567].
otp_6321(doc) ->
"OTP_6321. Bug fix of exprs().";
@@ -813,7 +814,7 @@ otp_8150(doc) ->
"OTP_8150. Types.";
otp_8150(suite) -> [];
otp_8150(Config) when is_list(Config) ->
- ?line _ = [{N,ok} = {N,pp_forms(B)} ||
+ ?line _ = [{N,ok} = {N,pp_forms(B)} ||
{N,B} <- type_examples()
],
ok.
@@ -918,7 +919,7 @@ otp_8473(suite) -> [];
otp_8473(Config) when is_list(Config) ->
Ex = [{ex1,<<"-type 'fun'(A) :: A.\n"
"-type funkar() :: 'fun'(fun((integer()) -> atom())).\n">>}],
- ?line _ = [{N,ok} = {N,pp_forms(B)} ||
+ ?line _ = [{N,ok} = {N,pp_forms(B)} ||
{N,B} <- Ex],
ok.
@@ -949,12 +950,57 @@ count_atom(L, A) when is_list(L) ->
count_atom(_, _) ->
0.
+otp_8567(doc) ->
+ "OTP_8567. Avoid duplicated 'undefined' in record field types.";
+otp_8567(suite) -> [];
+otp_8567(Config) when is_list(Config) ->
+ FileName = filename('otp_8567.erl', Config),
+ C = <<"-module otp_8567.\n"
+ "-compile export_all.\n"
+ "-spec(a).\n"
+ "-record r, {a}.\n"
+ "-record s, {a :: integer()}.\n"
+ "-type t() :: {#r{},#s{}}.\n">>,
+ ?line ok = file:write_file(FileName, C),
+ ?line {error,[{_,[{3,erl_parse,["syntax error before: ","')'"]}]}],_} =
+ compile:file(FileName, [return]),
+
+ F = <<"-module(otp_8567).\n"
+ "-compile(export_all).\n"
+ "-record(t, {a}).\n"
+ "-record(u, {a :: integer()}).\n"
+ "-opaque ot() :: {#t{}, #u{}}.\n"
+ "-opaque(ot1() :: atom()).\n"
+ "-type a() :: integer().\n"
+ "-spec t() -> a().\n"
+ "t() ->\n"
+ " 3.\n"
+ "\n"
+ "-spec(t1/1 :: (ot()) -> ot1()).\n"
+ "t1(A) ->\n"
+ " A.\n"
+ "\n"
+ "-spec(t2 (ot()) -> ot1()).\n"
+ "t2(A) ->\n"
+ " A.\n"
+ "\n"
+ "-spec(otp_8567:t3/1 :: (ot()) -> ot1()).\n"
+ "t3(A) ->\n"
+ " A.\n"
+ "\n"
+ "-spec(otp_8567:t4 (ot()) -> ot1()).\n"
+ "t4(A) ->\n"
+ " A.\n">>,
+ ?line ok = pp_forms(F),
+
+ ok.
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
compile(Config, Tests) ->
F = fun({N,P}, BadL) ->
case catch compile_file(Config, P) of
- ok ->
+ ok ->
case pp_forms(P) of
ok ->
BadL;
@@ -962,8 +1008,8 @@ compile(Config, Tests) ->
?t:format("~nTest ~p failed.~n", [N]),
fail()
end;
- Bad ->
- ?t:format("~nTest ~p failed. got~n ~p~n",
+ Bad ->
+ ?t:format("~nTest ~p failed. got~n ~p~n",
[N, Bad]),
fail()
end
@@ -993,7 +1039,7 @@ compile_file(Config, Test0) ->
Error ->
Error
end.
-
+
compile_file(Config, Test0, Opts0) ->
FileName = filename('erl_pp_test.erl', Config),
Test = list_to_binary(["-module(erl_pp_test). "
@@ -1002,7 +1048,7 @@ compile_file(Config, Test0, Opts0) ->
Opts = [export_all,return,nowarn_unused_record,{outdir,?privdir} | Opts0],
ok = file:write_file(FileName, Test),
case compile:file(FileName, Opts) of
- {ok, _M, _Ws} ->
+ {ok, _M, _Ws} ->
{ok, filename:rootname(FileName)};
Error -> Error
end.
@@ -1029,7 +1075,7 @@ pp_forms(Bin, Hook) ->
end.
parse_and_pp_forms(String, Hook) ->
- lists:append(lists:map(fun(AF) -> erl_pp:form(AF, Hook)
+ lists:append(lists:map(fun(AF) -> erl_pp:form(AF, Hook)
end, parse_forms(String))).
parse_forms(Chars) ->
@@ -1037,13 +1083,13 @@ parse_forms(Chars) ->
parse_forms2(String, [], 1, []).
parse_forms2([], _Cont, _Line, Forms) ->
- lists:reverse(Forms);
+ lists:reverse(Forms);
parse_forms2(String, Cont0, Line, Forms) ->
case erl_scan:tokens(Cont0, String, Line) of
{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(3, Cont) =:= [] ->
%% extra spaces after forms...
parse_forms2([], Cont, Line, Forms);
{more, Cont} ->
@@ -1061,10 +1107,10 @@ pp_expr(Bin, Hook) ->
PP2 = (catch parse_and_pp_expr(PPneg, 0, Hook)),
if
PP1 =:= PP2 -> % same line numbers
- case
+ case
(test_max_line(PP1) =:= ok) and (test_new_line(PPneg) =:= ok)
of
- true ->
+ true ->
ok;
false ->
not_ok
@@ -1097,7 +1143,7 @@ test_max_line(String) ->
end.
max_line(String) ->
- lists:max([0 | [length(Sub) ||
+ lists:max([0 | [length(Sub) ||
Sub <- string:tokens(String, "\n"),
string:substr(Sub, 1, 5) =/= "-file"]]).
diff --git a/lib/stdlib/test/erl_scan_SUITE.erl b/lib/stdlib/test/erl_scan_SUITE.erl
index 32a06d15c7..afeb67eeb1 100644
--- a/lib/stdlib/test/erl_scan_SUITE.erl
+++ b/lib/stdlib/test/erl_scan_SUITE.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1998-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 1998-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(erl_scan_SUITE).
@@ -34,7 +34,7 @@
-define(line, put(line, ?LINE), ).
-define(config(A,B),config(A,B)).
-define(t, test_server).
-%% config(priv_dir, _) ->
+%% config(priv_dir, _) ->
%% ".";
%% config(data_dir, _) ->
%% ".".
@@ -45,7 +45,7 @@
init_per_testcase(_Case, Config) when is_list(Config) ->
?line Dog=test_server:timetrap(test_server:seconds(1200)),
[{watchdog, Dog}|Config].
-
+
fin_per_testcase(_Case, Config) ->
Dog=?config(watchdog, Config),
test_server:timetrap_cancel(Dog),
@@ -97,7 +97,7 @@ assert_type(N, integer) when is_integer(N) ->
ok;
assert_type(N, atom) when is_atom(N) ->
ok.
-
+
check(String) ->
Error = erl_scan:string(String),
check_error(Error, erl_scan).
@@ -146,7 +146,7 @@ iso88591(Config) when is_list(Config) ->
ok -> ok %Aok
end.
-otp_7810(doc) ->
+otp_7810(doc) ->
["OTP-7810. White spaces, comments, and more.."];
otp_7810(suite) ->
[];
@@ -185,7 +185,7 @@ reserved_words() ->
'andalso', 'orelse', 'end', 'fun', 'if', 'let', 'of',
'query', 'receive', 'when', 'bnot', 'not', 'div',
'rem', 'band', 'and', 'bor', 'bxor', 'bsl', 'bsr',
- 'or', 'xor', 'spec'] , % 'spec' shouldn't be there...
+ 'or', 'xor'] ,
[begin
?line {RW, true} = {RW, erl_scan:reserved_word(RW)},
S = atom_to_list(RW),
@@ -203,7 +203,7 @@ atoms() ->
?line test_string("a@2", [{atom,1,a@2}]),
?line test_string([39,65,200,39], [{atom,1,'A�'}]),
?line test_string("�rlig �sten", [{atom,1,�rlig},{atom,1,�sten}]),
- ?line {ok,[{atom,_,'$a'}],{1,6}} =
+ ?line {ok,[{atom,_,'$a'}],{1,6}} =
erl_scan:string("'$\\a'", {1,1}),
?line test("'$\\a'"),
ok.
@@ -221,8 +221,8 @@ punctuations() ->
Three = ["/=:=", "<=:=", "==:=", ">=:="], % three tokens...
No = Three ++ L,
SL0 = [{S1++S2,{-length(S1),S1,S2}} ||
- S1 <- L,
- S2 <- L,
+ S1 <- L,
+ S2 <- L,
not lists:member(S1++S2, No)],
SL = family_list(SL0),
%% Two tokens. When there are several answers, the one with
@@ -250,15 +250,15 @@ comments() ->
?line test("a %%\n b"),
?line {ok,[],1} = erl_scan:string("%"),
?line test("a %%\n b"),
- ?line {ok,[{atom,_,a},{atom,_,b}],{2,3}} =
+ ?line {ok,[{atom,_,a},{atom,_,b}],{2,3}} =
erl_scan:string("a %%\n b",{1,1}),
- ?line {ok,[{atom,_,a},{comment,_,"%%"},{atom,_,b}],{2,3}} =
+ ?line {ok,[{atom,_,a},{comment,_,"%%"},{atom,_,b}],{2,3}} =
erl_scan:string("a %%\n b",{1,1}, [return_comments]),
?line {ok,[{atom,_,a},
{white_space,_," "},
{white_space,_,"\n "},
{atom,_,b}],
- {2,3}} =
+ {2,3}} =
erl_scan:string("a %%\n b",{1,1},[return_white_spaces]),
?line {ok,[{atom,_,a},
{white_space,_," "},
@@ -275,14 +275,14 @@ errors() ->
?line {error,{1,erl_scan,char},1} = erl_scan:string("$"),
?line test_string([34,65,200,34], [{string,1,"A�"}]),
?line test_string("\\", [{'\\',1}]),
- ?line {'EXIT',_} =
+ ?line {'EXIT',_} =
(catch {foo, erl_scan:string('$\\a', {1,1})}), % type error
- ?line {'EXIT',_} =
+ ?line {'EXIT',_} =
(catch {foo, erl_scan:tokens([], '$\\a', {1,1})}), % type error
?line "{a,tuple}" = erl_scan:format_error({a,tuple}),
ok.
-
+
integers() ->
[begin
I = list_to_integer(S),
@@ -299,14 +299,14 @@ base_integers() ->
?line test_string(BS++"#"++S, Ts)
end || {BS,S} <- [{"2","11"}, {"5","23234"}, {"12","05a"},
{"16","abcdef"}, {"16","ABCDEF"}] ],
-
+
?line {error,{1,erl_scan,{base,1}},1} = erl_scan:string("1#000"),
-
+
?line test_string("12#bc", [{integer,1,11},{atom,1,c}]),
-
+
[begin
Str = BS ++ "#" ++ S,
- ?line {error,{1,erl_scan,{illegal,integer}},1} =
+ ?line {error,{1,erl_scan,{illegal,integer}},1} =
erl_scan:string(Str)
end || {BS,S} <- [{"3","3"},{"15","f"}, {"12","c"}] ],
@@ -323,8 +323,8 @@ floats() ->
end || FS <- ["1.0","001.17","3.31200","1.0e0","1.0E17",
"34.21E-18", "17.0E+14"]],
?line test_string("1.e2", [{integer,1,1},{'.',1},{atom,1,e2}]),
-
- ?line {error,{1,erl_scan,{illegal,float}},1} =
+
+ ?line {error,{1,erl_scan,{illegal,float}},1} =
erl_scan:string("1.0e400"),
[begin
?line {error,{1,erl_scan,{illegal,float}},1} = erl_scan:string(S)
@@ -345,16 +345,16 @@ dots() ->
{".a", {ok,[{'.',1},{atom,1,a}],1}}
],
?line [R = erl_scan:string(S) || {S, R} <- Dot],
-
+
?line {ok,[{dot,_}=T1],{1,2}} = erl_scan:string(".", {1,1}, text),
- ?line [{column,1},{length,1},{line,1},{text,"."}] =
+ ?line [{column,1},{length,1},{line,1},{text,"."}] =
erl_scan:token_info(T1, [column, length, line, text]),
?line {ok,[{dot,_}=T2],{1,3}} = erl_scan:string(".%", {1,1}, text),
- ?line [{column,1},{length,1},{line,1},{text,"."}] =
+ ?line [{column,1},{length,1},{line,1},{text,"."}] =
erl_scan:token_info(T2, [column, length, line, text]),
?line {ok,[{dot,_}=T3],{1,6}} =
erl_scan:string(".% �h", {1,1}, text),
- ?line [{column,1},{length,1},{line,1},{text,"."}] =
+ ?line [{column,1},{length,1},{line,1},{text,"."}] =
erl_scan:token_info(T3, [column, length, line, text]),
?line {error,{{1,2},erl_scan,char},{1,3}} =
erl_scan:string(".$", {1,1}),
@@ -376,10 +376,10 @@ dots() ->
?line {done,{ok,[{comment,_,"%. "},
{white_space,_,"\n"},
{dot,_}],
- {2,3}}, ""} =
+ {2,3}}, ""} =
erl_scan:tokens(C, "\n. ", {1,1}, return), % any loc, any options
- ?line [test_string(S, R) ||
+ ?line [test_string(S, R) ||
{S, R} <- [{".$\n", [{'.',1},{char,1,$\n}]},
{"$\\\n", [{char,1,$\n}]},
{"'\\\n'", [{atom,1,'\n'}]},
@@ -392,7 +392,7 @@ chars() ->
Ts = [{char,1,C}],
?line test_string(L, Ts)
end || C <- lists:seq(0, 255)],
-
+
%% Leading zeroes...
[begin
L = lists:flatten(io_lib:format("$\\~3.8.0b", [C])),
@@ -406,13 +406,13 @@ chars() ->
Ts = [{char,1,C band 2#11111}],
?line test_string(L, Ts)
end || C <- lists:seq(0, 255)],
-
+
[begin
L = "$\\" ++ [C],
Ts = [{char,1,V}],
?line test_string(L, Ts)
- end || {C,V} <- [{$n,$\n}, {$r,$\r}, {$t,$\t}, {$v,$\v},
- {$b,$\b}, {$f,$\f}, {$e,$\e}, {$s,$\s},
+ end || {C,V} <- [{$n,$\n}, {$r,$\r}, {$t,$\t}, {$v,$\v},
+ {$b,$\b}, {$f,$\f}, {$e,$\e}, {$s,$\s},
{$d,$\d}]],
EC = [$\n,$\r,$\t,$\v,$\b,$\f,$\e,$\s,$\d],
@@ -445,7 +445,7 @@ chars() ->
end || C <- lists:seq(0, 255) -- (No ++ [$\\])],
?line test_string("$\n", [{char,1,$\n}]),
- ?line {error,{{1,1},erl_scan,char},{1,4}} =
+ ?line {error,{{1,1},erl_scan,char},{1,4}} =
erl_scan:string("$\\^",{1,1}),
?line test_string("$\\\n", [{char,1,$\n}]),
%% Robert's scanner returns line 1:
@@ -453,7 +453,7 @@ chars() ->
?line test_string("$\n\n", [{char,1,$\n}]),
?line test("$\n\n"),
ok.
-
+
variables() ->
?line test_string(" \237_Aou�eiy��", [{var,1,'_Aou�eiy��'}]),
@@ -469,8 +469,8 @@ eof() ->
?line {done,{eof,2},eof} = erl_scan:tokens(C1, eof, 1),
{more, C2} = erl_scan:tokens([], "abra", 1),
%% An error before R13A.
- %% ?line {done,Err={error,{1,erl_scan,scan},1},eof} =
- ?line {done,{ok,[{atom,1,abra}],1},eof} =
+ %% ?line {done,Err={error,{1,erl_scan,scan},1},eof} =
+ ?line {done,{ok,[{atom,1,abra}],1},eof} =
erl_scan:tokens(C2, eof, 1),
%% With column.
@@ -478,7 +478,7 @@ eof() ->
?line {done,{eof,{2,1}},eof} = erl_scan:tokens(C3, eof, 1),
{more, C4} = erl_scan:tokens([], "abra", {1,1}),
%% An error before R13A.
- %% ?line {done,{error,{{1,1},erl_scan,scan},{1,5}},eof} =
+ %% ?line {done,{error,{{1,1},erl_scan,scan},{1,5}},eof} =
?line {done,{ok,[{atom,_,abra}],{1,5}},eof} =
erl_scan:tokens(C4, eof, 1),
@@ -486,7 +486,7 @@ eof() ->
%% the R12B scanner returns eof as LeftoverChars: (eof is correct)
?line {more, C5} = erl_scan:tokens([], "a", 1),
%% An error before R13A.
- %% ?line {done,{error,{1,erl_scan,scan},1},eof} =
+ %% ?line {done,{error,{1,erl_scan,scan},1},eof} =
?line {done,{ok,[{atom,1,a}],1},eof} =
erl_scan:tokens(C5,eof,1),
@@ -528,7 +528,7 @@ illegal() ->
erl_scan:tokens([], "foo "++Atom++". ", {1,1}),
?line {error,{{1,1},erl_scan,{illegal,atom}},{1,1003}} =
erl_scan:string(QAtom, {1,1}),
- ?line {done,{error,{{1,5},erl_scan,{illegal,atom}},{1,1007}},". "} =
+ ?line {done,{error,{{1,5},erl_scan,{illegal,atom}},{1,1007}},". "} =
erl_scan:tokens([], "foo "++QAtom++". ", {1,1}),
?line {error,{{1,1},erl_scan,{illegal,var}},{1,1001}} =
erl_scan:string(Var, {1,1}),
@@ -553,7 +553,7 @@ crashes() ->
?line {'EXIT',_} = (catch {foo, erl_scan:string("\"\\v"++[-1,$"])}), %$"
?line {'EXIT',_} = (catch {foo, erl_scan:string([$",-1,$"])}),
?line {'EXIT',_} = (catch {foo, erl_scan:string("% foo"++[-1])}),
- ?line {'EXIT',_} =
+ ?line {'EXIT',_} =
(catch {foo, erl_scan:string("% foo"++[-1],{1,1})}),
?line {'EXIT',_} = (catch {foo, erl_scan:string([a])}), % type error
@@ -564,7 +564,7 @@ crashes() ->
?line {'EXIT',_} = (catch {foo, erl_scan:string("\"\\v"++[a,$"])}), %$"
?line {'EXIT',_} = (catch {foo, erl_scan:string([$",a,$"])}),
?line {'EXIT',_} = (catch {foo, erl_scan:string("% foo"++[a])}),
- ?line {'EXIT',_} =
+ ?line {'EXIT',_} =
(catch {foo, erl_scan:string("% foo"++[a],{1,1})}),
?line {'EXIT',_} = (catch {foo, erl_scan:string([3.0])}), % type error
@@ -573,26 +573,26 @@ crashes() ->
options() ->
%% line and column are not options, but tested here
- ?line {ok,[{atom,1,foo},{white_space,1," "},{comment,1,"% bar"}], 1} =
+ ?line {ok,[{atom,1,foo},{white_space,1," "},{comment,1,"% bar"}], 1} =
erl_scan:string("foo % bar", 1, return),
- ?line {ok,[{atom,1,foo},{white_space,1," "}],1} =
+ ?line {ok,[{atom,1,foo},{white_space,1," "}],1} =
erl_scan:string("foo % bar", 1, return_white_spaces),
- ?line {ok,[{atom,1,foo},{comment,1,"% bar"}],1} =
+ ?line {ok,[{atom,1,foo},{comment,1,"% bar"}],1} =
erl_scan:string("foo % bar", 1, return_comments),
- ?line {ok,[{atom,17,foo}],17} =
+ ?line {ok,[{atom,17,foo}],17} =
erl_scan:string("foo % bar", 17),
- ?line {'EXIT',{function_clause,_}} =
- (catch {foo,
+ ?line {'EXIT',{function_clause,_}} =
+ (catch {foo,
erl_scan:string("foo % bar", {a,1}, [])}), % type error
- ?line {ok,[{atom,_,foo}],{17,18}} =
+ ?line {ok,[{atom,_,foo}],{17,18}} =
erl_scan:string("foo % bar", {17,9}, []),
- ?line {'EXIT',{function_clause,_}} =
+ ?line {'EXIT',{function_clause,_}} =
(catch {foo,
erl_scan:string("foo % bar", {1,0}, [])}), % type error
- ?line {ok,[{foo,1}],1} =
+ ?line {ok,[{foo,1}],1} =
erl_scan:string("foo % bar",1, [{reserved_word_fun,
fun(W) -> W =:= foo end}]),
- ?line {'EXIT',{badarg,_}} =
+ ?line {'EXIT',{badarg,_}} =
(catch {foo,
erl_scan:string("foo % bar",1, % type error
[{reserved_word_fun,
@@ -618,14 +618,14 @@ more_options() ->
token_info() ->
?line {ok,[T1],_} = erl_scan:string("foo", {1,18}, [text]),
- {'EXIT',{badarg,_}} =
+ {'EXIT',{badarg,_}} =
(catch {foo, erl_scan:token_info(T1, foo)}), % type error
?line {line,1} = erl_scan:token_info(T1, line),
?line {column,18} = erl_scan:token_info(T1, column),
?line {length,3} = erl_scan:token_info(T1, length),
?line {text,"foo"} = erl_scan:token_info(T1, text),
?line [{category,atom},{column,18},{length,3},{line,1},
- {symbol,foo},{text,"foo"}] =
+ {symbol,foo},{text,"foo"}] =
erl_scan:token_info(T1),
?line [{length,3},{column,18}] =
erl_scan:token_info(T1, [length, column]),
@@ -648,9 +648,9 @@ token_info() ->
?line {category,'='} = erl_scan:token_info(T3, category),
?line [{symbol,'='}] = erl_scan:token_info(T3, [symbol]),
ok.
-
+
attributes_info() ->
- ?line {'EXIT',_} =
+ ?line {'EXIT',_} =
(catch {foo,erl_scan:attributes_info(foo)}), % type error
?line [{line,18}] = erl_scan:attributes_info(18),
?line {location,19} = erl_scan:attributes_info(19, location),
@@ -717,9 +717,9 @@ set_attribute() ->
?line [{line,{17,11}},{text,"foo"}] =
erl_scan:attributes_info(A7, [line,column,text]),
- ?line {'EXIT',_} =
+ ?line {'EXIT',_} =
(catch {foo, erl_scan:set_attribute(line, [], F2)}), % type error
- ?line {'EXIT',{badarg,_}} =
+ ?line {'EXIT',{badarg,_}} =
(catch {foo, erl_scan:set_attribute(column, [], F2)}), % type error
ok.
@@ -790,14 +790,14 @@ unicode() ->
?line {ok,[{char,1,83},{integer,1,45}],1} =
erl_scan:string("$\\12345"), % not unicode
- ?line {error,{1,erl_scan,{illegal,character}},1} =
+ ?line {error,{1,erl_scan,{illegal,character}},1} =
erl_scan:string([1089]),
- ?line {error,{{1,1},erl_scan,{illegal,character}},{1,2}} =
+ ?line {error,{{1,1},erl_scan,{illegal,character}},{1,2}} =
erl_scan:string([1089], {1,1}),
?line {error,{1,erl_scan,{illegal,character}},1} =
- %% ?line {error,{1,erl_scan,{illegal,atom}},1} =
+ %% ?line {error,{1,erl_scan,{illegal,atom}},1} =
erl_scan:string("'a"++[1089]++"b'"),
- ?line {error,{{1,3},erl_scan,{illegal,character}},{1,4}} =
+ ?line {error,{{1,3},erl_scan,{illegal,character}},{1,4}} =
erl_scan:string("'a"++[1089]++"b'", {1,1}),
?line test("\"a"++[1089]++"b\""),
?line {ok,[{char,1,1}],1} = erl_scan:string([$$,$\\,$^,1089]),
@@ -822,7 +822,7 @@ unicode() ->
?line {ok,[{integer,1,16#aaa}],1} = erl_scan:string(Qs),
?line {ok,[Q2],{1,9}} = erl_scan:string("$\\x{aaa}", {1,1}, text),
?line [{category,integer},{column,1},{length,8},
- {line,1},{symbol,16#aaa},{text,Qs}] =
+ {line,1},{symbol,16#aaa},{text,Qs}] =
erl_scan:token_info(Q2),
U1 = "\"\\x{aaa}\"",
@@ -830,11 +830,11 @@ unicode() ->
?line [{category,'['},{column,1},{length,1},{line,1},
{symbol,'['},{text,"\""}] = erl_scan:token_info(T1, Tags),
?line [{category,integer},{column,2},{length,7},
- {line,1},{symbol,16#aaa},{text,"\\x{aaa}"}] =
+ {line,1},{symbol,16#aaa},{text,"\\x{aaa}"}] =
erl_scan:token_info(T2, Tags),
?line [{category,']'},{column,9},{length,1},{line,1},
{symbol,']'},{text,"\""}] = erl_scan:token_info(T3, Tags),
- ?line {ok,[{'[',1},{integer,1,16#aaa},{']',1}],1} =
+ ?line {ok,[{'[',1},{integer,1,16#aaa},{']',1}],1} =
erl_scan:string(U1, 1),
U2 = "\"\\x41\\x{fff}\\x42\"",
@@ -844,7 +844,7 @@ unicode() ->
U3 = "\"a\n\\x{fff}\n\"",
?line {ok,[{'[',1},{char,1,$a},{',',1},{char,1,$\n},
{',',2},{integer,2,16#fff},{',',2},{char,2,$\n},
- {']',3}],3} =
+ {']',3}],3} =
erl_scan:string(U3, 1),
U4 = "\"\\^\n\\x{aaa}\\^\n\"",
@@ -867,10 +867,10 @@ unicode() ->
{char,_,$d},{']',_}],{1,8}} = erl_scan:string(Str1, {1,1}),
?line test(Str1),
Comment = "%% "++[1089],
- ?line {ok,[{comment,1,[$%,$%,$\s,1089]}],1} =
+ ?line {ok,[{comment,1,[$%,$%,$\s,1089]}],1} =
erl_scan:string(Comment, 1, return),
- ?line {ok,[{comment,_,[$%,$%,$\s,1089]}],{1,5}} =
- erl_scan:string(Comment, {1,1}, return),
+ ?line {ok,[{comment,_,[$%,$%,$\s,1089]}],{1,5}} =
+ erl_scan:string(Comment, {1,1}, return),
ok.
more_chars() ->
@@ -885,7 +885,7 @@ more_chars() ->
erl_scan:tokens(C1, eof, 1),
?line {ok,[{char,1,123},{atom,1,a},{'}',1}],1} =
erl_scan:string("$\\{a}"),
-
+
?line {error,{{1,1},erl_scan,char},{1,4}} =
erl_scan:string("$\\x", {1,1}),
?line {error,{{1,1},erl_scan,char},{1,5}} =
@@ -893,12 +893,12 @@ more_chars() ->
?line {more, C3} = erl_scan:tokens([], "$\\x", {1,1}),
?line {done,{error,{{1,1},erl_scan,char},{1,4}},eof} =
erl_scan:tokens(C3, eof, 1),
- ?line {error,{{1,1},erl_scan,char},{1,5}} =
+ ?line {error,{{1,1},erl_scan,char},{1,5}} =
erl_scan:string("$\\x{",{1,1}),
?line {more, C2} = erl_scan:tokens([], "$\\x{", {1,1}),
- ?line {done,{error,{{1,1},erl_scan,char},{1,5}},eof} =
+ ?line {done,{error,{{1,1},erl_scan,char},{1,5}},eof} =
erl_scan:tokens(C2, eof, 1),
- ?line {error,{1,erl_scan,{illegal,character}},1} =
+ ?line {error,{1,erl_scan,{illegal,character}},1} =
erl_scan:string("$\\x{g}"),
?line {error,{{1,1},erl_scan,{illegal,character}},{1,5}} =
erl_scan:string("$\\x{g}", {1,1}),
@@ -924,12 +924,12 @@ more_chars() ->
?line test("$\\x{10FFFF}"),
?line test("$\\x{10ffff}"),
?line test("\"$\n \\{1}\""),
- ?line {error,{1,erl_scan,{illegal,character}},1} =
+ ?line {error,{1,erl_scan,{illegal,character}},1} =
erl_scan:string("$\\x{110000}"),
- ?line {error,{{1,1},erl_scan,{illegal,character}},{1,12}} =
+ ?line {error,{{1,1},erl_scan,{illegal,character}},{1,12}} =
erl_scan:string("$\\x{110000}", {1,1}),
- ?line {error,{{1,1},erl_scan,{illegal,character}},{1,4}} =
+ ?line {error,{{1,1},erl_scan,{illegal,character}},{1,4}} =
erl_scan:string("$\\xfg", {1,1}),
?line test("$\\xffg"),
@@ -953,11 +953,11 @@ test(String) ->
{Wtokens, Wend},
{Ctokens, Cend},
{CWtokens, CWend},
- {CWtokens2, _}] =
+ {CWtokens2, _}] =
[scan_string_with_column(String, X) ||
- X <- [[],
- [return_white_spaces],
- [return_comments],
+ X <- [[],
+ [return_white_spaces],
+ [return_comments],
[return],
[return]]], % for white space compaction test
@@ -969,7 +969,7 @@ test(String) ->
{none,Tokens} = {none, filter_tokens(CWtokens, [white_space,comment])},
{comments,Ctokens} =
{comments,filter_tokens(CWtokens, [white_space])},
- {white_spaces,Wtokens} =
+ {white_spaces,Wtokens} =
{white_spaces,filter_tokens(CWtokens, [comment])},
%% Use token attributes to extract parts from the original string,
@@ -991,9 +991,9 @@ test(String) ->
%% Line attribute only:
[Simple,Wsimple,Csimple,WCsimple] = Simples =
[element(2, erl_scan:string(String, 1, Opts)) ||
- Opts <- [[],
- [return_white_spaces],
- [return_comments],
+ Opts <- [[],
+ [return_white_spaces],
+ [return_comments],
[return]]],
{consistent,true} = {consistent,consistent_attributes(Simples)},
{simple_wc,WCsimple} = {simple_wc,simplify(CWtokens)},
@@ -1004,19 +1004,19 @@ test(String) ->
%% Line attribute only, with text:
[SimpleTxt,WsimpleTxt,CsimpleTxt,WCsimpleTxt] = SimplesTxt =
[element(2, erl_scan:string(String, 1, [text|Opts])) ||
- Opts <- [[],
- [return_white_spaces],
- [return_comments],
+ Opts <- [[],
+ [return_white_spaces],
+ [return_comments],
[return]]],
TextTxt = get_text(WCsimpleTxt),
{text_txt,TextTxt,String} = {text_txt,String,TextTxt},
- {consistent_txt,true} =
+ {consistent_txt,true} =
{consistent_txt,consistent_attributes(SimplesTxt)},
- {simple_txt,SimpleTxt} =
+ {simple_txt,SimpleTxt} =
{simple_txt,filter_tokens(WCsimpleTxt, [white_space,comment])},
- {simple_c_txt,CsimpleTxt} =
+ {simple_c_txt,CsimpleTxt} =
{simple_c_txt,filter_tokens(WCsimpleTxt, [white_space])},
- {simple_w_txt,WsimpleTxt} =
+ {simple_w_txt,WsimpleTxt} =
{simple_w_txt,filter_tokens(WCsimpleTxt, [comment])},
ok.
@@ -1024,18 +1024,18 @@ test(String) ->
test_white_space_compaction(Tokens, Tokens2) when Tokens =:= Tokens2 ->
[WS, WS2] = [select_tokens(Ts, [white_space]) || Ts <- [Tokens, Tokens2]],
test_wsc(WS, WS2).
-
+
test_wsc([], []) ->
ok;
test_wsc([Token|Tokens], [Token2|Tokens2]) ->
- [Text, Text2] = [Text ||
- {text, Text} <-
+ [Text, Text2] = [Text ||
+ {text, Text} <-
[erl_scan:token_info(T, text) ||
T <- [Token, Token2]]],
Sz = erts_debug:size(Text),
Sz2 = erts_debug:size({Text, Text2}),
IsCompacted = Sz2 < 2*Sz+erts_debug:size({a,a}),
- ToBeCompacted = is_compacted(Text),
+ ToBeCompacted = is_compacted(Text),
if
IsCompacted =:= ToBeCompacted ->
test_wsc(Tokens, Tokens2);
@@ -1050,14 +1050,14 @@ is_compacted("\n\r") ->
is_compacted("\n\f") ->
true;
is_compacted([$\n|String]) ->
- all_spaces(String)
+ all_spaces(String)
orelse
all_tabs(String);
is_compacted(String) ->
all_spaces(String)
orelse
all_tabs(String).
-
+
all_spaces(L) ->
all_same(L, $\s).
@@ -1078,7 +1078,7 @@ newlines_first([Token|Tokens]) ->
_ ->
Nnls =:= 0
end,
- if
+ if
OK -> newlines_first(Tokens);
true -> OK
end.
@@ -1097,7 +1097,7 @@ simplify([]) ->
get_text(Tokens) ->
lists:flatten(
- [T ||
+ [T ||
Token <- Tokens,
({text,T} = erl_scan:token_info(Token, text)) =/= []]).
@@ -1108,7 +1108,7 @@ test_decorated_tokens(String, Tokens) ->
token_attrs(Tokens) ->
[{L,C,Len,T} ||
Token <- Tokens,
- ([{line,L},{column,C},{length,Len},{text,T}] =
+ ([{line,L},{column,C},{length,Len},{text,T}] =
erl_scan:token_info(Token, [line,column,length,text])) =/= []].
test_strings([], _S, Line, Column) ->
@@ -1150,7 +1150,7 @@ scan_string_with_column(String, Options0) ->
{ok, Ts1, End1} = erl_scan:string(String, StartLoc, Options),
TString = String ++ ". ",
{ok,Ts2,End2} = scan_tokens(TString, Options, [], StartLoc),
- {ok, Ts3, End3} =
+ {ok, Ts3, End3} =
scan_tokens_1({more, []}, TString, Options, [], StartLoc),
{end_2,End2,End3} = {end_2,End3,End2},
{EndLine1,EndColumn1} = End1,
@@ -1190,8 +1190,8 @@ consistent_attributes([Ts | TsL]) ->
L = [T || T <- Ts, is_integer(element(2, T))],
case L of
[] ->
- TagsL = [[Tag || {Tag,_} <-
- erl_scan:attributes_info(element(2, T))] ||
+ TagsL = [[Tag || {Tag,_} <-
+ erl_scan:attributes_info(element(2, T))] ||
T <- Ts],
case lists:usort(TagsL) of
[_] ->
diff --git a/lib/stdlib/test/re_SUITE.erl b/lib/stdlib/test/re_SUITE.erl
index 4e78568a87..46a84d4e24 100644
--- a/lib/stdlib/test/re_SUITE.erl
+++ b/lib/stdlib/test/re_SUITE.erl
@@ -18,12 +18,12 @@
%%
-module(re_SUITE).
--export([all/1, pcre/1,compile_options/1,run_options/1,combined_options/1,replace_autogen/1,global_capture/1,replace_input_types/1,replace_return/1,split_autogen/1,split_options/1,split_specials/1,error_handling/1,pcre_cve_2008_2371/1,pcre_compile_workspace_overflow/1]).
+-export([all/1, pcre/1,compile_options/1,run_options/1,combined_options/1,replace_autogen/1,global_capture/1,replace_input_types/1,replace_return/1,split_autogen/1,split_options/1,split_specials/1,error_handling/1,pcre_cve_2008_2371/1,pcre_compile_workspace_overflow/1,re_infinite_loop/1]).
-include("test_server.hrl").
-include_lib("kernel/include/file.hrl").
-all(suite) -> [pcre,compile_options,run_options,combined_options,replace_autogen,global_capture,replace_input_types,replace_return,split_autogen,split_options,split_specials,error_handling,pcre_cve_2008_2371,pcre_compile_workspace_overflow].
+all(suite) -> [pcre,compile_options,run_options,combined_options,replace_autogen,global_capture,replace_input_types,replace_return,split_autogen,split_options,split_specials,error_handling,pcre_cve_2008_2371,pcre_compile_workspace_overflow,re_infinite_loop].
pcre(doc) ->
["Run all applicable tests from the PCRE testsuites."];
@@ -552,3 +552,17 @@ pcre_compile_workspace_overflow(Config) when is_list(Config) ->
?line {error,{"internal error: overran compiling workspace",799}} =
re:compile([lists:duplicate(N, $(), lists:duplicate(N, $))]),
ok.
+re_infinite_loop(doc) ->
+ "Make sure matches that really loop infinitely actually fail";
+re_infinite_loop(Config) when is_list(Config) ->
+ Dog = ?t:timetrap(?t:minutes(1)),
+ ?line Str =
+ "http:/www.flickr.com/slideShow/index.gne?group_id=&user_id=69845378@N0",
+ ?line EMail_regex = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+"
+ ++ "(\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*"
+ ++ "@.*([a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+"
+ ++ "([a-zA-Z]{2}|com|org|net|gov|mil"
+ ++ "|biz|info|mobi|name|aero|jobs|museum)",
+ ?line nomatch = re:run(Str, EMail_regex),
+ ?t:timetrap_cancel(Dog),
+ ok.
diff --git a/lib/syntax_tools/src/erl_comment_scan.erl b/lib/syntax_tools/src/erl_comment_scan.erl
index 09ce21a428..e2c6976a2b 100644
--- a/lib/syntax_tools/src/erl_comment_scan.erl
+++ b/lib/syntax_tools/src/erl_comment_scan.erl
@@ -273,12 +273,8 @@ join_lines([], Txt, L, Col, Ind) ->
filename([C|T]) when is_integer(C), C > 0, C =< 255 ->
[C | filename(T)];
-filename([H|T]) ->
- filename(H) ++ filename(T);
filename([]) ->
[];
-filename(N) when is_atom(N) ->
- atom_to_list(N);
filename(N) ->
report_error("bad filename: `~P'.", [N, 25]),
exit(error).
diff --git a/lib/syntax_tools/src/erl_prettypr.erl b/lib/syntax_tools/src/erl_prettypr.erl
index 606441bcf1..c2c72d1ed2 100644
--- a/lib/syntax_tools/src/erl_prettypr.erl
+++ b/lib/syntax_tools/src/erl_prettypr.erl
@@ -384,7 +384,7 @@ lay_postcomments(Cs, D) ->
beside(D, floating(break(stack_comments(Cs, true)), 1, 0)).
%% Format (including padding, if `Pad' is `true', otherwise not)
-%% and stack the listed comments above each other,
+%% and stack the listed comments above each other.
stack_comments([C | Cs], Pad) ->
D = stack_comment_lines(erl_syntax:comment_text(C)),
@@ -405,9 +405,7 @@ stack_comments([C | Cs], Pad) ->
D1; % done
_ ->
above(D1, stack_comments(Cs, Pad))
- end;
-stack_comments([], _) ->
- empty().
+ end.
%% Stack lines of text above each other and prefix each string in
%% the list with a single `%' character.
diff --git a/lib/syntax_tools/src/igor.erl b/lib/syntax_tools/src/igor.erl
index e92e9593b6..702b399615 100644
--- a/lib/syntax_tools/src/igor.erl
+++ b/lib/syntax_tools/src/igor.erl
@@ -699,7 +699,7 @@ merge_files(Name, Trees, Files, Opts) ->
options :: [option()]
}).
--spec merge_sources(atom(), erl_syntax:forms(), [option()]) ->
+-spec merge_sources(atom(), [erl_syntax:forms()], [option()]) ->
{erl_syntax:syntaxTree(), [stubDescriptor()]}.
merge_sources(Name, Sources, Opts) ->
@@ -782,12 +782,12 @@ merge_sources_1(Name, Modules, Trees, Opts) ->
%% however not "safe" by default. If no modules are explicitly
%% specified as static, it is assumed that *all* are static.
Static0 = ordsets:from_list(proplists:append_values(static, Opts)),
- case proplists:is_defined(static, Opts) of
- false ->
- Static = All;
- true ->
- Static = ordsets:add_element(Name, Static0)
- end,
+ Static = case proplists:is_defined(static, Opts) of
+ false ->
+ All;
+ true ->
+ ordsets:add_element(Name, Static0)
+ end,
check_module_names(Static, All, "declared 'static'"),
verbose("static modules: ~p.", [Static], Opts),
@@ -806,8 +806,8 @@ merge_sources_1(Name, Modules, Trees, Opts) ->
verbose("safe modules: ~p.", [Safe], Opts),
Preserved = (ordsets:is_element(Name, Sources)
- and ordsets:is_element(Name, Export))
- or proplists:get_bool(no_banner, Opts),
+ andalso ordsets:is_element(Name, Export))
+ orelse proplists:get_bool(no_banner, Opts),
NoHeaders = proplists:get_bool(no_headers, Opts),
Notes = proplists:get_value(notes, Opts, always),
Rs = proplists:append_values(redirect, Opts),
@@ -2924,9 +2924,7 @@ make_attribute({Name, Term}) ->
[erl_syntax:abstract(Term)]).
is_auto_import({F, A}) ->
- erl_internal:bif(F, A);
-is_auto_import(_) ->
- false.
+ erl_internal:bif(F, A).
timestamp() ->
{{Yr, Mth, Dy}, {Hr, Mt, Sc}} = erlang:localtime(),
diff --git a/lib/test_server/doc/src/test_server_ctrl.xml b/lib/test_server/doc/src/test_server_ctrl.xml
index 4a778bcaf7..8b60849b61 100644
--- a/lib/test_server/doc/src/test_server_ctrl.xml
+++ b/lib/test_server/doc/src/test_server_ctrl.xml
@@ -538,9 +538,6 @@ Optional, if not given the test server controller node
test server controller node. The log must be formatted using
<c>ttb:format/1/2</c>.
</p>
- <p>This is valid for all targets except the OSE/Delta target
- for which all nodes will be logged and automatically formatted
- in one single text file called <c>allnodes-test_server</c>.</p>
</desc>
</func>
<func>
diff --git a/lib/test_server/doc/src/ts.xml b/lib/test_server/doc/src/ts.xml
index 0f91d3eea2..f60c79aadd 100644
--- a/lib/test_server/doc/src/ts.xml
+++ b/lib/test_server/doc/src/ts.xml
@@ -250,7 +250,7 @@
running test suites. If a remote host is to be used, the
<c>TargetSystem</c> argument must be given so that "cross
installation" can be done. This should be used for testing on
- VxWorks or OSE/Delta. Installation is required for any of the
+ VxWorks. Installation is required for any of the
functions in <c>ts</c> to work.
</p>
<p>Opts may be one or more of
@@ -275,7 +275,7 @@
strings.
</item>
<item><c>{slavetargets, SlaveTarges}</c><br></br>
- For VxWorks and OSE/Delta only. This is a list of
+ For VxWorks only. This is a list of
available hosts where slave nodes can be started. This is
necessary because only one node can run per host in the
VxWorks environment. This is not the same as
diff --git a/lib/test_server/src/test_server.erl b/lib/test_server/src/test_server.erl
index f918f47415..7db103a4c6 100644
--- a/lib/test_server/src/test_server.erl
+++ b/lib/test_server/src/test_server.erl
@@ -1763,7 +1763,7 @@ call_crash(Time,Crash,M,F,A) ->
%% Slave and Peer:
%% {remote, true} - Start the node on a remote host. If not specified,
%% the node will be started on the local host (with
-%% some exceptions, as for the case of VxWorks and OSE,
+%% some exceptions, for instance VxWorks,
%% where all nodes are started on a remote host).
%% {args, Arguments} - Arguments passed directly to the node.
%% {cleanup, false} - Nodes started with this option will not be killed
@@ -2014,14 +2014,8 @@ temp_name(Stem) ->
app_test(App) ->
app_test(App, pedantic).
app_test(App, Mode) ->
- case os:type() of
- {ose,_} ->
- Comment = "Skipping app_test on OSE",
- comment(Comment), % in case user ignores the return value
- {skip,Comment};
- _other ->
- test_server_sup:app_test(App, Mode)
- end.
+ test_server_sup:app_test(App, Mode).
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
diff --git a/lib/test_server/src/test_server_internal.hrl b/lib/test_server/src/test_server_internal.hrl
index 6fa5ef75b1..c9c52854e3 100644
--- a/lib/test_server/src/test_server_internal.hrl
+++ b/lib/test_server/src/test_server_internal.hrl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2002-2009. All Rights Reserved.
-%%
+%%
+%% Copyright Ericsson AB 2002-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%
%%
@@ -37,7 +37,7 @@
username, % string()
cookie, % string(); Cookie for target node
naming, % string(); "-name" | "-sname"
- master, % string(); For OSE this is the master
+ master, % string(); Was used for OSE's master
% node for main target and slave nodes.
% For other platforms the target node
% itself is master for slave nodes
diff --git a/lib/test_server/src/ts.erl b/lib/test_server/src/ts.erl
index 1b750c3858..e23b891392 100644
--- a/lib/test_server/src/ts.erl
+++ b/lib/test_server/src/ts.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -112,7 +112,7 @@
" Mandatory for remote targets\n"
" {master, {MasterHost, MasterCookie}}\n"
" - Master host and cookie for targets which are\n"
- " started as slave nodes (i.e. OSE/Delta targets\n"
+ " started as slave nodes.\n"
" erl_boot_server must be started on master before\n"
" test is run.\n"
" Optional, default is controller host and then\n"
diff --git a/lib/test_server/src/ts_erl_config.erl b/lib/test_server/src/ts_erl_config.erl
index 4fc46fc5d6..5cdbf0fbb8 100644
--- a/lib/test_server/src/ts_erl_config.erl
+++ b/lib/test_server/src/ts_erl_config.erl
@@ -1,19 +1,19 @@
%%
%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 1997-2009. All Rights Reserved.
-%%
+%%
+%% 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%
%%
@@ -161,7 +161,6 @@ system_include(Root, Vars) ->
case ts_lib:var(os, Vars) of
"Windows" ++ _T -> "sys/win32";
"VxWorks" -> "sys.vxworks";
- "OSE" -> "sys/ose";
_ -> "sys/unix"
end,
" -I" ++ filename:nativename(filename:join([Root, "erts", "emulator", SysDir])).
@@ -219,7 +218,7 @@ erl_interface(Vars,OsType) ->
{unix,_} ->
"-lpthread";
_ ->
- "" % VxWorks or OSE
+ "" % VxWorks
end,
CrossCompile = case OsType of
vxworks -> "true";
diff --git a/lib/test_server/src/ts_run.erl b/lib/test_server/src/ts_run.erl
index 1d611f501c..888ac98973 100644
--- a/lib/test_server/src/ts_run.erl
+++ b/lib/test_server/src/ts_run.erl
@@ -198,8 +198,6 @@ get_spec_filename_1(Vars, TestDir, File) ->
case ts_lib:var(os, Vars) of
"VxWorks" ->
check_spec_filename(TestDir, File, ".spec.vxworks");
- "OSE" ->
- check_spec_filename(TestDir, File, ".spec.ose");
"Windows"++_ ->
check_spec_filename(TestDir, File, ".spec.win");
_Other ->
@@ -306,53 +304,36 @@ make_make(Vars, Spec, State) ->
add_make_testcase(Vars, Spec, St) ->
Makefile = St#state.makefile,
Dir = filename:dirname(Makefile),
- case ts_lib:var(os, Vars) of
- "OSE" ->
- %% For OSE, C code in datadir must be linked in the image file,
- %% and erlang code is sent as binaries from test_server_ctrl
- %% Making erlang code here because the Makefile.src probably won't
- %% work.
- Erl_flags=[{i, "../../test_server"}|ts_lib:var(erl_flags,Vars)],
- {ok, Cwd} = file:get_cwd(),
- ok = file:set_cwd(Dir),
- Result = (catch make:all(Erl_flags)),
- ok = file:set_cwd(Cwd),
- case Result of
- up_to_date -> {ok, Vars, Spec, St};
- _error -> {error, {erlang_make_failed,Dir}}
- end;
+ Shortname = filename:basename(Makefile),
+ Suite = filename:basename(Dir, "_data"),
+ Config = [{data_dir,Dir},{makefile,Shortname}],
+ MakeModule = Suite ++ "_make",
+ MakeModuleSrc = filename:join(filename:dirname(Dir),
+ MakeModule ++ ".erl"),
+ MakeMod = list_to_atom(MakeModule),
+ case filelib:is_file(MakeModuleSrc) of
+ true -> ok;
+ false -> generate_make_module(ts_lib:var(make_command, Vars),
+ MakeModuleSrc,
+ MakeModule)
+ end,
+ case Suite of
+ "all_SUITE" ->
+ {ok,Vars,Spec,St#state{all={MakeMod,Config}}};
_ ->
- Shortname = filename:basename(Makefile),
- Suite = filename:basename(Dir, "_data"),
- Config = [{data_dir,Dir},{makefile,Shortname}],
- MakeModule = Suite ++ "_make",
- MakeModuleSrc = filename:join(filename:dirname(Dir),
- MakeModule ++ ".erl"),
- MakeMod = list_to_atom(MakeModule),
- case filelib:is_file(MakeModuleSrc) of
- true -> ok;
- false -> generate_make_module(ts_lib:var(make_command, Vars),
- MakeModuleSrc,
- MakeModule)
- end,
- case Suite of
- "all_SUITE" ->
- {ok,Vars,Spec,St#state{all={MakeMod,Config}}};
- _ ->
- %% Avoid duplicates of testcases. There is no longer
- %% a check for this in test_server_ctrl.
- TestCase = {list_to_atom(Suite),all},
- TopCase0 = case St#state.topcase of
- List when is_list(List) ->
- List -- [TestCase];
- Top ->
- [Top] -- [TestCase]
- end,
- TopCase = [{make,{MakeMod,make,[Config]},
- TestCase,
- {MakeMod,unmake,[Config]}}|TopCase0],
- {ok,Vars,Spec,St#state{topcase=TopCase}}
- end
+ %% Avoid duplicates of testcases. There is no longer
+ %% a check for this in test_server_ctrl.
+ TestCase = {list_to_atom(Suite),all},
+ TopCase0 = case St#state.topcase of
+ List when is_list(List) ->
+ List -- [TestCase];
+ Top ->
+ [Top] -- [TestCase]
+ end,
+ TopCase = [{make,{MakeMod,make,[Config]},
+ TestCase,
+ {MakeMod,unmake,[Config]}}|TopCase0],
+ {ok,Vars,Spec,St#state{topcase=TopCase}}
end.
generate_make_module(MakeCmd, Name, ModuleString) ->
@@ -629,9 +610,6 @@ make_test_server_args(Args0,Options,Vars) ->
"VxWorks" ->
F = write_parameterfile(vxworks,Vars),
" PARAMETERS " ++ F;
- "OSE" ->
- F = write_parameterfile(ose,Vars),
- " PARAMETERS " ++ F;
_ ->
""
end,
diff --git a/lib/tools/emacs/erlang-eunit.el b/lib/tools/emacs/erlang-eunit.el
index 05528aee6d..b2598f93e6 100644
--- a/lib/tools/emacs/erlang-eunit.el
+++ b/lib/tools/emacs/erlang-eunit.el
@@ -1,25 +1,28 @@
;;
;; %CopyrightBegin%
-;;
-;; Copyright Ericsson AB 2009. All Rights Reserved.
-;;
+;;
+;; 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%
;;;
;;; Purpose: Provide EUnit utilities.
;;;
;;; Author: Klas Johansson
+(eval-when-compile
+ (require 'cl))
+
(defvar erlang-eunit-separate-src-and-test-directories t
"*Whether or not to keep source and EUnit test files in separate directories")