~ubuntu-branches/debian/squeeze/erlang/squeeze

« back to all changes in this revision

Viewing changes to lib/snmp/src/snmp_trap.erl

  • Committer: Bazaar Package Importer
  • Author(s): Erlang Packagers, Sergei Golovan
  • Date: 2006-12-03 17:07:44 UTC
  • mfrom: (2.1.11 feisty)
  • Revision ID: james.westby@ubuntu.com-20061203170744-rghjwupacqlzs6kv
Tags: 1:11.b.2-4
[ Sergei Golovan ]
Fixed erlang-base and erlang-base-hipe prerm scripts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
%% ``The contents of this file are subject to the Erlang Public License,
2
 
%% Version 1.1, (the "License"); you may not use this file except in
3
 
%% compliance with the License. You should have received a copy of the
4
 
%% Erlang Public License along with this software. If not, it can be
5
 
%% retrieved via the world wide web at http://www.erlang.org/.
6
 
%% 
7
 
%% Software distributed under the License is distributed on an "AS IS"
8
 
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
9
 
%% the License for the specific language governing rights and limitations
10
 
%% under the License.
11
 
%% 
12
 
%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
13
 
%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
14
 
%% AB. All Rights Reserved.''
15
 
%% 
16
 
%%     $Id$
17
 
%%
18
 
-module(snmp_trap).
19
 
 
20
 
%%%-----------------------------------------------------------------
21
 
%%% This module takes care of all trap handling.
22
 
%%%-----------------------------------------------------------------
23
 
%% External exports
24
 
-export([construct_trap/2, try_initialise_vars/2, send_trap/6]).
25
 
 
26
 
%% Internal exports
27
 
-export([alias_to_oid/1, make_varbind/1, init_v2_inform/9, init_v3_inform/9]).
28
 
 
29
 
-include("snmp_types.hrl").
30
 
-include("SNMPv2-MIB.hrl").
31
 
-include("SNMP-FRAMEWORK-MIB.hrl").
32
 
-define(enterpriseSpecific, 6).
33
 
 
34
 
 
35
 
-define(VMODULE,"TRAP").
36
 
-include("snmp_verbosity.hrl").
37
 
 
38
 
 
39
 
%%-----------------------------------------------------------------
40
 
%% Trap mechanism
41
 
%% ==============
42
 
%% Distributed subagent (dSA) case
43
 
%%   The MIB with the TRAP-TYPE macro is loaded in dSA.  This means
44
 
%%   that dSA has info on all variables defined in the TRAP-TYPE,
45
 
%%   even though some variables may be located in other SA:s (or
46
 
%%   in the MA). Other variables that may be sent in the trap, 
47
 
%%   must be known by either the dSA, or some of its parent agents
48
 
%%   (e.g. the master agent), if the variable should be referred
49
 
%%   to by symbolic name. It is however possible to send other
50
 
%%   variables as well, but then the entire OID must be provided.
51
 
%%   The dSA locates the asn1 type, oid and value for as many
52
 
%%   variables as possible. This information, together with the
53
 
%%   variables for which the type, value or oid isn't known, is
54
 
%%   sent to the dSA's parent. This agent performs the same
55
 
%%   operation, and so on, until eventually the MA will receive the
56
 
%%   info. The MA then fills in the gaps, and at this point all
57
 
%%   oids and types must be known, otherwise an error is signalled,
58
 
%%   and the opertaion is aborted. For the unknown values for some 
59
 
%%   oids, a get-operation is performed by the MA. This will
60
 
%%   retreive the missing values.
61
 
%%   At this point, all oid, types and values are known, so the MA
62
 
%%   can distribute the traps according to the information in the
63
 
%%   internal tables.
64
 
%% 
65
 
%% Local subagent (lSA) case
66
 
%%   This case is similar to the case above.
67
 
%%
68
 
%% Master agent (MA) case
69
 
%%   This case is similar to the case above.
70
 
%%
71
 
%% NOTE: All trap forwarding between agents is made asynchronously.
72
 
%%
73
 
%% dSA: Distributed SA  (the #trap is loaded here)
74
 
%% nSA: [many] SAs between dSA and MA
75
 
%% MA:  Master Agent. (all trap info (destiniations is here))
76
 
%% 1) application decides to send a trap.
77
 
%% 2) dSA calls send_trap which initialises vars
78
 
%% 3) dSA sends all to nSA
79
 
%% 4) nSA tries to map symbolic names to oids and find the types
80
 
%%    of all variableoids with a value (and no type).
81
 
%% 5) nSA sends all to (n-1)SA
82
 
%% 6) MA tries to initialise vars
83
 
%% 7) MA makes a trappdu, and sends it to all destination.
84
 
%%
85
 
%% Problems with this implementation
86
 
%% =================================
87
 
%% It's ok to send {Oid, Value} but not just Oid. (it should be for
88
 
%%   any Oid)
89
 
%% It's ok to send {Name, Value} but not just Name. (it should be
90
 
%%   for Names in the hierarchy)
91
 
%% This approach might be too flexible; will people use it?
92
 
%% *NOTE*
93
 
%% Therefore, in this version we *do not* allow extra variables
94
 
%% in traps.
95
 
%% *YES* In _this_ version we do.
96
 
%%-----------------------------------------------------------------
97
 
 
98
 
%%-----------------------------------------------------------------
99
 
%% Func: construct_trap/2
100
 
%% Args: Trap is an atom
101
 
%%       Varbinds is a list of {Variable, Value},
102
 
%%         where Variable is an atom or an OID. |
103
 
%%         {SymbolicTableCol, RowIndex, Value},
104
 
%%         where RowIndex is the indexes for the row.
105
 
%%         We don't check the RowIndex.
106
 
%% Purpose: This is the initially-called function. It is called
107
 
%%          by the agent that found out that a trap should be
108
 
%%          sent.
109
 
%%          Initialize as many variables as possible.
110
 
%% Returns: {ok, TrapRecord, <list of Var>} | error
111
 
%%          where Var is returned from initiate_vars.
112
 
%% NOTE: Executed at the inital SA
113
 
%%-----------------------------------------------------------------
114
 
construct_trap(Trap, Varbinds) ->
115
 
    case snmp_symbolic_store:get_notification(Trap) of
116
 
        undefined -> 
117
 
            user_err("send_trap got undef Trap: ~w" , [Trap]),
118
 
            error;
119
 
        {value, TRec} when record(TRec, trap) ->
120
 
            ListOfVars = TRec#trap.oidobjects,
121
 
            OidVbs = snmp_misc:map({snmp_trap, alias_to_oid}, [], Varbinds),
122
 
            LV = initiate_vars(ListOfVars, OidVbs),
123
 
            {ok, TRec, try_initialise_vars(get(mibserver), LV)};
124
 
        {value, NRec} when record(NRec, notification) ->
125
 
            ListOfVars = NRec#notification.oidobjects,
126
 
            OidVbs = snmp_misc:map({snmp_trap, alias_to_oid}, [], Varbinds),
127
 
            LV = initiate_vars(ListOfVars, OidVbs),
128
 
            {ok, NRec, try_initialise_vars(get(mibserver), LV)}
129
 
    end.
130
 
 
131
 
alias_to_oid({Alias, Val}) when atom(Alias) ->
132
 
    case snmp_symbolic_store:aliasname_to_oid(Alias) of
133
 
        {value, Oid} -> {lists:append(Oid, [0]), {value, Val}};
134
 
        _ ->         {Alias, {value, Val}}
135
 
    end;
136
 
alias_to_oid({Alias, RowIndex, Val}) when atom(Alias) ->
137
 
    case snmp_symbolic_store:aliasname_to_oid(Alias) of
138
 
        {value, Oid} -> {lists:append(Oid, RowIndex), {value, Val}};
139
 
        _ ->         {Alias, RowIndex, {value, Val}}
140
 
    end;
141
 
alias_to_oid({Oid, Val}) -> {Oid, {value, Val}}.
142
 
 
143
 
%%-----------------------------------------------------------------
144
 
%% Func: initiate_vars/2
145
 
%% Args: ListOfVars is a list of {Oid, #asn1_type}
146
 
%%       Varbinds is a list of 
147
 
%%          {VariableOid, Value} | 
148
 
%%          {VariableAtom, Value} |
149
 
%%          {TableColAtom, RowIndex, Value}
150
 
%% Purpose: For each variable in specified in the TRAP-TYPE macro
151
 
%%          (each in ListOfVars), check if it's got a value given
152
 
%%          in the Varbinds list.
153
 
%%          For each Oid:
154
 
%%            1) It has corresponding VariableOid. Use Value.
155
 
%%            2) No corresponding VariableOid. No value.
156
 
%% Returns: A list of
157
 
%%            {VariableOid, #asn1_type, Value} |
158
 
%%            {VariableOid, #asn1_type} |
159
 
%%            {VariableOid, Value} |
160
 
%%            {VariableAtom, Value} |
161
 
%%            {TableColAtom, RowIndex, Value}
162
 
%% NOTE: Executed at the inital SA
163
 
%%-----------------------------------------------------------------
164
 
initiate_vars([{Oid, Asn1Type} | T], Varbinds) ->
165
 
    case delete_oid_from_varbinds(Oid, Varbinds) of
166
 
        {undefined, _, _} ->
167
 
            [{Oid, Asn1Type} | initiate_vars(T, Varbinds)];
168
 
        {Value, VarOid, RestOfVarbinds} ->
169
 
            [{VarOid, Asn1Type, Value} | initiate_vars(T, RestOfVarbinds)]
170
 
    end;
171
 
initiate_vars([], Varbinds) ->
172
 
    Varbinds.
173
 
    
174
 
delete_oid_from_varbinds(Oid, [{VarOid, Value} | T]) ->
175
 
    case lists:prefix(Oid, VarOid) of
176
 
        true -> 
177
 
            {Value, VarOid, T};
178
 
        _ -> 
179
 
            {Value2, VarOid2, T2} = delete_oid_from_varbinds(Oid, T),
180
 
            {Value2, VarOid2, [{VarOid, Value} | T2]}
181
 
    end;
182
 
delete_oid_from_varbinds(Oid, [H | T]) ->
183
 
    {Value, VarOid, T2} = delete_oid_from_varbinds(Oid, T),
184
 
    {Value, VarOid, [H | T2]};
185
 
delete_oid_from_varbinds(_Oid, []) -> {undefined, undefined, []}.
186
 
 
187
 
%%-----------------------------------------------------------------
188
 
%% Func: try_initialise_vars(Mib, Varbinds)
189
 
%% Args: Mib is the local mib process
190
 
%%       Varbinds is a list returned from initiate_vars.
191
 
%% Purpose: Try to initialise uninitialised vars.
192
 
%% Returns: see initiate_vars
193
 
%% NOTE: Executed at the intermediate SAs
194
 
%%-----------------------------------------------------------------
195
 
try_initialise_vars(Mib, Varbinds) ->
196
 
    V = try_map_symbolic(Varbinds),
197
 
    try_find_type(V, Mib).
198
 
 
199
 
%%-----------------------------------------------------------------
200
 
%% Func: try_map_symbolic/1
201
 
%% Args: Varbinds is a list returned from initiate_vars.
202
 
%% Purpose: Try to map symbolic name to oid for the 
203
 
%%          symbolic names left in the Varbinds list.
204
 
%% Returns: see initiate_vars.
205
 
%% NOTE: Executed at the intermediate SAs
206
 
%%-----------------------------------------------------------------
207
 
try_map_symbolic([Varbind | Varbinds]) ->
208
 
    [localise_oid(Varbind) | try_map_symbolic(Varbinds)];
209
 
try_map_symbolic([]) -> [].
210
 
 
211
 
localise_oid({VariableName, Value}) when atom(VariableName) ->
212
 
    alias_to_oid({VariableName, Value});
213
 
localise_oid({VariableName, RowIndex, Value}) when atom(VariableName) ->
214
 
    alias_to_oid({VariableName, RowIndex, Value});
215
 
localise_oid(X) -> X.
216
 
 
217
 
%%-----------------------------------------------------------------
218
 
%% Func: try_find_type/2
219
 
%% Args: Varbinds is a list returned from initiate_vars.
220
 
%%       Mib is a ref to the Mib process corresponding to
221
 
%%         this agent.
222
 
%% Purpose: Try to find the type for each variableoid with a value
223
 
%%          but no type.
224
 
%% Returns: see initiate_vars.
225
 
%% NOTE: Executed at the intermediate SAs
226
 
%%-----------------------------------------------------------------
227
 
try_find_type([Varbind | Varbinds], Mib) ->
228
 
    [localise_type(Varbind, Mib) | try_find_type(Varbinds, Mib)];
229
 
try_find_type([], _) -> [].
230
 
 
231
 
localise_type({VariableOid, Type}, _Mib) 
232
 
  when list(VariableOid), record(Type, asn1_type) ->
233
 
    {VariableOid, Type};
234
 
localise_type({VariableOid, Value}, Mib) when list(VariableOid) ->
235
 
    case snmp_mib:lookup(Mib, VariableOid) of
236
 
        {variable, ME} ->
237
 
            {VariableOid, ME#me.asn1_type, Value};
238
 
        {table_column, ME, _} ->
239
 
            {VariableOid, ME#me.asn1_type, Value};
240
 
        _ ->
241
 
            {VariableOid, Value}
242
 
    end;
243
 
localise_type(X, _) -> X.
244
 
 
245
 
%%-----------------------------------------------------------------
246
 
%% Func: make_v1_trap_pdu/4
247
 
%% Args: Enterprise = oid()
248
 
%%       Specific = integer()
249
 
%%       Varbinds is as returned from initiate_vars
250
 
%%         (but only {Oid, Type[, Value} permitted)
251
 
%%       SysUpTime = integer()
252
 
%% Purpose: Make a #trappdu
253
 
%%          Checks the Varbinds to see that no symbolic names are
254
 
%%          present, and that each var has a type. Performs a get
255
 
%%          to find any missing value.
256
 
%% Returns: {#trappdu, [byte()] | error
257
 
%% Fails: yes
258
 
%% NOTE: Executed at the MA
259
 
%%-----------------------------------------------------------------
260
 
make_v1_trap_pdu(Enterprise, Specific, VarbindList, SysUpTime) ->
261
 
    {Enterp,Generic,Spec} = 
262
 
        case Enterprise of
263
 
            ?snmp ->
264
 
                {sys_object_id(),Specific,0};
265
 
            _ ->
266
 
                {Enterprise,?enterpriseSpecific,Specific}
267
 
    end,
268
 
    {value, AgentIp} = snmp_framework_mib:intAgentIpAddress(get),
269
 
    #trappdu{enterprise = Enterp,
270
 
             agent_addr = AgentIp,
271
 
             generic_trap = Generic,
272
 
             specific_trap = Spec,
273
 
             time_stamp = SysUpTime,
274
 
             varbinds = VarbindList}.
275
 
 
276
 
make_v2_notif_pdu(Vbs, Type) ->
277
 
    #pdu{type = Type,
278
 
         request_id = snmp_mpd:generate_req_id(),
279
 
         error_status = noError,
280
 
         error_index = 0,
281
 
         varbinds = Vbs}.
282
 
 
283
 
make_varbind_list(Varbinds) ->
284
 
    {VariablesWithValueAndType, VariablesWithType} =
285
 
        split_variables(order(Varbinds)),
286
 
    V = get_all(VariablesWithType),
287
 
    Vars = lists:append([V, VariablesWithValueAndType]),
288
 
    snmp_misc:map({snmp_trap, make_varbind}, [], unorder(lists:keysort(1, Vars))).
289
 
 
290
 
%%-----------------------------------------------------------------
291
 
%% Func: send_trap/6
292
 
%% Args: TrapRec = #trap | #notification
293
 
%%       NotifyName = string()
294
 
%%       ContextName = string()
295
 
%%       Recv = no_receiver | {Ref, Receiver}
296
 
%%       Receiver = pid() | atom() | {M,F,A}
297
 
%%       Vbs = [varbind()]
298
 
%%       NetIf = pid()
299
 
%% Purpose: Default trap sending function.
300
 
%%          Sends the trap to the targets pointed out by NotifyName.
301
 
%%          If NotifyName is ""; the normal procedure defined in 
302
 
%%          SNMP-NOTIFICATION-MIB is used, i.e. the trap is sent to
303
 
%%          all managers.
304
 
%%          Otherwise, the NotifyName is used to find an entry in the
305
 
%%          SnmpNotifyTable which define how to send the notification
306
 
%%          (as an Inform or a Trap), and to select targets from
307
 
%%          SnmpTargetAddrTable (using the Tag).
308
 
%%-----------------------------------------------------------------
309
 
send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs, NetIf) ->
310
 
    VarbindList = make_varbind_list(Vbs),
311
 
    Dests = find_dests(NotifyName),
312
 
    send_trap_pdus(Dests, ContextName, {TrapRec, VarbindList}, [], [], [],
313
 
                   Recv, NetIf).
314
 
            
315
 
get_all(VariablesWithType) ->
316
 
    {Order, Varbinds} = extract_order(VariablesWithType, 1),
317
 
    case snmp_agent:do_get(snmp_acm:get_root_mib_view(), Varbinds, true) of
318
 
        {noError, _, NewVarbinds} ->
319
 
            contract_order(Order, NewVarbinds);
320
 
        {ErrorStatus, ErrorIndex, _} ->
321
 
            user_err("snmp_trap: get operation failed {~w, ~w}"
322
 
                     "~n    in ~w",
323
 
                     [ErrorStatus, ErrorIndex, Varbinds]),
324
 
            throw(error)
325
 
    end.
326
 
    
327
 
make_varbind(Varbind) when record(Varbind, varbind) ->
328
 
    Varbind;
329
 
make_varbind({VarOid, ASN1Type, Value}) ->
330
 
    case snmp_agent:make_value_a_correct_value(Value, ASN1Type, undef) of
331
 
        {value, Type, Val} ->
332
 
            #varbind{oid = VarOid, variabletype = Type, value = Val};
333
 
        {error, Reason} -> 
334
 
            user_err("snmp_trap: Invalid value: Oid ~w, Val:~w:"
335
 
                     "~n   ~w",
336
 
                     [VarOid, Value, Reason]),
337
 
            throw(error)
338
 
    end.
339
 
 
340
 
order(Varbinds) -> order(Varbinds, 1).
341
 
order([H | T], No) -> [{No, H} | order(T, No + 1)];
342
 
order([], _) -> [].
343
 
 
344
 
unorder([{_No, H} | T]) -> [H | unorder(T)];
345
 
unorder([]) -> [].
346
 
 
347
 
extract_order([{No, {VarOid, _Type}} | T], Index) ->
348
 
    {Order, V} = extract_order(T, Index+1),
349
 
    {[No | Order], [#varbind{oid = VarOid, org_index = Index} | V]};
350
 
extract_order([], _) -> {[], []}.
351
 
 
352
 
contract_order([No | Order], [Varbind | T]) ->
353
 
    [{No, Varbind} | contract_order(Order, T)];
354
 
contract_order([], []) -> [].
355
 
 
356
 
split_variables([{No, {VarOid, Type, Val}} | T]) when list(VarOid) ->
357
 
    {A, B} = split_variables(T),
358
 
    {[{No, {VarOid, Type, Val}} | A], B};
359
 
split_variables([{No, {VarOid, Type}} | T]) 
360
 
  when list(VarOid), record(Type, asn1_type) ->
361
 
    {A, B} = split_variables(T),
362
 
    {A, [{No, {VarOid, Type}} | B]};
363
 
split_variables([{_No, {VarName, Value}} | _T]) ->
364
 
    user_err("snmp_trap: Undefined variable ~w (~w)", [VarName, Value]),
365
 
    throw(error);
366
 
split_variables([{_No, {VarName, RowIndex, Value}} | _T]) ->
367
 
    user_err("snmp_trap: Undefined variable ~w ~w (~w)",
368
 
             [VarName, RowIndex, Value]),
369
 
    throw(error);
370
 
split_variables([]) -> {[], []}.
371
 
 
372
 
%%-----------------------------------------------------------------
373
 
%% Func: find_dests(NotifyName) -> 
374
 
%%          [{DestAddr, TargetName, TargetParams, NotifyType}]
375
 
%% Types: NotifyType = string()
376
 
%%        DestAddr = {TDomain, TAddr}
377
 
%%        TargetName = string()
378
 
%%        TargetParams = {MpModel, SecModel, SecName, SecLevel}
379
 
%%        NotifyType = trap | {inform, Timeout, Retry}
380
 
%% Returns: A list of all Destination addresses for this community.
381
 
%% NOTE: This function is executed in the master agent's context
382
 
%%-----------------------------------------------------------------
383
 
find_dests("") ->
384
 
    snmp_notification_mib:get_targets();
385
 
find_dests(NotifyName) ->
386
 
    case snmp_notification_mib:get_targets(NotifyName) of
387
 
        [] ->
388
 
            ?vlog("No dests found for snmpNotifyName: ~p",[NotifyName]),
389
 
            [];
390
 
        Dests ->
391
 
            Dests
392
 
    end.
393
 
 
394
 
%%-----------------------------------------------------------------
395
 
%% NOTE: This function is executed in the master agent's context
396
 
%% For each target, check if it has access to the objects in the
397
 
%% notification, determine which message version (v1, v2c or v3)
398
 
%% should be used for the target, and determine the message
399
 
%% specific parameters to be used.
400
 
%%-----------------------------------------------------------------
401
 
send_trap_pdus([{DestAddr, TargetName, {MpModel, SecModel, SecName, SecLevel},
402
 
                 Type} | T],
403
 
               ContextName,{TrapRec, Vbs}, V1Res, V2Res, V3Res, Recv, NetIf) ->
404
 
    ?vdebug("send trap pdus: "
405
 
            "~n   Destination address: ~p"
406
 
            "~n   Target name:         ~p"
407
 
            "~n   MP model:            ~p"
408
 
            "~n   Type:                ~p"
409
 
            "~n   V1Res:               ~p"
410
 
            "~n   V2Res:               ~p"
411
 
            "~n   V3Res:               ~p",
412
 
            [DestAddr,TargetName,MpModel,Type,V1Res,V2Res,V3Res]),
413
 
    case snmp_vacm:get_mib_view(notify, SecModel, SecName, SecLevel,
414
 
                                ContextName) of
415
 
        {ok, MibView} ->
416
 
            ?vtrace("mib view: ~w",[MibView]),
417
 
            case check_all_varbinds(TrapRec, Vbs, MibView) of
418
 
                true when MpModel == ?MP_V1 ->
419
 
                    ?vtrace("v1 mp model",[]),
420
 
                    ContextEngineId = snmp_framework_mib:get_engine_id(),
421
 
                    case snmp_community_mib:vacm2community({SecName,
422
 
                                                            ContextEngineId,
423
 
                                                            ContextName},
424
 
                                                           DestAddr) of
425
 
                        {ok, Community} ->
426
 
                            ?vdebug("community found  for v1 dest: ~p",
427
 
                                    [element(2, DestAddr)]),
428
 
                            send_trap_pdus(T, ContextName, {TrapRec, Vbs},
429
 
                                           [{DestAddr, Community} | V1Res],
430
 
                                           V2Res, V3Res, Recv, NetIf);
431
 
                        undefined ->
432
 
                            ?vdebug("No community found for v1 dest: ~p", 
433
 
                                    [element(2, DestAddr)]),
434
 
                            send_trap_pdus(T, ContextName, {TrapRec, Vbs},
435
 
                                           V1Res, V2Res, V3Res, Recv, NetIf)
436
 
                    end;
437
 
                true when MpModel == ?MP_V2C ->
438
 
                    ?vtrace("v2c mp model",[]),
439
 
                    ContextEngineId = snmp_framework_mib:get_engine_id(),
440
 
                    case snmp_community_mib:vacm2community({SecName,
441
 
                                                            ContextEngineId,
442
 
                                                            ContextName},
443
 
                                                           DestAddr) of
444
 
                        {ok, Community} ->
445
 
                            ?vdebug("community found for v2c dest: ~p", 
446
 
                                    [element(2, DestAddr)]),
447
 
                            send_trap_pdus(T, ContextName, {TrapRec, Vbs},
448
 
                                           V1Res,
449
 
                                           [{DestAddr, Community, Type}|V2Res],
450
 
                                           V3Res, Recv, NetIf);
451
 
                        undefined ->
452
 
                            ?vdebug("No community found for v2c dest: ~p", 
453
 
                                    [element(2, DestAddr)]),
454
 
                            send_trap_pdus(T, ContextName, {TrapRec, Vbs},
455
 
                                           V1Res, V2Res, V3Res, Recv, NetIf)
456
 
                    end;
457
 
                true when MpModel == ?MP_V3 ->
458
 
                    ?vtrace("v3 mp model",[]),
459
 
                    SecLevelF = mk_flag(SecLevel),
460
 
                    MsgData = {SecModel, SecName, SecLevelF, TargetName},
461
 
                    send_trap_pdus(T, ContextName, {TrapRec, Vbs},
462
 
                                   V1Res, V2Res,
463
 
                                   [{DestAddr, MsgData, Type} | V3Res],
464
 
                                   Recv, NetIf);
465
 
                true ->
466
 
                    ?vlog("bad MpModel ~p for dest ~p",
467
 
                          [MpModel, element(2, DestAddr)]),
468
 
                    send_trap_pdus(T, ContextName, {TrapRec, Vbs},
469
 
                                   V1Res, V2Res, V3Res, Recv, NetIf);
470
 
                _ ->
471
 
                    ?vlog("no access for dest: "
472
 
                          "~n   ~p in target ~p",
473
 
                          [element(2, DestAddr), TargetName]),
474
 
                    send_trap_pdus(T, ContextName, {TrapRec, Vbs},
475
 
                                   V1Res, V2Res, V3Res, Recv, NetIf)
476
 
            end;
477
 
        {discarded, Reason} ->
478
 
            ?vlog("mib view error ~p for"
479
 
                  "~n   dest:    ~p"
480
 
                  "~n   SecName: ~w", 
481
 
                  [Reason, element(2, DestAddr), SecName]),
482
 
            send_trap_pdus(T, ContextName, {TrapRec, Vbs},
483
 
                           V1Res, V2Res, V3Res, Recv, NetIf)
484
 
    end;
485
 
send_trap_pdus([], ContextName, {TrapRec, Vbs}, V1Res, V2Res, V3Res,
486
 
               Recv, NetIf) ->
487
 
    SysUpTime = snmp_standard_mib:sys_up_time(),
488
 
    ?vdebug("send trap pdus with sysUpTime ~p",[SysUpTime]),
489
 
    send_v1_trap(TrapRec, V1Res, Vbs, NetIf, SysUpTime),
490
 
    send_v2_trap(TrapRec, V2Res, Vbs, Recv, NetIf, SysUpTime),
491
 
    send_v3_trap(TrapRec, V3Res, Vbs, Recv, NetIf, SysUpTime, ContextName).
492
 
 
493
 
send_v1_trap(_TrapRec, [], _Vbs, _NetIf, _SysUpTime) ->
494
 
    ok;
495
 
send_v1_trap(#trap{enterpriseoid = Enter, specificcode = Spec},
496
 
             V1Res, Vbs, NetIf, SysUpTime) ->
497
 
    ?vdebug("prepare to send v1 trap "
498
 
            "~n   '~p'"
499
 
            "~n   with"
500
 
            "~n   ~p"
501
 
            "~n   to"
502
 
            "~n   ~p",[Enter,Spec,V1Res]),
503
 
    TrapPdu = make_v1_trap_pdu(Enter, Spec, Vbs, SysUpTime),
504
 
    AddrCommunities = mk_addr_communities(V1Res),
505
 
    lists:foreach(fun({Community, Addrs}) ->
506
 
                          ?vtrace("send v1 trap pdu to ~p",[Addrs]),
507
 
                          NetIf ! {send_pdu, 'version-1', TrapPdu,
508
 
                                   {community, Community}, Addrs}
509
 
                  end, AddrCommunities);
510
 
send_v1_trap(#notification{oid = Oid}, V1Res, Vbs, NetIf, SysUpTime) ->
511
 
    %% Use alg. in rfc2089 to map a v2 trap to a v1 trap
512
 
    % delete Counter64 objects from vbs
513
 
    ?vdebug("prepare to send v1 trap '~p'",[Oid]),
514
 
    NVbs = lists:filter(fun(Vb) when Vb#varbind.variabletype =/= 'Counter64' ->
515
 
                                true;
516
 
                           (_) -> false
517
 
                        end, Vbs),
518
 
    {Enter,Spec} = 
519
 
        case Oid of
520
 
            [1,3,6,1,6,3,1,1,5,Specific] ->
521
 
                {?snmp,Specific - 1};
522
 
            _ ->
523
 
                case lists:reverse(Oid) of
524
 
                    [Last, 0 | First] ->
525
 
                        {lists:reverse(First),Last};
526
 
                    [Last | First] ->
527
 
                        {lists:reverse(First),Last}
528
 
                end
529
 
        end,
530
 
    TrapPdu = make_v1_trap_pdu(Enter, Spec, NVbs, SysUpTime),
531
 
    AddrCommunities = mk_addr_communities(V1Res),
532
 
    lists:foreach(fun({Community, Addrs}) ->
533
 
                          ?vtrace("send v1 trap to ~p",[Addrs]),
534
 
                          NetIf ! {send_pdu, 'version-1', TrapPdu,
535
 
                                   {community, Community}, Addrs}
536
 
                  end, AddrCommunities).
537
 
    
538
 
send_v2_trap(_TrapRec, [], _Vbs, _Recv, _NetIf, _SysUpTime) ->
539
 
    ok;
540
 
send_v2_trap(TrapRec, V2Res, Vbs, Recv, NetIf, SysUpTime) ->
541
 
    ?vdebug("prepare to send v2 trap",[]),
542
 
    {_Oid, IVbs} = mk_v2_trap(TrapRec, Vbs, SysUpTime),
543
 
    TrapRecvs = get_trap_recvs(V2Res),
544
 
    InformRecvs = get_inform_recvs(V2Res),
545
 
    do_send_v2_trap(TrapRecvs, IVbs, NetIf),
546
 
    do_send_v2_inform(InformRecvs, IVbs, Recv, NetIf).
547
 
    
548
 
send_v3_trap(_TrapRec, [], _Vbs, _Recv, _NetIf, _SysUpTime, _ContextName) ->
549
 
    ok;
550
 
send_v3_trap(TrapRec, V3Res, Vbs, Recv, NetIf, SysUpTime, ContextName) ->
551
 
    ?vdebug("prepare to send v3 trap",[]),
552
 
    {_Oid, IVbs} = mk_v2_trap(TrapRec, Vbs, SysUpTime), % v2 refers to SMIv2;
553
 
    TrapRecvs = get_trap_recvs(V3Res),                 % same SMI for v3
554
 
    InformRecvs = get_inform_recvs(V3Res),
555
 
    do_send_v3_trap(TrapRecvs, ContextName, IVbs, NetIf),
556
 
    do_send_v3_inform(InformRecvs, ContextName, IVbs, Recv, NetIf).
557
 
    
558
 
 
559
 
mk_v2_trap(#notification{oid = Oid}, Vbs, SysUpTime) ->
560
 
    ?vtrace("make v2 notification '~p'",[Oid]),
561
 
    mk_v2_notif(Oid, Vbs, SysUpTime);
562
 
mk_v2_trap(#trap{enterpriseoid = Enter, specificcode = Spec}, Vbs, SysUpTime) ->
563
 
    %% Use alg. in rfc1908 to map a v1 trap to a v2 trap
564
 
    ?vtrace("make v2 trap for '~p' with ~p",[Enter,Spec]),
565
 
    {Oid,Enterp} = 
566
 
        case Enter of
567
 
            ?snmp ->
568
 
                {?snmpTraps ++ [Spec + 1],sys_object_id()};
569
 
            _ ->
570
 
                {Enter ++ [0, Spec],Enter}
571
 
        end,
572
 
    ExtraVb = #varbind{oid = ?snmpTrapEnterprise_instance,
573
 
                       variabletype = 'OBJECT IDENTIFIER',
574
 
                       value = Enterp},
575
 
    mk_v2_notif(Oid, Vbs ++ [ExtraVb], SysUpTime).
576
 
    
577
 
mk_v2_notif(Oid, Vbs, SysUpTime) ->
578
 
    IVbs = [#varbind{oid = ?sysUpTime_instance,
579
 
                     variabletype = 'TimeTicks',
580
 
                     value = SysUpTime},
581
 
            #varbind{oid = ?snmpTrapOID_instance,
582
 
                     variabletype = 'OBJECT IDENTIFIER',
583
 
                     value = Oid} | Vbs],
584
 
    {Oid, IVbs}.
585
 
 
586
 
%% Addr = {Domain, DomainAddr} ; e.g. {snmpUDPDomain, {IPasList, Udp}}
587
 
%% MsgData = CommunityString (v1, v2c) |
588
 
%%           {SecModel, SecName, SecLevel, TargetAddrName} (v3)
589
 
get_trap_recvs([{Addr, MsgData, trap} | T]) ->
590
 
    [{Addr, MsgData} | get_trap_recvs(T)];
591
 
get_trap_recvs([_ | T]) ->
592
 
    get_trap_recvs(T);
593
 
get_trap_recvs([]) ->
594
 
    [].
595
 
 
596
 
get_inform_recvs([{Addr, MsgData, {inform, Timeout, Retry}} | T]) ->
597
 
    [{Addr, MsgData, Timeout, Retry} | get_inform_recvs(T)];
598
 
get_inform_recvs([_ | T]) ->
599
 
    get_inform_recvs(T);
600
 
get_inform_recvs([]) ->
601
 
    [].
602
 
 
603
 
do_send_v2_trap([], _Vbs, _NetIf) ->
604
 
    ok;
605
 
do_send_v2_trap(Recvs, Vbs, NetIf) ->
606
 
    TrapPdu = make_v2_notif_pdu(Vbs, 'snmpv2-trap'),
607
 
    AddrCommunities = mk_addr_communities(Recvs),
608
 
    lists:foreach(fun({Community, Addrs}) ->
609
 
                          ?vtrace("~n   send v2 trap to ~p",[Addrs]),
610
 
                          NetIf ! {send_pdu, 'version-2', TrapPdu,
611
 
                                   {community, Community}, Addrs}
612
 
                  end, AddrCommunities),
613
 
    ok.
614
 
 
615
 
do_send_v2_inform([], _Vbs, Recv, _NetIf) ->
616
 
    deliver_recv(Recv, snmp_targets, []);
617
 
do_send_v2_inform(Recvs, Vbs, Recv, NetIf) ->
618
 
    Targets = lists:map(fun({Addr, _Community, _Timeout, _Retry}) ->
619
 
                                Addr
620
 
                        end, Recvs),
621
 
    deliver_recv(Recv, snmp_targets, Targets),
622
 
    lists:foreach(
623
 
      fun({Addr, Community, Timeout, Retry}) ->
624
 
              ?vtrace("~n   start inform sender to send v2 inform to ~p",
625
 
                      [Addr]),
626
 
              proc_lib:spawn_link(?MODULE, init_v2_inform,
627
 
                                  [Addr, Timeout, Retry, Vbs,
628
 
                                   Recv, NetIf, Community,
629
 
                                   get(verbosity),get(sname)])
630
 
      end, 
631
 
      Recvs).
632
 
 
633
 
do_send_v3_trap([], _ContextName, _Vbs, _NetIf) ->
634
 
    ok;
635
 
do_send_v3_trap(Recvs, ContextName, Vbs, NetIf) ->
636
 
    TrapPdu = make_v2_notif_pdu(Vbs, 'snmpv2-trap'), % Yes, v2
637
 
    ContextEngineId = snmp_framework_mib:get_engine_id(),
638
 
    lists:foreach(fun(Recv) ->
639
 
                          ?vtrace("~n   send v3 notif to ~p",[Recv]),
640
 
                          NetIf ! {send_pdu, 'version-3', TrapPdu,
641
 
                                   {v3, ContextEngineId, ContextName}, [Recv]}
642
 
                  end, Recvs),
643
 
    ok.
644
 
 
645
 
do_send_v3_inform([], _ContextName, _Vbs, Recv, _NetIf) ->
646
 
    deliver_recv(Recv, snmp_targets, []);
647
 
do_send_v3_inform(Recvs, ContextName, Vbs, Recv, NetIf) ->
648
 
    Targets = lists:map(fun({Addr, _, _, _}) -> Addr end, Recvs),
649
 
    deliver_recv(Recv, snmp_targets, Targets),
650
 
    lists:foreach(
651
 
      fun({Addr, MsgData, Timeout, Retry}) ->
652
 
              ?vtrace("~n   start inform sender to send v3 inform to ~p",
653
 
                      [Addr]),
654
 
              proc_lib:spawn_link(?MODULE, init_v3_inform,
655
 
                                  [{Addr, MsgData}, Timeout, Retry, Vbs,
656
 
                                   Recv, NetIf, ContextName,
657
 
                                   get(verbosity),get(sname)])
658
 
      end, 
659
 
      Recvs).
660
 
 
661
 
%% New process
662
 
init_v2_inform(Addr, Timeout, Retry, Vbs, Recv, NetIf, Community,V,S) ->
663
 
    %% Make a new Inform for each recipient; they need unique
664
 
    %% request-ids!
665
 
    put(verbosity,V),
666
 
    put(sname,inform_sender_short_name(S)),
667
 
    ?vdebug("~n   starting with timeout = ~p and retry = ~p",
668
 
            [Timeout,Retry]),
669
 
    InformPdu = make_v2_notif_pdu(Vbs, 'inform-request'),
670
 
    Msg = {send_pdu_req, 'version-2', InformPdu, {community, Community},
671
 
           [Addr], self()},
672
 
    send_inform(Addr, Timeout*10, Retry, Msg, Recv, NetIf).
673
 
    
674
 
 
675
 
send_inform(Addr, _Timeout, -1, _Msg,  Recv, _NetIf) ->
676
 
    ?vinfo("~n   Delivery of send-pdu-request to net-if failed: reply timeout",
677
 
           []),
678
 
    deliver_recv(Recv, snmp_notification, {no_response, Addr});
679
 
send_inform(Addr, Timeout, Retry, Msg, Recv, NetIf) ->
680
 
    ?vtrace("~n   deliver send-pdu-request to net-if when Retry = ~p",[Retry]),
681
 
    NetIf ! Msg,
682
 
    receive
683
 
        {snmp_response_received, _Vsn, _Pdu, _From} ->
684
 
            ?vtrace("~n   received response for ~p (~p)",[Recv,Retry]),
685
 
            deliver_recv(Recv, snmp_notification, {got_response, Addr})
686
 
    after
687
 
        Timeout ->
688
 
            send_inform(Addr, Timeout*2, Retry-1, Msg, Recv, NetIf)
689
 
    end.
690
 
 
691
 
%% New process
692
 
init_v3_inform(Addr, Timeout, Retry, Vbs, Recv, NetIf, ContextName,V,S) ->
693
 
    %% Make a new Inform for each recipient; they need unique
694
 
    %% request-ids!
695
 
    put(verbosity,V),
696
 
    put(sname,inform_sender_short_name(S)),
697
 
    ?vdebug("~n   starting with timeout = ~p and retry = ~p",
698
 
            [Timeout,Retry]),
699
 
    InformPdu = make_v2_notif_pdu(Vbs, 'inform-request'), % Yes, v2
700
 
    ContextEngineId = snmp_framework_mib:get_engine_id(),
701
 
    Msg = {send_pdu_req, 'version-3', InformPdu,
702
 
           {v3, ContextEngineId, ContextName}, [Addr], self()},
703
 
    send_inform(Addr, Timeout*10, Retry, Msg, Recv, NetIf).
704
 
 
705
 
% A nasty bit of verbosity setup...    
706
 
inform_sender_short_name(ma)   -> mais;
707
 
inform_sender_short_name(maw)  -> mais;
708
 
inform_sender_short_name(mats) -> mais;
709
 
inform_sender_short_name(_)    -> sais.
710
 
 
711
 
deliver_recv(no_receiver, _MsgId, _Result) ->
712
 
    ?vtrace("deliver_recv -> no receiver", []),
713
 
    ok;
714
 
deliver_recv({Tag, Receiver}, MsgId, Result) ->
715
 
    ?vtrace("deliver_recv -> entry with"
716
 
        "~n   Tag:      ~p"
717
 
        "~n   Receiver: ~p"
718
 
        "~n   MsgId:    ~p"
719
 
        "~n   Result:   ~p"
720
 
        "", [Tag, Receiver, MsgId, Result]),
721
 
    Msg = {MsgId, Tag, Result},
722
 
    case Receiver of
723
 
        Pid when pid(Pid) ->
724
 
            Pid ! Msg;
725
 
        Name when atom(Name) ->
726
 
            catch Name ! Msg;
727
 
        {M, F, A} ->
728
 
            catch M:F([Msg | A]);
729
 
        Else ->
730
 
            ?vinfo("~n   Cannot deliver acknowledgment: bad receiver = '~p'",
731
 
                   [Else]),
732
 
            user_err("snmp: bad receiver, ~w\n", [Else])
733
 
    end;
734
 
deliver_recv(Else, _MsgId, _Result) ->
735
 
    ?vinfo("~n   Cannot deliver acknowledgment: bad receiver = '~p'",
736
 
           [Else]),
737
 
    user_err("snmp: bad receiver, ~w\n", [Else]).
738
 
 
739
 
check_all_varbinds(#notification{oid = Oid}, Vbs, MibView) ->
740
 
    case snmp_acm:validate_mib_view(Oid, MibView) of
741
 
        true -> check_all_varbinds(Vbs, MibView);
742
 
        false -> false
743
 
    end;
744
 
check_all_varbinds(#trap{enterpriseoid = Enter, specificcode = Spec},
745
 
                   Vbs, MibView) ->
746
 
    %% Use alg. in rfc1908 to map a v1 trap to a v2 trap
747
 
    Oid = case Enter of
748
 
              ?snmp -> ?snmpTraps ++ [Spec + 1];
749
 
              _ -> Enter ++ [0, Spec]
750
 
          end,
751
 
    case snmp_acm:validate_mib_view(Oid, MibView) of
752
 
        true -> check_all_varbinds(Vbs, MibView);
753
 
        false -> false
754
 
    end.
755
 
 
756
 
check_all_varbinds([#varbind{oid = Oid} | Vbs], MibView) ->
757
 
    case snmp_acm:validate_mib_view(Oid, MibView) of
758
 
        true -> check_all_varbinds(Vbs, MibView);
759
 
        false -> false
760
 
    end;
761
 
check_all_varbinds([], _MibView) -> true.
762
 
 
763
 
%%--------------------------------------------------
764
 
%% Functions to access the local mib.
765
 
%%--------------------------------------------------
766
 
sys_object_id() ->
767
 
    case snmp_agent:do_get(snmp_acm:get_root_mib_view(),
768
 
                           [#varbind{oid = ?sysObjectID_instance}],
769
 
                           true) of
770
 
        {noError, _, [#varbind{value = Value}]} ->
771
 
            Value;
772
 
        X ->
773
 
            user_err("sysObjectID bad return value ~w", [X])
774
 
    end.
775
 
 
776
 
%% Collect all ADDRs for each community together.
777
 
%% In: [{Addr, Community}]
778
 
%% Out: [{Community, [Addr]}]
779
 
mk_addr_communities(Recvs) ->
780
 
    [{Addr, Comm} | T] = lists:keysort(2, Recvs),
781
 
    mic(T, Comm, [Addr], []).
782
 
 
783
 
mic([{Addr, Comm} | T], CurComm, AddrList, Res) when Comm == CurComm ->
784
 
    mic(T, CurComm, [Addr | AddrList], Res);
785
 
mic([{Addr, Comm} | T], CurComm, AddrList, Res) ->
786
 
    mic(T, Comm, [Addr], [{CurComm, AddrList} | Res]);
787
 
mic([], CurComm, AddrList, Res) ->
788
 
    [{CurComm, AddrList} | Res].
789
 
 
790
 
%%-----------------------------------------------------------------
791
 
%% Convert the SecurityLevel into a flag value used by snmp_mpd
792
 
%%-----------------------------------------------------------------
793
 
mk_flag(?'SnmpSecurityLevel_noAuthNoPriv') -> 0;
794
 
mk_flag(?'SnmpSecurityLevel_authNoPriv') -> 1;
795
 
mk_flag(?'SnmpSecurityLevel_authPriv') -> 3.
796
 
     
797
 
 
798
 
 
799
 
user_err(F, A) ->
800
 
    snmp_error_report:user_err(F, A).