//===========================================================================
//  @(#) $Name: arts++-1-1-a12 $
//  @(#) $Id: artsnets.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 <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.h>
#else
#include <fstream>
#endif

#include <string>
#include <iterator>

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

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

#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif

extern char *tzname[2];

using namespace std;

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

static bool        g_srcNetSpecified = false;
static bool        g_dstNetSpecified = false;
static bool        g_showRate = false;
static ipv4addr_t  g_srcNet = 0;
static uint8_t     g_srcMaskLen = 0;
static ipv4addr_t  g_dstNet = 0;
static uint8_t     g_dstMaskLen = 0;
static ArtsTimeIntervalSelectionSet  g_timeIntervalSet;

//-------------------------------------------------------------------------
//  static bool                               
//  NetEntryMatches(vector<ArtsNetMatrixEntry>::const_iterator & netEntry) 
//.........................................................................
//  
//-------------------------------------------------------------------------
static bool
NetEntryMatches(vector<ArtsNetMatrixEntry>::const_iterator & netEntry)
{
  ipv4addr_t      netmask, netaddr;
  struct in_addr  addrIn;

  netmask = htonl((0xffffffff) << (32 - g_srcMaskLen));
  if (g_srcNetSpecified) {
    if ((netEntry->Src() & netmask) != g_srcNet) {
      return(false);
    }
    if (g_srcMaskLen > netEntry->SrcMaskLen()) {
      return(false);
    }
  }

  netmask = htonl((0xffffffff) << (32 - g_dstMaskLen));
  if (g_dstNetSpecified) {
    if ((netEntry->Dst() & netmask) != g_dstNet) {
      return(false);
    }
    if (g_dstMaskLen > netEntry->DstMaskLen()) {
      return(false);
    }
  }
  return(true);
}

//----------------------------------------------------------------------------
//      static void ShowNetMatrix(const Arts & arts, bool sortByPkts, 
//                                ArtsIfIndexSelectionSet & ifIndexSet, 
//                                long & maxEntriesToShow) 
//............................................................................
//  
//----------------------------------------------------------------------------
static void ShowNetMatrix(const Arts & arts, bool sortByPkts,
                          ArtsIfIndexSelectionSet & ifIndexSet,
                          long & maxEntriesToShow)
{
  struct tm       *localTm;
  time_t           periodTimes[2];
  time_t           timeInterval;
  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;
  }
  cout << setfill(' ');
  cout << setw(20) << "Src Network"
       << setw(20) << "Dst Network";
  if (g_showRate) {
    cout << setw(15) << "pkts/sec"
         << setw(15) << "bits/sec"
         << endl;
  }
  else {
    cout << setw(15) << "Pkts"
         << setw(15) << "Bytes"
         << endl;
  }
  cout << setw(20) << "------------------"
       << setw(20) << "------------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << endl;

  if (g_showRate) {
    timeInterval = periodTimes[1] - periodTimes[0];
  }
  
  if (sortByPkts)
    arts.NetMatrixData()->SortEntriesByPkts();
  else
    arts.NetMatrixData()->SortEntriesByBytes();

  vector<ArtsNetMatrixEntry>::const_iterator  netEntry;
  long                                        entriesShown = 0;
  
  for (netEntry = arts.NetMatrixData()->NetEntries().begin();
       netEntry != arts.NetMatrixData()->NetEntries().end();
       netEntry++) {
    if (NetEntryMatches(netEntry)) {
      if (maxEntriesToShow > 0) {
        if (entriesShown >= maxEntriesToShow) {
          break;
        }
      }
      inAddr.s_addr = netEntry->Src();
      cout << "  "
           << setw(15) << resetiosflags(ios::left) << inet_ntoa(inAddr)
           << setw(1) << "/"
           << setw(2) << setiosflags(ios::left) << (int)netEntry->SrcMaskLen()
           << "  ";
      inAddr.s_addr = netEntry->Dst();
      cout << setw(15) << resetiosflags(ios::left) << inet_ntoa(inAddr)
           << setw(1) << "/"
           << setw(2) << setiosflags(ios::left) << (int)netEntry->DstMaskLen()
           << resetiosflags(ios::left);
      if (g_showRate) {
        cout << setw(15) << (uint64_t)((double)netEntry->Pkts() / timeInterval)
             << setw(15)
             << (uint64_t)((netEntry->Bytes() * 8.0) / timeInterval)
             << endl;
      }
      else {
        cout << setw(15) << netEntry->Pkts()
             << setw(15) << netEntry->Bytes()
             << endl;
      }
      entriesShown++;
    }
  }
  cout << endl;
  
  return;
}
  
//-------------------------------------------------------------------------
//                      void Usage(const char *argv0)                      
//.........................................................................
//  
//-------------------------------------------------------------------------
void Usage(const char *argv0)
{
  cerr << "Usage: " << argv0
       << " [-v] [-r] [-p] [-i ifIndexList] [-l maxEntries] [-s srcNet/mask]"
       << " [-d dstNet/mask] 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;
  char        *ipAddrString;
  char        *maskLenString;
  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: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_srcNetSpecified = true;
        ipAddrString = strtok(optarg,"/");
        if (! ipAddrString) {
          Usage(argv[0]);
          exit(1);
        }
        g_srcNet = inet_addr(ipAddrString);
        if (g_srcNet == INADDR_NONE) {
          cerr << "'" << ipAddrString << "'"
               << " is an illegal source network address."
               << endl;
          Usage(argv[0]);
          exit(1);
        }
        maskLenString = strtok(NULL," ");
        if (! maskLenString) {
          Usage(argv[0]);
          exit(1);
        }
        g_srcMaskLen = (uint8_t)atoi(maskLenString);
        if (g_srcMaskLen > 32 || g_srcMaskLen == 0) {
          cerr << maskLenString
               << " is an illegal source network mask length." << endl;
          Usage(argv[0]);
          exit(1);
        }
        break;
      case 'd':
        g_dstNetSpecified = true;
        ipAddrString = strtok(optarg,"/");
        if (! ipAddrString) {
          Usage(argv[0]);
          exit(1);
        }
        g_dstNet = inet_addr(ipAddrString);
        if (g_dstNet == INADDR_NONE) {
          cerr << "'" << ipAddrString << "'"
               << " is an illegal destination network address."
               << endl;
          Usage(argv[0]);
          exit(1);
        }
        maskLenString = strtok(NULL," ");
        if (! maskLenString) {
          Usage(argv[0]);
          exit(1);
        }
        g_dstMaskLen = (uint8_t)atoi(maskLenString);
        if (g_dstMaskLen > 32 || g_dstMaskLen == 0) {
          cerr << maskLenString
               << " is an illegal destination network mask length." << endl;
          Usage(argv[0]);
          exit(1);
        }
        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);
    
  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<ArtsNetMatrix>   inStreamIter(*artsStream);
    istream_iterator<ArtsNetMatrix>   inStreamEnd;

    for (; inStreamIter != inStreamEnd; inStreamIter++) {
      ShowNetMatrix(*inStreamIter,sortByPkts,ifIndexSet,maxEntriesToShow);
    }
    delete(artsStream);
  }

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