/* 0915, Thu 30 Apr 98

   PK_TRACE: Collect packet arrival-time trace

   Copyright (C) 1997-2002 by Nevil Brownlee,
   ITSS Technology Development, The University of Auckland */

#if HAVE_CONFIG_H
#include <ntm_conf.h>
#endif

#define noUX_TESTING
#define noCOPY_STRUCTS  /* True to copy fddi 'ethernet header' info.
                              Solaris 2.4 doesn't need this */
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <sys/utsname.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
#include <limits.h>

#ifdef SUNOS
#include <stropts.h>
#define void
#define const
#endif

#define MXINTERFACES  4  /* Max nbr of interfaces to meter */

#define SNAPSIZE   0L  /* We only want the size and timestamp */

char tfname[50] = "ptrace.dat";

int target_pps = 500;  /* Default reqd packet rate */

int trace_sz = 5001;

struct p_t {
   struct timeval tv;  /* Arrival time */
   unsigned int sz;  /* Packet size, bytes */
   };
struct p_t *p_table;
int n_p = 0;  /* Nbr of packets in buffer */
int nxp = 0;  /* Index to next packet position */

int time_to_stop = 0;

void pkt_trace(struct timeval ts, int len, unsigned char *p)
{
   if (!time_to_stop) {
      p_table[nxp].tv = ts;
      p_table[nxp].sz = len;
      if (n_p != trace_sz) ++n_p;
      if (++nxp == trace_sz) nxp = 0;
      }
   }

int pps(void)
{
   struct timeval inter, from,to;
   unsigned long us;
   double rate;

   if (n_p != trace_sz) {
      from = p_table[0].tv;
      to = p_table[n_p-1].tv;
      }
   else {
      from = p_table[nxp].tv;
      to = p_table[nxp == 0 ? trace_sz-1 : nxp-1].tv;
      }
   if (to.tv_usec < from.tv_usec) {
      --to.tv_sec;
      to.tv_usec += 1000000;
      }
   inter.tv_sec = to.tv_sec - from.tv_sec;
   inter.tv_usec = to.tv_usec - from.tv_usec;
   us = inter.tv_sec*1000000 + inter.tv_usec;
   rate = (double)(n_p-1) * 1000000 / (double)us;
   printf("%d packets, %.1f s elapsed, %.0f pps\n", 
      n_p-1, (double)us/1000000.0, rate);
   if ((int)rate >= target_pps && n_p == trace_sz)
      time_to_stop = 1;
   }

double start_time;
int rec_nbr = 0;

void write_pkt_info(FILE *f, struct p_t *ptp)
{
   double at = (double)ptp->tv.tv_sec + (double)ptp->tv.tv_usec/1000000.0;
   fprintf(f, "%.6f %u\n",  at-start_time, ptp->sz);
   if (++rec_nbr % 1000 == 0) printf(".");
   }

void write_data()
{
   FILE *f;
   struct timeval t;
   int j;

   f = fopen(tfname, "w");
   if (f == NULL) {
      printf("couldn't open %s for write\n", tfname);
      return;
      }
   printf("file %s opened for write\n", tfname);
   if (n_p == trace_sz) {  /* Buffer full */
      t = p_table[nxp].tv;  /* 'next' position, not written out */
      start_time = (double)t.tv_sec + (double)t.tv_usec/1000000.0;
      for (j = nxp+1; j != trace_sz; ++j)
         write_pkt_info(f, &p_table[j]);
      for (j = 0; j != nxp; ++j)
         write_pkt_info(f, &p_table[j]);
      }
   else {  /* Buffer not full */
      t = p_table[0].tv;
      start_time = (double)t.tv_sec + (double)t.tv_usec/1000000.0;
      for (j = 1; j != n_p; ++j) {
         write_pkt_info(f, &p_table[j]);
         }
      }
   printf("\n");
   fclose(f);
   }

/* ===== Interface code using libpcap to get see packet headers ===== */

#include <unistd.h>

#include <pcap-int.h>
#include <pcap.h>

unsigned long last_t_sec = 0;

struct ether_hdr {  
   unsigned char dest[6];    /* MAC addresses */
   unsigned char source[6];
   unsigned char type[2];    /* Length or protocol type */
   };

#include <llc.h>

struct interface_info {
   u_char nbr;  /* Interface number (for Surce/DestInterface attributes) */
   char name[20];  /* Interface name, e.g. nf0 */
   u_int SampleRate,  /* 1 = count every packet on this interface */
      sample_count;
   pcap_t *pd;
   int fd;
   pcap_handler callback;
   u_int ipackets;  /* Total packets since last stats reset */
   u_int idrops;  /* Dropped packets since last stats reset */
   u_int noflowpackets;
   };
struct interface_info *pci[MXINTERFACES];
int n_interfaces;  /* Nbr of active interfaces */

/* ----- Following fddi code is from tcpdump's print-fddi.c ----- */

#ifdef __GNUC__  /* These defines from interface.h .. */
#define inline __inline
#ifndef __dead
#define __dead volatile
#endif
#else
#define inline
#define __dead
#endif

#include <fddi.h>

/*
 * Some FDDI interfaces use bit-swapped addresses.
 */
#if defined(ultrix) || defined(__alpha)
int	fddi_bitswap = 0;
#else
int	fddi_bitswap = 1;
#endif

/*
 * FDDI support for tcpdump, by Jeffrey Mogul [DECWRL], June 1992
 *
 * Based in part on code by Van Jacobson, which bears this note:
 *
 * NOTE:  This is a very preliminary hack for FDDI support.
 * There are all sorts of wired in constants & nothing (yet)
 * to print SMT packets as anything other than hex dumps.
 * Most of the necessary changes are waiting on my redoing
 * the "header" that a kernel fddi driver supplies to bpf:  I
 * want it to look like one byte of 'direction' (0 or 1
 * depending on whether the packet was inbound or outbound),
 * two bytes of system/driver dependent data (anything an
 * implementor thinks would be useful to filter on and/or
 * save per-packet, then the real 21-byte FDDI header.
 * Steve McCanne & I have also talked about adding the
 * 'direction' byte to all bpf headers (e.g., in the two
 * bytes of padding on an ethernet header).  It's not clear
 * we could do this in a backwards compatible way & we hate
 * the idea of an incompatible bpf change.  Discussions are
 * proceeding.
 *
 * Also, to really support FDDI (and better support 802.2
 * over ethernet) we really need to re-think the rather simple
 * minded assumptions about fixed length & fixed format link
 * level headers made in gencode.c.  One day...
 *
 *  - vj
 */

#define FDDI_HDRLEN (sizeof(struct fddi_header))

static u_char fddi_bit_swap[] = {
	0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
	0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
	0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
	0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
	0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
	0x14, 0x94, 0x54, 0xd4, 0x34, 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x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
	0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
	0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
	0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
};

/* Extract src, dst addresses */
static inline void extract_fddi_addrs(
   const struct fddi_header *fddip, 
   unsigned char *fsrc, unsigned char *fdst)
{
	register int i;

	if (fddi_bitswap) {
		/*
		 * bit-swap the fddi addresses (isn't the IEEE standards
		 * process wonderful!) then convert them to names.
		 */
		for (i = 0; i < 6; ++i)
			fdst[i] = fddi_bit_swap[fddip->fddi_dhost[i]];
		for (i = 0; i < 6; ++i)
			fsrc[i] = fddi_bit_swap[fddip->fddi_shost[i]];
	}
	else {
		memcpy(fdst, fddip->fddi_dhost, 6);
	        memcpy(fsrc, fddip->fddi_shost, 6);
	}
}

/* ----- End of fddi code from tcpdump's print-fddi.c ----- */

#define get_short(a)  (a[0] << 8 | a[1])

void fddi_callback(struct interface_info *user, struct pcap_pkthdr *h, u_char *p)
{
   const struct fddi_header *fp = (struct fddi_header *)p;
   int caplen = h->len;  /* Use len rather than caplen here !!! */
   struct ether_hdr ehdr;
#ifdef COPY_STRUCTS
   struct llc llc;
#else
   struct llc *llc;
#endif
   unsigned int ether_type, lsap;

   if (--user->sample_count == 0) {  /* Process only 1 pkt per SampleRate */
      user->sample_count = user->SampleRate;

      if (caplen < FDDI_HDRLEN) return;  /* Too short! */

      if ((fp->fddi_fc & FDDIFC_CLFF) == FDDIFC_LLC_ASYNC) {
         caplen -= FDDI_HDRLEN;
         if (caplen < sizeof(struct llc)) return;  /* Too short! */
         p += FDDI_HDRLEN;
         pkt_trace(h->ts, h->len, p);
         last_t_sec = h->ts.tv_sec;
         }
      }
   }

void ether_callback(struct interface_info *user, struct pcap_pkthdr *h, u_char *p)
{
   struct ether_hdr *ethp;
   struct llc *llcp;
   unsigned int ether_type, lsap;
   int len, j;

   if (--user->sample_count == 0) {  /* Process only 1 pkt per SampleRate */
      user->sample_count = user->SampleRate;

      ethp = (struct ether_hdr *)p;
      ether_type = get_short(ethp->type);
      p += sizeof(struct ether_hdr);
      pkt_trace(h->ts, h->len, p);
      last_t_sec = h->ts.tv_sec;
      }
   }

void interface_read(struct interface_info *pi)
{
   pcap_read(pi->pd, -1, pi->callback, (u_char *)pi);
   }

int init_interface(struct interface_info *pi)
{
   char *interface, errbuf[PCAP_ERRBUF_SIZE];
   pcap_t *pd;
   int type;

   if (pi->name[0] == '\0')
      if (!(interface = pcap_lookupdev(errbuf))) {
         printf("pcap_lookupdevice(): %s\n",errbuf);
         return 0;  /* Fail */
         }
      else strcpy(pi->name,interface);
   if ((pd = pcap_open_live(pi->name, SNAPSIZE, 1, 250, errbuf)) == NULL) {
      printf("pcap_open_live(%s): %s\n", pi->name,errbuf);
      return 0;  /* Fail */
      }
   setuid(getuid());
   pi->pd = pd;  pi->fd = pd->fd;

   type = pcap_datalink(pd);
   if (type == DLT_EN10MB) {
      pi->callback = (pcap_handler)ether_callback;
      }
   else if (type == DLT_FDDI) {
      pi->callback = (pcap_handler)fddi_callback;
      }
   else {   
      printf("pcap bad link type 0x%x!\n", type);
      pcap_close(pd);
      return 0;  /* Fail */
      }
   return 1;  /* OK */
   }

/* ===== End of libpcap interface code ===== */

extern int errno;

char *strmov(char *d, char *s)
{
   while (*s != '\0') *d++ = *s++;
   return d;
   }

char interface_name[32] = "";  /* Interface name (used by met_vars.c) */

int main(int argc, char *argv[])
{
   int arg,c, sd, s_n;
   char *ap;
   struct sockaddr_in me;
   struct utsname name;

   if (argc == 1) {
      printf("sudo ./ptrace [-p kilopackets] [-r rate] [-f tracefilename]\n");
      printf("   defaults are -p5 -r500 -fptrace.dat\n");
      exit(0);
      }

   for (n_interfaces = 0;  n_interfaces != MXINTERFACES; ++n_interfaces)
      pci[n_interfaces] = NULL;
   s_n = 1;  n_interfaces = 0;
   for (c = 0, arg = 1; arg < argc; ++arg) {
      if (argv[arg][0] == '-') {
         ap = argv[arg]+2;
	 switch (argv[arg][1]) {
	 case 'f':  /* name of trace file */
	    if (*ap == '\0') ap = argv[++arg];
            ap = strmov(tfname, ap);
            *ap = '\0';
	    break;
	 case 'i':  /* -i name of interface to monitor */
	    if (*ap == '\0') ap = argv[++arg];
            pci[n_interfaces] = (struct interface_info *)calloc(
               sizeof(struct interface_info), 1);
            strcpy(pci[n_interfaces]->name,ap);
	    pci[n_interfaces]->nbr = n_interfaces+1;  /* 1-org */
            ++n_interfaces;
	    break;
	 case 'p':  /* kilopackets to collect */
	    if (*ap == '\0') ap = argv[++arg];
            trace_sz = atoi(ap)*1000 +1;
	    break;
	 case 'r':  /* target packet rate (pps) */
	    if (*ap == '\0') ap = argv[++arg];
            target_pps = atoi(ap);
	    break;
	 default:
	    printf("Invalid option: -%c\n", argv[arg][1]);
	    exit(0);
	    }
	 }
      }
   if (n_interfaces == 0) {
      pci[0] = 
         (struct interface_info *)calloc(sizeof(struct interface_info),1);
      pci[0]->nbr = n_interfaces = 1;
      }
   for (c = 0; c != n_interfaces; ++c)
      pci[c]->SampleRate = pci[c]->sample_count = 1;

   printf("running on interface ");
   ap = interface_name;
   for (c = 0; c != n_interfaces; ++c) {
      if (!init_interface(pci[c])) exit(3);
      if (c != 0) ap = strmov(ap,", ");
      ap = strmov(ap,pci[c]->name);
      }
   *ap = '\0';
   printf("%s\n", interface_name);
   printf("collecting %d packets, rate %d pps writing to %s\n",
      trace_sz-1, target_pps, tfname);
   printf("   press ESC CR  to terminate early\n\n");
   p_table = (struct p_t *)calloc(sizeof(struct p_t),trace_sz);
   if (p_table == NULL) {
      printf("Couldn't allocate packet table\n");
      exit(3);
      }

   receive(n_interfaces);
   }

handle_keyboard()
{
   char kb_buf[25];
   int ch;
   fgets(kb_buf, sizeof kb_buf, stdin);
   if ((ch = kb_buf[0]) == 27) {  /* ESC */
      printf("Shutting down\n");
      write_data();
      exit(0);
      }
   switch (tolower(ch)) {
   case 'v':
      break;
   default:
      break;
      }
   }

receive(int n_interfaces)
{
   fd_set fdset;
   int j, width, count, osc = 10;
   struct timeval t;
   long last_t_s;

   width = STDIN_FILENO;  /* Determine size of fd_set */
#if !CYGWIN32
   for (j = 0; j != n_interfaces; ++j)
      if (pci[j]->fd > width) width = pci[j]->fd;
#endif
   ++width;

   for (;;) {
      if (last_t_sec != last_t_s) {  /* One-second process */
         if (--osc == 0) {
            pps();
            osc = 10;
            }
	 }
      last_t_s = last_t_sec;
      if (time_to_stop) {
         printf("Time to stop !!!\n");
         write_data();
         exit(0);
         }

      FD_ZERO(&fdset);
#if CYGWIN32
      t.tv_sec = 0;  t.tv_usec =  15000;  /* 15 ms */
      for (j = 0; j != n_interfaces; ++j)  /* Read interfaces every cycle */
         interface_read(pci[j]);  /* Can block for several seconds !!!!!! */
#else
      t.tv_sec = 0;  t.tv_usec = 250000;  /* 0.25 s */
      for (j = 0; j != n_interfaces; ++j) FD_SET(pci[j]->fd,&fdset);
#endif
      for (j = 0; j != n_interfaces; ++j) FD_SET(pci[j]->fd,&fdset);
      FD_SET(STDIN_FILENO, &fdset);  /* stdin */
      count = select(width, &fdset, 0, 0, &t);
      if (count > 0) {
#if !CYGWIN32
         for (j = 0; j != n_interfaces; ++j) {
            if (FD_ISSET(pci[j]->fd, &fdset))
               interface_read(pci[j]);
	    }
#endif
         if (FD_ISSET(STDIN_FILENO, &fdset))  /* stdin */
            handle_keyboard();
         }
      else switch (count) {
      case 0:
	 break;
      case -1:
	 if (errno == EINTR) continue;
	 else perror("select");
	 return -1;
      default:
	 printf("select returned %d\n", count);
	 return -1;
	 }
      }
   }
