This file is indexed.

/usr/share/perl5/CampusIO.pm is in flowscan 1.006-13.2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
#  CampusIO.pm - a FlowScan module for reporting on campus traffic I/O
#  Copyright (C) 1998-2001  Dave Plonka
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# $Id: CampusIO.pm,v 1.63 2001/02/28 21:31:02 dplonka Exp $
# Dave Plonka <plonka@doit.wisc.edu>

use strict;

package CampusIO;

require 5;
require Exporter;
use FlowScan 1.005;

@CampusIO::ISA=qw(FlowScan Exporter);
# convert the RCS revision to a reasonable Exporter VERSION:
'$Revision: 1.63 $' =~ m/(\d+)\.(\d+)/ && (( $CampusIO::VERSION ) = sprintf("%d.%03d", $1, $2));

=head1 NAME

CampusIO - a FlowScan module for reporting on campus traffic I/O

=head1 SYNOPSIS

   $ flowscan CampusIO

or in F<flowscan.cf>:

   ReportClasses CampusIO

=head1 DESCRIPTION

CampusIO is a general flowscan report for reporting on flows of traffic
in and out of a site or campus.  It does this by processing flows
reported by one or more routers at the network border.  The site or
campus may be an Autonomous System (AS), as is often the case for large
universities, but this is not necessary.  CampusIO can be used by
smaller institutions and other enterprises as well.

C<flowscan> will run the CampusIO report if you configure this in
your F<flowscan.cf>:

   ReportClasses CampusIO

=head1 CONFIGURATION

CampusIO's configuration file is F<CampusIO.cf>.  This configuration
file is located in the directory in which the F<flowscan> script
resides.

The CampusIO configuration directives include:

=over 4

=item B<NextHops>

This directive is suggested if C<OutputIfIndexes> is not defined.
Defining C<NextHops> causes C<flowscan> to identify outbound flows by
their nexthop value.  C<NextHops> is a comma-seperated list of IP
addresses or resolvable hostnames, e.g.:

   # NextHops
   NextHops gateway.provider.net, gateway.other.net

If neither C<NextHops> nor C<OutputIfIdexes> is defined, C<CampusIO>
will use the flows' destination addresses to determine whether or not
they are outbound.  This is a less reliable and more CPU intensive
method than C<NextHops> or C<OutputIfIdexes>.

=item B<OutputIfIndexes>

This directive is suggested if C<NextHops> is not defined.  Defining
C<OutputIfIndexes> causes C<flowscan> to identify outbound flows by
their output interface value.  C<OutputIfIndexes> is a comma-seperated
list of ifIndexes as determined using SNMP, e.g.:

   $ snmpwalk router.our.domain public interfaces.ifTable.ifEntry.ifDescr

or by looking at the raw flows from Cflowd to determine the C<$output_if>.
e.g.:

   # OutputIfIndexes
   OutputIfIndexes 1, 2, 3

If neither C<NextHops> nor C<OutputIfIdexes> is defined, C<CampusIO>
will use the flows' destination addresses to determine whether or not
they are outbound.  This is a less reliable and more CPU intensive
method than C<NextHops> or C<OutputIfIdexes>.

=item B<LocalSubnetFiles>

This directive is required.
It is a a comma-seperated list of files containing the definitions of
"local" subnets.
E.g.:

   # LocalSubnetFiles local_nets.boulder
   LocalSubnetFiles bin/local_nets.boulder

=item B<OutputDir>

This directive is required.
It is the directory in which RRD files will be written.
E.g.:

   # OutputDir /var/local/flows/graphs
   OutputDir graphs

=item B<LocalNextHops>

This is an "advanced" option which is only required if you are
exporting and collecting flows from multiple routers to the same
FlowScan.  It is a comma-seperated list of IP addresses or resolvable
hostnames.

Specify all the local routers for which you have configured cflowd to
collecting flows on this FlowScan host.  This will ensure that the same
traffic isn't counted twice by ignoring flows destined for these
next-hops, which otherwise might look as if they're inbound flows.
FlowScan will only count flows that represent traffic forwarded outside
this set of local routers.

E.g.:

   # LocalNextHops other-router.our.domain

=item B<TCPServices>

This directive is optional, but is required if you wish to produce the
CampusIO service graphs.  It is a comma-seperated list of TCP services
by name or number.  E.g., it is recommended that it contain at least
the services shown here:

   # TCPServices ftp-data, ftp, smtp, nntp, www, 7070, 554
   TCPServices ftp-data, ftp, smtp, nntp, www, 7070, 554

=item B<UDPServices>

This directive is optional.  It is a comma-seperated list of UDP
services by name or number.  E.g.:

   # UDPServices domain, snmp, snmp-trap

=item B<Protocols>

This directive is optional, but is required if you wish to produce the
CampusIO protocol graphs.  It is a comma-seperated list of IP protocols
by name.  E.g.:

   # Protocols icmp, tcp, udp
   Protocols icmp, tcp, udp

=item B<ASPairs>

This directive is optional, but is required if you wish to build any
custom AS graphs.  It is a list of source and destination AS pairs.
E.g.:

   # source_AS:destination_AS, e.g.:
   # ASPairs 0:0
   ASPairs 0:0

Note that the effect of setting ASPairs will be different based on
whether you specified "peer-as" or "origin-as" when you configured your
Cisco.  This option was intended to be used when "peer-as" is
configured.

See the C<BGPDumpFile> directive for other AS-related features.

=item B<Verbose>

This directive is optional.
If non-zero, it makes C<flowscan> more verbose with respect to messages
and warnings.  Currently the values C<1> and C<2> are understood, the
higher value causing more messages to be produced.
E.g.:

   # Verbose (OPTIONAL, non-zero = true)
   Verbose 1

=item B<NapsterSubnetFiles>

This directive is optional, but is required if you wish to produce the
CampusIO service graphs.
It is a comma-seperated list of files containing the definitions of
"Napster" subnets.
E.g.:

   # NapsterSubnetFiles (OPTIONAL)
   NapsterSubnetFiles bin/Napster_subnets.boulder

=item B<NapsterSeconds>

This directive is optional.
It is the number of seconds after which a given campus host has
communicated with a host within the "Napster" subnet(s) will no longer
be considered to be using the Napster application.
E.g. Half an hour:

   # NapsterSeconds (OPTIONAL)
   NapsterSeconds 1800

=item B<NapsterPorts>

This directive is optional.
It a comma-seperated list of default TCP ports used by Napster.  These
will be used to determine the confidence level of whether or not it's
really Napster traffic.  If confidence is low, it will be reported as
"NapsterMaybe" rather than "NapUser" traffic.
E.g., reasonable values are:

   # NapsterPorts (OPTIONAL)
   NapsterPorts 8875, 4444, 5555, 6666, 6697, 6688, 6699, 7777, 8888

=item B<TopN>

This directive is optional.  It's use requires the C<HTML::Table> perl
module.  C<TopN> is the number of entries to show in the tables that
will be generated in HTML top reports.  E.g.:

   # TopN (OPTIONAL)
   TopN 10

If you'd prefer to see hostnames rather than IP addresses in your top
reports, use the F<ip2hostname> script.  E.g.:

   $ ip2hostname -I *.*.*.*_*.html

=item B<ReportPrefixFormat>

This directive is optional.  It is used to specify the file name prefix
for the HTML or text reports such as the "originAS", "pathAS", and "Top
Talkers" reports.  You should use strftime(3) format specifiers in the
value, and it may also specify sub-directories.  If not set, the prefix
defaults to the null string, which means that, every five minutes,
subsequent reports will overwrite the previous.
E.g.:

   # Preserve one day of HTML reports using the time of day as the dir name:
   ReportPrefixFormat html/CampusIO/%H:%M/

or:

   # Preserve one month by using the day of month in the dir name (like sar(1)):
   ReportPrefixFormat html/CampusIO/%d/%H:%M_

=item B<BGPDumpFile>

This directive is optional and is B<experimental>.  In combination with
C<TopN> and C<ASNFile> it causes FlowScan to produce "Top ASN" reports
which show the "top" Autonomous Systems with which your site exchanges
traffic.

C<BGPDumpFile> requires the C<ParseBGPDump> perl module by Sean
McCreary, which is supplied with CAIDA's CoralReef Package:

   http://www.caida.org/tools/measurement/coralreef/status.xml

Unfortunately, CoralReef is governed by a different license than
FlowScan itself.  The F<Copyright> file says this:

   Permission to use, copy, modify and distribute any part of this
   CoralReef software package for educational, research and non-profit
   purposes, without fee, and without a written agreement is hereby
   granted, provided that the above copyright notice, this paragraph
   and the following paragraphs appear in all copies.
   [...]

   The CoralReef software package is developed by the CoralReef
   development team at the University of California, San Diego under
   the Cooperative Association for Internet Data Analysis (CAIDA)
   Program. Support for this effort is provided by the CAIDA grant
   NCR-9711092, and by CAIDA members.

After fetching the C<coral> release from:

   http://www.caida.org/tools/measurement/coralreef/dists/coral-3.4.1-public.tar.gz

install C<ParseBGPDump.pm> in FlowScan's perl include path, such as in
the C<bin> sub-directory:

   $ cd /tmp
   $ gunzip -c coral-3.4.1-public.tar.gz |tar x coral-3.4.1-public/./libsrc/misc-perl/ParseBGPDump.pm
   $ mv coral-3.4.1-public/./libsrc/misc-perl/ParseBGPDump.pm $PREFIX/bin/ParseBGPDump.pm

Also you must specify C<TopN> to be greater than zero, e.g. 10, and the
C<HTML::Table> perl module is required if you do so.

The C<BGPDumpFile> value is the name of a file containing the output of
C<show ip bgp> from a Cisco router, ideally from the router that is
exporting flows.  If this option is used, and the specified file
exists, it will cause the "originAS" and "pathAS" reports to be
generated.  E.g.:

   TopN 10
   BGPDumpFile etc/router.our.domain.bgp

One way to create the file itself, is to set up rsh access to your
Cisco, e.g.:

   ip rcmd rsh-enable
   ip rcmd remote-host username 10.10.42.69 username

Then do something like this:

   $ cd $PREFIX
   $ mkdir etc
   $ echo show ip bgp >etc/router.our.domain.bgp # required by ParseBGPDump.pm
   $ time rsh router.our.domain "show ip bgp" >>etc/router.our.domain.bgp
      65.65s real     0.01s user     0.05s system
   $ wc -l /tmp/router.our.domain.bgp
    197883 /tmp/router.our.domain.bgp

Once C<flowscan> is up and running with C<BGPDumpFile> configured, it
will reload that file if its timestamp indicates that it has been
modified.  This allows you to "freshen" the image of the routing table
without having to restart C<flowscan> itself.

Using the C<BGPDumpFile> option causes C<FlowScan> to use much more
memory than usual.  This memory is used to store a C<Net::Patricia>
trie containing a node for every prefix in the BGP routing table.  For
instance, on my system it caused the C<FlowScan> process to grow to
over 50MB, compared to less than 10MB without C<BGPDumpFile>
configured.

=item B<ASNFile>

This directive is optional and is only useful in conjunction with
C<BGPDumpFile>.  If specified, this directive will cause the AS names
rather than just their numbers to appear in the Top ASN HTML reports.
Its value should be the path to a file having the format of the file
downloaded from this URL:

   ftp://ftp.arin.net/netinfo/asn.txt

E.g.:

   TopN 10
   BGPDumpFile etc/router.our.domain.bgp
   ASNfile etc/asn.txt

Once C<flowscan> is up and running with C<ASNFile> configured, it will
reload the file if its timestamp indicates that it has been modified.

=back

=head1 METHODS

This module provides no public methods.  It is a report module meant
only for use by C<flowscan>.  Please see the C<FlowScan> module
documentation for information on how to write a FlowScan report
module.

=head1 SEE ALSO

perl(1), FlowScan, SubNetIO, flowscan(1), Net::Patricia.

=cut

use FindBin;
use Cflow qw(:flowvars 1.024); # for use in wanted sub
use RRDs;
use Boulder::Stream;
use Socket; # for inet_ntoa, inet_aton
use POSIX; # for UINT_MAX, strftime
use IO::File;
use File::Basename;
use ConfigReader::DirectiveStyle;
use Net::Patricia 1.010;

my $c = new ConfigReader::DirectiveStyle;
$c->directive('NextHops');
$c->directive('OutputIfIndexes');
$c->required('OutputDir');
$c->directive('TCPServices');
$c->directive('UDPServices');
$c->directive('Protocols');
$c->directive('ASPairs');
$c->directive('LocalNextHops');
$c->directive('LocalSubnetFiles');
$c->directive('Rateup');
$c->directive('Verbose');
$c->directive('TopN');
$c->directive('ReportPrefixFormat');
$c->directive('NapsterSubnetFiles');
$c->directive('NapsterSeconds');
$c->directive('NapsterPorts');
$c->directive('BGPDumpFile');
$c->directive('ASNFile');
$c->directive('WebProxyIfIndex');
#$c->load("${FindBin::Bin}/CampusIO.cf");
$c->load("/etc/${FindBin::Script}/CampusIO.cf");

if (1 <= $c->value('Verbose')) {
   $CampusIO::verbose = 1
}
if (2 <= $c->value('Verbose')) {
   $CampusIO::Verbose = 1
}

# outputdir can be absolute or relative (to the flow file's directory):
$CampusIO::outputdir = $c->value('OutputDir');

# this is a global set by report subroutine and used by the sort subs:
$CampusIO::thingy;
$CampusIO::thing = 'bytes';

# { these vars are used by the wanted subroutine:

foreach my $if (split(m/\s*,\s*/, $c->value('OutputIfIndexes'))) {
   push(@CampusIO::output_if, $if)
}

# This hash contains hashes of 'in' and 'out' totals for origin ASNs *and*
# path ASNs.  The DESTROY method zeroes the counters once per flow file.
%CampusIO::originAS;

$CampusIO::TopN = $c->value('TopN');
if ($CampusIO::TopN) {
   eval "use HTML::Table";
   die "$@" if $@;
}

if ($c->value('BGPDumpFile')) {
   eval "use ParseBGPDump";
   die "$@" if $@;
   # load the BGPDumpFile
   load_bgp($c->value('BGPDumpFile'))
}

$CampusIO::hops_ptrie = new Net::Patricia;
die unless ref($CampusIO::hops_ptrie);

my $hop;
my $addr_length = length pack("N"); # remember the length of an IPv4 address
foreach $hop (split(m/\s*,\s*/, $c->value('NextHops'))) {
   my $n = inet_aton($hop);
   die "invalid NextHop: \"$hop\"\n" if $addr_length != length($n);
   my $i = unpack("N", inet_aton($hop));
   die "invalid NextHop: \"$hop\"" if 0 == $i;
   my $ihop = inet_ntoa($n); # convert the $hop to an IP address
   my $rv;
   $rv = $CampusIO::hops_ptrie->add_string($ihop);
   if ($rv ne $ihop) {
      die "hops_ptrie->add(\"$ihop\") failed for \"$hop\": $@\n"
   }
   push(@CampusIO::hops, $i)
}

$CampusIO::WebProxy_ifIndex = $c->value('WebProxyIfIndex');

if (!@CampusIO::output_if && !@CampusIO::hops) {
   warn("NextHops and OutputIfIndexes are undefined.\n",
	"Identifying outbound flows based solely on destination address ...\n")
      if -t
}

$CampusIO::localhops_ptrie = new Net::Patricia;
die unless ref($CampusIO::localhops_ptrie);

foreach $hop (split(m/\s*,\s*/, $c->value('LocalNextHops'))) {
   my $n = inet_aton($hop);
   die "invalid LocalNextHop: \"$hop\"\n" if $addr_length != length($n);
   my $i = unpack("N", inet_aton($hop));
   die "invalid LocalNextHop: \"$hop\"" if 0 == $i;
   my $ihop = inet_ntoa($n); # convert the $hop to an IP address
   my $rv;
   eval '$rv = $CampusIO::localhops_ptrie->add_string($ihop)';
   if ($rv ne $ihop || $@) {
      die "localhops_ptrie->add(\"$ihop\") failed for \"$hop\": $@\n"
   }
}

# { Handle interesting services...
my %services = (tcp => 'TCPServices',
		udp => 'UDPServices');
while (my($protoname, $option) = each(%services)) {
   my $service;
   my $port;
   my $proto = scalar(getprotobyname($protoname));
   die("undefined protocol \"$protoname\"!") unless $proto;
   foreach $service (split(m/\s*,\s*/, $c->value($option))) {
      if ($service !~ m/^\d+$/) {
         $port = getservbyname($service, $protoname);
         $port || die "undefined $protoname service \"$service\"!"
      } else {
	 $port = $service
      }
      $CampusIO::service{$proto}{$port} = 1
   }
}
# }

{ # Handle interesting protocols...
   my $proto; # don't collide with imported $Cflow::protocol!
   foreach $proto (split(m/\s*,\s*/, $c->value('Protocols'))) {
      my $proto = scalar(getprotobyname($proto));
      die "undefined protocol \"$proto\"!" if (!$proto);
      $CampusIO::proto{$proto} = 1
   }
}

# These are the ASes for which we'll create ".rrd" files:
@CampusIO::as2as = split(m/\s*,\s*/, $c->value('ASPairs'));

# %CampusIO::RealServer will be a cache of hosts that we think are "Real"
# Servers based on having seen a flow involving their "well known" TCP ports.
# If we subsequently see traffic from one of these hosts involving the
# "well known" range of UDP ports we'll count that as "Real" Traffic.
%CampusIO::RealServer = ();

# Multicast stuff:
$CampusIO::MCAST_NET = unpack('N', inet_aton('224.0.0.0'));
$CampusIO::MCAST_MASK = unpack('N', inet_aton('240.0.0.0'));

# Handle Napster stuff if it's configured:
@CampusIO::napster_files = split(m/\s*,\s*/, $c->value('NapsterSubnetFiles'));
if (@CampusIO::napster_files &&
    (@CampusIO::napster_files = <@CampusIO::napster_files>)) {

   if (!(@CampusIO::NapsterPorts =
	    split(m/\s*,\s*/, $c->value('NapsterPorts')))) {
     # these are the defaults as of this writing (Mar  9 2000):
     @CampusIO::NapsterPorts = (4444, 5555, 6666, 6699, 7777, 8875, 8888);
     warn("NapsterPorts is unset... using defaults: ",
          join(", ", @CampusIO::NapsterPorts), "\n");
   }
   $CampusIO::NapsterSeconds = $c->value('NapsterSeconds');
   if (0 >= $CampusIO::NapsterSeconds) { # default to 1/2 hour if unset:
      $CampusIO::NapsterSeconds = 30*60; # minutes*seconds
      warn("NapsterSeconds is unset... using default: ",
	   $CampusIO::NapsterSeconds, "\n")
   }

   # { initialize the Napster Patricia Trie:
   $CampusIO::nptrie = new Net::Patricia;
   die unless ref($CampusIO::nptrie);

   @CampusIO::napster_files = <@CampusIO::napster_files>;
   my($file, $stream, $cargo);
   foreach $file (@CampusIO::napster_files) {
      print(STDERR "Loading \"$file\" ...\n") if -t;
      my $fh = new IO::File "<$file";
      $fh || die "open \"$file\", \"r\": $!\n";
      $stream = new Boulder::Stream $fh;
      while ($cargo = $stream->read_record) {
         my $subnet = $cargo->get('SUBNET');
         die unless $subnet;
	 my $collision;
	 if ($collision = $CampusIO::nptrie->match_string($subnet)) {
            warn "$subnet nptrie->add skipped - collided with $collision->{SUBNET}\n";
	    next
	 }
	 if (!$CampusIO::nptrie->add_string($subnet)) {
            warn "$subnet nptrie->add failed!\n";
	 }
      }
      undef $fh
   }
   # }
}

@CampusIO::subnet_files = split(m/\s*,\s*/, $c->value('LocalSubnetFiles'));

# { initialize the "local" Patricia Tree
# flows with a source that is not within the $ptrie will be considered to
# be candidate inbound flows...

@CampusIO::subnets_files = <@CampusIO::subnet_files>;
$CampusIO::ptrie = new Net::Patricia;
die unless ref($CampusIO::ptrie);
my($subnets_file, $stream, $cargo);
foreach $subnets_file (@CampusIO::subnets_files) {
   print(STDERR "Loading \"$subnets_file\" ...\n") if -t;
   my $fh = new IO::File "<$subnets_file";
   $fh || die "open \"$subnets_file\", \"r\": $!\n";
   $stream = new Boulder::Stream $fh;
   while ($cargo = $stream->read_record) {
      my $subnet = $cargo->get('SUBNET');
      my $hr = { SUBNET => $subnet };
      my $collision;
      if ($collision = $CampusIO::ptrie->match_string($subnet)) {
         warn "$subnet skipped.  It collided with $collision->{SUBNET}\n";
	 next
      }
      if ($CampusIO::ptrie->add_string($subnet, $hr)) {
         push(@CampusIO::subnets, $hr);
      } else {
         warn "$subnet add failed!\n";
	 next
      }
   }
   undef $fh
}
# }

# }

die("No subnets defined in subnet files? (\"", join('", "', @CampusIO::subnet_files), "\")\n") unless @CampusIO::subnets;

sub new {
   my $self = {};
   my $class = shift;
   return bless _init($self), $class
}

sub _init {
   my $self = shift;
   $self->{CampusIO}{wanted} = 0; # boolean value returned by wanted subroutine
   $self->{CampusIO}{which} = ''; # 'in'/'out' (valid when {wanted} is non-zero)

   # initialize the totals for "interesting" services ($self->{total}{service}):
   foreach my $protocol (keys %CampusIO::service) {
      foreach my $port (keys %{$CampusIO::service{$protocol}}) {
         foreach my $direction ('src', 'dst') {
            foreach my $which ('in', 'out') {
               $self->{total}{service}{$protocol}{$direction}{$port}{$which}{bytes} = 0;
               $self->{total}{service}{$protocol}{$direction}{$port}{$which}{pkts} = 0;
               $self->{total}{service}{$protocol}{$direction}{$port}{$which}{flows} = 0
            }
         }
      }
   }

   return $self
}

# Quake - apparently Quake 3 uses UDP with source and destination port of 27960

sub QuakeWanted {
   my $self = shift;
   my $which = shift;
   my $ref = shift;
   if (27960 == $srcport && 27960 == $dstport && 17 == $protocol) {
      $ref->{app}{Quake}{$which}{flows}++;
      $ref->{app}{Quake}{$which}{bytes} += $bytes;
      $ref->{app}{Quake}{$which}{pkts} += $pkts;
      return 1
   }
   return 0
}

# As of this writing, apparently Real Network's "RealMeadia" (Audio and/or
# Video) clients and servers uses these ports:
#
#    TCP port 7070 for connecting to pre-G2 RealServers
#    TCP port 554 and 7070 for connecting to G2 RealServers 
#    UDP ports 6970 - 7170 (inclusive) for incoming traffic only 
#
# Apparently the content can also be sent in HTTP format... which we
# couldn't differentiate from other HTTP traffic. Ugh.
#
# This was gleaned from "http://service.real.com/firewall/adminfw.html".

sub RealWanted {
   my $self = shift;
   my $which = shift;
   my $ref = shift;
   if (6 == $protocol && (7070 == $srcport || 554 == $srcport)) {
      # build a cache of hosts that look like "Real" servers:
      # (FIXME - this cache should be purged of old entries periodically.)
      $CampusIO::RealServer{$srcaddr} = $endtime;
      return 1
   } elsif (17 == $protocol && $dstport >= 6970 && $dstport <= 7170 &&
	    defined($CampusIO::RealServer{$srcaddr})) {
      $ref->{app}{RealAudio}{$which}{flows}++;
      $ref->{app}{RealAudio}{$which}{bytes} += $bytes;
      $ref->{app}{RealAudio}{$which}{pkts} += $pkts;
      return 1
   }
   return 0
}

# PASV mode ftp data

sub ftpPASVWanted {
   my $self = shift;
   my $which = shift;
   my $ref = shift;

   # FIXME?  Handle ftp-data in some way?  But how?
   return(0) unless 6 == $Cflow::protocol && (21 == $Cflow::srcport ||
				              21 == $Cflow::dstport ||
				              (1024 <= $Cflow::srcport &&
				               1024 <= $Cflow::dstport));

   # Only flows representing ftp (control) or TCP traffic on unprivileged
   # ports should get to this point in the code.

   my($client, # client IP address (as host-ordered integer)
      $server, # server IP address (as host-ordered integer)
      $direction); # 'src' or 'dst'

   return(0) unless 6 == $Cflow::protocol; # must be tcp

   # Skip pathalogical flows since $srcaddr == $dstaddr will break
   # "$client:$server" stuff below:
   return(0) if ($Cflow::srcaddr == $Cflow::dstaddr);

   # FIXME? What happens when two host simultaneous have ESTABLISHED ftp
   # command (and PASV mode data) streams between each other, negotiated
   # in opposite directions? (Something bad I think, esp. regarding 'src'
   # and 'dst'.)  For the time being, we'll assume "never happens."

   if (1024 <= $Cflow::srcport && 1024 <= $Cflow::dstport) {
      # At the point we've got unreserverd TCP ports for src and dst...
      # This *could* be a ftp PASV data flow...

      # See if we get a hit on the FTPSession, cache...
      my $r = $CampusIO::FTPSession{"$Cflow::srcaddr:$Cflow::dstaddr"};
      # If not, skip this candidate flow (it still might be PASV ftp, but
      # we can't tell since we have yet to see an ftp control TCP stream
      # between these hosts):
      return(0) if !ref($r) || (-1 != $r->[1] && $r->[1] <= $Cflow::endtime);

      warn "ftp-PASV data flow: $srcip.$srcport -> $dstip.$dstport $protocol $pkts $bytes\n" if $CampusIO::Verbose;

      $ref->{app}{"ftpPASV_$r->[2]"}{$which}{flows}++;
      $ref->{app}{"ftpPASV_$r->[2]"}{$which}{bytes} += $Cflow::bytes;
      $ref->{app}{"ftpPASV_$r->[2]"}{$which}{pkts} += $Cflow::pkts;

      if ($self->{ftpPASVFH}) {
	 syswrite($self->{ftpPASVFH}, $Cflow::raw, length $Cflow::raw)
      }

      return 1

   } elsif (21 == $dstport) {

      $server = $Cflow::dstaddr;
      $client = $Cflow::srcaddr

   } elsif (21 == $Cflow::srcport) {

      $server = $Cflow::srcaddr;
      $client = $Cflow::dstaddr

   } else {
      return 0
   }

   # At this point we think we have an ftp control flow (using TCP port 21)...
   if ($Cflow::TH_ACK & $Cflow::tcp_flags ||
       0 == $Cflow::tcp_flags) {
       # thanks to Simon Leinen <simon@limmat.switch.ch> for hint to look
       # for ACK in TCP stream, to be sure it is an active session.
       # As a kludge however for RiverStone's LFAP, we also accept flows
       # with no tcp_flags set, since LFAP doesn't supply the flags.
       # This is not likely to be harmful in a NetFlow environment, since
       # nearly all TCP NetFlow v5 flows have a non-zero $tcp_flags value.
       # (An experiment showed that only .0005% of NetFlow v5 TCP flows
       # had no flags set.)
      if (-1 == $CampusIO::FTPSession{"$client:$server"}[0] ||
	  $CampusIO::FTPSession{"$client:$server"}[0] < $Cflow::endtime) {
	 # We don't want to be too liberal with what we presume are PASV
	 # ftp data flows since users of other sharing applications (such
	 # as gnutella) may be ftp "power users" as well, and could have
	 # both running simultaneously, which would inadvertently lead us
	 # to believe that they are the result of PASV ftp transfers.

         # [0] stores the time_t value for the last flow seen  with ACK set
         # [1] stores the time_t value for the last flow seen with FIN set
         # [2] stores the "direction", either 'src' or 'dst' (meaning that
	 #     the ftp server is either the source or destination of traffic
	 #     for flows that get a hit using
	 #     $CampusIO::FTPSession{"$srcaddr:$dstaddr"}.
	 # (Traditionally (time_t)-1 is an invalid time_t value.)
	 $CampusIO::FTPSession{"$client:$server"}[0] = $Cflow::endtime;
	 $CampusIO::FTPSession{"$client:$server"}[1] = -1; # no FIN seen yet
	 $CampusIO::FTPSession{"$client:$server"}[2] = 'dst';
	 # Duplicate the entry in the hash (with the client and server
	 # address reversed in the key, so that we only have to do one
	 # hash lookup when testing candidate ftp PASV data flows:
	 $CampusIO::FTPSession{"$server:$client"}[0] = $Cflow::endtime;
	 $CampusIO::FTPSession{"$server:$client"}[1] = -1; # no FIN seen yet
	 $CampusIO::FTPSession{"$server:$client"}[2] = 'src';
      }
   }
   if ($Cflow::TH_FIN & $tcp_flags) {
      # lose the ACK time, we've got FIN:
      $CampusIO::FTPSession{"$client:$server"}[0] = -1;
      $CampusIO::FTPSession{"$client:$server"}[1] = $Cflow::endtime; # FIN time
      $CampusIO::FTPSession{"$client:$server"}[2] = 'dst';
      # Duplicate the entry in the hash (with the client and server
      # address reversed in the key), so that we only have to do one
      # hash lookup when testing candidate ftp PASV data flows:
      # lose the ACK time, we've got FIN:
      $CampusIO::FTPSession{"$server:$client"}[0] = -1;
      $CampusIO::FTPSession{"$server:$client"}[1] = $Cflow::endtime; # FIN time
      $CampusIO::FTPSession{"$server:$client"}[2] = 'src';
   }

   # FIXME? Should we be keeping a count of the number of ftp control streams
   # between a given client and server?  (While it is probably unlikely for
   # this to occur, the code certainly can't do the right thing unless it
   # keeps count of the current number of ftp control streams.)

   return 0
}

# Napster
#
#    TCP port 8875 to connect to napster.com servers:
#
#       208.49.228.0/255.255.255.0
#       208.184.216.0/255.255.255.0
#       208.49.239.240/255.255.255.240
#       208.178.175.128/255.255.255.248
#       208.178.163.56/255.255.255.248
#
#    any TCP port to connect to other napster users' servers,
#    unreserved ports are the most likely(?).  Defaults are
#    4444,5555,6666,7777,8888.  I have read that ports 6697 and
#    6699 are used as well.

sub NapsterWanted {
   my $self = shift;
   my $which = shift;
   my $ref = shift;
   my($outside_addr, $inside_addr);

   # Skip TCP traffic on reserved ports:
   # We check for the protocol here since some Napster traffic may be ICMP, no?
   # FIXME? should the following test for reserved ports be "1024 <= $val"?
   return(0) unless (1 == $protocol ||
		     (6 == $protocol && 1024 < $srcport && 1024 < $dstport));

   if ('in' eq $which) {
      $outside_addr = $srcaddr;
      $inside_addr = $dstaddr
   } elsif ('out' eq $which) {
      $outside_addr = $dstaddr;
      $inside_addr = $srcaddr
   } else {
      die
   }

   # FIXME - we should only consider it to be an "active" NapServer
   # (either a redirect or index server) if it is the *source* and
   # has the ACK bit set:  
   if (6 == $protocol &&
       (($Cflow::TH_ACK & $tcp_flags)
	|| 0 == $Cflow::tcp_flags) # kludge for LFAP which has zero flags
	&& $CampusIO::nptrie->match_integer($outside_addr)) {
      # OK, this looks like traffic involving a a NapServer...
      # build a cache of hosts that look like "Napster" servers:
      # Periodically, these caches are purged of old entries by the
      # NapsterPurgeCache subroutine.
      $CampusIO::NapServer{$outside_addr} = $endtime;
      $CampusIO::NapUser{$inside_addr} = $endtime;
   } elsif (defined($CampusIO::NapUser{$inside_addr})) {
      # FIXME - check $outside_port against the default ports (above) and
      # report "high" and "low" confidence traffic accordingly.
   } else {
      return 0
   }
   if (((grep($srcport == $_, @CampusIO::NapsterPorts) ||
         grep($dstport == $_, @CampusIO::NapsterPorts)) &&
        6 == $protocol) ||
	(1 == $protocol &&
	 (0 == $pkts || # avoid div by 0 for slate2cflow/sfas flows with 0 pkts
	  28 == $bytes/$pkts))) {
      # In addition the the TCP streams to pass data,
      # I've seen Napster application users doing lots of these 28-byte "pings".
      # "Confidence is high -- I repeat -- Confidence is high."
      warn "HIGH confidence NapFlow: $srcip.$srcport -> $dstip.$dstport $protocol $pkts $bytes\n" if $CampusIO::Verbose;
      $ref->{app}{NapUser}{$which}{flows}++;
      $ref->{app}{NapUser}{$which}{bytes} += $bytes;
      $ref->{app}{NapUser}{$which}{pkts} += $pkts;
      if ($self->{NapUserFH}) {
	 syswrite($self->{NapUserFH}, $Cflow::raw, length $Cflow::raw)
      }
   } else { # low/no confidence...
      warn " LOW confidence NapFlow: $srcip.$srcport -> $dstip.$dstport $protocol $pkts $bytes\n" if $CampusIO::Verbose;
      $ref->{app}{NapUserMaybe}{$which}{flows}++;
      $ref->{app}{NapUserMaybe}{$which}{bytes} += $bytes;
      $ref->{app}{NapUserMaybe}{$which}{pkts} += $pkts;
      if ($self->{NapUserMaybeFH}) {
	 syswrite($self->{NapUserMaybeFH}, $Cflow::raw, length $Cflow::raw)
      }
   }
   return 1
}

sub ASwanted {
   my $self = shift;
   my $ref = shift;
   my $aspair = "$src_as:$dst_as";
   $ref->{as}{$aspair}{flows}++;
   $ref->{as}{$aspair}{bytes} += $bytes;
   $ref->{as}{$aspair}{pkts} += $pkts
}

sub wanted_app {
   my $self = shift @_;

   # Trying to identifying applications is tricky business...
   # These tests should be mutually excusive (I think) and they should
   # be ordered from most to least confidence based on the method used
   # to identify the application:
   $self->ftpPASVWanted($self->{CampusIO}{which}, $self->{total}) or
   $self->RealWanted($self->{CampusIO}{which}, $self->{total}) or
   $self->QuakeWanted($self->{CampusIO}{which}, $self->{total}) or
   (@CampusIO::napster_files &&
    $self->NapsterWanted($self->{CampusIO}{which}, $self->{total}))
}

sub wanted_service {
   my $self = shift @_;

   # keep totals by service
   if (defined $CampusIO::service{$protocol}) {
      my $ref = $self->{total};
      if (defined $CampusIO::service{$protocol}{$srcport}) {
	  $ref->{service}{$protocol}{src}{$srcport}{$self->{CampusIO}{which}}{flows}++;
	  $ref->{service}{$protocol}{src}{$srcport}{$self->{CampusIO}{which}}{bytes} += $bytes;
	  $ref->{service}{$protocol}{src}{$srcport}{$self->{CampusIO}{which}}{pkts} += $pkts;
	  return 1
      }
      if (defined $CampusIO::service{$protocol}{$dstport}) {
	 $ref->{service}{$protocol}{dst}{$dstport}{$self->{CampusIO}{which}}{flows}++;
	 $ref->{service}{$protocol}{dst}{$dstport}{$self->{CampusIO}{which}}{bytes} += $bytes;
	 $ref->{service}{$protocol}{dst}{$dstport}{$self->{CampusIO}{which}}{pkts} += $pkts;
	 return 1
      }
   }
   return 0
}
sub wanted {
   my $self = shift;
   my $ref;

   $self->{CampusIO}{which} = ''; # unknown if this is an in or out-bound flow

   # check for multicast:
   if ($CampusIO::MCAST_NET == ($CampusIO::MCAST_MASK & $dstaddr)) {
      my $srcnet = $CampusIO::ptrie->match_integer($srcaddr);
      # FIXME?  What if multicast flow is intracampus (neither 'in' nor 'out')?:
      $self->{CampusIO}{which} = (ref($srcnet))? 'out' : 'in';
      # keep multicast grand totals...
      $self->{multicast}{total}{$self->{CampusIO}{which}}{flows}++;
      $self->{multicast}{total}{$self->{CampusIO}{which}}{bytes} += $bytes;
      $self->{multicast}{total}{$self->{CampusIO}{which}}{pkts} += $pkts;

      # return zero since we don't really know whether or not this multicast flows really represents Campus I/O or not
      return 0
   }

   if (0 == $nexthop) { # skip non-routable unicast traffic
      return 0
   }

   # FIXME - keep stats for flows where 0 == $output_if && 0 != $nexthop, then:
   return(0) if (0 == $output_if); # skip black-holed unicast traffic
   
   if ($CampusIO::hops_ptrie->match_integer($nexthop) ||
       (@CampusIO::output_if && grep($output_if == $_, @CampusIO::output_if)) ||
       !$CampusIO::ptrie->match_integer($dstaddr)) {
      # this looks like its an outbound flow...

      # check to see if this traffic involves the web proxy:
      # we must use the ifIndex number because that's the only indication
      # NetFlow gives that it was policy routed.  Why the nexthop doesn't
      # reflect this, I don't know.
      if ($CampusIO::WebProxy_ifIndex == $output_if &&
          6 == $protocol &&
          80 == $dstport) {
         warn "Web Proxy flow: ifIndex $input_if $srcip.$srcport -> ifIndex $output_if $dstip.$dstport $protocol $pkts $bytes\n" if $CampusIO::Verbose;
         return 0
      }

      # maintain AS matrices
      # this isn't strictly "Campus I/O" - here we accumulate totals for
      # everything the router saw (that had a nexthop)...
      $self->ASwanted($self->{total});

      $self->{CampusIO}{which} = 'out';

      if (ref($CampusIO::originAS_pt)) {
         my $as_ref;
         if ($as_ref = $CampusIO::originAS_pt->match_integer($dstaddr)) {
	    $as_ref->{origin}{out} += $bytes;
	    foreach my $pathas (@{$as_ref->{path}}) {
	       $pathas->{out} += $bytes
	    }
         } else {
	    $CampusIO::originAS{unidentified}{origin}{out} += $bytes
         }
      }

      # keep track of which interface it went out on...
      # Later, this will help us to determine if a other flows represents
      # inbound traffic.  (I.e. if a flow's input_if is one of the output_ifs
      # that was used to get to one of the @hops, then it is likely to be an 
      # inbound flow.  No?)
      $exporterip && $self->{if}->{$exporterip}{$self->{CampusIO}{which}}{$output_if}++;

      # keep outbound grand totals...
      $self->{total}->{$self->{CampusIO}{which}}{flows}++;
      $self->{total}->{$self->{CampusIO}{which}}{bytes} += $bytes;
      $self->{total}->{$self->{CampusIO}{which}}{pkts} += $pkts;

      # keep totals by proto
      if (defined $CampusIO::proto{$protocol}) {
	 $ref = $self->{total};
	 $ref->{proto}{$protocol}{$self->{CampusIO}{which}}{flows}++;
	 $ref->{proto}{$protocol}{$self->{CampusIO}{which}}{bytes} += $bytes;
	 $ref->{proto}{$protocol}{$self->{CampusIO}{which}}{pkts} += $pkts
      }

      my $identified = $self->wanted_app;
      if ($self->wanted_service) {
         $identified = 1
      }
      if (!$identified && $self->{otherFH}) {
	 syswrite($self->{otherFH}, $Cflow::raw, length $Cflow::raw)
      }

      my $cargo = $CampusIO::ptrie->match_integer($srcaddr);
      if (!ref($cargo)) { # keep outbound totals for unknown nets
         $self->{unknown}->{$self->{CampusIO}{which}}{flows}++;
         $self->{unknown}->{$self->{CampusIO}{which}}{bytes} += $bytes;
         $self->{unknown}->{$self->{CampusIO}{which}}{pkts} += $pkts;
         return(0)
      }

      # keep outbound totals for subnet...
      $cargo->{$self->{CampusIO}{which}}{bytes} += $bytes;
      $cargo->{$self->{CampusIO}{which}}{pkts} += $pkts;
      $cargo->{$self->{CampusIO}{which}}{flows}++;

      my $hr; # hashref to src/dst host stats
      if (!($hr = $cargo->{src_pt}->match_integer($srcaddr))) {
         $hr = $cargo->{src_pt}->add_string($srcip, { addr => $srcip,
                                                      bytes => 0,
                                                      pkts => 0,
                                                      flows => 0 });
         die unless ref($hr)
      }
      # keep stats by src or dst address within the CIDR block:
      $hr->{bytes} += $bytes;
      $hr->{pkts} += $pkts;
      $hr->{flows}++;

      return 1

   } else { # Hmm, this *might* be an inbound flow...

      # be sure its nexthop is not another local router, lest we count the
      # traffic twice.
      if ($CampusIO::localhops_ptrie->match_integer($nexthop)) {
	 warn "Skipping \"inbound\" candidate flow from ${srcip} destined for ${dstip} via \"local\" nexthop ${nexthopip}.\n" if $CampusIO::Verbose;
	 return(0)
      }
      my $srcnet = $CampusIO::ptrie->match_integer($srcaddr);
      if (!ref($srcnet)) { # looks like it's a flow from an outside network...

         # check to see if this traffic involves the web proxy:
         # we must use the ifIndex number because that's the only indication
         # NetFlow gives that it was policy routed.  Why the nexthop doesn't
         # reflect this, I don't know.
         if ($CampusIO::WebProxy_ifIndex == $input_if &&
             6 == $protocol &&
             80 == $srcport) {
            warn "Web Proxy flow: ifIndex $input_if $srcip.$srcport -> ifIndex $output_if $dstip.$dstport $protocol $pkts $bytes\n" if $CampusIO::Verbose;
            return 0
         }

         # maintain AS matrices
         # this isn't strictly "Campus I/O" - here we accumulate totals for
         # everything the router saw (that had a nexthop)...
         $self->ASwanted($self->{total});

         $self->{CampusIO}{which} = 'in';

         if (ref($CampusIO::originAS_pt)) {
            my $as_ref;
            if ($as_ref = $CampusIO::originAS_pt->match_integer($srcaddr)) {
	       $as_ref->{origin}{in} += $bytes;
	       foreach my $pathas (@{$as_ref->{path}}) {
	          $pathas->{in} += $bytes
	       }
            } else {
	       $CampusIO::originAS{unidentified}{origin}{in} += $bytes
            }
         }

         # keep inbound grand totals...
         $self->{total}->{$self->{CampusIO}{which}}{flows}++;
         $self->{total}->{$self->{CampusIO}{which}}{bytes} += $bytes;
         $self->{total}->{$self->{CampusIO}{which}}{pkts} += $pkts;

      # keep totals by proto
      if (defined $CampusIO::proto{$protocol}) {
	 $ref = $self->{total};
	 $ref->{proto}{$protocol}{$self->{CampusIO}{which}}{flows}++;
	 $ref->{proto}{$protocol}{$self->{CampusIO}{which}}{bytes} += $bytes;
	 $ref->{proto}{$protocol}{$self->{CampusIO}{which}}{pkts} += $pkts
      }

      my $identified = $self->wanted_app;
      if ($self->wanted_service) {
         $identified = 1
      }
      if (!$identified && $self->{otherFH}) {
	 syswrite($self->{otherFH}, $Cflow::raw, length $Cflow::raw)
      }

	 # keep a count of how many times we see this input interface
         $exporterip && $self->{if}->{$exporterip}{$self->{CampusIO}{which}}{$input_if}++;

         my $cargo = $CampusIO::ptrie->match_integer($dstaddr);
         if (!ref($cargo)) { # keep inbound totals for unknown nets
            $self->{unknown}->{$self->{CampusIO}{which}}{flows}++;
            $self->{unknown}->{$self->{CampusIO}{which}}{bytes} += $bytes;
            $self->{unknown}->{$self->{CampusIO}{which}}{pkts} += $pkts;
         } else {
            # keep inbound totals for subnet...
            $cargo->{$self->{CampusIO}{which}}{bytes} += $bytes;
            $cargo->{$self->{CampusIO}{which}}{pkts} += $pkts;
            $cargo->{$self->{CampusIO}{which}}{flows}++;
         }

         my $hr; # hashref to src/dst host stats
         if (!($hr = $cargo->{dst_pt}->match_integer($dstaddr))) {
            $hr = $cargo->{dst_pt}->add_string($dstip, { addr => $dstip,
                                                         bytes => 0,
                                                         pkts => 0,
                                                         flows => 0 });
            die unless ref($hr)
         }
         # keep stats by src or dst address within the CIDR block:
         $hr->{bytes} += $bytes;
         $hr->{pkts} += $pkts;
         $hr->{flows}++;

	 return 1

      } else {
	 # even though this doesn't look like an inbound flow, check which
	 # interface it came in on and warn if it looks like it should have
	 # been selected as an inbound flow...
	 if ($CampusIO::Verbose && $exporterip && $self->{if}->{$exporterip}{out}{$input_if}) {
	    warn "Skipping flow from ${srcip} destined for ${dstip} via nexthop ${nexthopip} because it looks like an inbound flow, but is sourced from a local network/subnet.  It came in via interface $input_if (on router $exporterip), which is one of this router's known interfaces to the outside world: ", join(", ", keys(%{$self->{if}->{$exporterip}{out}})), ".\n"
	 }
	 return 0
      }
      # NOTREACHED
      die
   }
   # NOTREACHED
   die
}

sub perfile {
   my $self = shift;
   my $file = shift;

   $self->SUPER::perfile($file);

   if ('' eq ${CampusIO::outputdir}) { # write to the same directory
      $self->{outputdir} = dirname($file)
   } elsif (${CampusIO::outputdir} =~ m|^/|) { # write to the absolute directory
      $self->{outputdir} = ${CampusIO::outputdir}
   } else { # write to the relative directory
      $self->{outputdir} = dirname($file) . '/' . ${CampusIO::outputdir}
   }

   # Purge "old" entries from the RealServer hash:
   $self->RealServerPurge;

   # Purge "old" entries from the FTPSession hash:
   $self->FTPSessionPurge;

   if (@CampusIO::NapsterPorts) {
      # before processing the file, clear the NapsterCache of "old" entries:
      $self->NapsterCachePurge; # relies on filetime being set...
   }

   my $dirname = dirname $file;
   my $basename = basename $file;
   for my $bin (qw(ftpPASV NapUser NapUserMaybe other)) {
      undef $self->{"${bin}FH"}; # close the previous raw flow file
      if (-d "$dirname/saved/${bin}") {
	 my $filename = "$dirname/saved/${bin}/$basename";
	 if (!($self->{"${bin}FH"} = new IO::File ">${filename}")) {
            warn(strftime("%Y/%m/%d %H:%M:%S", localtime),
	       " open \"$filename\" failed: $!\n")
         }
      }
   }
   $CampusIO::ptrie->climb(sub { $self->clear_node_users(@_) });

   # reload the ASNFile (if it is newer than that last read)
   load_asn($c->value('ASNFile'))
}

sub NapsterCachePurge {
   my $self = shift;
   my $whence = $self->{filetime} - $CampusIO::NapsterSeconds;

   warn(strftime("%Y/%m/%d %H:%M:%S", localtime),
	" %CampusIO::NapServer -> ",
	scalar(%CampusIO::NapServer),
	" %CampusIO::NapUser -> ",
	scalar(%CampusIO::NapUser),
	"\n") if $CampusIO::verbose;

   while (my($k, $v) = each(%CampusIO::NapServer)) {
      if ($v < $whence) {
         warn("Purging NapServer ", inet_ntoa(pack("N", $k)), " ",
	      scalar(strftime("%Y/%m/%d %H:%M:%S", localtime($v))), " < ",
	      scalar(strftime("%Y/%m/%d %H:%M:%S", localtime($whence))), "\n")
		 if $CampusIO::Verbose;
         delete($CampusIO::NapServer{$k})
      }
   }
   while (my($k, $v) = each(%CampusIO::NapUser)) {
      if ($v < $whence) {
         warn("Purging NapUser ", inet_ntoa(pack("N", $k)), " ",
	      scalar(strftime("%Y/%m/%d %H:%M:%S", localtime($v))), " < ",
	      scalar(strftime("%Y/%m/%d %H:%M:%S", localtime($whence))), "\n")
		 if $CampusIO::Verbose;
         delete($CampusIO::NapUser{$k})
      }
   }

   warn(strftime("%Y/%m/%d %H:%M:%S", localtime),
	" %CampusIO::NapServer -> ",
	scalar(%CampusIO::NapServer),
	" %CampusIO::NapUser -> ",
	scalar(%CampusIO::NapUser),
	"\n") if $CampusIO::verbose;
}

sub FTPSessionPurge {
   my $self = shift;

   # For the timers below, experimentation with ~ an hour of flows on
   # 2000/07/18 ~23:00:00 CDT showed that I counted about 90% the total
   # number of PASV mode ftp traffic in bytes when the timeouts were
   # 5 and 15 minutes rather than 15 and 30, respectively.

   # purge sessions for which we've seen FIN after only 15 minutes:
   my $whence_fin = $self->{filetime} - 15*60;
   # purge sessions for which we've seen ACK (but no FIN) after 30 minutes:
   my $whence_ack = $self->{filetime} - 30*60;

   warn(strftime("%Y/%m/%d %H:%M:%S", localtime),
	" %CampusIO::FTPSession -> ",
	scalar(%CampusIO::FTPSession), "\n") if $CampusIO::verbose;

   while (my($k, $v) = each(%CampusIO::FTPSession)) {
      if ((-1 != $v->[1] && $v->[1] < $whence_fin) ||
	  $v->[0] < $whence_ack) {
         delete($CampusIO::FTPSession{$k})
      }
   }

   warn(strftime("%Y/%m/%d %H:%M:%S", localtime),
	" %CampusIO::FTPSession -> ",
	scalar(%CampusIO::FTPSession), "\n") if $CampusIO::verbose;
}

sub RealServerPurge {
   my $self = shift;
   # purge Real servers after 60 minutes of inactivity:
   my $whence = $self->{filetime} - 60*60;

   while (my($k, $v) = each(%CampusIO::RealServer)) {
      delete($CampusIO::RealServer{$k}) if ($v < $whence)
   }
}

sub createRRD {
   my $self = shift;
   die unless ref($self);
   my $file = shift;
   if (@_) {
      @CampusIO::prefix = @_
   } else {
      @CampusIO::prefix = ('')
   }

   my $time_t = $self->{filetime};

   my $startwhen = $time_t - 300;
   my(@DS, $prefix, $thingy);
   foreach $thingy ('bytes', 'pkts', 'flows') {
      foreach $prefix (@CampusIO::prefix) {
         push(@DS, "DS:${prefix}${thingy}:ABSOLUTE:400:U:U")
      }
   }
   RRDs::create($file,
      '--start', $startwhen,
      '--step', 300,
      @DS,
      qw(
         RRA:AVERAGE:0:1:600
         RRA:AVERAGE:0:6:600
         RRA:AVERAGE:0:24:600
         RRA:AVERAGE:0:288:732
         RRA:MAX:0:24:600
         RRA:MAX:0:288:732
	 )
      );
   my $err=RRDs::error;
   warn "ERROR creating $file: $err\n" if $err;
}

sub updateRRD {
   my $self = shift;
   die unless ref($self);
   my $file = shift;
   my @values = @_;

   RRDs::update($file, $self->{filetime} . ':' . join(':', @values));
   my $err=RRDs::error;
   if ($err) {
      warn "ERROR updating $file: $err\n"
   }
}

sub MulticastReportRRD {
   my $self = shift;
   my $file = $self->{outputdir} . "/MCAST.rrd";
   $self->createRRD($file, 'in_', 'out_') unless -f $file;

   my @values = ();
   my $thingy;
   foreach $thingy ('bytes', 'pkts', 'flows') {
      push(@values,
	   0+$self->{multicast}{total}{in}{$thingy},
	   0+$self->{multicast}{total}{out}{$thingy}
	  );
   }
   $self->updateRRD($file, @values)
}

sub RealReportRRD {
   my $self = shift;
   my $file = $self->{outputdir} . "/RealAudio.rrd";
   $self->createRRD($file, 'in_', 'out_') unless -f $file;

   my @values = ();
   my $thingy;
   foreach $thingy ('bytes', 'pkts', 'flows') {
      push(@values,
	   0+$self->{total}->{app}{RealAudio}{in}{$thingy},
	   0+$self->{total}->{app}{RealAudio}{out}{$thingy}
	  );
   }
   $self->updateRRD($file, @values);

   warn(strftime("%Y/%m/%d %H:%M:%S", localtime), " scalar(%CampusIO::RealServer) -> ", scalar(%CampusIO::RealServer), "\n") if $CampusIO::verbose;
}

sub AppReportRRD {
   my $self = shift;
   my $app = shift;
   my $file = $self->{outputdir} . "/${app}.rrd";
   $self->createRRD($file, 'in_', 'out_') unless -f $file;

   my @values = ();
   my $thingy;
   foreach $thingy ('bytes', 'pkts', 'flows') {
      push(@values,
	   0+$self->{total}->{app}{$app}{in}{$thingy},
	   0+$self->{total}->{app}{$app}{out}{$thingy}
	  );
   }
   $self->updateRRD($file, @values);
}

sub originASreport {
   my $self = shift;
   my $whence = shift;

   foreach my $type ('origin', 'path') {
      foreach my $which ('in', 'out') {
         my $htmlfile = $self->{outputdir} . '/'; # to be continued:
         if ($c->value('ReportPrefixFormat')) {
            $htmlfile .= strftime($c->value('ReportPrefixFormat'),
				  localtime($whence));
         }
         $htmlfile .= "${type}AS_${which}.html";

	 $self->mkdirs_as_necessary($htmlfile);

         my $fh = new IO::File ">$htmlfile";
         if (!ref($fh)) {
            warn "open \"$htmlfile\": $!";
            next
         }
         print $fh "<body bgcolor=\"#ffffff\">\n<center>\n\n";
      
         my $table = new 'HTML::Table';
         die unless ref($table);
         $table->setBorder(1);
         $table->setCellSpacing(0);
         $table->setCellPadding(3);
         $table->setCaption("Top $CampusIO::TopN ${type} ASNs " .
			    "by bytes <b>$which</b><br>\n" .
                            "for five minute flow sample ending " .
		            scalar(localtime($self->{filetime})),
			    'TOP');
         $table->addRow('<b>rank</b>',
		        "<b>${type}-AS</b>",
		        '<b>bits/sec in</b>',
		        "<b>% of total in</b>",
		        '<b>bits/sec out</b>',
		        "<b>% of total out</b>");
         my $row = 1;
         $table->setRowBGColor($row, '#FFFFCC'); # pale yellow
         $table->setCellBGColor($row,
				3+2*('out' eq $which),
				'#90ee90'); # light green
         $table->setCellBGColor($row,
				4+2*('out' eq $which),
				'#90ee90'); # light green
      
         my $n = $CampusIO::TopN;
         my $m = 1;
         foreach my $as (sort {
	                    $CampusIO::originAS{$b}{$type}{$which} <=>
	                       $CampusIO::originAS{$a}{$type}{$which}
	                 } keys %CampusIO::originAS) {
	    my $asname = $CampusIO::asn[$as]? "$CampusIO::asn[$as] ($as)" : $as;
            $row++;
            $table->addRow("#$m",
   "<a href=\"http://arin.net/cgi-bin/whois.pl?queryinput=AS+$as\">$asname</a>",
                           scale("%.1f",
				 ($CampusIO::originAS{$as}{$type}{in}*8)/300),
                           sprintf("%.1f%%",
				   percent($CampusIO::originAS{$as}{$type}{in},
					   $self->{total}{in}{bytes})),
                           scale("%.1f",
				 ($CampusIO::originAS{$as}{$type}{out}*8)/300),
		           sprintf("%.1f%%",
				   percent($CampusIO::originAS{$as}{$type}{out},
					   $self->{total}{out}{bytes})));

	    $table->setRowAlign($row, 'RIGHT');
            $table->setCellBGColor($row,
				   3+2*('out' eq $which),
				   '#add8e6'); # light blue
            $table->setCellBGColor($row,
				   4+2*('out' eq $which),
				   '#add8e6'); # light blue
            last unless --$n;
            $m++
         }
         print $fh "<p>\n$table</p>\n\n";
         print $fh "\n</center>\n</body>\n";
         undef $fh; # close the file
      }
   }
}

sub ASreportRRD {
   my $self = shift;
   my $aspair;

   foreach $aspair (@CampusIO::as2as) {
      my $file = $self->{outputdir} . "/$aspair.rrd";
      $self->createRRD($file, '') unless -f $file;

      my @values = ();
      my $thingy;
      foreach $thingy ('bytes', 'pkts', 'flows') {
         push(@values, 0+$self->{total}->{as}{$aspair}{$thingy});
      }
      $self->updateRRD($file, @values);
   }
}

sub scale($$) { # This is based somewhat on Tobi Oetiker's code in rrd_graph.c: 
   my $fmt = shift;
   my $value = shift;
   my @symbols = ("a", # 10e-18 Ato
                  "f", # 10e-15 Femto
                  "p", # 10e-12 Pico
                  "n", # 10e-9  Nano
                  "u", # 10e-6  Micro
                  "m", # 10e-3  Milli
                  " ", # Base
                  "k", # 10e3   Kilo
                  "M", # 10e6   Mega
                  "G", # 10e9   Giga
                  "T", # 10e12  Terra
                  "P", # 10e15  Peta
                  "E");# 10e18  Exa

   my $symbcenter = 6;
   my $digits = (0 == $value)? 0 : floor(log($value)/log(1000));
   return sprintf(${fmt} . " %s", $value/pow(1000, $digits),
                  $symbols[$symbcenter+$digits])
}

sub percent($$) {
   my $num = shift;
   my $denom = shift;
   return(0) if (0 == $denom);
   return 100*($num/$denom)
}

sub report_users {
   my $self = shift(@_);
   die unless ref($self);
   my $hr = shift(@_);
   die unless ref($hr);
   my $top = shift(@_);
   my $prefix = shift(@_);
   my $whence = shift(@_);
   my @topn;

   my $subnet = $hr->{SUBNET};
   die unless $subnet;
   $subnet =~ s:/:_:; # "/" not allowed in file names...

   if ($top) {
   # report top talkers ('src') and listeners ('dst') in bytes, pkts, and flows:

   my $htmlfile = $self->{outputdir} . '/'; # to be continued:
   if ($prefix) {
      $htmlfile .= strftime($prefix,
			    localtime($whence? $whence : $self->{rrdtime}));
   }
   $htmlfile .= "${subnet}_top.html";

   $self->mkdirs_as_necessary($htmlfile);

   my $fh = new IO::File ">$htmlfile";
   if (!ref($fh)) {
      warn "open \"$htmlfile\": $!";
      next
   }
   print $fh "<body bgcolor=\"#ffffff\">\n<center>\n\n";
   my %direction = ('src' => 'out', 'dst' => 'in');
   my %other = ('src' => 'dst', 'dst' => 'src');
   foreach my $x ('src', 'dst') {
      my @top = ();
      # populate @top with hashrefs:
      $hr->{$x . '_pt'}->climb(sub { push(@top, $_[0]) });

      # rank => 1, addr => 2:
      my %thingy = ('bytes' => 3, 'pkts' => 5, 'flows' => 7);
      foreach my $thingy (sort { $thingy{$a} <=> $thingy{$b} } keys(%thingy)) {
         my $n = $top;
	 my $table = new 'HTML::Table';
	 die unless ref($table);
	 $table->setBorder(1);
	 $table->setCellSpacing(0);
	 $table->setCellPadding(3);
         $table->setCaption("Top $top $hr->{SUBNET} hosts " .
			    "by <b>$thingy $direction{$x}</b><br>\n" .
                            "for five minute flow sample ending " .
		            scalar(localtime($self->{filetime})),
			    'TOP');
	 my $row = 1;
	 $table->addRow('<b>rank</b>',
			"<b>$x Address</b>",
			'<b>bits/sec in</b>',
			'<b>bits/sec out</b>',
			'<b>pkts/sec in</b>',
			'<b>pkts/sec out</b>',
			'<b>flows/sec in</b>',
			'<b>flows/sec out</b>');
	 $table->setRowBGColor($row, '#FFFFCC'); # pale yellow
	 $table->setCellBGColor($row,
				$thingy{$thingy} + ('out' eq $direction{$x}),
				'#90ee90'); # light green
	 $row++;
         foreach my $tophr (sort { $b->{$thingy} <=> $a->{$thingy} } @top) {
	    my $other;
            if (!($other =
		     $hr->{$other{$x} . '_pt'}->match_string($tophr->{addr}))) {
	       $other->{bytes} = 0;
	       $other->{pkts} = 0;
	       $other->{flows} = 0
	    }
	    my($in, $out);
	    if ('in' eq $direction{$x}) {
	       $in = $tophr;
	       $out = $other;
            } else {
	       $out = $tophr;
	       $in = $other;
	    }
	    $table->addRow(sprintf("#%d", $row-1), # rank
			   $tophr->{addr},
                           scale("%.1f", ($in->{bytes}*8)/300)
			      . sprintf(" (%.1f%%)",
				       percent($in->{bytes}, $hr->{in}{bytes})),
                           scale("%.1f", ($out->{bytes}*8)/300)
			      . sprintf(" (%.1f%%)",
				     percent($out->{bytes}, $hr->{out}{bytes})),
			   scale("%.1f", $in->{pkts}/300)
			      . sprintf(" (%.1f%%)",
				         percent($in->{pkts}, $hr->{in}{pkts})),
			   scale("%.1f", $out->{pkts}/300)
			      . sprintf(" (%.1f%%)",
				       percent($out->{pkts}, $hr->{out}{pkts})),
			   scale("%.1f", $in->{flows}/300)
			      . sprintf(" (%.1f%%)",
				       percent($in->{flows}, $hr->{in}{flows})),
			   scale("%.1f", $out->{flows}/300)
			      . sprintf(" (%.0f%%)",
				    percent($out->{flows}, $hr->{out}{flows})));
	    $table->setRowAlign($row, 'RIGHT');
	    $table->setCellBGColor($row,
				   $thingy{$thingy} + ('out' eq $direction{$x}),
				   '#add8e6'); # light blue
	    push(@topn, $hr);
            last unless --$n;
	    $row++
         }
	 print $fh "<p>\n$table</p>\n\n";
      }
   }
   print $fh "\n</center>\n</body>\n"
   }

   return ($hr->{src_pt}->climb(sub { 1 }), # tx
	   $hr->{dst_pt}->climb(sub { 1 }), # rx
	   @topn)
}

sub report_node {
   my $self = shift(@_);
   die unless ref($self);
   my $hr = shift(@_);
   die unless ref($hr);
   my $top = shift(@_);
   my $prefix = shift(@_);
   my $whence = shift(@_);

   my $subnet = $hr->{SUBNET};
   die unless $subnet;
   $subnet =~ s:/:_:; # "/" not allowed in file names...
   my $file = $self->{outputdir} . "/${subnet}.rrd";
   $self->createGeneralRRD($file,
			   qw(
			      ABSOLUTE in_bytes
			      ABSOLUTE out_bytes
			      ABSOLUTE in_pkts
			      ABSOLUTE out_pkts
			      ABSOLUTE in_flows
			      ABSOLUTE out_flows
			      GAUGE    tx
			      GAUGE    rx
			     )
			  ) unless -f $file;

   my @values = ();
   foreach my $thingy ('bytes', 'pkts', 'flows') {
      push(@values, 0+$hr->{in}{$thingy}, 0+$hr->{out}{$thingy});
   }
   # report the number of active users by subnet:
   my($tx, $rx) = $self->report_users($hr, $top, $prefix, $whence);
   $self->updateRRD($file, @values, $tx, $rx);
   return($tx, $rx)
}

sub report {
   my $self = shift;
   $self->ASreportRRD;
   $self->AppReportRRD('ftpPASV_src');
   $self->AppReportRRD('ftpPASV_dst');
   $self->RealReportRRD;
   $self->AppReportRRD('Quake');
   $self->AppReportRRD('NapUser') if @CampusIO::napster_files;
   $self->AppReportRRD('NapUserMaybe') if @CampusIO::napster_files;
   $self->MulticastReportRRD;

   # { do unknown

   # we have no tx/rx counters for unknown hosts, so do unknown the "old" way:
   my $grand; # a grand total
   foreach $grand ('unknown') {
      my $file = $self->{outputdir} . "/${grand}.rrd";
      $self->createRRD($file, 'in_', 'out_') unless -f $file;

      my @values = ();
      my $thingy;
      foreach $thingy ('bytes', 'pkts', 'flows') {
         push(@values,
	      0+$self->{$grand}->{in}{$thingy},
	      0+$self->{$grand}->{out}{$thingy}
	     );
      }
      $self->updateRRD($file, @values);
   }

   # }{ kludge - find the timestamp that rrdtool used as an approximation of
   #             the current time.  We'll then use this in the HTML file names
   #             so that they'll "line up" evenly during every hour.
   #             I.e. if we set ReportPrefixFormat to "%M_" then our html file
   #             names will be "05_top.html", "10_top.html", "15_top.html"
   #             rather than being skewed with our update times as in
   #             "05_top.html", "11_top.html", etc.  This is advantageous
   #             because the files will overwrite each other every hour, so
   #             that there would never be more than 12 at a time and our
   #             disk won't fill.
   # We use "unknown.rrd" just because it's always there:
   my $file = $self->{outputdir} . "/unknown.rrd";
   my $last = $self->{filetime};
   my($start) = RRDs::fetch($file, 'AVERAGE', '-s', $last, '-e', $last);
   my $whence;
   if (300 < abs($last - $start)) {
      warn("Unexpected timestamp in \"$file\": ",
	scalar(localtime($start)), " ($start) not within 300 seconds of ",
	scalar(localtime($last)), " ($last)\n");
      $whence = $last
   } else {
      $whence = $start
   }
   $self->{rrdtime} = $whence;

   # }{ do the origin and path AS report(s):

   $self->originASreport($whence) if ref($CampusIO::originAS_pt);

   # }{ do networks/subnets

   # kludge to calculate total tx and rx by adding them up from each local net:
   $CampusIO::tx = 0;
   $CampusIO::rx = 0;

   $CampusIO::ptrie->climb(
      sub {
         my($tx, $rx) = $self->report_node(@_, $CampusIO::TopN,
				           $c->value('ReportPrefixFormat'),
					   $whence);
	 $CampusIO::tx += $tx;
	 $CampusIO::rx += $rx;
      }
   );

   # }{ do totals

   foreach $grand ('total') {
      my $file = $self->{outputdir} . "/${grand}.rrd";
      $self->createGeneralRRD($file,
			      qw(
			         ABSOLUTE in_bytes
			         ABSOLUTE out_bytes
			         ABSOLUTE in_pkts
			         ABSOLUTE out_pkts
			         ABSOLUTE in_flows
			         ABSOLUTE out_flows
			         GAUGE    tx
			         GAUGE    rx
			        )
			     ) unless -f $file;
      my @values = ();
      my $thingy;
      foreach $thingy ('bytes', 'pkts', 'flows') {
         push(@values,
	      0+$self->{$grand}->{in}{$thingy},
	      0+$self->{$grand}->{out}{$thingy}
	     );
      }
      $self->updateRRD($file, @values, $CampusIO::tx, $CampusIO::rx)
   }

   # }{ do protocols

   { # for scope only
   my $proto;
   foreach $proto (keys %CampusIO::proto) {
      my $name = getprotobynumber($proto);
      if ('' eq $name) {
	 $name = $proto
      }
      my $file = $self->{outputdir} . "/${name}.rrd";
      $self->createRRD($file, 'in_', 'out_') unless -f $file;

      my @values = ();
      my $thingy;
      foreach $thingy ('bytes', 'pkts', 'flows') {
         push(@values,
	      0+$self->{total}->{proto}{$proto}{in}{$thingy},
	      0+$self->{total}->{proto}{$proto}{out}{$thingy}
	     );
      }
      $self->updateRRD($file, @values);
   }
   }

   # }{ do services
   my($proto, $port, $direction);
   foreach $proto (keys %{$self->{total}->{service}}) {
      my $protoname = getprotobynumber($proto);
      die if ('' eq $protoname);
      foreach $direction ('src', 'dst') {
	 if ('tcp' eq $protoname ||
	     'udp' eq $protoname) {
	 foreach $port (keys %{$self->{total}->{service}{$proto}{$direction}}) {
	    my $service = getservbyport($port, $protoname);
	    if ('' eq $service) {
	       $service = $port
	    }

            my $file = $self->{outputdir} . "/"; # to be continued...
	    if ('tcp' eq $protoname) {
	       # For now keep the old file names for backward compatibility
	       # with RRD files that were created back when there were only
	       # TCPServices (no UDPServices).  FIXME
	       $file .= "${service}_${direction}.rrd"
	    } else {
	       $file .= "${protoname}_${service}_${direction}.rrd"
	    }

            $self->createRRD($file, 'in_', 'out_') unless -f $file;

            my @values = ();
            my $thingy;
            foreach $thingy ('bytes', 'pkts', 'flows') {
             push(@values,
	    0+$self->{total}->{service}{$proto}{$direction}{$port}{in}{$thingy},
	    0+$self->{total}->{service}{$proto}{$direction}{$port}{out}{$thingy}
	     );
            }
            $self->updateRRD($file, @values);
         }
	 } elsif ('icmp' eq $protoname) {
	    # FIXME - add the reporting of ICMP by type/code
	 }
      }
   }
   # }
}

sub clear_node_users {
   my $self = shift(@_);
   my $hr = shift(@_);
   die unless ref($hr);

   # (re-)initialize the patricia tries of active src and dst hosts
   $hr->{src_pt} = new Net::Patricia;
   die unless ref($hr->{src_pt});
   $hr->{dst_pt} = new Net::Patricia;
   die unless ref($hr->{dst_pt});
}

sub DESTROY {
   # zero the subnet counters (since they are class-level rather than
   # instance-level data objects)
   my $subnet;
   foreach $subnet (@CampusIO::subnets) {
      delete $subnet->{in};
      delete $subnet->{out}
   }
   # clear out the totals for all the AS counters:
   # (We do this rather than simply destroy CampusIO::originAS because the
   # originAS_pthas nodes with references pointing into it.)
   foreach my $ref (values(%CampusIO::originAS)) {
      foreach my $type ('origin', 'path') {
         foreach my $which ('in', 'out') {
            $ref->{$type}{$which} = 0;
	 }
      }
   }

   # reload the BGPDumpFile (if it has been modified)
   load_bgp($c->value('BGPDumpFile'))
}

sub process_bgp {
   my($unused, $originAS, $prefix, $masklen, $nexthop, $nexthopAS, $aspath,
      $status_code, $origin_code, $med, $locprf, $weight) = @_;

   next if ('CONT' eq $prefix);

   my @aspath = ();
   foreach my $as (split(m/[\s{},]+/, $aspath)) {
      # skip adjacent duplicates in AS path (because of hack to lengthen path)
      next if ($as eq $aspath[$#aspath]);
      push(@aspath, $as)
   }
   # FIXME - The route weight is sometimes getting prepended to the $aspath.
   #         Something is weird about the "show ip bgp" output; it looks as
   #         though the "Metric LocPrf" value is sometimes missing, and the
   #         weight is getting misinterpreted as being the first ASN in the
   #         path.
   if (0) {
      my $weight = 1000;
      if ($weight == $aspath[0]) {
         # FIXME - kludge to drop weigth from AS path
         shift @aspath
      }
   }
   my @pathref = ();
   foreach my $as (@aspath) {
      push(@pathref, \%{$CampusIO::originAS{$as}{path}})
   }

   my $oref = \%{$CampusIO::originAS{$originAS}{origin}};
   die unless $CampusIO::originAS_pt->add_string("$prefix/$masklen", {
						    origin => $oref,
						    path => [ @pathref ]
						 })
}

sub load_bgp($) {
   my $bgpfile = shift;
   return unless $bgpfile;
   
   # reload the BGPDumpFile if it has been modified
   my @stat;
   if (!(@stat = stat($bgpfile)) or
       $stat[9] <= $CampusIO::bgp_mtime) {
      return $CampusIO::originAS_pt
   }

   my $fh = new IO::File "<$bgpfile";
   die unless ref($fh);
   $CampusIO::originAS_pt = new Net::Patricia;
   die unless ref($CampusIO::originAS_pt);
   print(STDERR "Loading \"$bgpfile\" ... ") if -t;
   eval 'ParseBGPDump::parse_table(1, \&process_bgp, $fh)';
   my $loaded = $CampusIO::originAS_pt->climb(sub { 1 });
   printf(STDERR "%d prefixes loaded.\n", $loaded) if -t;

   if (0 >= $loaded) { # failure... try again next time
      $CampusIO::originAS_pt = undef;
      $CampusIO::bgp_mtime = 0
   } else {
      $CampusIO::bgp_mtime = $stat[9]
   }

   return $CampusIO::originAS_pt
}

sub load_asn($) {
   my $asnfile = shift;
   return() unless $asnfile;

   # reload the ASNFile if it has been modified
   my @stat;
   if (!(@stat = stat($asnfile)) or
       $stat[9] <= $CampusIO::asn_mtime) {
      return @CampusIO::asn
   }

   my $fh = new IO::File "<$asnfile";
   die unless ref($fh);
   $CampusIO::asn = ();
   print(STDERR "Loading \"$asnfile\" ... ") if -t;

   foreach my $line (<$fh>) {
      next unless $line =~ m/^\s*(\d+)(-(\d+))?\s+(\S+)\s+(\S+)\s*$/;
      my $n = $1;
      do {
         $CampusIO::asn[$n] = $4;
	 $n++
      } while ($3 && $n <= $3)
   }
   printf(STDERR "%d ASNs loaded.\n", scalar(@CampusIO::asn)) if -t;

   if (0 >= @CampusIO::asn) { # failure... try again next time
      $CampusIO::asn_mtime = 0
   } else {
      $CampusIO::asn_mtime = $stat[9]
   }

   return @CampusIO::asn
}

=head1 BUGS

When using the C<BGPDumpFile> directive, C<ParseBGPDump> issues a bunch
of warnings which can safely be ignored:

   Failed to parse table version from: show ip bgp
    at (eval 4) line 1
   Failed to parse router IP address from: show ip bgp
    at (eval 4) line 1
   Nexthop not found:    Network          Next Hop            Metric LocPrf Weight Path
   $ at (eval 4) line 1
   Metric not found:    Network          Next Hop            Metric LocPrf Weight Path
   $ at (eval 4) line 1
   Local Preference not found:    Network          Next Hop            Metric LocPrf Weight Path
   $ at (eval 4) line 1
   Weight not found:    Network          Next Hop            Metric LocPrf Weight Path
   $ at (eval 4) line 1
   Origin code not found:    Network          Next Hop            Metric LocPrf Weight Path
   $ at (eval 4) line 1
   Possible truncated file, end-of-dump prompt not found
    at (eval 4) line 1

I'm not keen on patching C<ParseBGPDump> to fix this since its license
isn't compatible with the GPL.  We probably just need to hack up a
complete replacement for C<ParseBGPDump>.

When using the C<BGPDumpFile> directive, C<ParseBGPDump> sometimes
mistakes the C<Weight> for the first ASN in the path.  This has the
totally undesirable effect of producing a "Top Path ASNs" report that
erroneously reports the weight as one of the Top ASNs!  I assume this
is an indication of the difficulty of parsing the output of C<show ip
bgp>, which apparently was meant for human consumption.

When using the C<ASPairs> directive, CampusIO will create RRD files
that have a C<:> character in the file name.  While RRDTool is able to
create RRD files with those names, it is not able to graph from them.
To work around this problem, create symbolic links in your C<OutputDir>
before attempting to graph from these files.  For example:

   $ ln -s 0:n.rrd Us2Them.rrd
   $ ln -s n:0.rrd Them2Us.rrd

=head1 AUTHOR

Dave Plonka <plonka@doit.wisc.edu>

Copyright (C) 1998-2001  Dave Plonka.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

=head1 VERSION

The version number is the module file RCS revision number
(B<$Revision: 1.63 $>)
with the minor number printed right justified with leading zeroes to 3
decimal places.  For instance, RCS revision 1.1 would yield a package
version number of 1.001.

This is so that revision 1.10 (which is version 1.010), for example,
will test greater than revision 1.2 (which is version 1.002) when you
want to B<require> a minimum version of this module.

=cut

1