aboutsummaryrefslogtreecommitdiffstats
path: root/lib/snmp/src/agent/snmpa_mpd.erl
blob: 39a4246d268fb0735df1dec3ff2cc553d857b949 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1997-2010. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(snmpa_mpd).

-export([init/1, reset/0, inc/1, counters/0, 
	 discarded_pdu/1,
	 process_packet/6, process_packet/7, 
	 generate_response_msg/5, generate_response_msg/6, 
	 generate_msg/5, generate_msg/6, 
	 generate_discovery_msg/4, 
	 process_taddrs/1, 
	 generate_req_id/0]).

-define(SNMP_USE_V3, true).
-include("snmp_types.hrl").
-include("SNMP-MPD-MIB.hrl").
-include("SNMPv2-TM.hrl").
-include("SNMP-FRAMEWORK-MIB.hrl").

-define(VMODULE,"MPD").
-include("snmp_verbosity.hrl").
-include("snmpa_internal.hrl").

-define(empty_msg_size, 24).

-record(state, {v1 = false, v2c = false, v3 = false}).
-record(note, {sec_engine_id, 
	       sec_model, 
	       sec_name, 
	       sec_level, 
	       ctx_engine_id, 
	       ctx_name, 
	       disco = false, 
	       req_id}).

					
%%%-----------------------------------------------------------------
%%% This module implemets the Message Processing and Dispatch part of
%%% the multi-lingual SNMP agent.
%%%
%%% The MPD is responsible for:
%%%   *) call the security module (auth/priv).
%%%   *) decoding the message into a PDU.
%%%   *) decide a suitable Access Control Model, and provide it with
%%%      the data it needs.
%%%   *) maintaining SNMP counters.
%%%
%%% In order to take care of the different versions of counters, it
%%% implements and maintains the union of all SNMP counters (i.e. from
%%% rfc1213 and from rfc1907).  It is up to the administrator of the
%%% agent to load the correct MIB.  Note that this module implements
%%% the counters only, it does not provide instrumentation functions
%%% for the counters.
%%%
%%% With the terms defined in rfc2271, this module implememts part
%%% of the Dispatcher and the Message Processing functionality.
%%%-----------------------------------------------------------------
init(Vsns) ->
    ?vlog("init -> entry with"
	"~n   Vsns: ~p", [Vsns]),
    {A,B,C} = erlang:now(),
    random:seed(A,B,C),
    ets:insert(snmp_agent_table, {msg_id, random:uniform(2147483647)}),
    ets:insert(snmp_agent_table, {req_id, random:uniform(2147483647)}),
    init_counters(),
    init_versions(Vsns, #state{}).


reset() ->
    reset_counters(),
    ok.


%%-----------------------------------------------------------------
%% Purpose: We must calculate the length of a
%%          message with an empty Pdu, and zero-length community
%%          string.  This length is used to calculate the max
%%          pdu size allowed for each request. This size is 
%%          dependent on two dynamic fields, the community string
%%          and the pdu (varbinds actually). It is calculated
%%          as EmptySize + length(CommunityString) + 4.
%%          We assume that the length of the CommunityString is
%%          less than 128 (thus requiring just one octet for the
%%          length field (the same as the zero-length community
%%          string)). 4 comes from the fact that the maximum pdu
%%          size needs 31 bits which needs 5 * 7 bits to be
%%          expressed. One 7bit octet is already present in the
%%          empty msg, leaving 4 more 7bit octets.
%% Actually, this function is not used, we use a constant instead.
%%-----------------------------------------------------------------
%% Ret: 24
%empty_msg() ->
%    M = #message{version = 'version-1', community = "", data = 
%		 #pdu{type = 'get-response', request_id = 1,
%		      error_status = noError, error_index = 0, varbinds = []}},
%    length(snmp_pdus:enc_message(M)) + 4.

%%-----------------------------------------------------------------
%% Func: process_packet(Packet, TDomain, TAddress, State, Log) ->
%%       {ok, SnmpVsn, Pdu, PduMS, ACMData} | {discarded, Reason}
%% Types: Packet = binary()
%%        TDomain = snmpUDPDomain | transportDomain()
%%        TAddress = {Ip, Udp} (*but* depends on TDomain)
%%        State = #state
%% Purpose: This is the main Message Dispatching function. (see
%%          section 4.2.1 in rfc2272)
%%-----------------------------------------------------------------
process_packet(Packet, TDomain, TAddress, State, NoteStore, Log) ->
    LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID, 
    process_packet(Packet, TDomain, TAddress, LocalEngineID, 
		   State, NoteStore, Log).

process_packet(Packet, TDomain, TAddress, LocalEngineID, 
	       State, NoteStore, Log) ->
    inc(snmpInPkts),
    case catch snmp_pdus:dec_message_only(binary_to_list(Packet)) of

	#message{version = 'version-1', vsn_hdr = Community, data = Data} 
	  when State#state.v1 =:= true ->
	    ?vlog("v1, community: ~s", [Community]),
	    HS = ?empty_msg_size + length(Community),
	    v1_v2c_proc('version-1', NoteStore, Community, 
			TDomain, TAddress, 
			LocalEngineID, Data, HS, Log, Packet);

	#message{version = 'version-2', vsn_hdr = Community, data = Data}
	  when State#state.v2c =:= true ->
	    ?vlog("v2c, community: ~s", [Community]),
	    HS = ?empty_msg_size + length(Community),
	    v1_v2c_proc('version-2', NoteStore, Community, 
			TDomain, TAddress, 
			LocalEngineID, Data, HS, Log, Packet);

	#message{version = 'version-3', vsn_hdr = V3Hdr, data = Data}
	  when State#state.v3 =:= true ->
	    ?vlog("v3, msgID: ~p, msgFlags: ~p, msgSecModel: ~p",
		  [V3Hdr#v3_hdr.msgID,
		   V3Hdr#v3_hdr.msgFlags,
		   V3Hdr#v3_hdr.msgSecurityModel]),
	    v3_proc(NoteStore, Packet, 
		    TDomain, TAddress, 
		    LocalEngineID, V3Hdr, Data, Log);

	{'EXIT', {bad_version, Vsn}} ->
	    ?vtrace("exit: bad version: ~p",[Vsn]),
	    inc(snmpInBadVersions),
	    {discarded, snmpInBadVersions};

	{'EXIT', Reason} ->
	    ?vtrace("exit: ~p", [Reason]),
	    inc(snmpInASNParseErrs),
	    {discarded, Reason};

	UnknownMessage ->
	    ?vtrace("Unknown message: ~n   ~p"
		"~nwhen"
		"~n   State: ~p", [UnknownMessage, State]),
	    inc(snmpInBadVersions),
	    {discarded, snmpInBadVersions}
    end.

discarded_pdu(false) -> ok;
discarded_pdu(Variable) -> inc(Variable).


%%-----------------------------------------------------------------
%% Handles a Community based message (v1 or v2c).
%%-----------------------------------------------------------------
v1_v2c_proc(Vsn, NoteStore, Community, Domain, 
	    {Ip, Udp}, LocalEngineID, 
	    Data, HS, Log, Packet) ->
    TDomain  = snmp_conf:mk_tdomain(Domain), 
    TAddress = snmp_conf:mk_taddress(Domain, Ip, Udp),
    AgentMS  = get_engine_max_message_size(LocalEngineID),
    MgrMS    = snmp_community_mib:get_target_addr_ext_mms(TDomain, TAddress),
    PduMS    = case MgrMS of
		   {ok, MMS} when MMS < AgentMS -> MMS - HS;
		   _ -> AgentMS - HS
	       end,
    case (catch snmp_pdus:dec_pdu(Data)) of
	Pdu when is_record(Pdu, pdu) ->
	    Log(Pdu#pdu.type, Packet),
	    inc_snmp_in_vars(Pdu),
	    #pdu{request_id = ReqId} = Pdu,
	    
	    %% <TDomain>
	    %% We have added TDomain, what are the consequences?
	    ACMData = 
		{community, sec_model(Vsn), Community, TDomain, TAddress}, 
	    OkRes = {ok, Vsn, Pdu, PduMS, ACMData},
	    %% </TDomain>

	    %% Make sure that we don't process duplicate SET request
	    %% twice.  We don't know what could happen in that case.
	    %% The mgr does, so he has to generate a new SET request.
	    ?vdebug("PDU type: ~p", [Pdu#pdu.type]),
	    case Pdu#pdu.type of
		'set-request' ->
		    %% Check if this message has already been processed
		    Key = {agent, Ip, ReqId},
		    case snmp_note_store:get_note(NoteStore, Key) of
			undefined -> 
			    %% Set the processed note _after_ pdu processing. 
			    %% This makes duplicated requests be ignored even 
			    %% if pdu processing took long time.
			    snmp_note_store:set_note(NoteStore, 
						     100, Key, true),
			    %% Uses ACMData that snmpa_acm knows of.
			    OkRes;
			true ->
			    {discarded, duplicate_pdu}
		    end;
		_ ->
		    OkRes
	    end;
	{'EXIT', Reason} ->
	    ?vtrace("PDU decode exit: ~p",[Reason]),
	    inc(snmpInASNParseErrs),
	    {discarded, Reason};
	_TrapPdu ->
	    {discarded, trap_pdu}
    end;
v1_v2c_proc(_Vsn, _NoteStore, _Community, snmpUDPDomain, TAddress, 
	    _LocalEngineID, _Data, _HS, _Log, _Packet) ->
    {discarded, {badarg, TAddress}};
v1_v2c_proc(_Vsn, _NoteStore, _Community, TDomain, _TAddress, 
	    _LocalEngineID, _Data, _HS, _Log, _Packet) ->
    {discarded, {badarg, TDomain}}.

sec_model('version-1') -> ?SEC_V1;
sec_model('version-2') -> ?SEC_V2C.


%%-----------------------------------------------------------------
%% Handles a SNMPv3 Message, following the procedures in rfc2272,
%% section 4.2 and 7.2
%%-----------------------------------------------------------------
v3_proc(NoteStore, Packet, _TDomain, _TAddress, LocalEngineID, 
	V3Hdr, Data, Log) ->
    case (catch v3_proc(NoteStore, Packet, LocalEngineID, V3Hdr, Data, Log)) of
	{'EXIT', Reason} ->
	    exit(Reason);
	Result ->
	    Result
    end.

v3_proc(NoteStore, Packet, LocalEngineID, V3Hdr, Data, Log) ->
    ?vtrace("v3_proc -> entry with"
	    "~n   LocalEngineID: ~p",
	    [LocalEngineID]),
    %% 7.2.3
    #v3_hdr{msgID                 = MsgID, 
	    msgMaxSize            = MMS, 
	    msgFlags              = MsgFlags,
	    msgSecurityModel      = MsgSecurityModel,
	    msgSecurityParameters = SecParams, 
	    hdr_size              = HdrSize} = V3Hdr,
    ?vdebug("v3_proc -> version 3 message header [7.2.3]:"
	    "~n   msgID                 = ~p"
	    "~n   msgMaxSize            = ~p"
	    "~n   msgFlags              = ~p"
	    "~n   msgSecurityModel      = ~p"
	    "~n   msgSecurityParameters = ~w",
	    [MsgID, MMS, MsgFlags, MsgSecurityModel, SecParams]),
    %% 7.2.4
    SecModule    = get_security_module(MsgSecurityModel),
    %% 7.2.5
    SecLevel     = check_sec_level(MsgFlags),
    IsReportable = snmp_misc:is_reportable(MsgFlags),
    %% 7.2.6
    ?vtrace("v3_proc -> [7.2.4-7.2.6]"
	    "~n   SecModule    = ~p"
	    "~n   SecLevel     = ~p"
	    "~n   IsReportable = ~p",
	    [SecModule, SecLevel, IsReportable]),
    SecRes = (catch SecModule:process_incoming_msg(Packet, Data,
						   SecParams, SecLevel, 
						   LocalEngineID)),
    ?vtrace("v3_proc -> message processing result: "
	    "~n   SecRes: ~p", [SecRes]),
    {SecEngineID, SecName, ScopedPDUBytes, SecData, DiscoOrPlain} =
	check_sec_module_result(SecRes, V3Hdr, Data, 
				LocalEngineID, IsReportable, Log),
    ?vtrace("v3_proc -> "
	    "~n   DiscoOrPlain: ~w"
	    "~n   SecEngineID:  ~w"
	    "~n   SecName:      ~p", [DiscoOrPlain, SecEngineID, SecName]),
    %% 7.2.7
    #scopedPdu{contextEngineID = ContextEngineID,
	       contextName     = ContextName,
	       data            = PDU} =
	case (catch snmp_pdus:dec_scoped_pdu(ScopedPDUBytes)) of
	    ScopedPDU when is_record(ScopedPDU, scopedPdu) -> 
		?vtrace("v3_proc -> message processing result: "
			"~n   ScopedPDU: ~p", [ScopedPDU]),
		ScopedPDU;
	    {'EXIT', Reason} ->
		inc(snmpInASNParseErrs),
		throw({discarded, Reason})
	end,
    %% We'll have to take care of the unlikely case that we receive an
    %% v1 trappdu in a v3 message explicitly...
    if
	is_record(PDU, trappdu) ->
	    inc(snmpUnknownPDUHandlers),
	    throw({discarded, received_v1_trap});
	true ->
	    ok
    end,
    ?vlog("7.2.7 result: "
	  "~n   contextEngineID: ~w"
	  "~n   ContextName:     \"~s\"", [ContextEngineID, ContextName]),
    if
	SecLevel =:= ?'SnmpSecurityLevel_authPriv' -> 
	    %% encrypted message - log decrypted pdu
	    Log(PDU#pdu.type, {V3Hdr, ScopedPDUBytes});
	true -> % otherwise, log binary
	    Log(PDU#pdu.type, Packet)
    end,
    %% Make sure a get_bulk doesn't get too big.
    AgentMS = get_engine_max_message_size(LocalEngineID),
    %% PduMMS is supposed to be the maximum total length of the response
    %% PDU we can send.  From the MMS, we need to subtract everything before
    %% the PDU, i.e. Message and ScopedPDU.
    %%   Message: [48, TotalLen, Vsn, [Tag, LH, Hdr], [Tag, LM, MsgSec], Data]
    %%             1              3   <----------- HdrSize ----------->
    %%   HdrSize = everything up to and including msgSecurityParameters.
    %% ScopedPduData follows.  This is
    %%   [Tag, Len, [Tag, L1, CtxName], [Tag, L2, CtxEID]]
    %%   i.e. 6 + length(CtxName) + length(CtxEID)
    %% 
    %% Total: 1 + TotalLenOctets + 3 + ScopedPduDataLen
    TotMMS = if AgentMS > MMS -> MMS;
		true -> AgentMS
	     end,
    TotalLenOctets = snmp_pdus:get_encoded_length(TotMMS - 1),
    PduMMS = TotMMS - TotalLenOctets - 10 - HdrSize - 
	length(ContextName) - length(ContextEngineID),
    ?vdebug("v3_proc -> PDU type: ~p", [PDU#pdu.type]),
    case PDU#pdu.type of
	report when DiscoOrPlain =:= discovery ->
	    %% Discovery stage 1 response
	    Key  = {agent, MsgID}, 
	    Note = snmp_note_store:get_note(NoteStore, Key), 
	    case Note of
                #note{sec_engine_id = "",
                      sec_model     = _MsgSecModel,
                      sec_name      = "",
                      sec_level     = _SecLevel,
                      ctx_engine_id = _CtxEngineID,
                      ctx_name      = _CtxName,
                      disco         = true,
                      req_id        = _ReqId} ->
                    %% This is part of the discovery process initiated by us.
                    %% Response to the discovery stage 1 request
                    ?vdebug("v3_proc -> discovery stage 1 response", []),
                    {ok, 'version-3', PDU, PduMMS, {discovery, SecEngineID}};
                #note{sec_engine_id = SecEngineID,
                      sec_model     = _MsgSecModel,
                      sec_name      = SecName,
                      sec_level     = SecLevel,
                      ctx_engine_id = _CtxEngineID,
                      ctx_name      = _CtxName,
                      disco         = true,
                      req_id        = _ReqId} ->
                    %% This is part of the discovery process initiated by us.
                    %% Response to the discovery stage 2 request
                    ?vdebug("v3_proc -> discovery stage 2 response", []),
                    {ok, 'version-3', PDU, PduMMS, discovery};
		_ ->
		    %% 7.2.11
		    DiscardReason = {bad_disco_note, Key, Note}, 
		    throw({discarded, DiscardReason})
	    end;
	report ->
	    %% 7.2.11
	    throw({discarded, report});
	'get-response' -> %% As a result of a sent inform-request?
	    %% 7.2.12
	    Key  = {agent, MsgID}, 
	    Note = snmp_note_store:get_note(NoteStore, Key), 
	    case Note of
                #note{sec_engine_id = "",
                      sec_model     = _MsgSecModel,
                      sec_name      = "",
                      sec_level     = _SecLevel,
                      ctx_engine_id = _CtxEngineID,
                      ctx_name      = _CtxName,
                      disco         = true,
                      req_id        = _ReqId} ->
                    %% This is part of the discovery process initiated by us.
                    %% Response to the discovery stage 1 request
                    ?vdebug("v3_proc -> discovery stage 1 response", []),
                    {ok, 'version-3', PDU, PduMMS, {discovery, SecEngineID}};
                #note{sec_engine_id = SecEngineID,
                      sec_model     = _MsgSecModel,
                      sec_name      = SecName,
                      sec_level     = SecLevel,
                      ctx_engine_id = _CtxEngineID,
                      ctx_name      = _CtxName,
                      disco         = true,
                      req_id        = _ReqId} ->
                    %% This is part of the discovery process initiated by us.
                    %% Response to the discovery stage 2 request
                    ?vdebug("v3_proc -> discovery stage 2 response", []),
                    {ok, 'version-3', PDU, PduMMS, discovery};
		#note{sec_engine_id = SecEngineID, 
		      sec_model     = MsgSecurityModel, 
		      sec_name      = SecName, 
		      sec_level     = SecLevel,
		      ctx_engine_id = ContextEngineID, 
		      ctx_name      = ContextName,
		      disco         = false,
		      req_id        = _ReqId} ->
		    {ok, 'version-3', PDU, PduMMS, undefined};
		_ ->
		    inc(snmpUnknownPDUHandlers),
		    throw({discarded, {no_outstanding_req, MsgID}})
	    end;
	'snmpv2-trap' ->
	    inc(snmpUnknownPDUHandlers),
	    throw({discarded, received_v2_trap});
	Type ->
	    %% 7.2.13
	    SnmpEngineID = LocalEngineID, 
	    ?vtrace("v3_proc -> 7.2.13", []),
	    case SecEngineID of
		SnmpEngineID when (DiscoOrPlain =:= discovery) ->
		    %% This is a discovery step 2 message!
		    ?vtrace("v3_proc -> discovery stage 2", []),
		    generate_discovery2_report_msg(MsgID, 
						   MsgSecurityModel, 
						   SecName, 
						   SecLevel, 
						   ContextEngineID, 
						   ContextName,
						   SecData, 
						   PDU, 
						   LocalEngineID, 
						   Log);

		SnmpEngineID when (DiscoOrPlain =:= plain) ->
		    %% 4.2.2.1.1 - we don't handle proxys yet => we only 
		    %% handle ContextEngineID to ourselves
		    case ContextEngineID of
			SnmpEngineID ->
			    %% Uses ACMData that snmpa_acm knows of.
			    {ok, 'version-3', PDU, PduMMS, 
			     {v3, MsgID, MsgSecurityModel, SecName, SecLevel,
			      ContextEngineID, ContextName, SecData}};
			_ ->
			    %% 4.2.2.1.2
			    NIsReportable = snmp_misc:is_reportable_pdu(Type),
			    Val = inc(snmpUnknownPDUHandlers),
			    ErrorInfo = 
				{#varbind{oid = ?snmpUnknownPDUHandlers,
					  variabletype = 'Counter32',
					  value = Val},
				 SecName,
				 [{securityLevel,   SecLevel},
				  {contextEngineID, ContextEngineID},
				  {contextName,     ContextName}]},
			    case generate_v3_report_msg(MsgID, 
							MsgSecurityModel,
							Data, LocalEngineID, 
							ErrorInfo, Log) of
				{ok, Report} when NIsReportable =:= true ->
				    {discarded, snmpUnknownPDUHandlers, Report};
				_ ->
				    {discarded, snmpUnknownPDUHandlers}
			    end
		    end;

		"" ->
		    %% This is a discovery step 1 message!!
		    ?vtrace("v3_proc -> discovery step 1", []),
		    generate_discovery1_report_msg(MsgID, 
						   MsgSecurityModel, 
						   SecName, 
						   SecLevel, 
						   ContextEngineID, 
						   ContextName,
						   SecData, 
						   PDU, 
						   LocalEngineID, 
						   Log);
		    
		_ ->
		    {discarded, {badSecurityEngineID, SecEngineID}}
	    end
    end.


get_security_module(?SEC_USM) ->
    snmpa_usm;
get_security_module(_) ->
    inc(snmpUnknownSecurityModels),
    throw({discarded, snmpUnknownSecurityModels}).
    
check_sec_level([MsgFlag]) ->
    SecLevel = MsgFlag band 3,
    if 
	SecLevel == 2 -> 
	    inc(snmpInvalidMsgs),
	    throw({discarded, snmpInvalidMsgs});
	true ->
	    SecLevel
    end;
check_sec_level(Unknown) ->
    ?vlog("invalid msgFlags: ~p",[Unknown]), 
    inc(snmpInvalidMsgs),
    throw({discarded, snmpInvalidMsgs}).

check_sec_module_result(Res, V3Hdr, Data, LocalEngineID, IsReportable, Log) ->
    case Res of
	{ok, X} -> 
	    X;
	{error, Reason, []} ->         % case 7.2.6 b
	    ?vdebug("security module result [7.2.6-b]:"
		    "~n   Reason: ~p", [Reason]),
	    throw({discarded, {securityError, Reason}});
	{error, Reason, ErrorInfo} when IsReportable =:= true -> % case 7.2.6 a
	    ?vdebug("security module result when reportable [7.2.6-a]:"
		    "~n   Reason:    ~p"
		    "~n   ErrorInfo: ~p", [Reason, ErrorInfo]),
	    #v3_hdr{msgID = MsgID, msgSecurityModel = MsgSecModel} = V3Hdr,
	    Pdu = get_scoped_pdu(Data),
	    case generate_v3_report_msg(MsgID, MsgSecModel, Pdu,
					LocalEngineID, ErrorInfo, Log) of
		{ok, Report} ->
		    throw({discarded, {securityError, Reason}, Report});
		{discarded, _SomeOtherReason} ->
		    throw({discarded, {securityError, Reason}})
	    end;
	{error, Reason, ErrorInfo} ->
	    ?vdebug("security module result when not reportable:"
		    "~n   Reason:    ~p"
		    "~n   ErrorInfo: ~p", [Reason, ErrorInfo]),
	    throw({discarded, {securityError, Reason}});
	Else ->
	    ?vdebug("security module result:"
		    "~n   Else: ~p", [Else]),
	    throw({discarded, {securityError, Else}})
    end.

get_scoped_pdu(D) when is_list(D) ->
    (catch snmp_pdus:dec_scoped_pdu(D));
get_scoped_pdu(D) ->
    D.


%%-----------------------------------------------------------------
%% Executed when a response or report message is generated.
%%-----------------------------------------------------------------
generate_response_msg(Vsn, RePdu, Type, ACMData, Log) ->
    generate_response_msg(Vsn, RePdu, Type, ACMData, Log, 1).

generate_response_msg(Vsn, RePdu, Type, ACMData, Log, N) when is_integer(N) ->
    LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID, 
    generate_response_msg(Vsn, RePdu, Type, ACMData, LocalEngineID, Log, N);
generate_response_msg(Vsn, RePdu, Type, ACMData, LocalEngineID, Log) ->
    generate_response_msg(Vsn, RePdu, Type, ACMData, LocalEngineID, Log, 1).

generate_response_msg(Vsn, RePdu, Type, 
		      {community, _SecModel, Community, _TDomain, _TAddress},
		      LocalEngineID, 
		      Log, _) ->
	case catch snmp_pdus:enc_pdu(RePdu) of
	    {'EXIT', Reason} ->
		user_err("failed encoding pdu: "
			 "(pdu: ~w, community: ~w): ~n~w",
			 [RePdu, Community, Reason]),
		{discarded, Reason};
	    PduBytes ->
		Message = #message{version = Vsn, 
				   vsn_hdr = Community, 
				   data    = PduBytes},
		case catch list_to_binary(
			     snmp_pdus:enc_message_only(Message)) of
		    {'EXIT', Reason} ->
			user_err("failed encoding message only "
				 "(pdu: ~w, community: ~w): ~n~w",
				 [RePdu, Community, Reason]),
			{discarded, Reason};
		    Packet ->
			MMS = get_engine_max_message_size(LocalEngineID),
			case size(Packet) of
			    Len when Len =< MMS ->
				Log(Type, Packet),
				inc_snmp_cnt_vars(Type, RePdu),
				inc_snmp_out_vars(RePdu),
				{ok, Packet};
			    Len ->
				?vlog("pdu to big:"
				      "~n   Max message size:     ~p"
				      "~n   Encoded message size: ~p",
				      [MMS,Len]),
				too_big(Vsn, RePdu, Community, Log, MMS, Len)
			end
		end
	end;
generate_response_msg(Vsn, RePdu, Type, 
		      {v3, MsgID, MsgSecurityModel, SecName, SecLevel,
		       ContextEngineID, ContextName, SecData},
		      LocalEngineID, 
		      Log, N) ->
    %% rfc2272: 7.1 steps 6-8
    ScopedPDU = #scopedPdu{contextEngineID = ContextEngineID,
			   contextName     = ContextName,
			   data            = RePdu},
    case catch snmp_pdus:enc_scoped_pdu(ScopedPDU) of
	{'EXIT', Reason} ->
	    user_err("failed encoded scoped pdu "
		     "(pdu: ~w, contextName: ~w): ~n~w",
		     [RePdu, ContextName, Reason]),
	    {discarded, Reason};
	ScopedPDUBytes -> 
	    AgentMS = get_engine_max_message_size(LocalEngineID),
	    V3Hdr = #v3_hdr{msgID      = MsgID,
			    msgMaxSize = AgentMS,
			    msgFlags = snmp_misc:mk_msg_flags(Type, SecLevel),
			    msgSecurityModel = MsgSecurityModel},
	    Message = #message{version = Vsn, 
			       vsn_hdr = V3Hdr, 
			       data    = ScopedPDUBytes},
	    %% We know that the security model is valid when we
	    %% generate a response.
	    SecModule = 
		case MsgSecurityModel of
		    ?SEC_USM ->
			snmpa_usm
		end,
	    SecEngineID = LocalEngineID, 
	    ?vtrace("generate_response_msg -> SecEngineID: ~w", [SecEngineID]),
	    case (catch SecModule:generate_outgoing_msg(Message, 
							SecEngineID,
							SecName, 
							SecData, 
							SecLevel,
							LocalEngineID)) of
		{'EXIT', Reason} ->
		    config_err("~p (message: ~p)", [Reason, Message]),
		    {discarded, Reason};
		{error, Reason} ->
		    config_err("~p (message: ~p)", [Reason, Message]),
		    {discarded, Reason};
		OutMsg when is_list(OutMsg) ->
		    %% Check the packet size.  Send the msg even
		    %% if it's larger than the mgr can handle - it
		    %% will be dropped.  Just check against the
		    %% internal size.  For GET-BULk responses: we
		    %% *know* that we're within the right limits,
		    %% because of the calculation we do when we
		    %% receive the bulk-request.
		    Packet = list_to_binary(OutMsg),
		    case size(Packet) of
			Len when Len =< AgentMS ->
			    if
				SecLevel =:= 3 -> 
				    %% encrypted - log decrypted pdu
				    Log(Type, {V3Hdr, ScopedPDUBytes});
				true -> 
				    %% otherwise log the entire msg
				    Log(Type, Packet)
			    end,
			    inc_snmp_cnt_vars(Type, RePdu),
			    inc_snmp_out_vars(RePdu),
			    {ok, Packet};
			Len when N =:= 2 ->
			    ?vlog("packet max size exceeded: "
				  "~n   Max: ~p"
				  "~n   Len: ~p",
				  [AgentMS,Len]),
			    inc(snmpSilentDrops),
			    {discarded, tooBig};
			Len ->
			    ?vlog("packet max size exceeded: "
				  "~n   N:   ~p"
				  "~n   Max: ~p"
				  "~n   Len: ~p",
				  [N, AgentMS, Len]),
			    TooBigPdu = RePdu#pdu{error_status = tooBig,
						  error_index  = 0, 
						  varbinds     = []},
			    generate_response_msg(Vsn, TooBigPdu, Type, 
						  {v3, MsgID, 
						   MsgSecurityModel,
						   SecName, SecLevel,
						   ContextEngineID, 
						   ContextName,
						   SecData}, 
						  LocalEngineID, Log, N+1)
		    end
	    end
    end.

generate_v3_report_msg(MsgID, MsgSecurityModel, Data, LocalEngineID, 
		       ErrorInfo, Log) ->
    {Varbind, SecName, Opts} = ErrorInfo,
    ReqId =
	if 
	    is_record(Data, scopedPdu) -> 
		(Data#scopedPdu.data)#pdu.request_id;
	   true -> 
		0 %% RFC2572, 7.1.3.c.4
	end,
    ?vtrace("Report ReqId: ~p",[ReqId]),
    Pdu = #pdu{type         = report, 
	       request_id   = ReqId,
	       error_status = noError, 
	       error_index  = 0,
	       varbinds     = [Varbind]},
    SecLevel        = snmp_misc:get_option(securityLevel, Opts, 0),
    SnmpEngineID    = LocalEngineID, 
    ContextEngineID = 
	snmp_misc:get_option(contextEngineID, Opts, SnmpEngineID),
    ContextName     = snmp_misc:get_option(contextName, Opts, ""),
    SecData         = snmp_misc:get_option(sec_data,    Opts, []),

    generate_response_msg('version-3', Pdu, report,
			  {v3, MsgID, MsgSecurityModel, SecName, SecLevel,
			   ContextEngineID, ContextName, SecData}, 
			  LocalEngineID, Log).

%% req_id(#scopedPdu{data = #pdu{request_id = ReqId}}) ->
%%     ?vtrace("Report ReqId: ~p",[ReqId]),
%%     ReqId;
%% req_id(_) ->
%%     0. % RFC2572, 7.1.3.c.4

    
%% maybe_generate_discovery1_report_msg() ->
%%     case (catch DiscoveryHandler:handle_discovery1(Ip, Udp, EngineId)) of
%% 	{ok, Entry} when is_record(Entry, snmp_discovery_data1) ->
%% 	    ok;
%% 	ignore ->
%% 	    ok;
%% 	{error, Reason} ->
	    
%% Response to stage 1 discovery message (terminating, i.e. from the manager)
generate_discovery1_report_msg(MsgID, MsgSecurityModel, 
			       SecName, SecLevel, 
			       ContextEngineID, ContextName,
			       {SecData, Oid, Value}, 
			       #pdu{request_id = ReqId}, 
			       LocalEngineID, Log) ->
    ?vtrace("generate_discovery1_report_msg -> entry with"
	    "~n   ReqId: ~p"
	    "~n   Value: ~p", [ReqId, Value]),
    Varbind = #varbind{oid          = Oid, 
		       variabletype = 'Counter32',
		       value        = Value, 
		       org_index    = 1}, 
    PduOut = #pdu{type         = report, 
		  request_id   = ReqId,
		  error_status = noError, 
		  error_index  = 0,
		  varbinds     = [Varbind]},
    case generate_response_msg('version-3', PduOut, report,
			       {v3, MsgID, MsgSecurityModel, SecName, SecLevel,
				ContextEngineID, ContextName, SecData}, 
			       LocalEngineID, Log) of
	{ok, Packet} ->
	    {discovery, Packet};
	Error ->
	    Error
    end.

%% Response to stage 2 discovery message (terminating, i.e. from the manager)
generate_discovery2_report_msg(MsgID, MsgSecurityModel, 
			       SecName, SecLevel, 
			       ContextEngineID, ContextName,
			       SecData, #pdu{request_id = ReqId}, 
			       LocalEngineID, Log) ->
    ?vtrace("generate_discovery2_report_msg -> entry with"
	    "~n   ReqId: ~p", [ReqId]),
    SecModule = get_security_module(MsgSecurityModel), 
    Vb = SecModule:current_statsNotInTimeWindows_vb(), 
    PduOut = #pdu{type         = report, 
		  request_id   = ReqId,
		  error_status = noError, 
		  error_index  = 0,
		  varbinds     = [Vb]},
    case generate_response_msg('version-3', PduOut, report,
			       {v3, MsgID, MsgSecurityModel, SecName, SecLevel,
				ContextEngineID, ContextName, SecData}, 
			       LocalEngineID, Log) of
	{ok, Packet} ->
	    {discovery, Packet};
	Error ->
	    Error
    end.


too_big(Vsn, Pdu, Community, Log, _MMS, _Len) 
  when Pdu#pdu.type =:= 'get-response' ->
    ErrPdu =
	if 
	    Vsn =:= 'version-1' ->
		%% In v1, the varbinds should be identical to the incoming
		%% request.  It isn't identical now!
		%% Make acceptable (?) approximation.
		V = set_vb_null(Pdu#pdu.varbinds),
		Pdu#pdu{error_status = tooBig, error_index = 0, varbinds = V};
	    true ->
		%% In v2, varbinds should be empty (reasonable!)
		Pdu#pdu{error_status = tooBig, error_index = 0, varbinds = []}
	end,

    case catch snmp_pdus:enc_pdu(ErrPdu) of
	{'EXIT', Reason} ->
	    user_err("failed encoding pdu (pdu: ~w, community: ~w): ~n~w", 
		     [ErrPdu, Community, Reason]),
	    {discarded, Reason};
	PduBytes -> 
	    Message = #message{version = Vsn, vsn_hdr = Community, 
			       data = PduBytes},
	    case catch snmp_pdus:enc_message_only(Message) of
		{'EXIT', Reason} ->
		    user_err("failed encoding message only"
			     "(pdu: ~w, community: ~w): ~n~w", 
			     [ErrPdu, Community, Reason]),
		    {discarded, Reason};
		Packet -> 
		    Bin = list_to_binary(Packet),
		    Log(Pdu#pdu.type, Bin),
		    inc_snmp_out_vars(ErrPdu),
		    {ok, Bin}
	    end
    end;
too_big(_Vsn, Pdu, _Community, _Log, MMS, Len) ->
    user_err("encoded pdu, ~p bytes, exceeded "
	     "max message size of ~p bytes. Pdu: ~n~w", 
	     [Len, MMS, Pdu]),
    {discarded, tooBig}.

set_vb_null([Vb | Vbs]) ->
    [Vb#varbind{variabletype = 'NULL', value = 'NULL'} | set_vb_null(Vbs)];
set_vb_null([]) ->
    [].

%%-----------------------------------------------------------------
%% Executed when a message that isn't a response is generated, i.e.
%% a trap or an inform.
%%-----------------------------------------------------------------
generate_msg(Vsn, NoteStore, Pdu, ACMData, To) ->
    LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID, 
    generate_msg(Vsn, NoteStore, Pdu, ACMData, LocalEngineID, To).

generate_msg(Vsn, _NoteStore, Pdu, {community, Community}, LocalEngineID, To) ->
    Message = #message{version = Vsn, vsn_hdr = Community, data = Pdu},
    case catch list_to_binary(snmp_pdus:enc_message(Message)) of
	{'EXIT', Reason} ->
	    user_err("failed encoding message "
		     "(pdu: ~w, community: ~w): ~n~w",
		     [Pdu, Community, Reason]),
	    {discarded, Reason};
	Packet ->
	    AgentMax = get_engine_max_message_size(LocalEngineID),
	    case size(Packet) of
		Len when Len =< AgentMax ->
		    {ok, mk_v1_v2_packet_list(To, Packet, Len, Pdu)};
		Len ->
		    ?vlog("packet max size exceeded: "
			  "~n   Max: ~p"
			  "~n   Len: ~p",
			  [AgentMax, Len]),
		    {discarded, tooBig}
	    end
    end;
generate_msg('version-3', NoteStore, Pdu, 
	     {v3, ContextEngineID, ContextName}, LocalEngineID, To) ->
    %% rfc2272: 7.1 step 6
    ScopedPDU = #scopedPdu{contextEngineID = LocalEngineID, 
			   contextName = ContextName,
			   data = Pdu},
    case (catch snmp_pdus:enc_scoped_pdu(ScopedPDU)) of
	{'EXIT', Reason} ->
	    user_err("failed encoding scoped pdu "
		     "(pdu: ~w, contextName: ~w): ~n~w",
		     [Pdu, ContextName, Reason]),
	    {discarded, Reason};
	ScopedPDUBytes -> 
	    {ok, mk_v3_packet_list(NoteStore, To, ScopedPDUBytes, Pdu, 
				   ContextEngineID, ContextName, 
				   LocalEngineID)}
    end.


generate_discovery_msg(NoteStore, Pdu, MsgData, To) ->
    Timeout = 1500, 
    generate_discovery_msg(NoteStore, Pdu, MsgData, Timeout, To).

generate_discovery_msg(NoteStore, Pdu, MsgData, Timeout, To) ->
    {SecData, ContextEngineID, ContextName}       = MsgData,
    {SecModel, SecName, SecLevelFlag, TargetName} = SecData,
    {ManagerEngineId, InitialUserName} = 
	case get_target_engine_id(TargetName) of
	    {ok, discovery} ->  
		{"", ""};             % Discovery stage 1
	    {ok, {discovery, IUN}} ->  
		{"", IUN};            % Discovery stage 1
	    {ok, TargetEngineId} ->
		{TargetEngineId, ""}  % Discovery stage 2
	end,
    generate_discovery_msg(NoteStore, Pdu, 
			   ContextEngineID, ContextName, 
			   SecModel, SecName, SecLevelFlag, 
			   ManagerEngineId, 
			   InitialUserName, 
			   Timeout, To).

generate_discovery_msg(NoteStore, Pdu, 
		       ContextEngineID, ContextName, 
		       SecModel, _SecName, _SecLevelFlag, 
		       "" = ManagerEngineID, 
		       InitialUserName,
		       Timeout, To) ->
    %% Discovery step 1 uses SecLevel = noAuthNoPriv
    SecName      = "", 
    SecLevelFlag = 0, % ?'SnmpSecurityLevel_noAuthNoPriv', 
    generate_discovery_msg2(NoteStore, Pdu, 
			    ContextEngineID, ManagerEngineID, 
			    SecModel, SecName, SecLevelFlag,
			    InitialUserName, 
			    ContextName, Timeout, To);
generate_discovery_msg(NoteStore, Pdu, 
		       ContextEngineID, ContextName, 
		       SecModel, SecName, SecLevelFlag, 
		       ManagerEngineID, 
		       InitialUserName,
		       Timeout, To) ->
    %% SecLevelFlag = 1, % ?'SnmpSecurityLevel_authNoPriv', 
    generate_discovery_msg2(NoteStore, Pdu, 
			    ContextEngineID, ManagerEngineID, 
			    SecModel, SecName, SecLevelFlag,
			    InitialUserName, 
			    ContextName, Timeout, To).

generate_discovery_msg2(NoteStore, Pdu, 
			ContextEngineID, ManagerEngineID, 
			SecModel, SecName, SecLevelFlag,
			InitialUserName, 
			ContextName, Timeout, To) ->
    %% rfc2272: 7.1.6
    ScopedPDU = #scopedPdu{contextEngineID = ContextEngineID,
			   contextName     = ContextName,
			   data            = Pdu},
    case (catch snmp_pdus:enc_scoped_pdu(ScopedPDU)) of
	{'EXIT', Reason} ->
	    user_err("failed encoding scoped pdu "
		     "(pdu: ~w, contextName: ~w): ~n~w",
		     [Pdu, ContextName, Reason]),
	    {discarded, Reason};
	ScopedPDUBytes -> 
	    {ok, generate_discovery_msg(NoteStore, To, 
					Pdu, ScopedPDUBytes, 
					ContextEngineID, ManagerEngineID,
					SecModel, SecName, SecLevelFlag,
					InitialUserName, 
					ContextName, Timeout)}
    end.

%% Timeout is in msec but note timeout is in 1/10 seconds
discovery_note_timeout(Timeout) ->
    (Timeout div 100) + 1.
    
generate_discovery_msg(NoteStore, {?snmpUDPDomain, [A,B,C,D,U1,U2]}, 
		       Pdu, ScopedPduBytes, 
		       ContextEngineID, ManagerEngineID, 
		       SecModel, SecName, SecLevelFlag, 
		       InitialUserName, 
		       ContextName, Timeout) ->
    %% 7.1.7
    ?vdebug("generate_discovery_msg -> 7.1.7 (~w)", [ManagerEngineID]),
    MsgID     = generate_msg_id(),
    PduType   = Pdu#pdu.type,
    MsgFlags  = mk_msg_flags(PduType, SecLevelFlag), 
    V3Hdr     = #v3_hdr{msgID            = MsgID,
			msgMaxSize       = get_max_message_size(),
			msgFlags         = MsgFlags,
			msgSecurityModel = SecModel},
    Message   = #message{version = 'version-3', 
			 vsn_hdr = V3Hdr,
			 data    = ScopedPduBytes},
    SecModule = sec_module(SecModel),

    %% 7.1.9b
    ?vdebug("generate_discovery_msg -> 7.1.9b", []),
    case generate_sec_discovery_msg(Message, SecModule, 
				    ManagerEngineID, 
				    SecName, SecLevelFlag,
				    InitialUserName) of
	{ok, Packet} ->
	    %% 7.1.9c
	    %% Store in cache for Timeout msec.
	    NoteTimeout = discovery_note_timeout(Timeout),
	    ?vdebug("generate_discovery_msg -> 7.1.9c [~w]", [NoteTimeout]),
	    %% The request id is just in case when we receive a 
	    %% report with incorrect securityModel and/or securityLevel
	    Key  = {agent, MsgID}, 
	    Note = #note{sec_engine_id = ManagerEngineID, 
			 sec_model     = SecModel, 
			 sec_name      = SecName, 
			 sec_level     = SecLevelFlag,
			 ctx_engine_id = ContextEngineID, 
			 ctx_name      = ContextName, 
			 disco         = true, 
			 req_id        = Pdu#pdu.request_id},
	    snmp_note_store:set_note(NoteStore, Timeout, Key, Note),
	    %% Log(Packet),
	    inc_snmp_out_vars(Pdu),
	    ?vdebug("generate_discovery_msg -> done", []),
	    {Packet, {{A,B,C,D}, U1 bsl 8 + U2}};

	Error ->
	    throw(Error)
    end.

generate_sec_discovery_msg(Message, SecModule, 
			   SecEngineID, SecName, SecLevelFlag, 
			   InitialUserName) ->
    case (catch SecModule:generate_discovery_msg(Message, SecEngineID, 
						 SecName, SecLevelFlag,
						 InitialUserName)) of
	{'EXIT', Reason} ->
	    config_err("~p (message: ~p)", [Reason, Message]),
	    {discarded, Reason};
	{error, Reason} ->
	    config_err("~p (message: ~p)", [Reason, Message]),
	    {discarded, Reason};
	Bin when is_binary(Bin) ->
	    {ok, Bin};
	OutMsg when is_list(OutMsg) ->
	    case (catch list_to_binary(OutMsg)) of
		Bin when is_binary(Bin) ->
		    {ok, Bin};
		{'EXIT', Reason} ->
		    {error, Reason}
	    end
    end.
	
    
process_taddrs(Dests) ->
    ?vtrace("process_taddrs -> entry with"
	    "~n   Dests: ~p", [Dests]),
    process_taddrs(Dests, []).

process_taddrs([], Acc) ->
    ?vtrace("process_taddrs -> entry when done with"
	    "~n   Acc: ~p", [Acc]),
    lists:reverse(Acc);

%% v3
process_taddrs([{{?snmpUDPDomain, [A,B,C,D,U1,U2]}, SecData} | T], Acc) ->
    ?vtrace("process_taddrs -> entry when v3 with"
	    "~n   A:       ~p"
	    "~n   B:       ~p"
	    "~n   C:       ~p"
	    "~n   D:       ~p"
	    "~n   U1:      ~p"
	    "~n   U2:      ~p"
	    "~n   SecData: ~p", [A, B, C, D, U1, U2, SecData]),
    Entry = {{snmpUDPDomain, {{A,B,C,D}, U1 bsl 8 + U2}}, SecData}, 
    process_taddrs(T, [Entry | Acc]);
%% Bad v3
process_taddrs([{{TDomain, TAddr}, _SecData} | T], Acc) ->
    ?vtrace("process_taddrs -> entry when bad v3 with"
	    "~n   TDomain: ~p"
	    "~n   TAddr:   ~p", [TDomain, TAddr]),
    user_err("Bad TDomain/TAddr: ~w/~w", [TDomain, TAddr]),
    process_taddrs(T, Acc);
%% v1 & v2
process_taddrs([{?snmpUDPDomain, [A,B,C,D,U1,U2]} | T], Acc) ->
    ?vtrace("process_taddrs -> entry when v1/v2 with"
	    "~n   A:  ~p"
	    "~n   B:  ~p"
	    "~n   C:  ~p"
	    "~n   D:  ~p"
	    "~n   U1: ~p"
	    "~n   U2: ~p", [A, B, C, D, U1, U2]),
    Entry = {snmpUDPDomain, {{A,B,C,D}, U1 bsl 8 + U2}}, 
    process_taddrs(T, [Entry | Acc]);
%% Bad v1 or v2
process_taddrs([{TDomain, TAddr} | T], Acc) ->
    ?vtrace("process_taddrs -> entry when bad v1/v2 with"
	    "~n   TDomain: ~p"
	    "~n   TAddr:   ~p", [TDomain, TAddr]),
    user_err("Bad TDomain/TAddr: ~w/~w", [TDomain, TAddr]),
    process_taddrs(T, Acc);
process_taddrs(Crap, Acc) ->
    throw({error, {taddrs_crap, Crap, Acc}}).


mk_v1_v2_packet_list(To, Packet, Len, Pdu) ->
    mk_v1_v2_packet_list(To, Packet, Len, Pdu, []).

mk_v1_v2_packet_list([], _Packet, _Len, _Pdu, Acc) ->
    lists:reverse(Acc);

%% This (old) clause is for backward compatibillity reasons
%% If this is called, then the filter function is not used
mk_v1_v2_packet_list([{?snmpUDPDomain, [A,B,C,D,U1,U2]} | T],
		     Packet, Len, Pdu, Acc) ->
    %% Sending from default UDP port
    inc_snmp_out_vars(Pdu),
    Entry = {snmpUDPDomain, {{A,B,C,D}, U1 bsl 8 + U2}, Packet},
    mk_v1_v2_packet_list(T, Packet, Len, Pdu, [Entry | Acc]);

%% This is the new clause
%% This is only called if the actual target was accepted
%% (by the filter module)
mk_v1_v2_packet_list([{Domain, Addr} | T], 
		     Packet, Len, Pdu, Acc) ->
    %% Sending from default UDP port
    inc_snmp_out_vars(Pdu),
    Entry = {Domain, Addr, Packet},
    mk_v1_v2_packet_list(T, Packet, Len, Pdu, [Entry | Acc]).


get_max_message_size() ->
    snmp_framework_mib:get_engine_max_message_size().

mk_msg_flags(PduType, SecLevel) ->
    snmp_misc:mk_msg_flags(PduType, SecLevel).

mk_v3_packet_entry(NoteStore, Domain, Addr, 
		   {SecModel, SecName, SecLevel, TargetAddrName},
		   ScopedPDUBytes, Pdu, _ContextEngineID, ContextName,
		   LocalEngineID) ->
    %% rfc2272 7.1 step 77
    ?vtrace("mk_v3_packet_entry -> entry - RFC2272-7.1:7", []),
    MsgVersion  = 'version-3',                     % 7.1:7a
    MsgID       = generate_msg_id(),               % 7.1:7b
    MaxMsgSz    = get_max_message_size(),          % 7.1:7c
    PduType     = Pdu#pdu.type,      
    MsgFlags    = mk_msg_flags(PduType, SecLevel), % 7.1:7d
    MsgSecModel = SecModel,                        % 7.1:7e
    V3Hdr     = #v3_hdr{msgID            = MsgID,
			msgMaxSize       = MaxMsgSz, 
			msgFlags         = MsgFlags, 
			msgSecurityModel = MsgSecModel},
    Message   = #message{version = MsgVersion, 
			 vsn_hdr = V3Hdr,
			 data    = ScopedPDUBytes},
    SecModule = 
	case SecModel of
	    ?SEC_USM ->
		snmpa_usm
	end,

    %% 
    %% 7.1:8 - If the PDU is from the Response Class or the Internal Class
    %%         securityEngineID = snmpEngineID (local/source)
    %% 7.1:9 - If the PDU is from the Unconfirmed Class
    %%         securityEngineID = snmpEngineID (local/source)
    %%         else
    %%         securityEngineID = targetEngineID (remote/destination)
    %% 

    %% 7.1.9a
    ?vtrace("mk_v3_packet_entry -> sec engine id - 7.1.9a", []),
    SecEngineID =
	case PduType of
	    'snmpv2-trap' ->
		LocalEngineID; 
	    _ ->
		%% This is the implementation dependent target engine id
		%% procedure.
		case get_target_engine_id(TargetAddrName) of
		    {ok, discovery} ->  
			config_err("Discovery has not yet been performed for "
				   "snmpTargetAddrName ~p~n", 
				   [TargetAddrName]),
			throw({discarded, {discovery, TargetAddrName}});
		    {ok, TargetEngineId} ->
			?vtrace("TargetEngineId: ~p", [TargetEngineId]),
			TargetEngineId;
		    undefined ->
			config_err("Can't find engineID for "
				   "snmpTargetAddrName ~p~n",
				   [TargetAddrName]),
			"" % this will trigger error in secmodule
		end
	end,

    ?vdebug("mk_v3_packet_entry -> secEngineID: ~p", [SecEngineID]),
    %% 7.1.9b
    case (catch SecModule:generate_outgoing_msg(Message, SecEngineID,
						SecName, [], SecLevel,
						LocalEngineID)) of
	{'EXIT', Reason} ->
	    config_err("~p (message: ~p)", [Reason, Message]),
	    skip;
	{error, Reason} ->
	    ?vlog("~n   ~w error ~p\n", [SecModule, Reason]),
	    skip;
	OutMsg when is_list(OutMsg) ->
	    %% 7.1.9c
	    %% Store in cache for 150 sec.
	    Packet = list_to_binary(OutMsg),
	    ?vdebug("mk_v3_packet_entry -> generated: ~w bytes", 
		    [size(Packet)]),
	    Data = 
		if
		    SecLevel =:= 3 -> 
			%% encrypted - log decrypted pdu
			{Packet, {V3Hdr, ScopedPDUBytes}};
		    true -> 
			%% otherwise log the entire msg
			Packet
		end,
	    CacheKey = {agent, MsgID}, 
	    CacheVal = #note{sec_engine_id = SecEngineID, 
			     sec_model     = SecModel, 
			     sec_name      = SecName, 
			     sec_level     = SecLevel, 
			     ctx_engine_id = LocalEngineID, 
			     ctx_name      = ContextName,
			     disco         = false,
			     req_id        = Pdu#pdu.request_id},
	    snmp_note_store:set_note(NoteStore, 1500, CacheKey, CacheVal),
	    inc_snmp_out_vars(Pdu),
	    {ok, {Domain, Addr, Data}}
    end.


mk_v3_packet_list(NoteStore, To, 
		  ScopedPDUBytes, Pdu, ContextEngineID, ContextName, 
		  LocalEngineID) ->
    mk_v3_packet_list(NoteStore, To, 
		      ScopedPDUBytes, Pdu, 
		      ContextEngineID, ContextName, LocalEngineID, []).

mk_v3_packet_list(_, [], 
		  _ScopedPDUBytes, _Pdu, 
		  _ContextEngineID, _ContextName, 
		  _LocalEngineID, Acc) ->
    lists:reverse(Acc);

%% This clause is for backward compatibillity reasons
%% If this is called the filter function is not used
mk_v3_packet_list(NoteStore, 
		  [{{?snmpUDPDomain, [A,B,C,D,U1,U2]}, SecData} | T], 
		  ScopedPDUBytes, Pdu, ContextEngineID, ContextName, 
		  LocalEngineID, Acc) ->
    case mk_v3_packet_entry(NoteStore, 
			    snmpUDPDomain, {{A,B,C,D}, U1 bsl 8 + U2}, SecData,
			    ScopedPDUBytes, Pdu, 
			    ContextEngineID, ContextName, LocalEngineID) of
	skip ->
	    mk_v3_packet_list(NoteStore, T, 
			      ScopedPDUBytes, Pdu, 
			      ContextEngineID, ContextName, LocalEngineID, 
			      Acc);
	{ok, Entry} ->
	    mk_v3_packet_list(NoteStore, T, 
			      ScopedPDUBytes, Pdu, 
			      ContextEngineID, ContextName, LocalEngineID, 
			      [Entry | Acc])
    end;

%% This is the new clause
%% This is only called if the actual target was accepted
%% (by the filter module)
mk_v3_packet_list(NoteStore, 
		  [{{Domain, Addr}, SecData} | T], 
		  ScopedPDUBytes, Pdu, ContextEngineID, ContextName,
		  LocalEngineID, Acc) ->
    case mk_v3_packet_entry(NoteStore, 
			    Domain, Addr, SecData,
			    ScopedPDUBytes, Pdu, 
			    ContextEngineID, ContextName, LocalEngineID) of
	skip ->
	    mk_v3_packet_list(NoteStore, T, 
			      ScopedPDUBytes, Pdu, 
			      ContextEngineID, ContextName, Acc);
	{ok, Entry} ->
	    mk_v3_packet_list(NoteStore, T, 
			      ScopedPDUBytes, Pdu, 
			      ContextEngineID, ContextName, 
			      LocalEngineID, [Entry | Acc])
    end.


generate_msg_id() ->
    gen(msg_id).

generate_req_id() ->
    gen(req_id).

gen(Id) ->
    case ets:update_counter(snmp_agent_table, Id, 1) of
	N when N =< 2147483647 ->
	    N;
	_N ->
	    ets:insert(snmp_agent_table, {Id, 0}),
	    0
    end.


get_target_engine_id(TargetAddrName) ->
    snmp_target_mib:get_target_engine_id(TargetAddrName).

get_engine_max_message_size(_LocalEngineID) ->
    snmp_framework_mib:get_engine_max_message_size().

sec_module(?SEC_USM) ->
    snmpa_usm.


%%-----------------------------------------------------------------
%% Version(s) functions
%%-----------------------------------------------------------------
init_versions([], S) ->
    S;
init_versions([v1|Vsns], S) ->
    init_versions(Vsns, S#state{v1 = true});
init_versions([v2|Vsns], S) ->
    init_versions(Vsns, S#state{v2c = true});
init_versions([v3|Vsns], S) ->
    init_versions(Vsns, S#state{v3 = true}).


%%-----------------------------------------------------------------
%% Counter functions
%%-----------------------------------------------------------------
init_counters() -> 
    F = fun(Counter) -> maybe_create_counter(Counter) end,
    lists:map(F, counters()).

reset_counters() -> 
    F = fun(Counter) -> init_counter(Counter) end,
    lists:map(F, counters()).

maybe_create_counter(Counter) ->
    case ets:lookup(snmp_agent_table, Counter) of
	[_] -> ok;
	_ -> init_counter(Counter)
    end.

init_counter(Counter) -> 
    ets:insert(snmp_agent_table, {Counter, 0}).

counters() ->
    [
     snmpInPkts,
     snmpOutPkts,
     snmpInBadVersions,
     snmpInBadCommunityNames,
     snmpInBadCommunityUses,
     snmpInASNParseErrs,
     snmpInTooBigs,
     snmpInNoSuchNames,
     snmpInBadValues,
     snmpInReadOnlys,
     snmpInGenErrs,
     snmpInTotalReqVars,
     snmpInTotalSetVars,
     snmpInGetRequests,
     snmpInGetNexts,
     snmpInSetRequests,
     snmpInGetResponses,
     snmpInTraps,
     snmpOutTooBigs,
     snmpOutNoSuchNames,
     snmpOutBadValues,
     snmpOutGenErrs,
     snmpOutGetRequests,
     snmpOutGetNexts,
     snmpOutSetRequests,
     snmpOutGetResponses,
     snmpOutTraps,
     snmpSilentDrops,
     snmpProxyDrops,
     %% From SNMP-MPD-MIB
     snmpUnknownSecurityModels,
     snmpInvalidMsgs,
     snmpUnknownPDUHandlers
    ].
    


%%-----------------------------------------------------------------
%%  inc(VariableName) increments the variable (Counter) in
%%  the local mib. (e.g. snmpInPkts)
%%-----------------------------------------------------------------
inc(Name)    -> ets:update_counter(snmp_agent_table, Name, 1).
inc(Name, N) -> ets:update_counter(snmp_agent_table, Name, N).

inc_snmp_in_vars(#pdu{type = Type}) ->
    inc_in_type(Type).

inc_snmp_cnt_vars(_, #pdu{error_status = ErrStat}) when ErrStat =/= noError ->
    ok;
inc_snmp_cnt_vars('get-request', #pdu{varbinds = Vbs}) ->
    inc(snmpInTotalReqVars, length(Vbs));
inc_snmp_cnt_vars('get-next-request', #pdu{varbinds = Vbs}) ->
    inc(snmpInTotalReqVars, length(Vbs));
inc_snmp_cnt_vars('set-request', #pdu{varbinds = Vbs}) ->
    inc(snmpInTotalSetVars, length(Vbs));
inc_snmp_cnt_vars(_, _) ->
    ok.

inc_snmp_out_vars(#pdu{type         = Type, 
		       error_status = ErrorStatus}) ->
    inc(snmpOutPkts),
    inc_out_err(ErrorStatus),
    inc_out_vars_2(Type);
inc_snmp_out_vars(TrapPdu) when is_record(TrapPdu, trappdu) ->
    inc(snmpOutPkts),
    inc(snmpOutTraps).

inc_out_vars_2('get-response')     -> inc(snmpOutGetResponses);
inc_out_vars_2('get-request')      -> inc(snmpOutGetRequests);
inc_out_vars_2('get-next-request') -> inc(snmpOutGetNexts);
inc_out_vars_2('set-request')      -> inc(snmpOutSetRequests);
inc_out_vars_2(_)                  -> ok.

inc_out_err(genErr)     -> inc(snmpOutGenErrs);
inc_out_err(tooBig)     -> inc(snmpOutTooBigs);
inc_out_err(noSuchName) -> inc(snmpOutNoSuchNames);
inc_out_err(badValue)   -> inc(snmpOutBadValues);
% snmpOutReadOnlys is not used any more (rfc1213)
%inc_out_err(readOnly) -> inc(snmpOutReadOnlys);
inc_out_err(_)          -> ok.

inc_in_type('get-request')      -> inc(snmpInGetRequests);
inc_in_type('get-next-request') -> inc(snmpInGetNexts);
inc_in_type('set-request')      -> inc(snmpInSetRequests);
inc_in_type(_)                  -> ok.


user_err(F, A) ->
    snmpa_error:user_err(F, A).

config_err(F, A) ->
    snmpa_error:config_err(F, A).