//===========================================================================
//  @(#) $Name: arts++-1-1-a12 $
//  @(#) $Id: artsports.cc,v 1.2 2004/04/21 23:51:23 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 <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <errno.h>
}

#ifdef HAVE_FSTREAM
#include <fstream.h>
#else
#include <fstream>
#endif

#include <string>

#include "Arts.hh"
#include "ArtsIfIndexSelectionSet.hh"
#include "ArtsTimeIntervalSelectionSet.hh"
#include "ArtsPackageVersion.hh"

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

extern char *tzname[2];

using namespace std;

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

static bool        g_showNames = true;
static ArtsTimeIntervalSelectionSet  g_timeIntervalSet;

//----------------------------------------------------------------------------
// void ShowPortTable(const Arts & arts, bool sortByPkts, bool showTotals, 
//                    ArtsIfIndexSelectionSet & ifIndexSet, 
//                    long & maxEntriesToShow) 
//............................................................................
//  
//----------------------------------------------------------------------------
void ShowPortTable(const Arts & arts, bool sortByPkts, bool showTotals,
                   ArtsIfIndexSelectionSet & ifIndexSet,
                   long & maxEntriesToShow)
{
  struct tm       *localTm;
  time_t           periodTimes[2], timeDelta;
  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;
  
  hostAttribute = arts.FindHostAttribute();
  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;
      }
    }
  }
  
  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()) {
    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;
    timeDelta = periodTimes[1] - periodTimes[0];
  }
  cout << setfill(' ');
  cout << setw(15) << "Port";
  if (!showTotals) {
    cout << setw(15) << "InPkts"
         << setw(15) << "InBytes"
         << setw(15) << "OutPkts"
         << setw(15) << "OutBytes" << endl;
  }
  else {
    cout << setw(15) << "TotalPkts"
         << setw(15) << "Total pps"
         << setw(15) << "TotalBytes"
         << setw(15) << "total bps"
         << endl;
  }
  cout << setw(15) << "-----";
  cout << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------" << endl;

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

  vector<ArtsPortTableEntry>::const_iterator  portEntry;
  struct servent                             *serviceEntry;
  long                                        entriesShown = 0;
  for (portEntry = arts.PortTableData()->PortEntries().begin();
       portEntry != arts.PortTableData()->PortEntries().end();
       portEntry++) {
    if (maxEntriesToShow > 0) {
      if (entriesShown >= maxEntriesToShow) {
        break;
      }
    }
    
    if (g_showNames) {
      setservent(1);
      serviceEntry = getservbyport((int)htons(portEntry->PortNumber()),NULL);
      if (serviceEntry != (struct servent *)0) {
        cout << setw(15) << serviceEntry->s_name;
      }
      else {
        cout << setw(15) << (int)portEntry->PortNumber();
      }
    }
    else {
      cout << setw(15) << (int)portEntry->PortNumber();
    }
    
    if (!showTotals) {
      cout << setw(15) << portEntry->InPkts()
           << setw(15) << portEntry->InBytes()
           << setw(15) << portEntry->OutPkts()
           << setw(15) << portEntry->OutBytes()
           << endl;
    }
    else {
      cout << setw(15) << portEntry->InPkts() + portEntry->OutPkts()
           << setw(15)
           << (portEntry->InPkts() + portEntry->OutPkts()) / timeDelta
           << setw(15) << portEntry->InBytes() + portEntry->OutBytes()
           << ((portEntry->InBytes() + portEntry->OutBytes()) * 8) / timeDelta
           << endl;
    }
    entriesShown++;
  }
  cout << endl;
  if (g_showNames)
    endservent();
  
  return;
}

//----------------------------------------------------------------------------
//      void ShowSelectedPortTable(const Arts & arts, bool sortByPkts, 
//                                 bool showTotals, 
//                            ArtsIfIndexSelectionSet & ifIndexSet, 
//                            long & maxEntriesToShow) 
//............................................................................
//  
//----------------------------------------------------------------------------
void ShowSelectedPortTable(const Arts & arts, bool sortByPkts,
                           bool showTotals,
                           ArtsIfIndexSelectionSet & ifIndexSet,
                           long & maxEntriesToShow)
{
  struct tm       *localTm;
  time_t           periodTimes[2], timeDelta;
  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;
  
  hostAttribute = arts.FindHostAttribute();
  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;
      }
    }
  }
  
  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;

  periodAttribute = arts.FindPeriodAttribute();
  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;
    timeDelta = periodTimes[1] - periodTimes[0];
  }
  cout << setfill(' ');
  cout << "selected ports: ";
  vector<ArtsPortChoice>::const_iterator  portChoiceIter;
  portChoiceIter =
    arts.SelectedPortTableData()->PortChooser().PortChoices().begin();
  cout << (*portChoiceIter);
  for (portChoiceIter++;
       portChoiceIter !=
         arts.SelectedPortTableData()->PortChooser().PortChoices().end();
       portChoiceIter++) {
    cout << "," << (*portChoiceIter);
  }
  cout << endl;
  
  cout << setw(15) << "Port";
  if (!showTotals) {
    cout << setw(15) << "InPkts"
         << setw(15) << "InBytes"
         << setw(15) << "OutPkts"
         << setw(15) << "OutBytes" << endl;
  }
  else {
    cout << setw(15) << "TotalPkts"
         << setw(15) << "Total pps"
         << setw(15) << "TotalBytes"
         << setw(15) << "Total bps"
         << endl;
  }
  
  cout << setw(15) << "-----";
  cout << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------" << endl;

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

  vector<ArtsPortTableEntry>::const_iterator  portEntry;
  struct servent                             *serviceEntry;
  long                                        entriesShown = 0;
  
  for (portEntry = arts.SelectedPortTableData()->PortEntries().begin();
       portEntry != arts.SelectedPortTableData()->PortEntries().end();
       portEntry++) {
    if (maxEntriesToShow > 0) {
      if (entriesShown >= maxEntriesToShow) {
        break;
      }
    }
    setservent(1);
    if (g_showNames) {
      serviceEntry = getservbyport((int)htons(portEntry->PortNumber()),NULL);
      if (serviceEntry != (struct servent *)0) {
        cout << setw(15) << serviceEntry->s_name;
      }
      else {
        cout << setw(15) << (int)portEntry->PortNumber();
      }
    }
    else {
      cout << setw(15) << (int)portEntry->PortNumber();
    }
    
    if (!showTotals) {
      cout << setw(15) << portEntry->InPkts()
           << setw(15) << portEntry->InBytes()
           << setw(15) << portEntry->OutPkts()
           << setw(15) << portEntry->OutBytes()
           << endl;
    }
    else {
      cout << setw(15) << portEntry->InPkts() + portEntry->OutPkts()
           << setw(15)
           << (portEntry->InPkts() + portEntry->OutPkts()) / timeDelta
           << setw(15) << portEntry->InBytes() + portEntry->OutBytes()
           << setw(15)
           << ((portEntry->InBytes() + portEntry->OutBytes()) * 8) / timeDelta
           << endl;
    }
    entriesShown++;
  }
  cout << endl;
  if (g_showNames)
    endservent();
  
  return;
}

//-------------------------------------------------------------------------
//                      void Usage(const char *argv0)                      
//.........................................................................
//  
//-------------------------------------------------------------------------
void Usage(const char *argv0)
{
  cerr << "Usage: " << argv0
       << " [-v] [-n] [-p] [-t] [-i ifIndexList] [-l maxEntries]" << endl
       << "       [-b beginTime] [-e endTime] file(s)"
       << endl;
  return;
}

//-------------------------------------------------------------------------
//                     int main(int argc, char *argv[])                    
//.........................................................................
//  
//-------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  Arts        *arts;
  ArtsHeader  *artsHeader;
  ifstream    *artsStream;
  extern char *optarg;
  extern int   optind;
  int          optChar;
  bool         sortByPkts = false;
  bool         showTotals = 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:nptv")) != 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 'n':
        g_showNames = false;
        break;
      case 'p':
        sortByPkts = true;
        break;
      case 't':
        showTotals = true;
        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;
    }
    
    while (*artsStream) {
      //  save our stream position, we might want to back up
      //  and read a whole ARTS object.
      streamPosition = artsStream->tellg();

      //  Read the object header from the stream.  We'll use it to
      //  determine whether or not the object is a port table
      //  object.
      artsHeader = new ArtsHeader();
      artsHeader->read(*artsStream);
      if (! *artsStream) {
        delete(artsHeader);
        break;
      }
      switch (artsHeader->Identifier()) {
        case artsC_OBJECT_PORT:
          artsStream->seekg(streamPosition,ios::beg);
          arts = new Arts();
          assert(arts != (Arts *)0);
          arts->read(*artsStream);
          ShowPortTable(*arts,sortByPkts,showTotals,ifIndexSet,
                        maxEntriesToShow);
          delete(arts);
          break;
        case artsC_OBJECT_SELECTED_PORT:
          artsStream->seekg(streamPosition,ios::beg);
          arts = new Arts();
          assert(arts != (Arts *)0);
          arts->read(*artsStream);
          ShowSelectedPortTable(*arts,sortByPkts,showTotals,ifIndexSet,
                                maxEntriesToShow);
          delete(arts);
          break;
        default:
          artsStream->seekg(artsHeader->AttrLength() +
                            artsHeader->DataLength(),ios::cur);
          break;
      }
      delete(artsHeader);
    }
    artsStream->close();
  }

  #ifndef NDEBUG
    atexit(ShowArtsObjectsNotFreed);
  #endif

  exit(0);
}
