//===========================================================================
//  @(#) $Name: arts++-1-1-a12 $
//  @(#) $Id: artsases.cc,v 1.2 2004/04/21 23:51:22 kkeys Exp $
//===========================================================================
//  Copyright Notice
//
//  By accessing this software, arts++, you are duly informed
//  of and agree to be bound by the conditions described below in this
//  notice:
//
//  This software product, arts++, is developed by Daniel W. McRobb, and
//  copyrighted(C) 1998 by the University of California, San Diego
//  (UCSD), with all rights reserved.  UCSD administers the CAIDA grant,
//  NCR-9711092, under which part of this code was developed.
//
//  There is no charge for arts++ software.  You can redistribute it
//  and/or modify it under the terms of the GNU Lesser General Public
//  License, Version 2.1, February 1999, which is incorporated by
//  reference herein.
//
//  arts++ is distributed WITHOUT ANY WARRANTY, IMPLIED OR EXPRESS, OF
//  MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE or that the use
//  of it will not infringe on any third party's intellectual
//  property rights.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with arts++.  Copies can also be obtained from:
//
//    http://www.gnu.org/copyleft/lesser.html
//
//  or by writing to:
//
//  Free Software Foundation, Inc.
//  59 Temple Place, Suite 330
//  Boston, MA 02111-1307
//  USA
//
//  Or contact:
//
//    info@caida.org
//===========================================================================

extern "C" {
#include "artslocal.h"
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <errno.h>
}

#ifdef HAVE_FSTREAM
  #include <fstream>
#else
  #include <fstream.h>
#endif
#include <string>
#include <algorithm>
#include <iterator>

#include "ArtsAsMatrix.hh"
#include "ArtsPackageVersion.hh"
#include "AsTrafficTotal.hh"
#include "ArtsIfIndexSelectionSet.hh"
#include "ArtsTimeIntervalSelectionSet.hh"

#ifndef NDEBUG
  #include "ArtsDebug.hh"
#endif


extern char *tzname[2];

using namespace std;

const string rcsid = "@(#) $Name: arts++-1-1-a12 $ $Id: artsases.cc,v 1.2 2004/04/21 23:51:22 kkeys Exp $";
static const ArtsPackageVersion  k_artsVersion = ArtsPackageVersion(rcsid);

static bool                          g_srcAsSpecified = false;
static bool                          g_dstAsSpecified = false;
static bool                          g_showRate = false;
static bool                          g_showTotals = false;
static uint16_t                      g_srcAs = 0;
static uint16_t                      g_dstAs = 0;
static int                           g_totalAs = -1;
static ArtsTimeIntervalSelectionSet  g_timeIntervalSet;

//-------------------------------------------------------------------------
//   static bool                               
//   AsEntryMatches(vector<ArtsAsMatrixEntry>::const_iterator & asEntry) 
//.........................................................................
//  
//-------------------------------------------------------------------------
static bool
AsEntryMatches(vector<ArtsAsMatrixEntry>::const_iterator & asEntry)
{
  if (g_srcAsSpecified)
    if (g_srcAs != asEntry->Src())
      return(false);
  if (g_dstAsSpecified)
    if (g_dstAs != asEntry->Dst())
      return(false);

  return(true);
}

//----------------------------------------------------------------------------
//    static void ShowAsMatrixTotals(const Arts & arts, bool sortByPkts, 
//                                   ArtsIfIndexSelectionSet & ifIndexSet, 
//                                long & maxEntriesToShow) 
//............................................................................
//  
//----------------------------------------------------------------------------
static void ShowAsMatrixTotals(const Arts & arts, bool sortByPkts,
                               ArtsIfIndexSelectionSet & ifIndexSet,
                               long & maxEntriesToShow)
{
  struct tm       *localTm;
  time_t           periodTimes[2];
  struct in_addr   inAddr;
  
  vector<ArtsAttribute>::const_iterator  periodAttribute;
  vector<ArtsAttribute>::const_iterator  hostAttribute;
  vector<ArtsAttribute>::const_iterator  ifIndexAttribute;
  vector<ArtsAttribute>::const_iterator  ifDescrAttribute;
  vector<ArtsAttribute>::const_iterator  ifIpAddrAttribute;

  if (ifIndexSet.size() > 0) {
    ifIndexAttribute = arts.FindIfIndexAttribute();
    if (ifIndexAttribute != arts.Attributes().end()) {
      if (! ifIndexSet.Matches(ifIndexAttribute->IfIndex())) {
        return;
      }
    }
    else {
      return;
    }
  }
  
  periodAttribute = arts.FindPeriodAttribute();
  if (periodAttribute != arts.Attributes().end()) {
    if (g_timeIntervalSet.size() > 0) {
      if ((! g_timeIntervalSet.Matches(periodAttribute->Period()[0])) ||
          (! g_timeIntervalSet.Matches(periodAttribute->Period()[1]))) {
        return;
      }
    }
  }
  
  hostAttribute = arts.FindHostAttribute();
  if (hostAttribute != arts.Attributes().end()) {
    inAddr.s_addr = hostAttribute->Host();
    cout << "router:  " << inet_ntoa(inAddr) << endl;
  }

  ifIndexAttribute = arts.FindIfIndexAttribute();
  if (ifIndexAttribute != arts.Attributes().end()) {
    cout << "ifIndex: " << ifIndexAttribute->IfIndex();
  }
  ifDescrAttribute = arts.FindIfDescrAttribute();
  ifIpAddrAttribute = arts.FindIfIpAddrAttribute();
  if (ifDescrAttribute != arts.Attributes().end() &&
      ifIpAddrAttribute != arts.Attributes().end()) {
    cout << " (" << ifDescrAttribute->IfDescr() << " ";
    inAddr.s_addr = ifIpAddrAttribute->IfIpAddr();
    cout << inet_ntoa(inAddr) << ")";
  }
  cout << endl;
  
  if (periodAttribute != arts.Attributes().end()) {
    periodTimes[0] = periodAttribute->Period()[0];
    periodTimes[1] = periodAttribute->Period()[1];
    localTm = localtime(&(periodTimes[0]));
    cout << "period:  " << setfill('0')
         << setw(2) << (int)localTm->tm_mon+1 << "/"
         << setw(2) << localTm->tm_mday << "/"
         << setw(4) << localTm->tm_year + 1900 << " "
         << setw(2) << localTm->tm_hour << ":"
         << setw(2) << localTm->tm_min << ":"
         << setw(2) << localTm->tm_sec << " - ";
    localTm = localtime(&(periodTimes[1]));
    cout << setw(2) << (int)localTm->tm_mon+1 << "/"
         << setw(2) << localTm->tm_mday << "/"
         << setw(4) << localTm->tm_year + 1900 << " "
         << setw(2) << localTm->tm_hour << ":"
         << setw(2) << localTm->tm_min << ":"
         << setw(2) << localTm->tm_sec << " " << tzname[localTm->tm_isdst]
         << endl;
  }

  time_t timeInterval = periodTimes[1] - periodTimes[0];
  
  map<uint16_t,AsTrafficTotal,less<uint16_t> >  asTotalMap;
  vector<ArtsAsMatrixEntry>::const_iterator  asEntry;
  for (asEntry = arts.AsMatrixData()->AsEntries().begin();
       asEntry != arts.AsMatrixData()->AsEntries().end();
       asEntry++) {
    if ((*asEntry).Src() == (uint16_t)g_totalAs || g_totalAs == -1) {
      asTotalMap[asEntry->Src()].As(asEntry->Src());
      asTotalMap[asEntry->Src()].OutPkts(asTotalMap[asEntry->Src()].OutPkts() +
                                         asEntry->Pkts());
      asTotalMap[asEntry->Src()].OutBytes(asTotalMap[asEntry->Src()].OutBytes() + asEntry->Bytes());
    }
    if ((*asEntry).Dst() == (uint16_t)g_totalAs || g_totalAs == -1) {
      asTotalMap[asEntry->Dst()].As(asEntry->Dst());
      asTotalMap[asEntry->Dst()].InPkts(asTotalMap[asEntry->Dst()].InPkts() +
                                        asEntry->Pkts());
      asTotalMap[asEntry->Dst()].InBytes(asTotalMap[asEntry->Dst()].InBytes() +
                                         asEntry->Bytes());
    }
  }

  map<uint16_t,AsTrafficTotal,less<uint16_t> >::const_iterator asTotalMapIter;
  vector<AsTrafficTotal>  asTotalVector;
  AsTrafficTotal          newAsTotalVectorEntry;
  
  for (asTotalMapIter = asTotalMap.begin();
       asTotalMapIter != asTotalMap.end(); asTotalMapIter++) {
    if ((*asTotalMapIter).second.InPkts() > 0 ||
        (*asTotalMapIter).second.OutPkts() > 0) {
      newAsTotalVectorEntry.As((*asTotalMapIter).second.As());
      newAsTotalVectorEntry.InPkts((*asTotalMapIter).second.InPkts());
      newAsTotalVectorEntry.OutPkts((*asTotalMapIter).second.OutPkts());
      newAsTotalVectorEntry.InBytes((*asTotalMapIter).second.InBytes());
      newAsTotalVectorEntry.OutBytes((*asTotalMapIter).second.OutBytes());
      asTotalVector.push_back(newAsTotalVectorEntry);
    }
  }
  if (sortByPkts)
    sort (asTotalVector.begin(),asTotalVector.end(),
          AsTrafficTotalGreaterPkts());
  else
    sort (asTotalVector.begin(),asTotalVector.end(),
          AsTrafficTotalGreaterBytes());
  cout << setfill(' ');
  cout << setw(8) << "AS";
  if (g_showRate) {
    cout << setw(15) << "InPkts/sec"
         << setw(15) << "InBits/sec"
         << setw(15) << "OutPkts/sec"
         << setw(15) << "OutBits/sec"
         << endl;
  }
  else {
    cout << setw(15) << "Input Pkts"
         << setw(15) << "Input Bytes"
         << setw(15) << "Output Pkts"
         << setw(15) << "Output Bytes"
         << endl;
  }
  cout << setw(8) << "------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << endl;

  vector<AsTrafficTotal>::const_iterator  asTotalVectIter;
  long                                    entriesShown = 0;
  
  for (asTotalVectIter = asTotalVector.begin();
       asTotalVectIter != asTotalVector.end(); asTotalVectIter++) {
    if (maxEntriesToShow > 0) {
      if (entriesShown >= maxEntriesToShow) {
        break;
      }
    }
    
    cout << setw(8) << (*asTotalVectIter).As();
    if (g_showRate) {
      cout << setw(15) << (*asTotalVectIter).InPkts() / timeInterval
           << setw(15)
           << (uint64_t)(((*asTotalVectIter).InBytes() * 8.0) / timeInterval)
           << setw(15) << (*asTotalVectIter).OutPkts() / timeInterval
           << setw(15)
           << (uint64_t)(((*asTotalVectIter).OutBytes() * 8.0) / timeInterval)
           << endl;
    }
    else {
      cout << setw(15) << (*asTotalVectIter).InPkts()
           << setw(15) << (*asTotalVectIter).InBytes()
           << setw(15) << (*asTotalVectIter).OutPkts()
           << setw(15) << (*asTotalVectIter).OutBytes()
           << endl;
    }
    entriesShown++;
  }
  return;
}

//----------------------------------------------------------------------------
//       static void ShowAsMatrix(const Arts & arts, bool sortByPkts, 
//                                ArtsIfIndexSelectionSet & ifIndexSet, 
//                          long & maxEntriesToShow) 
//............................................................................
//  
//----------------------------------------------------------------------------
static void ShowAsMatrix(const Arts & arts, bool sortByPkts,
                         ArtsIfIndexSelectionSet & ifIndexSet,
                         long & maxEntriesToShow)
{
  struct tm       *localTm;
  time_t           periodTimes[2];
  struct in_addr   inAddr;
  
  vector<ArtsAttribute>::const_iterator  periodAttribute;
  vector<ArtsAttribute>::const_iterator  hostAttribute;
  vector<ArtsAttribute>::const_iterator  ifIndexAttribute;
  vector<ArtsAttribute>::const_iterator  ifDescrAttribute;
  vector<ArtsAttribute>::const_iterator  ifIpAddrAttribute;
  
  ifIndexAttribute = arts.FindIfIndexAttribute();
  
  if (ifIndexSet.size() > 0) {
    if (ifIndexAttribute != arts.Attributes().end()) {
      if (! ifIndexSet.Matches(ifIndexAttribute->IfIndex())) {
        return;
      }
    }
    else {
      return;
    }
  }

  periodAttribute = arts.FindPeriodAttribute();
  if (periodAttribute != arts.Attributes().end()) {
    if (g_timeIntervalSet.size() > 0) {
      if ((! g_timeIntervalSet.Matches(periodAttribute->Period()[0])) ||
          (! g_timeIntervalSet.Matches(periodAttribute->Period()[1]))) {
        return;
      }
    }
  }
  
  hostAttribute = arts.FindHostAttribute();
  if (hostAttribute != arts.Attributes().end()) {
    inAddr.s_addr = hostAttribute->Host();
    cout << "router:  " << inet_ntoa(inAddr) << endl;
  }

  if (ifIndexAttribute != arts.Attributes().end()) {
    cout << "ifIndex: " << ifIndexAttribute->IfIndex();
  }
  ifDescrAttribute = arts.FindIfDescrAttribute();
  ifIpAddrAttribute = arts.FindIfIpAddrAttribute();
  if (ifDescrAttribute != arts.Attributes().end() &&
      ifIpAddrAttribute != arts.Attributes().end()) {
    cout << " (" << ifDescrAttribute->IfDescr() << " ";
    inAddr.s_addr = ifIpAddrAttribute->IfIpAddr();
    cout << inet_ntoa(inAddr) << ")";
  }
  cout << endl;
    
  if (periodAttribute != arts.Attributes().end()) {
    memcpy(periodTimes,periodAttribute->Period(),8);
    localTm = localtime(&(periodTimes[0]));
    cout << "period:  " << setfill('0')
         << setw(2) << (int)localTm->tm_mon+1 << "/"
         << setw(2) << localTm->tm_mday << "/"
         << setw(4) << localTm->tm_year + 1900 << " "
         << setw(2) << localTm->tm_hour << ":"
         << setw(2) << localTm->tm_min << ":"
         << setw(2) << localTm->tm_sec << " - ";
    localTm = localtime(&(periodTimes[1]));
    cout << setw(2) << (int)localTm->tm_mon+1 << "/"
         << setw(2) << localTm->tm_mday << "/"
         << setw(4) << localTm->tm_year + 1900 << " "
         << setw(2) << localTm->tm_hour << ":"
         << setw(2) << localTm->tm_min << ":"
         << setw(2) << localTm->tm_sec << " " << tzname[localTm->tm_isdst]
         << endl;
  }

  time_t timeInterval = periodTimes[1] - periodTimes[0];
  
  cout << setfill(' ');
  cout << setw(8) << "Src AS"
       << setw(8) << "Dst AS"
       << setw(15) << "Pkts"
       << setw(15) << "Pkts/sec"
       << setw(15) << "Bytes"
       << setw(15) << "Bits/sec"
       << endl;
  cout << setw(8) << "------"
       << setw(8) << "------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << endl;

  if (sortByPkts)
    arts.AsMatrixData()->SortEntriesByPkts();
  else
    arts.AsMatrixData()->SortEntriesByBytes();

  vector<ArtsAsMatrixEntry>::const_iterator  asEntry;
  long                                       entriesShown = 0;
  for (asEntry = arts.AsMatrixData()->AsEntries().begin();
       asEntry != arts.AsMatrixData()->AsEntries().end();
       asEntry++) {
    if (AsEntryMatches(asEntry)) {
      if (maxEntriesToShow > 0) {
        if (entriesShown >= maxEntriesToShow){
          break;
        }
      }
      cout << setw(8) << asEntry->Src()
           << setw(8) << asEntry->Dst()
           << setw(15) << asEntry->Pkts()
           << setw(15) << (double)asEntry->Pkts() / timeInterval
           << setw(15) << asEntry->Bytes()
           << setw(15) << ((double)asEntry->Bytes() * 8.0) / timeInterval
           << endl;
      entriesShown++;
    }
  }
  cout << endl;
  
  return;
}
  
//-------------------------------------------------------------------------
//                      void Usage(const char *argv0)                      
//.........................................................................
//  
//-------------------------------------------------------------------------
void Usage(const char *argv0)
{
  cerr << "Usage: " << argv0
       << " [-v] [-p] [-i ifIndexList] [-l maxEntries] [-t AS] [-r]"
       << " [-s srcAS] [-d dstAS] [-b beginTime] [-e endTime] file(s)"
       << endl;
  return;
}

//-------------------------------------------------------------------------
//                     int main(int argc, char *argv[])                    
//.........................................................................
//  
//-------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  ifstream                 *artsStream;
  extern char              *optarg;
  extern int                optind;
  int                       optChar;
  bool                      sortByPkts = false;
  ArtsIfIndexSelectionSet   ifIndexSet;
  long                      maxEntriesToShow = 0;
  char                     *startTimeExpression = (char *)0;
  char                     *endTimeExpression = (char *)0;
  
  if (argc < 2) {
    Usage(argv[0]);
    exit(1);
  }

  while ((optChar = getopt(argc,argv,"b:e:i:l:prs:t:d:v")) != EOF) {
    switch (optChar) {
      case 'b':
        startTimeExpression = (char *)strdup(optarg);
        break;
      case 'e':
        endTimeExpression = (char *)strdup(optarg);
        break;
      case 'i':
        ifIndexSet.Load(optarg);
        break;
      case 'l':
        maxEntriesToShow = strtol(optarg,(char **)0,10);
        break;
      case 'p':
        sortByPkts = true;
        break;
      case 'r':
        g_showRate = true;
        break;
      case 's':
        g_srcAsSpecified = true;
        g_srcAs = (uint16_t)atoi(optarg);
        break;
      case 't':
        g_showTotals = true;
        g_totalAs = atoi(optarg);
        break;
      case 'd':
        g_dstAsSpecified = true;
        g_dstAs = (uint16_t)atoi(optarg);
        break;
      case 'v':
        cerr << k_artsVersion.Name() << "  " << k_artsVersion.Id() << endl;
        exit(0);
        break;
      case '?':
      default:
        Usage(argv[0]);
        exit(1);
        break;
    }
  }

  if (optind >= argc) {
    Usage(argv[0]);
    exit(1);
  }

  if (startTimeExpression || endTimeExpression)
    g_timeIntervalSet.Load(startTimeExpression,endTimeExpression);

  streampos  streamPosition;
  
  for (int fileNum = optind; fileNum < argc; fileNum++) {
    artsStream = new ifstream(argv[fileNum]);
    if (! artsStream || !*artsStream) {
      cerr << "[E] unable to open input file '" << argv[fileNum] << "': "
           << strerror(errno) << endl;
      continue;
    }
    
    istream_iterator<ArtsAsMatrix>  inStreamIter(*artsStream);
    istream_iterator<ArtsAsMatrix>  inStreamEnd;

    for (; inStreamIter != inStreamEnd; inStreamIter++) {
      if ((*inStreamIter).AsMatrixData()->AsEntries().size() > 0) {
        if (g_showTotals) {
          ShowAsMatrixTotals(*inStreamIter,sortByPkts,ifIndexSet,
                             maxEntriesToShow);
        }
        else {
          ShowAsMatrix(*inStreamIter,sortByPkts,ifIndexSet,maxEntriesToShow);
        }
      }
    } //.......... for (; inStreamIter != inStreamEnd; ++inStreamIter)
    
    delete(artsStream);
    
  } //.......... for (int fileNum = optind; ...)

  #ifndef NDEBUG
    atexit(ShowArtsObjectsNotFreed);
  #endif
  
  exit(0);
}
