#  CampusIO.pm - a FlowScan module for reporting on campus traffic I/O
#  Copyright (C) 1998-2004  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.77 2004/04/06 19:51:56 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.77 $' =~ 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<PacketSamplingInterval>

This directive is optional.  This is the packet sampling interval
configured on your exporting routers, if you have configured them to do
packet sampling.  Each flows packet and byte counts are simply
multipled by this factor before they are recorded.

It defaults to 1 if unspecified, meaning that packets are not being
sampled, so every IP packet is represented in the flow records being
processed.

=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, http, 7070, 554
   TCPServices ftp-data, ftp, smtp, nntp, http, 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.  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<Net::ParseRouteTable> perl module.

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.

C<BGPDumpFile>'s value should be a comma-seperated list of file names
each 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

With a Juniper, you might do this:

   $ ssh router.our.domain "show route protocol bgp terse" > etc/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.  With 3 files configured, the process has been as large as
180MB.

=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('PacketSamplingInterval');
$c->directive('WebProxyIfIndex');
$c->load("${FindBin::Bin}/CampusIO.cf");

if ($c->value('PacketSamplingInterval')) {
   $CampusIO::PacketSamplingInterval = $c->value('PacketSamplingInterval')
} else {
   $CampusIO::PacketSamplingInterval = 1
}

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 $@;
}

$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;

if ($c->value('BGPDumpFile')) {    
   eval "use Net::ParseRouteTable";
   die "$@" if $@;
   # load the BGPDumpFile
   foreach my $bgp_dump (split(m/\s*,\s*/, $c->value('BGPDumpFile'))) {
   push(@CampusIO::BGP_files, $bgp_dump);
      load_bgp($bgp_dump)
   }
}

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
   }

   # NOTE: The Juniper/JUNOS implementation of flow-export has had a number
   #       of bugs which require the following tests to be changed to
   #       workaround.  For instance, for point-to-point egress interfaces
   #       Juniper flow-export records sometimes have zero as the $nexthop,
   #       or instead report the IP address at the wrong end of the link.

   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::hops &&
	!@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)) { # BGPDumpFile(s) is(are) configured
	 my $pt = $CampusIO::originAS_pt->match_integer($exporter);
	 if (ref($pt)) {
            my $as_ref;
            if ($as_ref = $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
            }
	 } else {
	    warn "BGPDumpFile(s) is(are) configured, but not for $exporterip.\n"
	 }
      }

      # 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)) { # BGPDumpFile(s) is(are) configured
	    my $pt = $CampusIO::originAS_pt->match_integer($exporter);
	    if (ref($pt)) {
               my $as_ref;
               if ($as_ref = $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
               }
	    } else {
	    warn "BGPDumpFile(s) is(are) configured, but not for $exporterip.\n"
	    }
         }

         # 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 $when = $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 < $when) {
         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($when))), "\n")
		 if $CampusIO::Verbose;
         delete($CampusIO::NapServer{$k})
      }
   }
   while (my($k, $v) = each(%CampusIO::NapUser)) {
      if ($v < $when) {
         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($when))), "\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 $when_fin = $self->{filetime} - 15*60;
   # purge sessions for which we've seen ACK (but no FIN) after 30 minutes:
   my $when_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] < $when_fin) ||
	  $v->[0] < $when_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 $when = $self->{filetime} - 60*60;

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

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:1827
         RRA:MAX:0:24:600
         RRA:MAX:0:288:1827
	 )
      );
   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 = @_;

   # { kludge to scale the appropriate bytes and pkts values in the two
   #   types of RRD files that CampusIO creates:
   #   a) 3 Data Sources (the "asnX:asnY.rrd": bytes, pkts, flows)
   #   b) 8 Data Sources (in/out_bytes, in/out_pkts, in/out_flows, rx, tx)
   #   For type "a", we muliply the first 2 values (bytes, pkts).
   #   For type "b", we muliply the first 4 values (in/out_pkts, in/out_flows).
   #
   my $boundary = (3 == @values)? 1 : 3;
   for (my $n = 0; $n <= $boundary; $n++) {
      $values[$n] *= $CampusIO::PacketSamplingInterval
   }
   # }

   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 $when = 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($when));
         }
         $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("<a name=\"top_by_bytes\">" .
			    "Top $CampusIO::TopN ${type} ASNs " .
			    "by bytes <b>$which</b><br>\n" .
                            "for five minute flow sample dated " .
		            scalar(localtime($self->{filetime})) .
			    '</a>',
			    '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, $asown, $url);
	    if ($CampusIO::asn[$as]) {
	       $asname = "$CampusIO::asn[$as] ($as)";
	       $asown = $CampusIO::asown[$as];
	       if ($asown =~ m/RIPE-NCC-ARIN/) { # RIPE
	          $url = "http://www.ripe.net/perl/whois?AS$as"
	       } elsif ($asown =~ m/SA90-ARIN|APNIC/) { # APNIC
	          $url = "http://www.apnic.net/apnic-bin/whois.pl?search=AS$as"
	       } else { # ARIN
	          $url = "http://www.arin.net/cgi-bin/whois.pl?queryinput=AS+$as"
	       }
	    } else {
	       $asname = $as;
	       # default to ARIN:
	       $url = "http://www.arin.net/cgi-bin/whois.pl?queryinput=AS$as"
	    }
            $row++;
            $table->addRow("#$m",
                           "<a href=\"$url\">$asname</a>",
                           scale("%.1f",
				 ($CampusIO::PacketSamplingInterval *
				  $CampusIO::originAS{$as}{$type}{in}*8)/300),
                           sprintf("%.1f%%",
				   percent($CampusIO::originAS{$as}{$type}{in},
					   $self->{total}{in}{bytes})),
                           scale("%.1f",
				 ($CampusIO::PacketSamplingInterval *
				  $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 $name = shift(@_);
   my $hr = shift(@_);
   die unless ref($hr);
   my $top = shift(@_);
   my $prefix = shift(@_);
   my $when = shift(@_);
   my $agg = shift(@_); # aggregate heavy-hitter stats under this node
   my @topn;

   die unless $name;
   $name =~ tr:/ :_: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($when? $when : $self->{rrdtime}));
   }
   $htmlfile .= "${name}_top.html";

   $self->mkdirs_as_necessary($htmlfile);

   my $fh = new IO::File ">$htmlfile";
   if (!ref($fh)) {
      warn "open \"$htmlfile\": $!";
      next
   }
   print $fh <<_EOF_;
<body bgcolor="#ffffff">
<ul>
<li><a href="#bytes_out">Top $top by <b>bytes out</b></a></li>
<li><a href="#pkts_out">Top $top by <b>pkts out</b></a></li>
<li><a href="#flows_out">Top $top by <b>flows out</b></a></li>
<li><a href="#bytes_in">Top $top by <b>bytes in</b></a></li>
<li><a href="#pkts_in">Top $top by <b>pkts in</b></a></li>
<li><a href="#flows_in">Top $top by <b>flows in</b></a></li>
</ul>
<center>

_EOF_
   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);
	 my $cidr = $hr->{SUBNET};
	 # change the `dots' in the IP address into codes (of the ASCII/ISO
	 # period character) so that the ip2hostname script, if run on the
	 # resulting HTML file, won't try to translate it into a hostname:
	 $cidr =~ s/\./&#46;/g;
         $table->setCaption("<a name=\"${thingy}_$direction{$x}\">" .
	                    "Top $top $cidr hosts " .
			    "by <b>$thingy $direction{$x}</b><br>\n" .
                            "for five minute flow sample dated " .
		            scalar(localtime($self->{filetime})) .
			    "</a>",
			    '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;
	    }

	    if (ref($agg)) {
	       # Note: collisions are OK here (it may very well be that a 
	       # top talker or listener for one thingy (pkts, bytes, or flows)
	       # may also be a top talker for another
               $agg->{$x . '_pt'}->add_string($tophr->{addr}, $tophr);
	    }

	    $table->addRow(sprintf("#%d", $row-1), # rank
			   $tophr->{addr},
                           scale("%.1f", ($CampusIO::PacketSamplingInterval *
					  $in->{bytes}*8)/300)
			      . sprintf(" (%.1f%%)",
				       percent($in->{bytes}, $hr->{in}{bytes})),
                           scale("%.1f", ($CampusIO::PacketSamplingInterval *
					  $out->{bytes}*8)/300)
			      . sprintf(" (%.1f%%)",
				     percent($out->{bytes}, $hr->{out}{bytes})),
			   scale("%.1f", $CampusIO::PacketSamplingInterval *
					 $in->{pkts}/300)
			      . sprintf(" (%.1f%%)",
				         percent($in->{pkts}, $hr->{in}{pkts})),
			   scale("%.1f", $CampusIO::PacketSamplingInterval *
					 $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 $name = shift(@_);   # basename for rrd file
   my $hr = shift(@_);     # hashref for the current node
   die unless ref($hr);
   my $top = shift(@_);    # number of heavy-hitters to report
   my $prefix = shift(@_); # path prefix for HTML reports
   my $when = shift(@_);   # time
   my $agg = shift(@_);    # aggregate heavy-hitters under this node

   die unless $name;
   $name =~ tr:/ :_:s; # "/" not allowed in file names...
   my $file = $self->{outputdir} . "/${name}.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});
   }
   # find the number of active users (and report top talkers and listeners):
   my($tx, $rx) = $self->report_users($name,
				      $hr,
				      $top,
				      $prefix,
				      $when,
				      $agg);
   $self->updateRRD($file,
		    @values,
		    defined($hr->{tx})? $hr->{tx} : $tx,
		    defined($hr->{rx})? $hr->{rx} : $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 $when;
   if (300 < abs($last - $start)) {
      warn("Unexpected timestamp in \"$file\": ",
	scalar(localtime($start)), " ($start) not within 300 seconds of ",
	scalar(localtime($last)), " ($last)\n");
      $when = $last
   } else {
      $when = $start
   }
   $self->{rrdtime} = $when;

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

   $self->originASreport($when) 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;

   # { prepare the total src/dst ptrie to store the heavy-hitters from each net:
   $self->{total}->{SUBNET} = 'total';
   $self->{total}->{src_pt} = new Net::Patricia;
   die unless ref($self->{total}->{src_pt});
   $self->{total}->{dst_pt} = new Net::Patricia;
   die unless ref($self->{total}->{dst_pt});
   # }

   $CampusIO::ptrie->climb(
      sub {
         my($tx, $rx) = $self->report_node($_[0]->{SUBNET},
                                           $_[0],
                                           $CampusIO::TopN,
                                           $c->value('ReportPrefixFormat'),
                                           $when,
					   $self->{total});
	 $CampusIO::tx += $tx;
	 $CampusIO::rx += $rx;
      }
   );

   # }{ do totals

   # override the total tx and rx counters, so that report_node won't use the
   # number of nodes in the src_pt and dst_pt, which is innaccurate since
   # total ptries contain just the subset of hosts that were heavy-hitters in
   # the configured nets
   $self->{total}->{tx} = $CampusIO::tx;
   $self->{total}->{rx} = $CampusIO::rx;

   # report TopN for total (accross all configured networks)
   $self->report_node('total',
		      $self->{total},
		      $CampusIO::TopN,
		      $c->value('ReportPrefixFormat'),
		      $when,
		      undef);

   # }{ 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(s) if modified
   if ($c->value('BGPDumpFile')) {
      foreach my $bgp_dump (@CampusIO::BGP_files) {
         load_bgp($bgp_dump)
      }
   }
}

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

   return 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 weight 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 undef unless $bgpfile;

   my $n = inet_aton(basename($bgpfile, '.bgp')); # host-ordered long
   if (4 != length($n)) {
 warn "couldn't resolve exporter IP address in BGPDumpFile name \"$bgpfile\"\n";
      return undef
   }
   my $a = inet_ntoa($n); # ascii version of IP address

   if (!ref($CampusIO::originAS_pt)) {
      $CampusIO::originAS_pt = new Net::Patricia;
      die unless ref($CampusIO::originAS_pt)
   }

   # be sure this exporter hasn't already been added
   my $pt = $CampusIO::originAS_pt->match_string($a);
   my @stat = stat($bgpfile);
   if (ref($pt)) {
      # reload the BGPDumpFile only if it has been modified
      if (!@stat or $stat[9] <= $CampusIO::bgp_mtime{$a}) {
         return $pt
      }
      $CampusIO::originAS_pt->remove_string($a)
   } else {
      $pt = new Net::Patricia;
      die unless ref($pt);
      die unless $CampusIO::originAS_pt->add_string($a, $pt);
   }

   # $Net::ParseRouteTable::debug = $CampusIO::verbose? 1 : 0;
   if ($CampusIO::verbose) {
      warn "Loading \"$bgpfile\" ($a) ... \n"
   }
   my $table = Net::ParseRouteTable->new({ filename => $bgpfile });

   while (!$table->eof()) {
      my $data = $table->next_row();
      last unless $data;

      if ($data->{aspath} =~ m/{[^0-9]+}/) {
         warn "Not loading $data->{'prefix'}/$data->{'masklen'} because of AS-SET in AS path, $data->{aspath}\n" if $CampusIO::verbose;
      }
      my @aspath = split(m/[\s{},]+/, $data->{aspath});

      my @pathref;
      foreach my $as (@aspath) {
      	 push(@pathref, \%{$CampusIO::originAS{$as}{path}})
      }

      my $oref = \%{$CampusIO::originAS{$aspath[@aspath-1]}{origin}};

      if ($data->{'best'}) {
	 #print "found $data->{'prefix'}/$data->{'masklen'} - using @aspath\n";
         die unless $pt->add_string("$data->{'prefix'}/$data->{'masklen'}", {
                                    # nexthop => $data->{nexthop},
                                    # path_array => [ @aspath ],
                                    # status_code => $data->{status_code},
                                    # origin_code => $data->{origin_code},
                                    # med => $data->{med},
                                    # locprf => $data->{locprf},
                                    # weight => $data->{weight},
	                            origin => $oref,
                                    path => [ @pathref ],
                                 })
      }
   }

   if (!$table->eot()) {
      warn "Table did not end with a router prompt.  Possible truncated file\n"
         if $CampusIO::verbose;
   }

   my $loaded = $pt->climb(sub { 1 });
   printf(STDERR "%d prefixes loaded.\n", $loaded) if $CampusIO::verbose;

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

   return $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 = ();
   $CampusIO::asown = ();
   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;
         $CampusIO::asown[$n] = $5;
	 $n++
      } while ($3 && $n <= $3)
   }
   printf(STDERR "%d autonomous system numbers 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-2004  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.77 $>)
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
