1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 2007-2021. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20
21%%
22%%----------------------------------------------------------------------
23%% Purpose: megaco sequence generator for the megaco test suite
24%%----------------------------------------------------------------------
25
26-module(megaco_test_megaco_generator).
27
28-behaviour(megaco_test_generator).
29
30-compile({no_auto_import,[error/1]}).
31
32%% API
33-export([
34         start_link/1, start_link/2,
35	 stop/1,
36         exec/2, exec/3
37        ]).
38
39%% genarator behaviour callback exports
40-export([
41         init/1,
42         handle_parse/2,
43         handle_exec/2,
44         terminate/2
45        ]).
46
47%% Megaco callback api
48-export([
49         handle_connect/3, handle_connect/4,
50         handle_disconnect/4,
51         handle_syntax_error/4,        handle_syntax_error/5,
52         handle_message_error/4,       handle_message_error/5,
53         handle_trans_request/4,       handle_trans_request/5,
54         handle_trans_long_request/4,  handle_trans_long_request/5,
55         handle_trans_reply/5,         handle_trans_reply/6,
56         handle_trans_ack/5,           handle_trans_ack/6,
57         handle_trans_request_abort/5, handle_trans_request_abort/6,
58         handle_unexpected_trans/4,    handle_unexpected_trans/5
59        ]).
60
61
62%%----------------------------------------------------------------------
63
64-include_lib("megaco/include/megaco.hrl").
65
66
67%%----------------------------------------------------------------------
68
69-define(DELIVER_MOD, megaco_test_deliver).
70
71
72%%----------------------------------------------------------------------
73
74-record(state,
75	{
76	  mid,
77	  recv_handle,
78	  port,
79	  send_handle,
80	  conn_handle,
81
82	  transport_sup,
83	  ctrl_pid,
84
85	  result = [] % Accumulated results from verification
86	 }).
87
88
89%%----------------------------------------------------------------------
90%% API
91%%----------------------------------------------------------------------
92
93start_link(Name) ->
94    megaco_test_generator:start_link(?MODULE, [], Name).
95
96start_link(Name, Node) ->
97    megaco_test_generator:start_link(?MODULE, [], Name, Node).
98
99stop(Server) ->
100    megaco_test_generator:stop(Server).
101
102exec(Server, Instructions) when is_list(Instructions) ->
103    megaco_test_generator:exec(Server, Instructions).
104
105exec(Server, Instructions, Timeout) when is_list(Instructions) ->
106    megaco_test_generator:exec(Server, Instructions, Timeout).
107
108
109%%----------------------------------------------------------------------
110%% generator callback functions
111%%----------------------------------------------------------------------
112
113init([]) ->
114    random_init(),
115    {ok, #state{}}.
116
117
118%% ----- instruction parser -----
119
120handle_parse({debug, Debug} = Instruction, State)
121  when is_boolean(Debug) ->
122    {ok, Instruction, State};
123
124handle_parse({expect_nothing, To} = Instruction, State)
125  when is_integer(To) andalso (To > 0) ->
126    {ok, Instruction, State};
127
128handle_parse({megaco_trace, Level} = Instruction, State)
129  when (Level =:= disable) orelse
130       (Level =:= max)     orelse
131       (Level =:= min)     orelse
132       is_integer(Level) ->
133    {ok, Instruction, State};
134
135handle_parse({sleep, To} = Instruction, State)
136  when is_integer(To) andalso (To > 0) ->
137    {ok, Instruction, State};
138
139handle_parse(megaco_start = Instruction, State) ->
140    {ok, Instruction, State};
141
142handle_parse(megaco_stop = Instruction, State) ->
143    {ok, Instruction, State};
144
145handle_parse({megaco_start_user, _Mid, _RecvInfo, Conf} = Instruction, State)
146  when is_list(Conf) ->
147    {ok, Instruction, State};
148
149handle_parse(megaco_stop_user = Instruction, State) ->
150    {ok, Instruction, State};
151
152handle_parse(megaco_info = Instruction, State) ->
153    {ok, Instruction, State};
154
155handle_parse(megaco_system_info, State) ->
156    Verify = fun(_) -> ok end,
157    Instruction = {megaco_system_info, internal_system_info_tag, Verify},
158    {ok, Instruction, State};
159
160handle_parse({megaco_system_info, Tag}, State)
161  when is_atom(Tag) ->
162    Verify = fun(_) -> ok end,
163    Instruction = {megaco_system_info, Tag, Verify},
164    {ok, Instruction, State};
165
166handle_parse({megaco_system_info, Tag, Verify} = Instruction, State)
167  when is_atom(Tag) andalso is_function(Verify) ->
168    {ok, Instruction, State};
169
170handle_parse({megaco_user_info, Tag} = Instruction, State)
171  when is_atom(Tag) ->
172    {ok, Instruction, State};
173
174handle_parse({megaco_update_user_info, Tag, _Val} = Instruction, State)
175  when is_atom(Tag) ->
176    {ok, Instruction, State};
177
178handle_parse({megaco_conn_info, Tag} = Instruction, State)
179  when is_atom(Tag) ->
180    {ok, Instruction, State};
181
182handle_parse({megaco_update_conn_info, Tag, _Val} = Instruction, State)
183  when is_atom(Tag) ->
184    {ok, Instruction, State};
185
186handle_parse(start_transport = Instruction, State) ->
187    {ok, Instruction, State};
188
189handle_parse(listen = _Instruction, State) ->
190    MeybeRetry  = make_connect_retry_fun2(),
191    Instruction = {listen, [], MeybeRetry},
192    {ok, Instruction, State};
193
194handle_parse({listen, Opts} = _Instruction, State)
195  when is_list(Opts) ->
196    MeybeRetry  = make_connect_retry_fun2(),
197    Instruction = {listen, Opts, MeybeRetry},
198    {ok, Instruction, State};
199
200handle_parse({listen, Opts, MeybeRetry} = Instruction, State)
201  when is_list(Opts) andalso is_function(MeybeRetry) ->
202    {ok, Instruction, State};
203
204handle_parse(connect = _Instruction, State) ->
205    case inet:gethostname() of
206	{ok, LocalHost} ->
207	    MeybeRetry  = make_connect_retry_fun2(),
208	    Instruction = {connect, LocalHost, [], MeybeRetry},
209	    {ok, Instruction, State};
210	Error ->
211	    Error
212    end;
213
214handle_parse({connect, Opts} = _Instruction, State)
215  when is_list(Opts) ->
216    verify_connect_opts(Opts),
217    case inet:gethostname() of
218	{ok, LocalHost} ->
219	    MeybeRetry  = make_connect_retry_fun2(),
220	    Instruction = {connect, LocalHost, Opts, MeybeRetry},
221	    {ok, Instruction, State};
222	Error ->
223	    Error
224    end;
225
226handle_parse({connect, Host} = _Instruction, State)
227  when is_atom(Host) ->
228    MeybeRetry  = make_connect_retry_fun2(),
229    Instruction = {connect, Host, [], MeybeRetry},
230    {ok, Instruction, State};
231
232handle_parse({connect, Host, Opts} = _Instruction, State)
233  when (is_atom(Host) orelse is_list(Host)) andalso is_list(Opts) ->
234    verify_connect_opts(Opts),
235    MeybeRetry  = make_connect_retry_fun2(),
236    Instruction = {connect, Host, Opts, MeybeRetry},
237    {ok, Instruction, State};
238
239handle_parse({connect, Host, Opts, MeybeRetry} = Instruction, State)
240  when (is_atom(Host) orelse is_list(Host)) andalso
241       is_list(Opts) andalso
242       is_function(MeybeRetry) ->
243    verify_connect_opts(Opts),
244    {ok, Instruction, State};
245
246handle_parse(disconnect = Instruction, State) ->
247    {ok, Instruction, State};
248
249handle_parse(megaco_connect = Instruction, State) ->
250    {ok, Instruction, State};
251
252handle_parse({megaco_connect, _} = Instruction, State) ->
253    {ok, Instruction, State};
254
255handle_parse(megaco_disconnect = Instruction, State) ->
256    {ok, Instruction, State};
257
258handle_parse({megaco_disconnect, _Reason} = Instruction, State) ->
259    {ok, Instruction, State};
260
261handle_parse({megaco_call, ARs, Opts} = Instruction, State)
262  when (is_list(ARs) orelse is_binary(ARs)) andalso is_list(Opts) ->
263    {ok, Instruction, State};
264
265handle_parse({megaco_call, _Mid, ARs, Opts} = Instruction, State)
266  when (is_list(ARs) orelse is_binary(ARs)) andalso is_list(Opts) ->
267    {ok, Instruction, State};
268
269handle_parse({megaco_cast, ARs, Opts} = Instruction, State)
270  when (is_list(ARs) orelse is_binary(ARs)) andalso is_list(Opts) ->
271    {ok, Instruction, State};
272
273handle_parse({megaco_cast, _Mid, ARs, Opts} = Instruction, State)
274  when (is_list(ARs) orelse is_binary(ARs)) andalso is_list(Opts) ->
275    {ok, Instruction, State};
276
277handle_parse({megaco_cancel, _Reason} = Instruction, State) ->
278    {ok, Instruction, State};
279
280handle_parse({megaco_callback, Tag, TimeoutOrVerify} = Instruction, State)
281  when (is_atom(Tag) andalso
282	((is_integer(TimeoutOrVerify) andalso
283	  (TimeoutOrVerify > 0)) orelse
284	 is_function(TimeoutOrVerify))) ->
285    {ok, Instruction, State};
286
287handle_parse({megaco_callback, Tag, Verify, Timeout} = Instruction, State)
288  when (is_atom(Tag) andalso
289	is_function(Verify) andalso
290	(is_integer(Timeout) andalso (Timeout > 0))) ->
291    {ok, Instruction, State};
292
293handle_parse({megaco_callback, Tag, {VMod, VFunc, VArgs}} = _Instruction,
294	     State)
295  when (is_atom(Tag) andalso
296	(is_atom(VMod) andalso is_atom(VFunc) andalso is_list(VArgs))) ->
297    Verify = fun(X) ->
298                     io:format("[megaco_callback ~w] calling ~w:~w with"
299                               "~n   X:     ~p"
300                               "~n   VArgs: ~w"
301                               "~n", [Tag, VMod, VFunc, X, VArgs]),
302                     (catch apply(VMod, VFunc, [X|VArgs]))
303             end,
304    Instruction = {megaco_callback, Tag, Verify},
305    {ok, Instruction, State};
306
307handle_parse({megaco_callback, Verifiers0} = _Instruction, State)
308  when is_list(Verifiers0) ->
309    Verifiers = [make_verifier(Verifier) || Verifier <- Verifiers0],
310    Instruction = {megaco_callback, Verifiers},
311    {ok, Instruction, State};
312
313handle_parse({trigger, Trigger} = Instruction, State)
314  when is_function(Trigger) ->
315    {ok, Instruction, State};
316handle_parse({trigger, Desc, Trigger} = Instruction, State)
317  when is_list(Desc) andalso is_function(Trigger) ->
318    {ok, Instruction, State};
319
320handle_parse(Instruction, _State) ->
321    error({invalid_instruction, Instruction}).
322
323
324make_verifier({Tag, No, VerifyFunc} = Verify)
325  when is_atom(Tag) andalso is_integer(No) andalso is_function(VerifyFunc) ->
326    Verify;
327make_verifier({Tag, No, {VMod, VFunc, VArgs}})
328  when is_atom(Tag) andalso is_integer(No) andalso
329       (is_atom(VMod) andalso is_atom(VFunc) andalso is_list(VArgs)) ->
330    VerifyFunc = fun(X) ->
331                         io:format("[megaco_callback ~w] calling ~w:~w with"
332                                   "~n   X: ~p"
333                                   "~n   VArgs: ~w"
334                                   "~n", [Tag, VMod, VFunc, X, VArgs]),
335                         (catch apply(VMod, VFunc, [X|VArgs]))
336                 end,
337    Verify = {Tag, No, VerifyFunc},
338    Verify;
339make_verifier(BadVerifier) ->
340    error({bad_verifier, BadVerifier}).
341
342
343verify_connect_opts([]) ->
344    ok;
345verify_connect_opts([{Key, _}|Opts]) when is_atom(Key) ->
346    verify_connect_opts(Opts);
347verify_connect_opts([H|_]) ->
348    error({bad_opts_list, H}).
349
350%% make_connect_retry_fun1() ->
351%%      fun(Error, _) ->
352%% 	     {false, Error}
353%%      end.
354
355make_connect_retry_fun2() ->
356     fun(Error, noError) ->
357	     Timeout = 250,
358	     sleep(random(Timeout) + 100),
359	     {true, {3, Timeout*2, Error}};
360	(_Error, {0, _Timeout, OriginalError}) ->
361	     {false, OriginalError};
362	(_Error, {N, Timeout, OriginalError}) ->
363	     sleep(random(Timeout) + 100),
364	     {true, {N-1, Timeout*2, OriginalError}}
365     end.
366
367
368%% ----- instruction exececutor -----
369
370handle_exec({debug, Debug}, State) ->
371    p("debug: ~p", [Debug]),
372    put(debug, Debug),
373    {ok, State};
374
375handle_exec({expect_nothing, To}, State) ->
376    p("expect nothing: ~p", [To]),
377    receive
378        Any ->
379            e("received unexpected: "
380              "~n   ~p", [Any]),
381            error({expect_nothing, Any})
382    after To ->
383            p("go nothing (~p) as expected", [To]),
384            {ok, State}
385    end;
386
387handle_exec({megaco_trace, disable}, State) ->
388    p("megaco trace: disable"),
389    megaco:disable_trace(),
390    {ok, State};
391handle_exec({megaco_trace, Level}, State) ->
392    p("megaco trace: enable [~w]", [Level]),
393    megaco:enable_trace(Level, io),
394    {ok, State};
395
396handle_exec(megaco_start, State) ->
397    p("start megaco"),
398    ok = megaco:start(),
399    {ok, State};
400
401handle_exec(megaco_stop, State) ->
402    p("stop megaco"),
403    ok = megaco:stop(),
404    {ok, State};
405
406handle_exec({megaco_start_user, Mid, RecvInfo, Conf}, State) ->
407    p("start megaco user: ~p", [Mid]),
408
409    d("megaco_start_user -> start user"),
410    ok = megaco:start_user(Mid, Conf),
411
412    d("megaco_start_user -> update user info: user_mod"),
413    ok = megaco:update_user_info(Mid, user_mod,  ?MODULE),
414
415    d("megaco_start_user -> update user info: user_args"),
416    ok = megaco:update_user_info(Mid, user_args,  [self()]),
417
418    Port = get_config(port,             RecvInfo),
419    EM   = get_config(encoding_module,  RecvInfo),
420    EC   = get_config(encoding_config,  RecvInfo),
421    TM   = get_config(transport_module, RecvInfo),
422    RH0  = megaco:user_info(Mid, receive_handle),
423
424    RH1  = RH0#megaco_receive_handle{send_mod        = TM,
425				     encoding_mod    = EM,
426				     encoding_config = EC},
427
428    State1 = State#state{mid = Mid, recv_handle = RH1, port = Port},
429    {ok, State1};
430
431handle_exec(megaco_stop_user, #state{mid = Mid} = State)
432  when Mid /= undefined ->
433    p("stop megaco user: ~p", [Mid]),
434    megaco_cleanup(State),
435    ok = megaco:stop_user(Mid),
436    {ok, State#state{mid = undefined}};
437
438handle_exec(start_transport,
439            #state{recv_handle = #megaco_receive_handle{send_mod = TM}} = State) ->
440    p("start transport ~p", [TM]),
441    case (catch TM:start_transport()) of
442	{ok, Sup} ->
443	    d("transport started: Sup: ~p", [Sup]),
444	    {ok, State#state{transport_sup = Sup}};
445	{error, Reason} ->
446	    e("failed starting transport (~w): "
447	      "~n   ~p", [TM, Reason]),
448	    error({failed_starting_transport, TM, Reason});
449	Crap ->
450	    e("failed starting transport (~w): "
451	      "~n   ~p", [TM, Crap]),
452	    error({failed_starting_transport, TM, Crap})
453    end;
454
455handle_exec({listen, Opts0, MaybeRetry},
456     #state{recv_handle = RH, port = Port, transport_sup = Pid} = State)
457  when RH#megaco_receive_handle.send_mod =:= megaco_tcp ->
458    p("listen(tcp)"),
459    Opts = [{module,         ?DELIVER_MOD},
460	    {port,           Port},
461	    {receive_handle, RH},
462	    {tcp_options,    [{nodelay, true}]} | Opts0],
463    case (catch handle_exec_listen_tcp(Pid, Opts, MaybeRetry)) of
464        ok ->
465            {ok, State};
466        Else ->
467            error({tcp_listen_failed, Opts0, Else})
468    end;
469handle_exec({listen, Opts0, _MaybeRetry},
470     #state{recv_handle = RH, port = Port, transport_sup = Pid} = State)
471  when RH#megaco_receive_handle.send_mod =:= megaco_udp ->
472    p("listen(udp) - open"),
473    Opts = [{module, ?DELIVER_MOD}, {port, Port}, {receive_handle, RH}|Opts0],
474    case (catch megaco_udp:open(Pid, Opts)) of
475        {ok, _SH, _CtrlPid} ->
476            {ok, State};
477        Else ->
478            error({udp_open, Opts0, Else})
479    end;
480handle_exec({listen, Opts0, _MaybeRetry},
481            #state{recv_handle = RH, port = Port, transport_sup = Pid} = State)
482  when RH#megaco_receive_handle.send_mod =:= megaco_test_generic_transport ->
483    p("listen(generic)"),
484    Opts = [{module, ?DELIVER_MOD}, {port, Port}, {receive_handle, RH}|Opts0],
485    case (catch megaco_test_generic_transport:listen(Pid, Opts)) of
486        {ok, _SH, _CtrlPid} ->
487            {ok, State};
488        Else ->
489            error({udp_open, Opts0, Else})
490    end;
491
492handle_exec({connect, Host, Opts0, MaybeRetry},
493     #state{transport_sup = Sup,
494	     recv_handle  = RH,
495	     port         = Port} = State)
496  when RH#megaco_receive_handle.send_mod =:= megaco_tcp ->
497    p("connect(tcp) to ~p:~p", [Host, Port]),
498    PrelMid = preliminary_mid,
499    Opts = [{host,           Host},
500	    {port,           Port},
501	    {receive_handle, RH},
502	    {tcp_options,    [{nodelay, true}]} | Opts0],
503    case (catch handle_exec_connect_tcp(Host, Opts, Sup, MaybeRetry)) of
504	{ok, SH, ControlPid} ->
505	    d("connected(tcp): ~p, ~p", [SH, ControlPid]),
506	    megaco_connector_start(RH, PrelMid, SH, ControlPid),
507	    {ok, State#state{send_handle = SH,
508			      ctrl_pid    = ControlPid}};
509	Error ->
510	    error({tcp_connect_failed, Host, Opts0, Error})
511    end;
512
513handle_exec({connect, Host, Opts0, _MaybeRetry},
514     #state{transport_sup = Sup,
515	     recv_handle   = RH,
516	     port          = Port} = State)
517  when RH#megaco_receive_handle.send_mod =:= megaco_udp ->
518    p("connect(udp) to ~p", [Host]),
519    PrelMid = preliminary_mid,
520    Opts = [{port, 0}, {receive_handle, RH}|Opts0],
521    d("udp open", []),
522    case (catch megaco_udp:open(Sup, Opts)) of
523	{ok, Handle, ControlPid} ->
524	    d("opened(udp): ~p, ~p", [Handle, ControlPid]),
525	    SH = megaco_udp:create_send_handle(Handle, Host, Port),
526	    megaco_connector_start(RH, PrelMid, SH, ControlPid),
527	    {ok, State#state{send_handle = SH,
528			      ctrl_pid    = ControlPid}};
529	Error ->
530	    error({udp_connect_failed, Host, Opts0, Error})
531    end;
532
533handle_exec({connect, Host, Opts0, _MaybeRetry},
534     #state{transport_sup = Sup,
535	     recv_handle   = RH,
536	     port          = Port} = State)
537  when RH#megaco_receive_handle.send_mod =:= megaco_test_generic_transport ->
538    p("connect(generic) to ~p", [Host]),
539    PrelMid = preliminary_mid,
540    Opts = [{host, Host}, {port, Port}, {receive_handle, RH}|Opts0],
541    case (catch megaco_test_generic_transport:connect(Sup, Opts)) of
542	{ok, SH, ControlPid} ->
543	    d("connected(generic): ~p, ~p", [SH, ControlPid]),
544	    megaco_connector_start(RH, PrelMid, SH, ControlPid),
545	    {ok, State#state{send_handle = SH,
546			      ctrl_pid    = ControlPid}};
547	Error ->
548	    error({generic_connect_failed, Host, Opts0, Error})
549    end;
550
551handle_exec(megaco_connect, State) ->
552    p("expect megaco_connect"),
553    receive
554        {megaco_connect_result, {ok, CH}} ->
555            p("received successful megaco_connect: ~p", [CH]),
556            {ok, State#state{conn_handle = CH}};
557        {megaco_connect_result, Error} ->
558            p("received failed megaco_connect: ~p", [Error]),
559            #state{result = Res} = State,
560            {ok, State#state{result = [Error|Res]}}
561    end;
562
563handle_exec({megaco_connect, Mid},
564	    #state{recv_handle = RH,
565		   send_handle = SH,
566		   ctrl_pid    = ControlPid} = State) ->
567    p("megaco connect: ~p", [Mid]),
568    megaco_connector_start(RH, Mid, SH, ControlPid),
569    {ok, State};
570
571handle_exec({megaco_user_info, Tag}, #state{mid = Mid, result = Res} = State)
572  when Mid /= undefined ->
573    p("megaco user-info: ~w", [Tag]),
574    Val = (catch megaco:user_info(Mid, Tag)),
575    d("megaco_user_info: ~p", [Val]),
576    {ok, State#state{result = [Val|Res]}};
577
578handle_exec({megaco_update_user_info, Tag, Val}, #state{mid = Mid} = State)
579  when Mid /= undefined ->
580    p("update megaco user-info: ~w -> ~p", [Tag, Val]),
581    ok = megaco:update_user_info(Mid, Tag, Val),
582    {ok, State};
583
584handle_exec({megaco_conn_info, Tag},
585     #state{conn_handle = CH, result = Res} = State)
586  when CH /= undefined ->
587    p("megaco conn-info: ~w", [Tag]),
588    Val = (catch megaco:conn_info(CH, Tag)),
589    d("megaco_conn_info: ~p", [Val]),
590    {ok, State#state{result = [Val|Res]}};
591
592handle_exec({megaco_update_conn_info, Tag, Val},
593     #state{conn_handle = CH} = State)
594  when CH /= undefined ->
595    p("update megaco conn-info: ~w -> ~p", [Tag, Val]),
596    case megaco:update_conn_info(CH, Tag, Val) of
597        ok ->
598            {ok, State};
599        Error ->
600            error({failed_updating_conn_info, Tag, Val, Error})
601    end;
602
603handle_exec(megaco_info, #state{result = Res} = State) ->
604    p("megaco info", []),
605    Val = (catch megaco:info()),
606    d("megaco_info: ~p", [Val]),
607    {ok, State#state{result = [Val|Res]}};
608
609handle_exec({megaco_system_info, Tag, Verify}, #state{result = Res} = State) ->
610    p("megaco system-info: ~w", [Tag]),
611    Val = (catch megaco:system_info(Tag)),
612    d("megaco system-info: ~p", [Val]),
613    case Verify(Val) of
614	ok ->
615	    {ok, State#state{result = [Val|Res]}};
616	Error ->
617	    {error, State#state{result = [Error|Res]}}
618    end;
619
620%% This is either a MG or a MGC which is only connected to one MG
621handle_exec({megaco_call, ARs, Opts}, #state{conn_handle = CH} = State)
622  when CH /= undefined ->
623    p("megaco_call: "
624      "~n      CH:   ~p"
625      "~n      ARs:  ~p"
626      "~n      Opts: ~p", [CH, ARs, Opts]),
627    {_PV, UserReply} = megaco:call(CH, ARs, Opts),
628    d("megaco_call -> UserReply: ~n~p", [UserReply]),
629    {ok, State};
630
631handle_exec({megaco_call, RemoteMid, ARs, Opts}, #state{mid = Mid} = State) ->
632    p("megaco_call: ~p", [RemoteMid]),
633    %% First we have to find the CH for this Mid
634    Conns = megaco:user_info(Mid, connections),
635    {value, {_, CH}} =
636        lists:keysearch(RemoteMid, #megaco_conn_handle.remote_mid, Conns),
637    p("megaco_call: "
638      "~n      CH:   ~p"
639      "~n      ARs:  ~p"
640      "~n      Opts: ~p", [CH, ARs, Opts]),
641    {_PV, UserReply} = megaco:call(CH, ARs, Opts),
642    d("megaco_call -> UserReply: ~n~p", [UserReply]),
643    {ok, State};
644
645%% This is either a MG or a MGC which is only connected to one MG
646handle_exec({megaco_cast, ARs, Opts}, #state{conn_handle = CH} = State)
647  when CH =/= undefined ->
648    p("megaco_cast: "
649      "~n      CH:  ~p"
650      "~n      ARs: ~p", [CH, ARs]),
651    case megaco:cast(CH, ARs, Opts) of
652        ok ->
653            {ok, State};
654        Error ->
655            e("failed sending (cast) message: ~n~p", [Error]),
656            #state{result = Acc} = State,
657            {error, State#state{result = [Error|Acc]}}
658    end;
659
660handle_exec({megaco_cast, RemoteMid, ARs, Opts}, #state{mid = Mid} = State) ->
661    p("megaco_cast with ~p", [RemoteMid]),
662    %% First we have to find the CH for this Mid
663    Conns = megaco:user_info(Mid, connections),
664    {value, {_, CH}} =
665        lists:keysearch(RemoteMid, #megaco_conn_handle.remote_mid, Conns),
666    p("megaco_cast: "
667      "~n      CH:   ~p"
668      "~n      ARs:  ~p"
669      "~n      Opts: ~p", [CH, ARs, Opts]),
670    case megaco:cast(CH, ARs, Opts) of
671        ok ->
672            {ok, State};
673        Error ->
674            e("failed sending (cast) message: "
675              "~n      ~p", [Error]),
676            #state{result = Acc} = State,
677            {error, State#state{result = [Error|Acc]}}
678    end;
679
680%% Nothing shall happen for atleast Timeout time
681handle_exec({megaco_callback, nocall, Timeout}, State) ->
682    p("expect no megaco_callback for ~w", [Timeout]),
683    receive
684        {handle_megaco_callback, Type, Msg, Pid} ->
685            e("received unexpected megaco callback: ~n~p", [Msg]),
686            #state{result = Res} = State,
687            Err = {unexpected_callback, Type, Msg, Pid},
688            {error, State#state{result = [Err|Res]}}
689    after Timeout ->
690            p("got no callback (~p) as expected", [Timeout]),
691            {ok, State}
692    end;
693
694handle_exec({megaco_callback, Tag, Verify}, State) when is_function(Verify) ->
695    p("expect megaco_callback ~w", [Tag]),
696    receive
697        {handle_megaco_callback, Type, Msg, Pid} ->
698            d("received megaco callback:"
699              "~n      ~p", [Msg]),
700            case Verify(Msg) of
701                {VRes, Res, Reply} ->
702                    d("megaco_callback [~w] ~w", [Tag, VRes]),
703                    handle_megaco_callback_reply(Pid, Type, Reply),
704                    validate(VRes, Tag, Res, State);
705                {VRes, Delay, Res, Reply} ->
706                    d("megaco_callback [~w] ~w, ~w", [Tag,Delay,VRes]),
707                    handle_megaco_callback_reply(Pid, Type, Delay, Reply),
708                    validate(VRes, Tag, Res, State)
709            end
710    end;
711
712handle_exec({megaco_callback, Tag, {VMod, VFunc, VArgs}}, State)
713  when is_atom(VMod) andalso is_atom(VFunc) andalso is_list(VArgs) ->
714    p("expect megaco_callback ~w", [Tag]),
715    receive
716        {handle_megaco_callback, Type, Msg, Pid} ->
717            d("received megaco callback: ~n~p"
718              "~n   VMod:  ~w"
719              "~n   VFunc: ~w"
720              "~n   VArgs: ~p", [Msg, VMod, VFunc, VArgs]),
721            case apply(VMod, VFunc, [Msg|VArgs]) of
722                {VRes, Res, Reply} ->
723                    d("megaco_callback [~w] ~w",[Tag, VRes]),
724                    handle_megaco_callback_reply(Pid, Type, Reply),
725                    validate(VRes, Tag, Res, State);
726                {VRes, Delay, Res, Reply} ->
727                    d("megaco_callback [~w] ~w, ~w",[Tag,Delay,VRes]),
728                    handle_megaco_callback_reply(Pid, Type, Delay, Reply),
729                    validate(VRes, Tag, Res, State)
730            end
731    end;
732
733handle_exec({megaco_callback, Tag, Verify, Timeout}, State)
734  when (is_function(Verify) andalso
735	(is_integer(Timeout) andalso (Timeout > 0))) ->
736    p("expect megaco_callback ~w (with ~w)", [Tag, Timeout]),
737    receive
738        {handle_megaco_callback, Type, Msg, Pid} ->
739            d("received megaco callback: ~n~p", [Msg]),
740            case Verify(Msg) of
741                {VRes, Res, Reply} ->
742                    d("megaco_callback [~w] ~w",[Tag,VRes]),
743                    handle_megaco_callback_reply(Pid, Type, Reply),
744                    validate(VRes, Tag, Res, State);
745                {VRes, Delay, Res, Reply} ->
746                    d("megaco_callback [~w] ~w, ~w",[Tag,Delay,VRes]),
747                    handle_megaco_callback_reply(Pid, Type, Delay, Reply),
748                    validate(VRes, Tag, Res, State)
749            end
750    after Timeout ->
751            e("megaco_callback ~w timeout", [Tag]),
752            #state{result = Res} = State,
753            Err = {callback_timeout, Tag, Timeout},
754            {error, State#state{result = [Err|Res]}}
755    end;
756
757handle_exec({megaco_callback, Verifiers}, State) ->
758    p("expect megaco_callback(s)"),
759    megaco_callback_verify(Verifiers, State);
760
761handle_exec({megaco_cancel, Reason}, #state{conn_handle = CH} = State) ->
762    p("megaco_cancel: ~w", [Reason]),
763    case megaco:cancel(CH, Reason) of
764        ok ->
765            {ok, State};
766        Error ->
767            e("failed cancel: ~n~p", [Error]),
768            #state{result = Acc} = State,
769            {error, State#state{result = [Error|Acc]}}
770    end;
771
772handle_exec({trigger, Trigger}, State) when is_function(Trigger) ->
773    p("trigger"),
774    (catch Trigger()),
775    {ok, State};
776handle_exec({trigger, Desc, Trigger}, State) when is_function(Trigger) ->
777    p("trigger: ~s", [Desc]),
778    (catch Trigger()),
779    {ok, State};
780
781handle_exec({sleep, To}, State) ->
782    p("sleep ~p", [To]),
783    megaco_test_generator:sleep(To),
784    {ok, State};
785
786handle_exec(BadInstruction, _State) ->
787    error({invalid_instruction, BadInstruction}).
788
789
790%% --- cleanup ---
791
792megaco_cleanup(#state{mid = Mid}) ->
793    Close = fun(CH) -> do_megaco_cleanup(CH) end,
794    Conns =
795	case (catch megaco:user_info(Mid, connections)) of
796	    Connections when is_list(Connections) ->
797		Connections;
798	    _ ->
799		[]
800	end,
801    lists:foreach(Close, Conns).
802
803do_megaco_cleanup(CH) ->
804    case (catch do_megaco_cleanup2(CH)) of
805        ok ->
806            ok;
807        {'EXIT', {no_such_connection, _}} ->
808            ok;
809        {'EXIT', Reason} ->
810            exit(Reason)
811    end.
812
813do_megaco_cleanup2(CH) ->
814    d("do_megaco_cleanup2 -> entry with"
815      "~n   CH: ~p", [CH]),
816    Reason     = {stopped_by_user,self()},
817    Pid        = megaco:conn_info(CH, control_pid),
818    SendMod    = megaco:conn_info(CH, send_mod),
819    SendHandle = megaco:conn_info(CH, send_handle),
820    d("do_megaco_cleanup2 -> disconnect"),
821    megaco:disconnect(CH, Reason),
822    d("do_megaco_cleanup2 -> disconnected, now cancel"),
823    megaco:cancel(CH, Reason),
824    d("do_megaco_cleanup2 -> canceled, now close"),
825    case SendMod of
826        megaco_tcp -> (catch megaco_tcp:close(SendHandle));
827        megaco_udp -> (catch megaco_udp:close(SendHandle));
828        SendMod    -> exit(Pid, Reason)
829    end,
830    ok.
831
832
833%% --- connector ---
834
835megaco_connector_start(RH, PrelMid, SH, ControlPid) ->
836    Self = self(),
837    Fun  = fun() -> megaco_connect(RH, PrelMid, SH, ControlPid, Self) end,
838    erlang:spawn_opt(Fun, [link]).
839
840megaco_connect(RH, PrelMid, SH, ControlPid, Parent) ->
841    Result = megaco:connect(RH, PrelMid, SH, ControlPid),
842    Parent ! {megaco_connect_result, Result},
843    exit(normal).
844
845
846%% --- megaco callback verify ---
847
848%% This is used when a number of callback's is expected, but where
849%% the specific order is unknown.
850megaco_callback_verify([], State) ->
851    d("megaco_callback_verify -> done"),
852    {ok, State};
853megaco_callback_verify(Verifiers0, State0) ->
854    d("megaco_callback_verify -> entry when"
855      "~n   length(Verifiers0): ~w", [length(Verifiers0)]),
856    receive
857        {handle_megaco_callback, Type, Msg, Pid} ->
858            d("megaco_callback_verify -> received megaco callback: ~w"
859	      "~n   Msg: ~p", [Type, Msg]),
860            case megaco_callback_verify(Verifiers0, Type, Msg, Pid, State0) of
861                {ok, Verifiers, State} ->
862                    megaco_callback_verify(Verifiers, State);
863                Error ->
864                    Error
865            end
866    end.
867
868megaco_callback_verify(Verifiers0, Type, Msg, Pid, State0) ->
869    d("megaco_callback_verify -> entry"),
870    Tag = element(1, Msg),
871    d("megaco_callback_verify -> Tag: ~w", [Tag]),
872    case lists:keysearch(Tag, 1, Verifiers0) of
873        {value, {Tag, N, Verify}} when (N > 0) andalso is_function(Verify) ->
874            d("megaco_callback_verify -> N: ~w",[N]),
875            case Verify(Msg) of
876                {VRes, Res, Reply} ->
877                    d("megaco_callback_verify -> VRes: ~w",[VRes]),
878                    handle_megaco_callback_reply(Pid, Type, Reply),
879                    case validate(VRes, Tag, Res, State0) of
880                        {error, _} = EState ->
881                            e("megaco_callback_verify -> (1) error", []),
882                            throw(EState);
883                        {ok, State} when N > 1 ->
884                            d("megaco_callback_verify -> (1) validated"),
885                            Rec = {Tag, N-1, Verify},
886                            Verifiers =
887                                lists:keyreplace(Tag, 1, Verifiers0, Rec),
888                            {ok, Verifiers, State};
889                        {ok, State} ->
890                            d("megaco_callback_verify -> (2) validated"),
891                            Verifiers = lists:keydelete(Tag, 1, Verifiers0),
892                            {ok, Verifiers, State}
893                    end;
894                {VRes, Delay, Res, Reply} ->
895                    d("megaco_callback_verify -> Delay: ~w, VRes: ~w",
896                      [Delay,VRes]),
897                    handle_megaco_callback_reply(Pid, Type, Delay, Reply),
898                    case validate(VRes, Tag, Res, State0) of
899                        {error, _} = EState ->
900                            e("megaco_callback_verify -> (2) error", []),
901                            throw(EState);
902                        {ok, State} when N > 1 ->
903                            d("megaco_callback_verify -> (3) validated"),
904                            Rec = {Tag, N-1, Verify},
905                            Verifiers =
906                                lists:keyreplace(Tag, 1, Verifiers0, Rec),
907                            {ok, Verifiers, State};
908                        {ok, State} ->
909                            d("megaco_callback_verify -> (4) validated"),
910                            Verifiers = lists:keydelete(Tag, 1, Verifiers0),
911                            {ok, Verifiers, State}
912                    end
913            end;
914        false ->
915            e("megaco_callback_verify -> no such tag ~w~n~p",
916              [Tag, Verifiers0]),
917            #state{result = Res} = State0,
918            State = State0#state{result = [{Type, error, Msg}|Res]},
919            error(State)
920    end.
921
922
923%% --- validate verify result ---
924
925validate(ok, handle_connect = Tag, CH, #state{result = Acc} = S) ->
926    {ok, S#state{conn_handle = CH, result = [{Tag, ok, CH}|Acc]}};
927validate(ok, Tag, Res, #state{result = Acc} = S) ->
928    {ok, S#state{result = [{Tag, ok, Res}|Acc]}};
929validate(error, Tag, Res, #state{result = Acc} = S) ->
930    {error, S#state{result = [{Tag, error, Res}|Acc]}}.
931
932
933%% ----- termination -----
934
935terminate(normal, #state{result = Result} = _State) ->
936    d("terminate -> entry when normal with"
937      "~n   Result: ~p", [Result]),
938    %% megaco_cleanup(State),
939    {ok, Result};
940
941terminate(Reason, #state{result = Result} = State) ->
942    d("terminate -> entry with"
943      "~n   Reason: ~p"
944      "~n   Result: ~p", [Reason, Result]),
945    megaco_cleanup(State),
946    {error, {Reason, Result}}.
947
948
949%%----------------------------------------------------------------------
950
951handle_exec_listen_tcp(Sup, Opts, MaybeRetry) ->
952    handle_exec_listen_tcp(Sup, Opts, MaybeRetry, noError).
953
954handle_exec_listen_tcp(Sup, Opts, MaybeRetry, Error0) ->
955    case (catch megaco_tcp:listen(Sup, Opts)) of
956        ok ->
957            ok;
958	Error1 ->
959	    case (catch MaybeRetry(Error1, Error0)) of
960		{true, Error2} ->
961		    handle_exec_listen_tcp(Sup, Opts, MaybeRetry, Error2);
962		{false, Error3} ->
963		    {error, Error3}
964	    end
965    end.
966
967
968handle_exec_connect_tcp(Host, Opts, Sup, MaybeRetry)
969  when is_function(MaybeRetry) ->
970    handle_exec_connect_tcp(Host, Opts, Sup, MaybeRetry, noError).
971
972handle_exec_connect_tcp(Host, Opts, Sup, MaybeRetry, Error0) ->
973    case (catch megaco_tcp:connect(Sup, Opts)) of
974	{ok, SH, ControlPid} ->
975	    d("tcp connected: ~p, ~p", [SH, ControlPid]),
976	    {ok, SH, ControlPid};
977	Error1 ->
978	    case (catch MaybeRetry(Error1, Error0)) of
979		{true, Error2} ->
980		    handle_exec_connect_tcp(Host, Opts, Sup,
981					    MaybeRetry, Error2);
982		{false, Error3} ->
983		    {error, Error3}
984	    end
985    end.
986
987
988
989%%----------------------------------------------------------------------
990%% megaco_user callback functions
991%%----------------------------------------------------------------------
992
993handle_connect(CH, PV, P) ->
994    Req = {handle_connect, CH, PV},
995    handle_megaco_callback_call(P, Req).
996
997handle_connect(CH, PV, Extra, P) ->
998    Req = {handle_connect, CH, PV, Extra},
999    handle_megaco_callback_call(P, Req).
1000
1001handle_disconnect(CH, PV, R, P) ->
1002    Msg   = {handle_disconnect, CH, PV, R},
1003    Reply = ok,
1004    handle_megaco_callback_cast(P, Msg, Reply).
1005
1006handle_syntax_error(RH, PV, ED, P) ->
1007    Req = {handle_syntax_error, RH, PV, ED},
1008    handle_megaco_callback_call(P, Req).
1009
1010handle_syntax_error(RH, PV, ED, Extra, P) ->
1011    Req = {handle_syntax_error, RH, PV, ED, Extra},
1012    handle_megaco_callback_call(P, Req).
1013
1014handle_message_error(CH, PV, ED, P) ->
1015    Msg   = {handle_message_error, CH, PV, ED},
1016    Reply = ok,
1017    handle_megaco_callback_cast(P, Msg, Reply).
1018
1019handle_message_error(CH, PV, ED, Extra, P) ->
1020    Msg   = {handle_message_error, CH, PV, ED, Extra},
1021    Reply = ok,
1022    handle_megaco_callback_cast(P, Msg, Reply).
1023
1024handle_trans_request(CH, PV, AR, P) ->
1025    Req = {handle_trans_request, CH, PV, AR},
1026    handle_megaco_callback_call(P, Req).
1027
1028handle_trans_request(CH, PV, AR, Extra, P) ->
1029    Req = {handle_trans_request, CH, PV, AR, Extra},
1030    handle_megaco_callback_call(P, Req).
1031
1032handle_trans_long_request(CH, PV, RD, P) ->
1033    Req = {handle_trans_long_request, CH, PV, RD},
1034    handle_megaco_callback_call(P, Req).
1035
1036handle_trans_long_request(CH, PV, RD, Extra, P) ->
1037    Req = {handle_trans_long_request, CH, PV, RD, Extra},
1038    handle_megaco_callback_call(P, Req).
1039
1040handle_trans_reply(CH, PV, AR, RD, P) ->
1041    Msg = {handle_trans_reply, CH, PV, AR, RD},
1042    Reply = ok,
1043    handle_megaco_callback_cast(P, Msg, Reply).
1044
1045handle_trans_reply(CH, PV, AR, RD, Extra, P) ->
1046    Msg = {handle_trans_reply, CH, PV, AR, RD, Extra},
1047    Reply = ok,
1048    handle_megaco_callback_cast(P, Msg, Reply).
1049
1050handle_trans_ack(CH, PV, AS, AD, P) ->
1051    Msg = {handle_trans_ack, CH, PV, AS, AD},
1052    Reply = ok,
1053    handle_megaco_callback_cast(P, Msg, Reply).
1054
1055handle_trans_ack(CH, PV, AS, AD, Extra, P) ->
1056    Msg = {handle_trans_ack, CH, PV, AS, AD, Extra},
1057    Reply = ok,
1058    handle_megaco_callback_cast(P, Msg, Reply).
1059
1060handle_unexpected_trans(CH, PV, T, P) ->
1061    Msg = {handle_unexpected_trans, CH, PV, T},
1062    Reply = ok,
1063    handle_megaco_callback_cast(P, Msg, Reply).
1064
1065handle_unexpected_trans(CH, PV, T, Extra, P) ->
1066    Msg = {handle_unexpected_trans, CH, PV, T, Extra},
1067    Reply = ok,
1068    handle_megaco_callback_cast(P, Msg, Reply).
1069
1070handle_trans_request_abort(RH, PV, TransNo, Pid, P) ->
1071    Msg = {handle_trans_request_abort, RH, PV, TransNo, Pid},
1072    Reply = ok,
1073    handle_megaco_callback_cast(P, Msg, Reply).
1074
1075handle_trans_request_abort(RH, PV, TransNo, Pid, Extra, P) ->
1076    Msg = {handle_trans_request_abort, RH, PV, TransNo, Pid, Extra},
1077    Reply = ok,
1078    handle_megaco_callback_cast(P, Msg, Reply).
1079
1080handle_megaco_callback_cast(P, Msg, Reply) ->
1081    d("handle_megaco_callback_cast -> entry with Msg: ~n~p", [Msg]),
1082    P ! {handle_megaco_callback, cast, Msg, self()},
1083    Reply.
1084
1085handle_megaco_callback_call(P, Msg) ->
1086    d("handle_megaco_callback_call -> entry with"
1087      "~n   P:   ~p"
1088      "~n   Msg: ~p", [P, Msg]),
1089    P ! {handle_megaco_callback, call, Msg, self()},
1090    receive
1091        {handle_megaco_callback_reply, Reply} ->
1092            d("handle_megaco_callback_call -> received reply: ~n~p", [Reply]),
1093            Reply;
1094        {handle_megaco_callback_reply, Delay, Reply} when is_integer(Delay) ->
1095            d("handle_megaco_callback_call -> "
1096              "received reply [~w]: "
1097              "~n   ~p", [Delay, Reply]),
1098            sleep(Delay),
1099            d("handle_megaco_callback_call -> deliver reply after delay [~w]",
1100              [Delay]),
1101            Reply;
1102        {'EXIT', Pid, Reason} when (Pid =:= P) ->
1103            d("handle_megaco_callback_call -> "
1104              "received unexpected EXIT signal (from ~p): "
1105              "~n   Reason: ~p", [Pid, Reason]),
1106            exit({unexpected_EXIT_signal, Pid, Reason});
1107        {'EXIT', SomePid, SomeReason} ->
1108            d("handle_megaco_callback_call -> "
1109              "received unexpected EXIT signal from unknown process: "
1110              "~n   Pid:    ~p"
1111              "~n   Reason: ~p", [SomePid, SomeReason]),
1112            exit({unexpected_EXIT_signal, SomePid, SomeReason})
1113    end.
1114
1115
1116handle_megaco_callback_reply(P, call, Reply) ->
1117    P ! {handle_megaco_callback_reply, Reply};
1118handle_megaco_callback_reply(_, _, _) ->
1119    ok.
1120
1121handle_megaco_callback_reply(P, call, Delay, Reply) ->
1122    P ! {handle_megaco_callback_reply, Delay, Reply};
1123handle_megaco_callback_reply(_, _, _, _) ->
1124    ok.
1125
1126
1127%%----------------------------------------------------------------------
1128%% internal utility functions
1129%%----------------------------------------------------------------------
1130
1131random_init() ->
1132    ok.
1133
1134random(N) ->
1135    rand:uniform(N).
1136
1137
1138get_config(Key, Opts) ->
1139    {value, {Key, Val}} = lists:keysearch(Key, 1, Opts),
1140    Val.
1141
1142sleep(X) -> megaco_test_generator:sleep(X).
1143
1144d(F)    -> megaco_test_generator:debug(F).
1145d(F, A) -> megaco_test_generator:debug(F, A).
1146
1147e(F, A) -> megaco_test_generator:error(F, A).
1148
1149p(F      ) -> p("", F, []).
1150p(F,    A) -> p("", F, A).
1151p(P, F, A) -> megaco_test_generator:print(P,    F, A).
1152
1153error(Reason) ->
1154    throw({error, Reason}).
1155
1156