summaryrefslogtreecommitdiff
path: root/lib/snmp/src/agent/snmpa_net_if.erl
blob: 72e3ac3e41b0ef7099303db7ddae1d84bc458c47 (plain)
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
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
%%
%% %CopyrightBegin%
%% 
%% Copyright Ericsson AB 2004-2023. All Rights Reserved.
%% 
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%% 
%% %CopyrightEnd%
%%
-module(snmpa_net_if).

-behaviour(snmpa_network_interface).

-export([start_link/4,
	 info/1, 
	 verbosity/2]).
-export([get_log_type/1,  set_log_type/2]).
-export([get_request_limit/1, set_request_limit/2]).
-export([system_continue/3, system_terminate/4, system_code_change/4]).
-export([init/5]).
-export([filter_reset/1]).

-include("snmp_types.hrl").
-include("snmpa_internal.hrl").
-include("snmpa_atl.hrl").
-include("snmp_debug.hrl").
-include("snmp_verbosity.hrl").


%% Regarding Trap/Notification transport(s),
%% it *should* be possible to specify either:
%% 1) A fixed set of transport(s) used for sending.
%%    For instance, one for IPv4 and one for IPv6.
%% 2) A single one-shot ephemeral port.
%%    That is, a port is created, used once, and then closed.
%% 3) A pool of ephemeral ports, used for "a time"
%%    (a configurable number of sends, a set number of bytes
%%     or time based) thar is cycled through.
%% Though, we do *not* currently implement ephemeral sockets,
%% so case 2 and 3 are not possible at the moment.

%% Also, the request-reponder and trap-sender transport(s),
%% has different needs.
%% The trap-sender transport will send more data then it will receive.
%% Therefore, we should be able to specify;
%% bind_to, no_reuse_address, recbuf and sndbuf individually:
%% {intAgentTransports,
%%  [{transportDomainUdpIpv4, {{141,213,11,24},   PortInfo},
%%    req_responder, Opts},
%%   {transportDomainUdpIpv4, {{141,213,11,24},   PortInfo},
%%    trap_sender,   Opts},
%%   {transportDomainUdpIpv6, {{0,0,0,0,0,0,0,1}, Portinfo},
%%    req_responder, Opts},
%%   {transportDomainUdpIpv6, {{0,0,0,0,0,0,0,1}, Portinfo},
%%    trap_sender,   Opts}]}.
%% Opts is basically "socket options" for this transport (the same
%% options as for net-if).
%% Also, always give the option to provide a port range:
%%    Port     :: pos_integer() | system | range() || ranges()
%%                system => Let the system choose
%%                (0 is unfortunately already used as 'default',
%%                 so we can't use that for 'system').
%%    range()  :: {Min :: pos_integer(), Max :: pos_integer()} when Min < Max
%%    ranges() :: [pos_integer() | range()]
%%                Examples:
%%                      [{2000, 2004}]
%%                      [2000, 2001, 2002, 2003, 2004]
%%                      [2000, 2001, {2002, 2004}]
%%                      [{5000, 5100}, {6000, 6100}]

%% <EPHEMERAL-FOR-FUTUR-USE>
%% , *but*
%% may also contain the tuple, {ephemeral, EphmOpts}.
%% Ephm sockets are created on the fly, used for the specified
%% time (number of sends, number of bytes sent, used time, ...).
%% </EPHEMERAL-FOR-FUTUR-USE>

-record(state,
	{parent,
	 note_store,
	 master_agent,
	 transports  = [],
	 mpd_state,
	 log,
	 reqs  = [],
	 debug = false,
	 limit = infinity,
	 filter}).

-type transport_kind() :: req_responder | trap_sender.
-type port_info() :: non_neg_integer() |
                     system |
                     {pos_integer(), pos_integer()}.

%% <EPHEMERAL-FOR-FUTUR-USE>
%% How would 'ephemeral' effect this?
%% What kind of usage would we have for emphemeral ports?
%%    once (send and maybe receive reply (inform)) |
%%    {sends, pos_integer()} (number of sends) |
%%    {data,  pos_integer()} (number of bytes sent) |
%%    {alive_time, pos_integer()} (once used for the first time, alive time)
%% You can't combine a ephemeral info with a fixed port (pos_integer())
%% The port_info() is used when creating a port, even an ephemeral port.
%% But it must either be 'system' or a range in that (ephemeral) case.
%% Also, ephemeral transports are only allowed if kind = trap_sender
%% -type ephemeral() :: none |
%%                      once |
%%                      {sends,      pos_integer()} |
%%                      {data,       pos_integer()} |
%%                      {alive_time, pos_integer()}.

%% Note that since informs require confirmation,
%% an ephemeral socket cannot be removed immediately
%% when it has been "used up".
%% We need to keep it for some time to receive responses
%% and in case a resend is needed!.
%% </EPHEMERAL-FOR-FUTUR-USE>

-record(transport,
	{socket,
         mref,
         kind         = all :: all | transport_kind(),
	 domain       = snmpUDPDomain,
         address   :: inet:ip_address(),
         port_no   :: pos_integer(),
         port_info :: port_info(),
         %% <EPHEMERAL-FOR-FUTUR-USE>
         ephm         = none, %%  :: ephemeral(),
         ephm_info    = undefined, % Only used if ephm =/= none and once
         %% </EPHEMERAL-FOR-FUTUR-USE>
         inet_backend = [],
	 opts         = [],
	 req_refs     = [] % Not used for trap/notification transports
        }).

-ifndef(default_verbosity).
-define(default_verbosity,silence).
-endif.

-define(DEFAULT_FILTER_MODULE, snmpa_net_if_filter).
-define(DEFAULT_FILTER_OPTS,   [{module, ?DEFAULT_FILTER_MODULE}]).

-define(ATL_SEQNO_INITIAL, 1).
-define(ATL_SEQNO_MAX,     2147483647).


%%%-----------------------------------------------------------------
%%% This module implements the default Network Interface part
%%% of the SNMP agent. It uses UDP, and read the agent.conf to find
%%% the UDP port.
%%%
%%% Opts = [Opt]
%%% Opt  = {verbosity,silence | log | debug} | 
%%%        {bind_to, bool()} |
%%%        {recbuf,integer()} |
%%%        {no_reuse, bool()} |
%%%        {req_limit, integer() | infinity}
%%%-----------------------------------------------------------------
start_link(Prio, NoteStore, MasterAgent, Opts) ->
    ?d("start_link -> entry with"
	"~n   Prio:        ~p"
	"~n   NoteStore:   ~p"
	"~n   MasterAgent: ~p"
	"~n   Opts:        ~p", [Prio, NoteStore, MasterAgent, Opts]),
    Args = [Prio, NoteStore, MasterAgent, self(), Opts],
    proc_lib:start_link(?MODULE, init, Args).

    
info(Pid) ->
    case call(Pid, info) of
	Info when is_list(Info) ->
	    Info;
	_ ->
	    []
    end.

verbosity(Pid, Verbosity) -> 
    Pid ! {verbosity, Verbosity}.

get_log_type(Pid) ->
    call(Pid, get_log_type).

set_log_type(Pid, NewType) ->
    call(Pid, {set_log_type, NewType}).

get_request_limit(Pid) ->
    call(Pid, get_request_limit).

set_request_limit(Pid, NewLimit) ->
    call(Pid, {set_request_limit, NewLimit}).

get_transports() ->
    {value, Transports} = snmp_framework_mib:intAgentTransports(get),
    Transports.

filter_reset(Pid) ->
    Pid ! filter_reset.


%%-----------------------------------------------------------------
%%-----------------------------------------------------------------

init(Prio, NoteStore, MasterAgent, Parent, Opts) ->
    ?d("init -> entry with"
      "~n   Prio:        ~p"
      "~n   NoteStore:   ~p"
      "~n   MasterAgent: ~p"
      "~n   Parent:      ~p"
      "~n   Opts:        ~p", [Prio, NoteStore, MasterAgent, Parent, Opts]),
    case (catch do_init(Prio, NoteStore, MasterAgent, Parent, Opts)) of
	{ok, State} ->
	    proc_lib:init_ack({ok, self()}),
	    try loop(State)
	    catch
		C:E:S when C =/= exit, E =/= shutdown ->
		    Fmt =
			"loop/1 EXCEPTION ~w:~w~n"
			"   ~p",
		    case C of
			exit ->
			    %% Externally killed, root cause is elsewhere
			    info_msg(Fmt, [C, E, S]);
			_ ->
			    error_msg(Fmt, [C, E, S])
		    end,
		    erlang:raise(C, E, S)
	    end;
	{error, {udp_open, {open, PortNo, Reason}}} ->
            OEFilters = get_open_err_filters(Opts),
            Class =
                case lists:member(Reason, OEFilters) of
                    false ->
                        error;
                    true ->
                        info
            end,
            proc_lib:init_ack({error, {Class, udp_open, PortNo, Reason}});
        {error, Reason} ->
            %% config_err("failed starting net-if: ~n~p", [Reason]),
            proc_lib:init_ack({error, Reason});
	Error ->
	    %% config_err("failed starting net-if: ~n~p", [Error]),
	    proc_lib:init_ack({error, Error})
    end.

do_init(Prio, NoteStore, MasterAgent, Parent, Opts) ->
    process_flag(trap_exit, true),
    process_flag(priority,  Prio),

    %% -- Verbosity --
    put(sname,     nif),
    put(verbosity, get_verbosity(Opts)),
    ?vlog("starting",[]),

    %% -- Versions --
    Vsns = get_vsns(Opts),
    ?vdebug("vsns: ~w",[Vsns]),

    %% -- Flow control --
    Limit      = get_req_limit(Opts),
    ?vdebug("Limit: ~w", [Limit]),
    FilterOpts = get_filter_opts(Opts),
    FilterMod  = create_filter(FilterOpts),
    ?vdebug("FilterMod: ~w FilterOpts: ~p", [FilterMod,FilterOpts]),

    %% -- Audit trail log
    Log = create_log(),
    ?vdebug("Log: ~w",[Log]),

    RawTransports = get_transports(),
    ?vdebug("Raw Transports: "
            "~n   ~p", [RawTransports]),
    try
	[begin
             %% Any socket option not explicitly configured for the transport
             %% will be taken from the "global" socket options (which serve as
             %% default values).
             %% Also, note that Ephm are not actually used at this time.
	     {Ephm, IpAddr, PortInfo, InetBackend, SocketOpts} =
                 socket_opts(Domain, Address, RawSocketOpts, Opts),
             ?vtrace("socket opts processed:"
                     "~n      Ephm:         ~p"
                     "~n      Port Info:    ~p"
                     "~n      Inet Backend: ~p"
                     "~n      Socket Opts:  ~p",
                     [Ephm, PortInfo, InetBackend, SocketOpts]),
	     {Socket, IpPort}             = socket_open(Domain, PortInfo,
                                                        InetBackend,
                                                        SocketOpts),
             SockMRef = inet:monitor(Socket),
             ?vtrace("socket opened:"
                     "~n      Socket:   ~p"
                     "~n      Port No:  ~p"
                     "~n      Info:     ~p",
                     [Socket, IpPort, inet:info(Socket)]),

             %% Should we really do this here?
             %% If Kind =:= trap_sender, we only need to receive after 
             %% we have sent an inform!
	     active_once(Socket),
             ?vtrace("socket activated:"
                     "~n      Info: ~p", [inet:info(Socket)]),
	     #transport{
                socket       = Socket,
                mref         = SockMRef,
                kind         = Kind,
                domain       = Domain,
                %% We may not have explicitly specified the port ('system'
                %% or a range), so it could have been "generated".
                %% Also, shall we push this into the transport (handled by the
                %% FRAMEWORK MIB)? Would not work for ephemeral sockets.
                address      = IpAddr,
                port_no      = IpPort,
                port_info    = PortInfo,
                ephm         = Ephm,
                inet_backend = InetBackend,
                opts         = SocketOpts}
             %% We need to fix this also
	 end || {Domain, Address, Kind, RawSocketOpts} <- RawTransports]
    of
	[] ->
	    ?vinfo("No transports configured: ~p", [RawTransports]),
	    {error, {no_transports, RawTransports}};
	Transports ->
	    MpdState = snmpa_mpd:init(Vsns),
	    init_counters(),
	    S = #state{parent       = Parent,
		       note_store   = NoteStore,
		       master_agent = MasterAgent, 
		       mpd_state    = MpdState,
		       transports   = Transports,
		       log          = Log,
		       limit        = Limit,
		       filter       = FilterMod},
	    ?vdebug("started with MpdState: ~p", [MpdState]),
	    {ok, S}
    catch
	Error ->
	    ?vinfo("Failed to initialize socket(s): ~p", [Error]),
	    {error, Error}
    end.


create_log() ->
    case ets:lookup(snmp_agent_table, audit_trail_log) of
	[] ->
	    {undefined, []};
	[{audit_trail_log, AtlOpts}] ->
	    ?vtrace("AtlOpts: ~p", [AtlOpts]),
	    Type   = get_atl_type(AtlOpts),
	    Dir    = get_atl_dir(AtlOpts),
	    Size   = get_atl_size(AtlOpts),
	    Repair = get_atl_repair(AtlOpts),
	    Name   = ?audit_trail_log_name,
	    File   = filename:absname(?audit_trail_log_file, Dir),
	    case get_atl_seqno(AtlOpts) of
		true ->
		    Initial  = ?ATL_SEQNO_INITIAL,
		    Max      = ?ATL_SEQNO_MAX, 
		    Module   = snmpa_agent, 
		    Function = increment_counter, 
		    Args     = [atl_seqno, Initial, Max], 
		    SeqNoGen = {Module, Function, Args}, 
		    case snmp_log:create(Name, File, 
					 SeqNoGen, Size, Repair, true) of
			{ok, Log} ->
			    ?vdebug("log created: ~w", [Log]),
			    {Log, Type};
			{error, Reason} ->
			    throw({error, {create_log, Reason}})
		    end;
		_ ->
		    case snmp_log:create(Name, File, Size, Repair, true) of
			{ok, Log} ->
			    ?vdebug("log created: ~w", [Log]),
			    {Log, Type};
			{error, Reason} ->
			    throw({error, {create_log, Reason}})
		    end
	    end
    end.


create_filter(Opts) when is_list(Opts) ->
    case get_filter_module(Opts) of
	?DEFAULT_FILTER_MODULE = Mod ->
	    Mod;
	Module ->
	    snmpa_network_interface_filter:verify(Module),
	    Module
    end;
create_filter(BadOpts) ->
    throw({error, {bad_filter_opts, BadOpts}}).


log({_, []}, _, _, _) ->
    ok;
log({Log, Types}, 'set-request', Packet, Address) ->
    case lists:member(write, Types) of
	true ->
	    snmp_log:log(Log, Packet, format_address(Address));
	false ->
	    ok
    end;
log({Log, Types}, _, Packet, Address) ->
     case lists:member(read, Types) of
	true ->
	    snmp_log:log(Log, Packet, format_address(Address));
	false ->
	    ok
    end.

format_address(Address) ->
    iolist_to_binary(snmp_conf:mk_addr_string(Address)).


socket_open(snmpUDPDomain = Domain, IpPort, InetBackend, Opts) ->
    ?vdebug("socket_open(~p) -> entry with"
            "~n   Port: ~p"
            "~n   Opts: ~p", [Domain, IpPort, Opts]),
    case init:get_argument(snmp_fd) of
	{ok, [[FdStr]]} ->
	    FD = list_to_integer(FdStr),
	    ?vdebug("socket_open(~p) -> open with fd - "
                    "(old) snmp_fd command line argument provided: "
                    "~n   FD:   ~p"
                    "~n   Port: ~p"
                    "~n   Opts: ~p", [Domain, FD, IpPort, Opts]),
	    gen_udp_open(0, InetBackend ++ [{fd, FD} | Opts]);
	error ->
	    case init:get_argument(snmpa_fd) of
		{ok, [[FdStr]]} ->
		    FD = list_to_integer(FdStr),
                    ?vdebug("socket_open(~p) -> open with fd - "
                            "snmpa_fd command line argument provided: "
                            "~n   FD:   ~p"
                            "~n   Port: ~p"
                            "~n   Opts: ~p", [Domain, FD, IpPort, Opts]),
		    gen_udp_open(0, InetBackend ++ [{fd, FD} | Opts]);
		error ->
		    ?vdebug("socket_open(~p) -> plain open"
                            "~n   Port: ~p"
                            "~n   Opts: ~p", [Domain, IpPort, Opts]),
		    gen_udp_open(IpPort, InetBackend ++ Opts)
	    end
    end;
socket_open(Domain, PortInfo, InetBackend, Opts)
  when (Domain =:= transportDomainUdpIpv4) orelse
       (Domain =:= transportDomainUdpIpv6) ->
    ?vdebug("socket_open(~p) -> entry with"
            "~n      PortInfo:    ~p"
            "~n      InetBackend: ~p"
            "~n      Opts:        ~p", [Domain, PortInfo, InetBackend, Opts]),
    gen_udp_open(PortInfo, InetBackend ++ Opts);
socket_open(Domain, PortInfo, InetBackend, Opts) ->
    ?vinfo("socket_open(~p) -> entry when invalid with"
           "~n   PortInfo:    ~p"
           "~n   InetBackend: ~p"
           "~n   Opts:        ~p", [Domain, PortInfo, InetBackend, Opts]),
    throw({socket_open, Domain, InetBackend, Opts}).


%% Make the system choose!
gen_udp_open(system, Opts) ->
    ?vtrace("gen_udp_open(system) -> entry"),
    case gen_udp:open(0, Opts) of
	{ok, Socket} ->
            case inet:port(Socket) of
                {ok, PortNo} ->
                    ?vtrace("gen_udp_open(system) -> created: "
                            "~n      ~p (~w)", [Socket, PortNo]),
                    {Socket, PortNo};
                {error, PReason} ->
                    (catch gen_udp:close(Socket)),
                    throw({udp_open, {port, PReason}})
            end;
	{error, OReason} ->
            throw({udp_open, {open, 0, OReason}})
    end;
%% This is for "future compat" since we cannot actually config '0'...
gen_udp_open(IpPort, Opts) when (IpPort =:= 0) ->
    ?vtrace("gen_udp_open(0) -> entry with"
            "~n   Opts: ~p", [Opts]),
    case gen_udp:open(IpPort, Opts) of
	{ok, Socket} ->
            case inet:port(Socket) of
                {ok, PortNo} ->
                    ?vtrace("gen_udp_open(0) -> created: "
                            "~n      ~p (~w)", [Socket, PortNo]),
                    {Socket, PortNo};
                {error, PReason} ->
                    (catch gen_udp:close(Socket)),
                    throw({udp_open, {port, PReason}})
            end;
	{error, Reason} ->
	    throw({udp_open, {open, IpPort, Reason}})
    end;
gen_udp_open(IpPort, Opts) when is_integer(IpPort) ->
    ?vtrace("gen_udp_open(~w) -> entry with"
            "~n   Opts: ~p", [IpPort, Opts]),
    case gen_udp:open(IpPort, Opts) of
	{ok, Socket} ->
            ?vtrace("gen_udp_open(~w) -> created: "
                    "~n      ~p", [Socket]),
	    {Socket, IpPort};
	{error, Reason} ->
	    throw({udp_open, {open, IpPort, Reason}})
    end;
%% A range is "pointless" if we allow reuseaddr...
%% ...but we leave that to the user...
gen_udp_open({Min, Max}, Opts) ->
    ?vtrace("gen_udp_open(~w,~w) -> entry", [Min, Max]),
    gen_udp_range_open(Min, Max, Opts);
%% A range is "pointless" if we allow reuseaddr...
%% ...but we leave that to the user...
gen_udp_open(Ranges, Opts) when is_list(Ranges) ->
    gen_udp_ranges_open(Ranges, Opts).

gen_udp_range_open(Min, Max, _Opts) when (Min > Max) ->
    ?vinfo("gen_udp_range_open -> entry when no available ports"),
    throw({udp_open, no_available_ports});
gen_udp_range_open(Min, Max, Opts) ->
    ?vtrace("gen_udp_range_open -> entry with"
            "~n      Min: ~w"
            "~n      Max: ~w", [Min, Max]),
    try gen_udp:open(Min, Opts) of
        {ok, Socket} ->
            ?vtrace("gen_udp_range_open(~w,~w) -> created: "
                    "~n      ~p", [Min, Max, Socket]),
            {Socket, Min};
        {error, eaddrinuse} ->
            ?vdebug("gen_udp_range_open(~w,~w) -> eaddrinuse"),
            gen_udp_range_open(Min+1, Max, Opts);
        {error, Reason} ->
            ?vdebug("gen_udp_range_open(~w,~w) -> ~w", [Reason]),
            throw({udp_open, {open, Min, Reason}})
    catch
        C:E:S ->
            ?vinfo("gen_udp_range_open(~w,~w) -> failed open socket: "
                   "~n      C: ~p"
                   "~n      E: ~p"
                   "~n      S: ~p", [Min, Max, C, E, S]),
            erlang:raise(C, E, S)
    end.

gen_udp_ranges_open([], _Opts) ->
    ?vinfo("gen_udp_ranges_open -> entry when no available ports"),
    throw({udp_open, no_available_ports});
gen_udp_ranges_open([PortNo|Ranges], Opts) when is_integer(PortNo) andalso
                                                (PortNo > 0) ->
    ?vtrace("gen_udp_ranges_open(~w) -> entry", [PortNo]),
    try gen_udp_open(PortNo, Opts) of
        {_Sock, PortNo} = SUCCESS when is_integer(PortNo) ->
            SUCCESS
    catch
        throw:{udp_open, _} ->
            gen_udp_ranges_open(Ranges, Opts)
    end;
gen_udp_ranges_open([{Min, Max}|Ranges], Opts) ->
    ?vtrace("gen_udp_ranges_open(~w,~w) -> entry", [Min, Max]),
    try gen_udp_range_open(Min, Max, Opts) of
        {_Sock, PortNo} = SUCCESS when is_integer(PortNo) ->
            SUCCESS
    catch
        throw:{udp_open, _} ->
            gen_udp_ranges_open(Ranges, Opts)
    end.


loop(#state{transports = Transports,
            limit      = Limit,
            parent     = Parent} = S) ->
    ?vdebug("loop(~p)", [S]),
    receive
        {udp, Socket, IpAddr, IpPort, Packet} = Msg ->
	    ?vlog("got packet from ~w:~w on ~w", [IpAddr, IpPort, Socket]),
	    case lists:keyfind(Socket, #transport.socket, Transports) of
		#transport{socket = Socket, domain = Domain} = Transport ->
		    From =
			case Domain of
			    snmpUDPDomain ->
				{IpAddr, IpPort};
			    _ ->
				{Domain, {IpAddr, IpPort}}
			end,
		    loop(maybe_handle_recv(S, Transport, From, Packet));
		false ->
		    error_msg("Packet on unknown socket: "
                              "~n   ~p", [Msg]),
		    loop(S)
	    end;

	{udp_error, Socket, Error} ->
	    ?vinfo("got udp-error on ~p: ~w", [Socket, Error]),
	    case lists:keyfind(Socket, #transport.socket, Transports) of
		#transport{socket = Socket} = Transport ->
		    loop(handle_udp_error(S, Transport, Error));
		false ->
		    loop(handle_udp_error_unknown(S, Socket, Error))
	    end;

	{info, ReplyRef, Pid} ->
	    Info = get_info(S),
	    Pid ! {ReplyRef, Info, self()},
	    loop(S);

	%% response (to get/get_next/get_bulk/set requests)
	{snmp_response, Vsn, RePdu, Type, ACMData, To, Extra} ->
	    ?vlog("reply pdu: "
		  "~n   ~s", 
		  [?vapply(snmp_misc, format, [256, "~w", [RePdu]])]),
	    {_, ReqRef} = lists:keyfind(request_ref, 1, Extra),
	    case
		case
		    (Limit =/= infinity) andalso
		    select_transport(ReqRef, Transports)
		of
		    false ->
			select_transport(address_to_domain(To), Type,
                                         Transports);
		    T ->
			T
		end
	    of
		false ->
		    error_msg(
		      "Can not find transport for response PDU to: ~s",
		      [format_address(To)]),
		    loop(S);
		Transport ->
		    NewS = update_req_counter_outgoing(S, Transport, ReqRef),
		    maybe_handle_reply_pdu(
		      NewS, Transport, Vsn, RePdu, Type, ACMData, To),
		    loop(NewS)
	    end;

	%% Traps/notification
	{send_pdu, Vsn, Pdu, MsgData, TDomAddrs} ->
	    ?vdebug("send pdu:~n"
		    "   Pdu:       ~p~n"
		    "   TDomAddrs: ~p", [Pdu, TDomAddrs]),
	    NewS =
		maybe_handle_send_pdu(
		  S, Vsn, Pdu, MsgData, TDomAddrs, undefined),
	    loop(NewS);

	%% We dont use the extra-info at this time, ...
	{send_pdu, Vsn, Pdu, MsgData, TDomAddrs, _ExtraInfo} ->
	    ?vdebug("send pdu:~n"
		    "   Pdu:        ~p~n"
		    "   TDomAddrs: ~p", [Pdu, TDomAddrs]),
	    NewS =
		maybe_handle_send_pdu(
		  S, Vsn, Pdu, MsgData, TDomAddrs, undefined),
	    loop(NewS);

	%% Informs
	{send_pdu_req, Vsn, Pdu, MsgData, TDomAddrs, From} ->
	    ?vdebug("send pdu request:~n"
		    "   Pdu:       ~p~n"
		    "   TDomAddrs: ~p~n"
		    "   From:      ~p",
		    [Pdu, TDomAddrs, toname(From)]),
	    NewS =
		maybe_handle_send_pdu(
		  S, Vsn, Pdu, MsgData, TDomAddrs, From),
	    loop(NewS);

	%% We dont use the extra-info at this time, ...
	{send_pdu_req, Vsn, Pdu, MsgData, TDomAddrs, From, _ExtraInfo} ->
	    ?vdebug("send pdu request:~n"
		    "   Pdu:       ~p~n"
		    "   TDomAddrs: ~p~n"
		    "   From:      ~p",
		    [Pdu, TDomAddrs, toname(From)]),
	    NewS =
		maybe_handle_send_pdu(
		  S, Vsn, Pdu, MsgData, TDomAddrs, From),
	    loop(NewS);

	%% Discovery Inform
	{send_discovery, Pdu, MsgData, To, From, ExtraInfo} ->
	    ?vdebug("received send discovery request: "
		    "~n   Pdu:       ~p"
		    "~n   To:        ~p"
		    "~n   From:      ~p"
		    "~n   ExtraInfo: ~p", 
		    [Pdu, To, toname(From), ExtraInfo]),
	    NewS = handle_send_discovery(S, Pdu, MsgData, To, From),
	    loop(NewS);

	{discarded_pdu, _Vsn, ReqId, _ACMData, Variable, Extra} ->
	    ?vdebug("discard PDU: ~p - ~p - ~p",
		    [Variable, Extra, Transports]),
	    snmpa_mpd:discarded_pdu(Variable),
	    {_, ReqRef} = lists:keyfind(request_ref, 1, Extra),
	    if
		Limit =:= infinity ->
		    %% The incoming PDU was not registered
		    loop(update_req_counter_outgoing(S, false, ReqRef));
		true ->
		    case
			select_transport(ReqRef, Transports)
		    of
			false ->
			    error_msg(
			      "Can not find transport for discarded PDU: ~p",
			      [ReqId]),
			    loop(S);
			Transport ->
			    loop(
			      update_req_counter_outgoing(
				S, Transport, ReqRef))
		    end
	    end;

	{get_log_type, ReplyRef, Pid} ->
	    ?vdebug("get log type: ~p", []),
	    {_, LogType} = S#state.log,
	    Pid ! {ReplyRef, {ok, LogType}, self()},
	    loop(S);

	{{set_log_type, NewType}, ReplyRef, Pid} ->
	    ?vdebug("set log type: ~p", [NewType]),
	    {NewState, Reply} = (catch handle_set_log_type(S, NewType)),
	    Pid ! {ReplyRef, Reply, self()},
	    loop(NewState);

	{get_request_limit, ReplyRef, Pid} ->
	    ?vdebug("get request limit: ~p", []),
	    Pid ! {ReplyRef, {ok, Limit}, self()},
	    loop(S);

	{{set_request_limit, NewLimit}, ReplyRef, Pid} ->
	    ?vdebug("set request limit: ~p", [NewLimit]),
	    {NewState, Reply} = (catch handle_set_request_limit(S, NewLimit)),
	    Pid ! {ReplyRef, Reply, self()},
	    loop(NewState);

	{disk_log, _Node, Log, Info} ->
	    ?vdebug("disk log event: ~p, ~p", [Log, Info]),
	    NewS = handle_disk_log(Log, Info, S),
	    loop(NewS);

	{verbosity, Verbosity} ->
	    ?vlog("verbosity: ~p -> ~p", [get(verbosity), Verbosity]),
	    put(verbosity, snmp_verbosity:validate(Verbosity)),
	    loop(S);

	filter_reset ->
	    reset_counters(),
	    loop(S);

	{'EXIT', Parent, Reason} ->
	    ?vlog("parent (~p) exited: "
		  "~n   ~p", [Parent, Reason]),
	    exit(Reason);

        {'DOWN', _SockMRef, Type, Socket, Reason} when (Type =:= port) orelse
                                                       (Type =:= socket) ->
	    case lists:keyfind(Socket, #transport.socket, Transports) of
		#transport{
                   socket       = Socket,
                   domain       = Domain,
                   port_info    = PortInfo,
                   inet_backend = InetBackend,
                   opts         = SocketOpts,
                   req_refs     = ReqRefs} = Transport ->
		    try socket_open(Domain, PortInfo, InetBackend, SocketOpts) of
			{NewSocket, PortNo} ->
			    error_msg(
			      "Socket ~p exited for reason"
			      "~n     ~p"
			      "~n     Re-opened (~p, ~w)",
			      [Socket, Reason, NewSocket, PortNo]),
			    (length(ReqRefs) < Limit) andalso
				active_once(NewSocket),
                            NewSockMRef = inet:monitor(NewSocket),
			    S#state{
			      transports =
				  lists:keyreplace(
				    Socket, #transport.socket, Transports,
				    Transport#transport{socket  = NewSocket,
                                                        mref    = NewSockMRef,
                                                        port_no = PortNo})}
		    catch
			ReopenReason ->
			    error_msg(
			      "Socket ~p exited for reason"
			      "~n     ~p"
			      "~n     Re-open failed with reason"
			      "~n     ~p",
			      [Socket, Reason, ReopenReason]),
			    exit(ReopenReason)
		    end;
		false ->
		    error_msg(
		      "Exit message from socket ~p for reason ~p~n",
		      [Socket, Reason]),
		    loop(S)
	    end;

	{'EXIT', Pid, Reason} when is_pid(Pid) ->
	    ?vlog("~p exited: "
		  "~n   ~p", [Pid, Reason]),
	    NewS = clear_reqs(Pid, S),
	    loop(NewS);

	{system, From, Msg} ->
	    ?vdebug("system event ~p from ~p", [Msg, From]),
	    sys:handle_system_msg(Msg, From, Parent, ?MODULE, [], S);

	_ ->
	    loop(S)
    end.

handle_udp_error(S, #transport{socket = Socket,
                               kind   = Kind}, Error) ->
    try inet:sockname(Socket) of
        {ok, {IP, Port}} ->
            error_msg("UDP Error for transport: "
                      "~n      Socket: ~p (~p, ~p)"
                      "~n      Kind:   ~p"
                      "~n      Error:  ~p", [Socket, IP, Port, Kind, Error]);
        {error, _} ->
            error_msg("UDP Error for transport: "
                      "~n      Socket: ~p"
                      "~n      Kind:   ~p"
                      "~n      Error:  ~p", [Socket, Kind, Error])
    catch
        _:_:_ ->
            error_msg("UDP Error for transport: "
                      "~n      Socket: ~p"
                      "~n      Kind:   ~p"
                      "~n      Error:  ~p", [Socket, Kind, Error])
    end,
    S.

handle_udp_error_unknown(S, Socket, Error) ->
    try inet:sockname(Socket) of
        {ok, {IP, Port}} ->
            warning_msg("UDP Error for unknown transport: "
                        "~n      Socket: ~p (~p, ~p)"
                        "~n      Error:  ~p", [Socket, IP, Port, Error]);
        {error, _} ->
            warning_msg("UDP Error for unknown transport: "
                        "~n      Socket: ~p"
                        "~n      Error:  ~p", [Socket, Error])
    catch
        _:_:_ ->
            warning_msg("UDP Error for transport: "
                        "~n      Socket: ~p"
                        "~n      Error:  ~p", [Socket, Error])
    end,
    S.


update_req_counter_incoming(
  #state{limit = infinity} = S,
  #transport{socket = Socket},
  _ReqRef) ->
    active_once(Socket), %% No limit so activate directly
    S; 
update_req_counter_incoming(
  #state{limit = Limit} = S,
  #transport{socket = Socket, req_refs = ReqRefs} = T,
  ReqRef) when length(ReqRefs) + 1 >= Limit ->
    %% Ok, one more and we are at the limit.
    %% Just make sure we are not already processing this one...
    case lists:member(ReqRef, ReqRefs) of
	false ->
	    %% We are at the limit, do _not_ activate socket
	    update_transport_req_refs(S, T, [ReqRef | ReqRefs]);
	true ->
	    active_once(Socket),
	    S
    end;
update_req_counter_incoming(
  #state{} = S,
  #transport{socket = Socket, req_refs = ReqRefs} = T,
  ReqRef) ->
    active_once(Socket),
    case lists:member(ReqRef, ReqRefs) of
	false ->
	    update_transport_req_refs(S, T, [ReqRef | ReqRefs]);
	true ->
	    S
    end.

update_req_counter_outgoing(
  #state{limit = infinity} = S,
  _Transport, _ReqRef) ->
    %% Already activated (in the incoming function)
    S;
update_req_counter_outgoing(
  #state{limit = Limit} = S,
  #transport{socket = Socket, req_refs = ReqRefs} = Transport,
  ReqRef) ->
    LengthReqRefs = length(ReqRefs),
    ?vtrace("update_req_counter_outgoing() -> entry with~n"
	    "   Limit:           ~w~n"
	    "   ReqRef:          ~w~n"
	    "   length(ReqRefs): ~w", [Limit, ReqRef, LengthReqRefs]),
    NewReqRefs = lists:delete(ReqRef, ReqRefs),
    (LengthReqRefs >= Limit) andalso (length(NewReqRefs) < Limit) andalso
	begin
	    ?vtrace("update_req_counter_outgoing -> "
		    "passed below limit: activate", []),
	    active_once(Socket)
	end,
    update_transport_req_refs(S, Transport, NewReqRefs).

update_transport_req_refs(
  #state{transports = Transports} = S,
  #transport{socket = Socket} = T,
  ReqRefs) ->
    S#state{
      transports =
	  lists:keyreplace(
	    Socket, #transport.socket, Transports,
	    T#transport{req_refs = ReqRefs})}.


maybe_handle_recv(
  #state{filter = FilterMod} = S,
  #transport{socket = Socket} = Transport,
  From, Packet) ->
    {From_1, From_2} = From,
    case
	try FilterMod:accept_recv(From_1, From_2)
	catch
	    Class:Exception:StackTrace ->
		error_msg(
		  "FilterMod:accept_recv(~p, ~p) crashed: ~w:~w~n    ~p",
		  [From_1, From_2, Class, Exception, StackTrace]),
		true
	end
    of
	false ->
	    %% Drop the received packet
            %% What if this is an expected (inform) reply
            %% on an ephemeral socket?
	    inc(netIfMsgInDrops),
	    active_once(Socket),
	    S;
	Other ->
	    case Other of
		true ->
		    ok;
		_ ->
		    error_msg(
		      "FilterMod:accept_recv(~p, ~p) returned: ~p",
		      [From_1,From_2,Other])
	    end,
	    handle_recv(S, Transport, From, Packet)
    end.

handle_recv(
  #state{mpd_state  = MpdState, note_store = NS, log = Log} = S,
  #transport{socket = Socket} = Transport,
  From, Packet) ->
    put(n1, erlang:monotonic_time(micro_seconds)),
    LogF =
	fun(Type, Data) ->
		log(Log, Type, Data, From)
	end,
    case (catch snmpa_mpd:process_packet(
		  Packet, From, MpdState, NS, LogF)) of
	{ok, _Vsn, Pdu, _PduMS, {discovery, ManagerEngineId}} ->
	    handle_discovery_response(
	      S, Transport, From, Pdu, ManagerEngineId);

	{ok, _Vsn, Pdu, _PduMS, discovery} ->
	    handle_discovery_response(
	      S, Transport, From, Pdu, undefined);

	{ok, Vsn, Pdu, PduMS, ACMData} ->
	    ?vlog("got pdu ~s", 
		  [?vapply(snmp_misc, format, [256, "~w", [Pdu]])]),
	    %% handle_recv_pdu(S, Transport, From, Vsn, Pdu, PduMS, ACMData);
	    maybe_handle_recv_pdu(
	      S, Transport, From, Vsn, Pdu, PduMS, ACMData);

	{discarded, Reason} ->
	    ?vlog("packet discarded for reason: ~s",
		  [?vapply(snmp_misc, format, [256, "~w", [Reason]])]),
	    active_once(Socket),
	    S;

	{discarded, Reason, ReportPacket} ->
	    ?vlog("sending report for reason: "
		"~n   ~s", 
		[?vapply(snmp_misc, format, [256, "~w", [Reason]])]),
	    (catch udp_send(Socket, From, ReportPacket)),
	    active_once(Socket),
	    S;
	
	{discovery, ReportPacket} ->
	    ?vlog("sending discovery report", []),
	    (catch udp_send(Socket, From, ReportPacket)),
	    active_once(Socket),
	    S;
	
	Error ->
	    error_msg("processing of received message failed: "
                      "~n   ~p", [Error]),
	    active_once(Socket),
	    S
    end.

handle_discovery_response(
  #state{reqs = Reqs} = S,
  #transport{socket = Socket},
  _From,
  #pdu{request_id = ReqId} = Pdu,
  ManagerEngineId) ->
    active_once(Socket),
    case lists:keyfind(ReqId, 1, S#state.reqs) of
	{ReqId, Pid} ->
	    Pid ! {snmp_discovery_response_received, Pdu, ManagerEngineId},
	    %% XXX Strange... Reqs from this Pid should be reaped
	    %% at process exit by clear_reqs/2 so the following
	    %% should be redundant.
            NReqs = lists:keydelete(ReqId, 1, Reqs -- [{0, Pid}]), % ERIERL-427
	    S#state{reqs = NReqs};

        %% <OTP-16207>
        %% For some reason 'snmptrapd' response in stage 2 with request-id
        %% of zero.
        false when (ReqId =:= 0) ->
            DiscoReqs = [X|| {0, From1}     <- S#state.reqs,
                             {_, From2} = X <- S#state.reqs, From1 =:= From2],
            case (length(DiscoReqs) =:= 2) of
                true ->
                    [{_, Pid}, _] = DiscoReqs,
                    Pid ! {snmp_discovery_response_received, Pdu,
                           ManagerEngineId},
                    NReqs = S#state.reqs -- DiscoReqs,
                    S#state{reqs = NReqs};
                false ->
                    S
            end;
        %% </OTP-16207>

	false ->
	    %% Ouch, timeout? resend?
	    S
    end.

maybe_handle_recv_pdu(
  #state{filter = FilterMod} = S,
  #transport{socket = Socket} = Transport,
  From, Vsn,
  #pdu{type = Type} = Pdu, PduMS, ACMData) ->
    {From_1, From_2} = From,
    case
	try FilterMod:accept_recv_pdu(From_1, From_2, Type)
	catch
	    Class:Exception:StackTrace ->
		error_msg(
		  "FilterMod:accept_recv_pdu(~p, ~p, ~p) crashed: ~w:~w~n"
		  "    ~p",
		  [From_1, From_2, Type, Class, Exception, StackTrace]),
		true
	end
    of
	false ->
	    inc(netIfPduInDrops),
	    active_once(Socket),
	    S;
	Other ->
	    case Other of
		true ->
		    ok;
		_ ->
		    error_msg(
		      "FilterMod:accept_recv_pdu(~p, ~p, ~p) returned: ~p",
		      [From_1,From_2,Type,Other])
	    end,
	    handle_recv_pdu(S, Transport, From, Vsn, Pdu, PduMS, ACMData)
    end.

handle_recv_pdu(
  #state{reqs = Reqs} = S,
  #transport{socket = Socket},
  From, Vsn,
  #pdu{type = 'get-response', request_id = ReqId} = Pdu,
  _PduMS, _ACMData) ->
    active_once(Socket),
    case lists:keyfind(ReqId, 1, Reqs) of
	{ReqId, Pid} ->
	    ?vdebug("handle_recv_pdu -> "
		    "~n   send response to receiver ~p", [Pid]),
	    Pid ! {snmp_response_received, Vsn, Pdu, From};
	false ->
	    ?vdebug("handle_recv_pdu -> "
		    "~n   No receiver available for response pdu", [])
    end,
    S;
handle_recv_pdu(
  #state{master_agent = Pid} = S,
  #transport{} = Transport,
  From, Vsn,
  #pdu{type = Type} = Pdu,
  PduMS, ACMData)
  when Type =:= 'set-request';
       Type =:= 'get-request';
       Type =:= 'get-next-request';
       Type =:= 'get-bulk-request' ->
    ?vtrace("handle_recv_pdu -> received request (~w)", [Type]),
    ReqRef = make_ref(),
    Extra = [{request_ref, ReqRef}],
    Pid ! {snmp_pdu, Vsn, Pdu, PduMS, ACMData, From, Extra},
    NewS = update_req_counter_incoming(S, Transport, ReqRef),
    ?vdebug("handle_recv_pdu -> ~p", [NewS]),
    NewS;
handle_recv_pdu(
  #state{master_agent = Pid} = S,
  #transport{socket = Socket},
  From, Vsn, Pdu, PduMS, ACMData) ->
    ?vtrace("handle_recv_pdu -> received other request", []),
    active_once(Socket),
    Pid ! {snmp_pdu, Vsn, Pdu, PduMS, ACMData, From, []},
    S.


maybe_handle_reply_pdu(
  #state{filter = FilterMod, transports = Transports} = S,
  #transport{} = Transport,
  Vsn,
  #pdu{} = Pdu,
  Type, ACMData, To) ->
    %%
    Addresses = [fix_filter_address(Transports, To)],
    case
	try
	    FilterMod:accept_send_pdu(Addresses, Type)
	catch
	    Class:Exception:StackTrace ->
		error_msg(
		  "FilterMod:accept_send_pdu(~p, ~p) crashed: ~w:~w~n    ~p",
		  [Addresses, Type, Class, Exception, StackTrace]),
		true
	end
    of
	false ->
	    inc(netIfPduOutDrops),
	    ok;
	Other ->
	    case Other of
		true ->
		    ok;
		_ ->
		    error_msg(
		      "FilterMod:accept_send_pdu(~p, ~p) returned: ~p",
		      [Addresses,Type,Other])
	    end,
	    handle_reply_pdu(S, Transport, Vsn, Pdu, Type, ACMData, To)
    end.

handle_reply_pdu(
  #state{log = Log} = S,
  #transport{} = Transport,
  Vsn,
  #pdu{} = Pdu,
  Type, ACMData, To) ->
    %%
    LogF =
	fun(Type2, Data) ->
		log(Log, Type2, Data, To)
	end,
    case (catch snmpa_mpd:generate_response_msg(Vsn, Pdu, Type,
						ACMData, LogF)) of
	{ok, Packet} ->
	    ?vinfo("time in agent: ~w mysec", [time_in_agent()]),
	    try maybe_udp_send_wo_log(S, Transport, To, Packet)
	    catch
		{Reason, Sz} ->
		    error_msg("Cannot send message "
			      "~n   size:   ~p"
			      "~n   reason: ~p"
			      "~n   pdu:    ~p",
			      [Sz, Reason, Pdu])
	    end;
	{discarded, Reason} ->
	    ?vlog("handle_reply_pdu -> "
		  "~n   reply discarded for reason: ~s", 
		[?vapply(snmp_misc, format, [256, "~w", [Reason]])]),
	    ok;
	{'EXIT', Reason} ->
	    user_err("failed generating response message: "
		     "~nPDU: ~p~n~p", [Pdu, Reason])
    end.



maybe_handle_send_pdu(#state{filter     = FilterMod,
                             transports = Transports} = S,
                       Vsn, Pdu, MsgData, TDomAddrSecs, From) ->
    
    ?vtrace("maybe_handle_send_pdu -> entry with"
	    "~n   FilterMod:    ~p"
	    "~n   TDomAddrSecs: ~p", [FilterMod, TDomAddrSecs]),

    DomAddrSecs = snmpa_mpd:process_taddrs(TDomAddrSecs),
    AddressesToFilter =
	case is_legacy_transports(Transports) of
	    true ->
		[fix_filter_legacy_mpd_address(DAS)
		 || DAS <- DomAddrSecs];
	    false ->
		[fix_filter_mpd_address(DAS)
		 || DAS <- DomAddrSecs]
	end,

    Type = pdu_type_of(Pdu),

    case
	try FilterMod:accept_send_pdu(AddressesToFilter, Type)
	catch
	    Class:Exception:StackTrace ->
		error_msg(
		  "FilterMod:accept_send_pdu(~p, ~p) crashed: ~w:~w~n    ~p",
		  [AddressesToFilter, Type, Class, Exception, StackTrace]),
		true
	end
    of
	false ->
	    inc(netIfPduOutDrops),
	    ok;
	true ->
	    handle_send_pdu(S, Vsn, Pdu, MsgData, DomAddrSecs, From);
	FilteredAddresses when is_list(FilteredAddresses) ->
	    FilteredDomAddrSecs =
		case is_legacy_transports(Transports) of
		    true ->
			[DAS ||
			    DAS <- DomAddrSecs,
			    lists:member(
				fix_filter_legacy_mpd_address(DAS),
				FilteredAddresses)];
		    false ->
			[DAS ||
			    DAS <- DomAddrSecs,
			    lists:member(
				fix_filter_mpd_address(DAS),
				FilteredAddresses)]
		end,
	    ?vtrace("maybe_handle_send_pdu -> FilteredDomAddrSecs:~n"
		    "   ~p", [FilteredDomAddrSecs]),
	    handle_send_pdu(S, Vsn, Pdu, MsgData, FilteredDomAddrSecs, From);
	Other ->
	    error_msg(
	      "FilterMod:accept_send_pdu(~p, ~p) returned: ~p",
	      [AddressesToFilter,Type,Other]),
	    handle_send_pdu(S, Vsn, Pdu, MsgData, DomAddrSecs, From)
    end.

handle_send_pdu(
  #state{note_store = NS} = S,
  Vsn, Pdu, MsgData, DomAddrSecs, From) ->
    %%
    ?vtrace("handle_send_pdu -> entry with~n"
	    "   Pdu:         ~p~n"
	    "   DomAddrSecs: ~p", [Pdu, DomAddrSecs]),

    case (catch snmpa_mpd:generate_msg(
		  Vsn, NS, Pdu, MsgData, DomAddrSecs)) of
	{ok, Addresses} ->
	    do_handle_send_pdu(S, Pdu, Addresses);
	{discarded, Reason} ->
	    ?vlog("handle_send_pdu -> "
		  "~n   PDU ~p not sent due to ~p", [Pdu, Reason]),
	    ok;
        {'EXIT', Reason} ->
            user_err("failed generating message: "
                     "~nPDU: ~p~n~p", [Pdu, Reason]),
            ok
    end,
    case From of
	undefined ->
	    S;
	Pid when is_pid(Pid) ->
	    ?vtrace("link to ~p and add to request list", [Pid]),
	    link(Pid),
	    NReqs =
		snmp_misc:keyreplaceadd(
		  Pid, 2, S#state.reqs, {Pdu#pdu.request_id, From}),
	    S#state{reqs = NReqs}
    end.


handle_send_discovery(
  #state{
     note_store = NS,
     log        = Log,
     reqs       = Reqs,
     transports = Transports} = S,
  #pdu{type = Type, request_id = ReqId} = Pdu,
  MsgData, To, From) when is_pid(From) ->
    
    ?vtrace("handle_send_discovery -> entry with"
	    "~n   Pdu:     ~p"
	    "~n   MsgData: ~p"
	    "~n   To:      ~p"
	    "~n   From:    ~p", [Pdu, MsgData, To, From]),

    case (catch snmpa_mpd:generate_discovery_msg(NS, Pdu, MsgData, To)) of
	{ok, {Domain, Address, Packet}} ->
	    case select_transport(Domain, Type, Transports) of
		false ->
		    error_msg(
		      "Can not find transport to: ~s",
		      [format_address(To)]),
		    S;
		#transport{socket = Socket} ->
		    log(Log, Type, Packet, {Domain, Address}),
		    udp_send(Socket, {Domain, Address}, Packet),
		    ?vtrace("handle_send_discovery -> sent (~w)", [ReqId]),
                    link(From),
		    NReqs  = snmp_misc:keyreplaceadd(From, 2, Reqs, {ReqId, From}),
                    NReqs2 = (NReqs -- [{0, From}]) ++ [{0, From}], % OTP-16207
		    S#state{reqs = NReqs2}
	    end;
	{discarded, Reason} ->
	    ?vlog("handle_send_discovery -> "
		  "~n   Discovery PDU ~p not sent due to ~p", [Pdu, Reason]),
	    S;
        {'EXIT', Reason} ->
            user_err("failed generating discovery message: "
                     "~n   PDU:    ~p"
		     "~n   Reason: ~p", [Pdu, Reason]),
            S
    end.


do_handle_send_pdu(S, #pdu{type = Type} = Pdu, Addresses) ->
    do_handle_send_pdu(S, Type, Pdu, Addresses);
do_handle_send_pdu(S, Trap, Addresses) ->
    do_handle_send_pdu(S, trappdu, Trap, Addresses).

do_handle_send_pdu(S, Type, Pdu, Addresses) ->
    try do_handle_send_pdu1(S, Type, Addresses)
    catch
	{Reason, Sz} ->
	    error_msg(
	      "Can not send message~n"
	      "   size:   ~p~n"
	      "   reason: ~p~n"
	      "   pdu:    ~p",
	      [Sz, Reason, Pdu])
    end.

%% Because of the ephemeral sockets used by some transports,
%% the list of transports may be update for each send...
do_handle_send_pdu1(S, _Type, []) ->
    S;
do_handle_send_pdu1(S, Type, [{Domain, Address, Pkg}|Addresses])
  when is_binary(Pkg) ->
    NewS = do_handle_send_pdu2(S, Type, Domain, Address,
                               Pkg, Pkg, ""),
    do_handle_send_pdu1(NewS, Type, Addresses);
do_handle_send_pdu1(S, Type, [{Domain, Address, {Pkg, LogPkg}}|Addresses])
  when is_binary(Pkg) ->
    NewS = do_handle_send_pdu2(S, Type, Domain, Address,
                               Pkg, LogPkg, " encrypted"),
    do_handle_send_pdu1(NewS, Type, Addresses).


do_handle_send_pdu2(#state{transports = Transports} = S,
                    Type, Domain, Address, Pkg, LogPkg, EncrStr) ->
    ?vdebug("[~w] sending~s packet:"
            "~n   size: ~p"
            "~n   to:   ~p", [Domain, EncrStr, sz(Pkg), Address]),
    To = {Domain, Address},
    case select_transport(Domain, Type, Transports) of
	false ->
	    error_msg("Transport not found: "
                      "~n   size: ~p"
                      "~n   to:   ~s",
                      [sz(Pkg), format_address(To)]),
            S;
	#transport{ephm = none} = Transport ->
            ?vtrace("do_handle_send_pdu2 -> transport(ephm = none) selected: "
                    "~n      ~p", [Transport]),
	    maybe_udp_send_w_log(S, Transport, To, Pkg, LogPkg, Type),
            S%;

            %% <EPHEMERAL-FOR-FUTUR-USE>
            %% #transport{} = Transport ->
            %% ?vtrace("do_handle_send_pdu2 -> transport selected: "
            %%         "~n      ~p", [Transport]),
	    %% case maybe_udp_send_w_log(S, Transport, To, Pkg, LogPkg, Type) of
            %%     {ok, Sz} -> % we actually sent something
            %%        maybe_update_ephm_transport(S, Transport, Type, Sz);
            %%     _ -> % Non-fatal error -> Nothing sent
            %%         S
            %% end
            %% </EPHEMERAL-FOR-FUTUR-USE>
    end.


%% <EPHEMERAL-FOR-FUTUR-USE>

%% For inform:
%% This will have a reply, so we cannot close it directly!
%% Also, we will resend (a couple of times), if we don't
%% get a reply in time.
%% So, how do we handle this transport in this case?
%% Shall we create a list of used sockets? Tagged with a key
%% so we can reuse the correct socket for a resend?

%%
%% Or shall we used the same socket for all the sends for this
%% trap/inform? That is, we send the trap/inform to a number of
%% targets (the Addresses list), and *that* is considered *one*
%% use?
%% That would mean that we would potentially need to wait for
%% replies from a large number of targets?
%% But it may be better in the long term, because we will not
%% use of so many sockets.
%%

%% maybe_update_ephm_transport(S, #transport{ephm = once} = _Transport,
%%                             'inform-request' = _Type, _Sz) ->
%%     S; % Figure out the above first!

%% %% Before we close the current socket, create the new.
%% %% This is done in case we fail to create a new socket
%% %% (if we first close the current and then fail to create
%% %%  the new, we are stuck).
%% %% If we fail to create the new socket, we keep the current.
%% %% Better then nothing!
%% maybe_update_ephm_transport(S, #transport{socket    = OldSocket,
%%                                           ephm      = once,
%%                                           port_info = PortInfo,
%%                                           opts      = Opts} = Transport,
%%                             _Type, _Sz) ->
%%     try
%%         begin
%%             {Socket, PortNo} = gen_udp_open(PortInfo, Opts),
%%             (catch gen_udp:close(OldSocket)),
%%             T2 = Transport#transport{socket  = Socket,
%%                                      port_no = PortNo},
%%             TS  = S#state.transports,
%%             TS2 = lists:keyreplace(OldSocket, #transport.socket, TS, T2),
%%             S#state{transports = TS2}
%%         end
%%     catch
%%         _:_:_ ->
%%             %% We need to identify which transport!
%%             error_msg("Failed creating new ephemeral socket for transport"),
%%             S
%%     end;

%% %% Note that we do not currently handle inform:s, as that adds a whole
%% %% set of issues. See above for more info.
%% maybe_update_ephm_transport(S, #transport{socket    = Socket,
%%                                           ephm      = {sends, MaxSends},
%%                                           ephm_info = NumSends,
%%                                           port_info = _PortInfo,
%%                                           opts      = _Opts} = Transport,
%%                             _Type, _Sz) when (MaxSends > NumSends) ->
%%     T2  = Transport#transport{ephm_info = NumSends + 1},
%%     TS  = S#state.transports,
%%     TS2 = lists:keyreplace(Socket, #transport.socket, TS, T2),
%%     S#state{transports = TS2};
%% maybe_update_ephm_transport(S, #transport{socket    = OldSocket,
%%                                           ephm      = {sends, _MaxSends},
%%                                           ephm_info = _NumSends,
%%                                           port_info = PortInfo,
%%                                           opts      = Opts} = Transport,
%%                             _Type, _Sz) ->
%%     try
%%         begin
%%             {Socket, PortNo} = gen_udp_open(PortInfo, Opts),
%%             (catch gen_udp:close(OldSocket)),
%%             T2 = Transport#transport{socket    = Socket,
%%                                      ephm_info = 0,
%%                                      port_no   = PortNo},
%%             TS  = S#state.transports,
%%             TS2 = lists:keyreplace(OldSocket, #transport.socket, TS, T2),
%%             S#state{transports = TS2}
%%         end
%%     catch
%%         _:_:_ ->
%%             %% We need to identify which transport!
%%             error_msg("Failed creating new ephemeral socket for transport"),
%%             S
%%     end;

%% %% Note that we do not currently handle inform:s, as that adds a whole
%% %% set of issues. See above for more info.
%% maybe_update_ephm_transport(S, #transport{socket    = Socket,
%%                                           ephm      = {data, MaxData},
%%                                           ephm_info = AccSent,
%%                                           port_info = _PortInfo,
%%                                           opts      = _Opts} = Transport,
%%                             _Type, Sz) when (MaxData > (AccSent + Sz)) ->
%%     T2 = Transport#transport{ephm_info = AccSent + Sz},
%%     TS  = S#state.transports,
%%     TS2 = lists:keyreplace(Socket, #transport.socket, TS, T2),
%%     S#state{transports = TS2};
%% maybe_update_ephm_transport(S, #transport{socket    = OldSocket,
%%                                           ephm      = {data, _MaxData},
%%                                           ephm_info = _AccSent,
%%                                           port_info = PortInfo,
%%                                           opts      = Opts} = Transport,
%%                             _Type, _Sz) ->
%%     try
%%         begin
%%             {Socket, PortNo} = gen_udp_open(PortInfo, Opts),
%%             (catch gen_udp:close(OldSocket)),
%%             T2 = Transport#transport{socket    = Socket,
%%                                      ephm_info = 0,
%%                                      port_no   = PortNo},
%%             TS  = S#state.transports,
%%             TS2 = lists:keyreplace(OldSocket, #transport.socket, TS, T2),
%%             S#state{transports = TS2}
%%         end
%%     catch
%%         _:_:_ ->
%%             %% We need to identify which transport!
%%             error_msg("Failed creating new ephemeral socket for transport"),
%%             S
%%     end;

%% %% Note that we do not currently handle inform:s, as that adds a whole
%% %% set of issues. See above for more info.
%% maybe_update_ephm_transport(S, #transport{socket    = Socket,
%%                                           ephm      = {alive_time, AliveTime},
%%                                           ephm_info = undefined} = Transport,
%%                             _Type, _Sz) ->
%%     AliveEnd = erlang:monotonic_time(micro_seconds) + AliveTime,
%%     T2 = Transport#transport{ephm_info = AliveEnd},
%%     TS  = S#state.transports,
%%     TS2 = lists:keyreplace(Socket, #transport.socket, TS, T2),
%%     S#state{transports = TS2};
%% maybe_update_ephm_transport(S, #transport{socket    = OldSocket,
%%                                           ephm      = {alive_time, _AliveTime},
%%                                           ephm_info = AliveEnd,
%%                                           port_info = PortInfo,
%%                                           opts      = Opts} = Transport,
%%                             _Type, _Sz) ->
%%     TS = erlang:monotonic_time(micro_seconds),
%%     if
%%         (TS > AliveEnd) ->
%%             try
%%                 begin
%%                     {Socket, PortNo} = gen_udp_open(PortInfo, Opts),
%%                     (catch gen_udp:close(OldSocket)),
%%                     T2 = Transport#transport{socket    = Socket,
%%                                              %% This will be set when the transport
%%                                              %% is first used
%%                                              ephm_info = undefined,
%%                                              port_no   = PortNo},
%%                     TS  = S#state.transports,
%%                     TS2 = lists:keyreplace(OldSocket, #transport.socket, TS, T2),
%%                     S#state{transports = TS2}
%%                 end
%%             catch
%%                 _:_:_ ->
%%                     %% We need to identify which transport!
%%                     error_msg("Failed creating new ephemeral socket for transport"),
%%                     S
%%             end;
%%         true ->
%%             S
%%     end;

%% maybe_update_ephm_transport(S, _Transport, _Type, _Sz) ->
%%     S.

%% </EPHEMERAL-FOR-FUTUR-USE>


%% This function is used when logging has already been done!
maybe_udp_send_wo_log(
  #state{filter = FilterMod, transports = Transports},
  #transport{socket = Socket},
  To, Packet) ->
    {To_1, To_2} = fix_filter_address(Transports, To),
    case
	try FilterMod:accept_send(To_1, To_2)
	catch
	    Class:Exception:StackTrace ->
		error_msg(
		  "FilterMod:accept_send(~p, ~p) crashed: ~w:~w~n    ~p",
		  [To_1, To_2, Class, Exception, StackTrace]),
		true
	end
    of
	false ->
	    inc(netIfMsgOutDrops),
	    ok;
	Other ->
	    case Other of
		true ->
		    ok;
		_ ->
		    error_msg(
		      "FilterMod:accept_send(~p, ~p) returned: ~p",
		      [To_1,To_2,Other])
	    end,
	    udp_send(Socket, To, Packet)
    end.

maybe_udp_send_w_log(
  #state{log = Log, filter = FilterMod, transports = Transports},
  #transport{socket = Socket},
  To, Pkg, LogPkg, Type) ->
    {To_1, To_2} = fix_filter_address(Transports, To),
    case
	try FilterMod:accept_send(To_1, To_2)
	catch
	    Class:Exception:StackTrace ->
		error_msg(
		  "FilterMod:accept_send(~p, ~p) crashed for: ~w:~w~n    ~p",
		  [To_1, To_2, Class, Exception, StackTrace]),
		true
	end
    of
	false ->
	    inc(netIfMsgOutDrops),
	    ok;
	Other ->
	    case Other of
		true ->
		    ok;
		_ ->
		    error_msg(
		      "FilterMod:accept_send(~p, ~p) returned: ~p",
		      [To_1, To_2, Other])
	    end,
	    log(Log, Type, LogPkg, To),
	    udp_send(Socket, To, Pkg)
    end.


udp_send(Socket, To, B) ->
    {IpAddr, IpPort} =
	case To of
	    {Domain, Addr} when is_atom(Domain) ->
		Addr;
	    {_, P} = Addr when is_integer(P) ->
		Addr
	end,
    try gen_udp:send(Socket, IpAddr, IpPort, B) of
	{error, emsgsize} ->
	    %% From this message we cannot recover, so exit sending loop
	    throw({emsgsize, sz(B)});
	{error, ErrorReason} ->
	    error_msg("[error] cannot send message "
		      "(destination: ~p:~p, size: ~p, reason: ~p)",
		      [IpAddr, IpPort, sz(B), ErrorReason]),
            ok;
	ok ->
            %% For future use! Ephemeral ports!
	    {ok, byte_size(B)}
    catch
	error:ExitReason:StackTrace ->
	    error_msg("[exit] cannot send message "
		      "(destination: ~p:~p, size: ~p, reason: ~p, at: ~p)",
		      [IpAddr, IpPort, sz(B), ExitReason, StackTrace])
    end.

sz(L) when is_list(L) -> length(L);
sz(B) when is_binary(B) -> byte_size(B);
sz(_) -> undefined.


handle_disk_log(_Log, {wrap, NoLostItems}, State) ->
    ?vlog("Audit Trail Log - wrapped: ~w previously logged items where lost", 
	  [NoLostItems]),
    State;
handle_disk_log(_Log, {truncated, NoLostItems}, State) ->
    ?vlog("Audit Trail Log - truncated: ~w items where lost when truncating", 
	  [NoLostItems]),
    State;
handle_disk_log(_Log, full, State) ->
    error_msg("Failure to write to Audit Trail Log (full)", []),
    State;
handle_disk_log(_Log, {error_status, ok}, State) ->
    State;
handle_disk_log(_Log, {error_status, {error, Reason}}, State) ->
    error_msg("Error status received from Audit Trail Log: "
	      "~n~p", [Reason]),
    State;
handle_disk_log(_Log, _Info, State) ->
    State.


clear_reqs(Pid, S) ->
    NReqs  = lists:keydelete(Pid, 2, S#state.reqs),
    NReqs2 = NReqs -- [{0, Pid}], % ERIERL-427
    S#state{reqs = NReqs2}.


toname(P) when is_pid(P) ->
    case process_info(P, registered_name) of
	{registered_name, Name} ->
	    Name;
	_ ->
	    P
    end;
toname(Else) ->
    Else.


active_once(Sock) ->
    ?vtrace("activate once", []),
    ok = inet:setopts(Sock, [{active, once}]).


select_transport(_, []) ->
    false;
select_transport(ReqRef,
                 [#transport{req_refs = ReqRefs} = Transport | Transports]) ->
    case lists:member(ReqRef, ReqRefs) of
	true ->
	    Transport;
	false ->
	    select_transport(ReqRef, Transports)
    end.

select_transport(snmpUDPDomain = Domain, Type, Transports) ->
    ?vtrace("select_transport -> entry with"
            "~n      Domain:     ~p"
            "~n      Type:       ~p"
            "~n      Transports: ~p",
            [Domain, Type, Transports]),
    case select_transport2(Domain, Type, Transports) of
	#transport{} = Transport ->
            ?vtrace("select_transport -> selected: "
                    "~n      ~p",
                    [Transport]),
 	    Transport;
 	false ->
 	    select_transport2(transportDomainUdpIpv4, Type, Transports)
    end;
select_transport(Domain, Type, Transports)
  when is_atom(Domain) ->
    ?vtrace("select_transport -> entry with"
            "~n      Domain:     ~p"
            "~n      Type:       ~p"
            "~n      Transports: ~p",
            [Domain, Type, Transports]),
    case select_transport2(Domain, Type, Transports) of
 	#transport{} = Transport ->
            ?vtrace("select_transport -> selected: "
                    "~n      ~p",
                    [Transport]),
 	    Transport;
 	false when Domain =:= transportDomainUdpIpv4 ->
            ?vdebug("select_transport -> (~p) not found: "
                    "~n      try ~p", [Domain, snmpUDPDomain]),
	    select_transport2(snmpUDPDomain, Type, Transports);
 	false ->
 	    false
    end.


%% Two kinds of (pdu) type that we (the agent) will ever attempt to send:
%%   req-responder: 'get-response'
%%   trap-sender:   'inform-request'   |
%%                  'snmpv2-trap'      |
%%                  report             |
%%                  trap (which is a 'fake' type (#trappdu{}))
select_transport2(_Domain, _Type,
                  []) ->
    false;
select_transport2(snmpUDPDomain = Domain, _Type,
                  [#transport{domain = Domain} = Transport|_Transports]) ->
    Transport;
select_transport2(snmpUDPDomain = Domain, Type,
                  [_|Transports]) ->
    select_transport2(Domain, Type, Transports);
select_transport2(Domain, Type,
                  [#transport{domain = Domain,
                              kind   = Kind} = Transport|_Transports])
  when ((Type =:= 'inform-request') orelse
        (Type =:= 'snmpv2-trap') orelse
        (Type =:= report) orelse
        (Type =:= trap) orelse 
        (Type =:= trappdu)) andalso 
       ((Kind =:= all) orelse (Kind =:= trap_sender)) ->
    Transport;
select_transport2(Domain, Type,
                  [#transport{domain = Domain,
                              kind   = Kind} = Transport|_Transports])
  when (Type =:= 'get-response') andalso 
       ((Kind =:= all) orelse (Kind =:= req_responder)) ->
    Transport;
select_transport2(Domain, Type, [_|Transports]) ->
    select_transport2(Domain, Type, Transports).



address_to_domain({Domain, _Addr}) when is_atom(Domain) ->
    Domain;
address_to_domain({_Ip, Port}) when is_integer(Port) ->
    snmpUDPDomain.

%% If the agent uses legacy snmpUDPDomain e.g has not set
%% intAgentTransportDomain, then make sure
%% snmpa_network_interface_filter gets legacy arguments
%% to not break backwards compatibility.
%%
fix_filter_address(Transports, Address) ->
    case is_legacy_transports(Transports) of
	true ->
	    case Address of
		{Domain, Addr} when is_atom(Domain) ->
		    Addr;
		{_, IpPort} = Addr when is_integer(IpPort) ->
		    Addr
	    end;
	false ->
	    Address
    end.

is_legacy_transports([#transport{domain = snmpUDPDomain}]) ->
    true;
is_legacy_transports([#transport{} | _]) ->
    false.

fix_filter_legacy_mpd_address(Domain_Address_SecData) ->
    case Domain_Address_SecData of
	{{Domain, Addr}, _SecData} when is_atom(Domain) -> % v3
	    Addr;
	{Domain, Addr} when is_atom(Domain) -> % v1 & v2
	    Addr
    end.

fix_filter_mpd_address(Domain_Address_SecData) ->
    case Domain_Address_SecData of
	{{Domain, _Addr} = Address, _SecData} when is_atom(Domain) -> % v3
	    Address;
	{Domain, _Addr} = Address when is_atom(Domain) -> % v1 & v2
	    Address
    end.

%%%-----------------------------------------------------------------

handle_set_log_type(#state{log = {Log, OldValue}} = State, NewType) 
  when (Log /= undefined) ->
    NewValue =
	case NewType of
	    read ->
		[read];
	    write ->
		[write];
	    read_write ->
		[read,write];
	    _ ->
		throw({State, {error, {bad_atl_type, NewType}}})
	end,
    NewState = State#state{log = {Log, NewValue}},
    OldType =
	case {lists:member(read, OldValue),
	      lists:member(write, OldValue)} of
	    {true, true} ->
		read_write;
	    {true, false} ->
		read;
	    {false, true} ->
		write;
	    {false, false} ->
		throw({State, {error, {bad_atl_type, OldValue}}})
	end,
    {NewState, {ok, OldType}};
handle_set_log_type(State, _NewType) ->
    {State, {error, not_enabled}}.


handle_set_request_limit(#state{limit = OldLimit} = State, NewLimit) 
  when ((is_integer(NewLimit) andalso (NewLimit >= 0)) orelse 
	(NewLimit == infinity)) ->
    NewState = State#state{limit = NewLimit},
    {NewState, {ok, OldLimit}};
handle_set_request_limit(State, BadLimit) ->
    {State, {error, {bad_request_limit, BadLimit}}}.


%%%-----------------------------------------------------------------
%%% System messages
%%%-----------------------------------------------------------------
system_continue(_Parent, _Dbg, S) ->
    loop(S).

system_terminate(Reason, _Parent, _Dbg, #state{log        = Log,
                                               transports = Transports}) ->
    ?vlog("system-terminate -> entry with"
	  "~n   Reason: ~p", [Reason]),
    %% Close all transports
    Close =
        fun(S) ->
                ?vlog("try close socket ~p", [S]),
                (catch gen_udp:close(S))
        end,
    _ = [Close(Socket) || #transport{socket = Socket} <- Transports],
    %% Close logs
    do_close_log(Log),
    exit(Reason).

system_code_change(OldState, _Module, _OldVsn, downgrade_to_pre_4_16) ->
    {OldLog, Type} = OldState#state.log, 
    NewLog   = snmp_log:downgrade(OldLog), 
    NewState = OldState#state{log = {NewLog, Type}}, 
    {ok, NewState};

system_code_change(OldState, _Module, _OldVsn, upgrade_from_pre_4_16) ->
    Initial  = ?ATL_SEQNO_INITIAL,
    Max      = ?ATL_SEQNO_MAX, 
    Module   = snmpa_agent, 
    Function = increment_counter, 
    Args     = [atl_seqno, Initial, Max], 
    SeqNoGen = {Module, Function, Args}, 
    {OldLog, Type} = OldState#state.log, 
    NewLog   = snmp_log:upgrade(OldLog, SeqNoGen), 
    NewState = OldState#state{log = {NewLog, Type}}, 
    {ok, NewState};

system_code_change(S, _Module, _OldVsn, _Extra) ->
    {ok, S}.

do_close_log({undefined, []}) ->
    ok;
do_close_log({Log, _}) ->
    (catch snmp_log:sync(Log)),
    (catch snmp_log:close(Log)),
    ok;
do_close_log(_) ->
    ok.


%%%-----------------------------------------------------------------
%%% DEBUG FUNCTIONS
%%%-----------------------------------------------------------------
time_in_agent() ->
    erlang:monotonic_time(micro_seconds) - get(n1).

%% ----------------------------------------------------------------

pdu_type_of(#pdu{type = Type}) ->
    Type;
pdu_type_of(TrapPdu) when is_record(TrapPdu, trappdu) ->
    trap.


%%-----------------------------------------------------------------
%% 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() ->
    [
     netIfMsgOutDrops,
     netIfMsgInDrops,
     netIfPduOutDrops,
     netIfPduInDrops
    ].

inc(Name) -> 
    ets:update_counter(snmp_agent_table, Name, 1).

get_counters() ->
    Counters = counters(),
    get_counters(Counters, []).

get_counters([], Acc) ->
    lists:reverse(Acc);
get_counters([Counter|Counters], Acc) ->
    case ets:lookup(snmp_agent_table, Counter) of
	[CounterVal] ->
	    get_counters(Counters, [CounterVal|Acc]);
	_ ->
	    get_counters(Counters, Acc)
    end.


%% ----------------------------------------------------------------

%% This extracts the socket options from what is specified for
%% the transport, or if not, from the "global" socket options.
socket_opts(Domain, {IpAddr, PortInfo}, SocketOpts, DefaultOpts) ->
    ?vtrace("socket_opts -> entry with"
            "~n      Domain:      ~p"
            "~n      IpAddr:      ~p"
            "~n      PortInfo:    ~p"
            "~n      SocketOpts:  ~p"
            "~n      DefaultOpts: ~p",
            [Domain, IpAddr, PortInfo, SocketOpts, DefaultOpts]),
    Opts =
        [binary |
         case snmp_conf:tdomain_to_family(Domain) of
             inet6 = Family ->
                 [Family, {ipv6_v6only, true}];
             Family ->
                 [Family]
         end ++
         case get_bind_to_ip_address(SocketOpts, DefaultOpts) of
             true ->
                 [{ip, IpAddr}];
             _ ->
                 []
         end ++
         case get_no_reuse_address(SocketOpts, DefaultOpts) of
             false ->
                 [{reuseaddr, true}];
             _ ->
                 []
         end ++
         case get_recbuf(SocketOpts, DefaultOpts) of
             use_default ->
                 [];
             Sz ->
                 [{recbuf, Sz}]
         end ++
             case get_sndbuf(SocketOpts, DefaultOpts) of
                 use_default ->
                     [];
                 Sz ->
                     [{sndbuf, Sz}]
             end
        ] ++
        case get_extra_sock_opts(SocketOpts, DefaultOpts) of
            ESO when is_list(ESO) ->
                ESO;
            BadESO ->
                error_msg("Invalid 'extra socket options' (=> ignored):"
                          "~n   ~p", [BadESO]),
                []
        end,
    InetBackend =
        case get_inet_backend(SocketOpts, DefaultOpts) of
            use_default ->
                [];
            Backend when (Backend =:= inet) orelse (Backend =:= socket) ->
                [{inet_backend, Backend}]
        end,
    %% <EPHEMERAL-FOR-FUTUR-USE>
    %% Ephm = get_ephemeral(SocketOpts),
    %% {Ephm, PortInfo, Opts}.
    %% </EPHEMERAL-FOR-FUTUR-USE>
    {none, IpAddr, PortInfo, InetBackend, Opts}.


%% ----------------------------------------------------------------

get_atl_type(Opts) ->
    case snmp_misc:get_option(type, Opts, read_write) of
	read_write ->
	    [read,write];
	write ->
	    [write];
	read ->
	    [read]
    end.
	
get_atl_dir(Opts) ->
    snmp_misc:get_option(dir, Opts).

get_atl_size(Opts) ->
    snmp_misc:get_option(size, Opts).

get_atl_repair(Opts) ->
    snmp_misc:get_option(repair, Opts, true).

get_atl_seqno(Opts) ->
    snmp_misc:get_option(seqno, Opts, false).

get_verbosity(Opts) ->
    snmp_misc:get_option(verbosity, Opts, ?default_verbosity).

get_vsns(Opts) ->
    snmp_misc:get_option(versions, Opts, [v1, v2, v3]).

get_req_limit(O) ->
    snmp_misc:get_option(req_limit, O, infinity).

get_filter_opts(O) ->
    snmp_misc:get_option(filter, O, []).

get_filter_module(O) ->
    snmp_misc:get_option(module, O, ?DEFAULT_FILTER_MODULE).

get_open_err_filters(O) ->
    case snmp_misc:get_option(open_err_filters, O, []) of
        Filters when is_list(Filters) ->
            Filters;
        Filter when is_atom(Filter) ->
            [Filter];
        _ ->
            []
    end.

get_recbuf(Opts, DefaultOpts) -> 
    get_socket_opt(recbuf, Opts, DefaultOpts, use_default).

get_sndbuf(Opts, DefaultOpts) -> 
    get_socket_opt(sndbuf, Opts, DefaultOpts, use_default).

get_bind_to_ip_address(Opts, DefaultOpts) ->
    get_socket_opt(bind_to, Opts, DefaultOpts, false).

get_no_reuse_address(Opts, DefaultOpts) -> 
    get_socket_opt(no_reuse, Opts, DefaultOpts, false).

get_extra_sock_opts(Opts, DefaultOpts) ->
    get_socket_opt(extra_sock_opts, Opts, DefaultOpts, []).

get_inet_backend(Opts, DefaultOpts) -> 
    get_socket_opt(inet_backend, Opts, DefaultOpts, use_default).

%% <EPHEMERAL-FOR-FUTUR-USE>
%% This is not really a socket option, but rather socket 'meta'
%% information. Its still put together with the actual socket
%% options.
%% get_ephemeral(SocketOpts) ->
%%     snmp_misc:get_option(ephemeral, SocketOpts, none).
%% </EPHEMERAL-FOR-FUTUR-USE>


get_socket_opt(Opt, Opts, DefaultOpts, DefaultVal) ->
    snmp_misc:get_option(Opt, Opts,
                         snmp_misc:get_option(Opt, DefaultOpts, DefaultVal)).
    


%% ----------------------------------------------------------------

%% error_msg(F) ->
%%     error_msg(F, []).

error_msg(F, A) -> 
    ?snmpa_error("NET-IF server: " ++ F, A).

warning_msg(F, A) -> 
    ?snmpa_warning("NET-IF server: " ++ F, A).

info_msg(F,A) ->
    ?snmpa_info("NET-IF server: " ++ F, A).

%% --- 

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

%% ----------------------------------------------------------------

call(Pid, Req) ->
    ReplyRef = make_ref(),
    Pid ! {Req, ReplyRef, self()},
    receive 
	{ReplyRef, Reply, Pid} ->
	    Reply
    after 5000 ->
	    {error, timeout}
    end.

		       
%% ----------------------------------------------------------------

get_info(#state{transports = Transports, reqs = Reqs}) ->
    ProcSize = proc_mem(self()),
    Counters = get_counters(),
    [{reqs,           Reqs},
     {counters,       Counters},
     {process_memory, ProcSize},
     {transport_info, [#{tdomain        => Domain,
                         taddress       => {Address, PortNo},
                         transport_kind => Kind,
                         port_info      => PortInfo,
                         opts           => Opts,
                         socket_info    => get_socket_info(Socket),
                         num_reqs       => length(Refs)} ||
                          #transport{socket    = Socket,
                                     domain    = Domain,
                                     address   = Address,
                                     port_no   = PortNo,
                                     port_info = PortInfo,
                                     opts      = Opts,
                                     kind      = Kind,
                                     req_refs  = Refs} <- Transports]}].

proc_mem(P) when is_pid(P) ->
    case (catch erlang:process_info(P, memory)) of
	{memory, Sz} when is_integer(Sz) ->
	    Sz;
	_ ->
	    undefined
    end.
%% proc_mem(_) ->
%%     undefined.

get_socket_info(Id) when is_port(Id) ->
    Info = inet:info(Id),
    IfList = 
	case (catch inet:getif(Id)) of
	    {ok, IFs} ->
		[{interfaces, IFs}];
	    _ ->
		[]
	end,
    BufSz = 
	case (catch inet:getopts(Id, [recbuf, sndbuf])) of
	    {ok, Sz} ->
		[{buffer_size, Sz}];
	    _ ->
		[]
	end,
    [{socket, Id}, {info, Info}] ++ IfList ++ BufSz;
get_socket_info(Id) ->
    Info = inet:info(Id),

    %% Does not exist for 'socket'
    IfList = [],
	%% case (catch inet:getif(Id)) of
	%%     {ok, IFs} ->
	%% 	[{interfaces, IFs}];
	%%     _ ->
	%% 	[]
	%% end,

    BufSz = 
	case (catch inet:getopts(Id, [recbuf, sndbuf])) of
	    {ok, Sz} ->
		[{buffer_size, Sz}];
	    _ ->
		[]
	end,

    [{socket, Id}, {info, Info}] ++ IfList ++ BufSz.



%% ---------------------------------------------------------------