/*
    Program:     tcpappend.c
    Author:      Rob Beverly <rbeverly \at\ mit \d0t\ edu>
    Date:        March 23, 2003
    Updated:     
    Description: Append tcpdump file B to end of tcpdump file A
*/

#define VERSION "0.1"
#define SNAPLEN 40

#include <stdio.h>
#include <unistd.h>
#include <pcap.h>

void usage(char *prog) {
    printf("%s v%s - Append tcpdump infile2 to infile1.\n", prog, VERSION);
    printf("usage: %s -1<infile1> -2<infile2> -o<outfile>\n", prog);
    exit(-1);
}


int main (int argc, char **argv) {
  pcap_t *pcap;
  pcap_dumper_t *pd;
  struct pcap_pkthdr header;
  char errbuf[256];
  double ts[2];
  char *output = NULL;
  char *input1 = NULL;
  char *input2 = NULL;
  int ch;

  if (argc < 3) usage(argv[0]);

  printf("%s v.%s.\n", argv[0], VERSION);

  /* Parse the command-line. */
  while ((ch = getopt(argc, argv, "ho:1:2:")) != EOF) {
      switch ((char) ch) {
      case 'o':
          output = optarg;
          break;
      case 'h':
          usage(argv[0]);
          break;
      case '1':
          input1 = optarg;
          break;
      case '2':
          input2 = optarg;
          break;
      }
  }
 
  /* Sanity check */
  if (input1 == NULL) { printf("No input 1 specified.\n"); exit(-1); }
  if (input2 == NULL) { printf("No input 2 specified.\n"); exit(-1); }
  if (output == NULL) { printf("No output specified.\n"); exit(-1); }

  /* Sanity check time */
  if ((pcap = pcap_open_offline(input1, errbuf)) == NULL)
     printf("Error: %s\n", errbuf);

  pcap_next(pcap, &header);
  ts[0] = (double) header.ts.tv_usec/1000000 + header.ts.tv_sec;

  if ((pcap = pcap_open_offline(input2, errbuf)) == NULL)
     printf("Error: %s\n", errbuf);

  pcap_next(pcap, &header);
  ts[1] = (double) header.ts.tv_usec/1000000 + header.ts.tv_sec;

  if (ts[0] > ts[1]) {
     printf("*** Error: Timestamp of [%s] preceeds [%s]!\n*** Error: Reverse argument order?\n",
         input2, input1);
     exit(-1);
  }

  /* Looks good, open pcap files */
  printf("Opening input 1: (%s).\n", input1);
  if ((pcap = pcap_open_offline(input1, errbuf)) == NULL)
     printf("Error: %s\n", errbuf);

  printf("Opening output: (%s).\n", output);
  if ((pd = pcap_dump_open(pcap, output)) == NULL)
     printf("Error! %s\n", pcap_geterr(pcap));

  pcap_loop(pcap, -1, pcap_dump, (u_char *) pd);
	
  printf("Opening input 2: (%s).\n", input2);
  if ((pcap = pcap_open_offline(input2, errbuf)) == NULL)
     printf("Error: %s\n", errbuf);

  pcap_loop(pcap, -1, pcap_dump, (u_char *) pd);
  
  /* Buh-bye */
  printf("Appended streams.\n");
  pcap_dump_close(pd);
  pcap_close(pcap);
  exit(0);
}
