/*
 * send_packets.c: from tcpreplay tools by Aaron Turner 
 * http://tcpreplay.sourceforge.net/
 * send_packets.c is under BSD license (see below)
 * SIPp is under GPL license
 */
/*
 * Copyright (c) 2001-2004 Aaron Turner.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the names of the copyright owners nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <pcap.h>
#include <libnet.h>
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>

#include "send_packets.h"

extern volatile unsigned long rtp_pckts;
extern volatile unsigned long rtp_bytes;

inline void
timerdiv (struct timeval *tvp, float div)
{
  double interval;

  if (div == 0 || div == 1)
    return;

  interval = ((double) tvp->tv_sec * 1000000 + tvp->tv_usec) / (double) div;
  tvp->tv_sec = interval / (int) 1000000;
  tvp->tv_usec = interval - (tvp->tv_sec * 1000000);
}

/*
 * converts a float to a timeval structure
 */
inline void
float2timer (float time, struct timeval *tvp)
{
  float n;

  n = time;

  tvp->tv_sec = n;

  n -= tvp->tv_sec;
  tvp->tv_usec = n * 100000;
}

/* buffer should be "file:interface:port_base" */
int
parse_play_args (char *buffer, play_args_t * args)
{
  char *colon, *interf;
  colon = strchr (buffer, ':');
  if (!colon)
    return -1;
  *colon = '\0';
  args->file = strdup (buffer);
  interf = colon + 1;
  colon = strchr (colon + 1, ':');
  if (!colon)
    return -1;
  *colon = '\0';
  args->interface = strdup (interf);
  args->base = atoi (colon + 1);
//  fprintf (stderr, "Parsed %s on %s[>%d]\n", args->file, args->interface, args->base);
}

/*Safe threaded version*/
void do_sleep (struct timeval *, struct timeval *, int, struct timeval *,
	       struct timeval *);

int
send_packets (play_args_t * play_args)
{
  libnet_t *l;
  pcap_t *pcap;
  struct timeval last = { 0, 0 };
  struct pcap_pkthdr *pkthdr = NULL;
  u_char *pktdata = NULL;
  int ret;
  u_long pktlen;
  u_char errbuf[PCAP_ERRBUF_SIZE];
  libnet_ptag_t ip = 0, l4 = 0;
  struct libnet_ipv4_hdr *ip_hdr = NULL;
  struct libnet_udp_hdr *udp_hdr = NULL;
  char *payload;
  int payload_s;
  int ip_len;
  int port_diff;
  struct timeval didsleep = { 0, 0 };
  struct timeval start = { 0, 0 };

  pcap = pcap_open_offline (play_args->file, errbuf);
  assert (pcap);

  l = libnet_init (LIBNET_RAW4, play_args->interface, errbuf);
  assert (l);


#if HAVE_PCAP_NEXT_EX
  while (pcap_next_ex (pcap, &pkthdr, (const u_char **) &pktdata) == 1)
    {
#else
  pkthdr = malloc (sizeof (*pkthdr));
  assert (pkthdr);
  while ((pktdata = pcap_next (pcap, pkthdr)) != NULL)
    {
#endif
      pktlen = (u_long) pkthdr->len;

      ip_hdr = (struct libnet_ipv4_hdr *) (pktdata + LIBNET_ETH_H);
      ip_len = 4 * ip_hdr->ip_hl;

      if (ip_hdr->ip_p == IPPROTO_UDP)
	{
	  udp_hdr = (struct libnet_udp_hdr *) (pktdata + LIBNET_ETH_H + ip_len);
	  payload = ((char *) udp_hdr + sizeof (*udp_hdr));
	  payload_s = pktlen - ip_len - sizeof (*udp_hdr) - LIBNET_ETH_H;
	  port_diff = ntohs (udp_hdr->uh_dport) - play_args->base;

	  l4 = libnet_build_udp (play_args->from.sin_port + port_diff,
				 play_args->to.sin_port + port_diff,
				 LIBNET_UDP_H + payload_s,
				 0, payload, payload_s, l, l4);
	  assert (l4 != -1);
	  ip = libnet_build_ipv4 (LIBNET_IPV4_H + LIBNET_UDP_H +
				  payload_s, 0, 666, 0, 64, IPPROTO_UDP,
				  0, play_args->from.sin_addr.s_addr,
				  play_args->to.sin_addr.s_addr, NULL, 0,
				  l, ip);
	  assert (ip != -1);
	}
      else if (ip_hdr->ip_p == IPPROTO_TCP)
	{
	}
      do_sleep ((struct timeval *) &pkthdr->ts, &last, pktlen, &didsleep,
		&start);

      do
	{
	  ret = libnet_write (l);
	  if (ret == -1)
	    {
	      if (errno == ENOBUFS)
		{
		  fprintf (stderr, "NOBUFS\n");
		  abort ();
		}
	      else
		{
		  fprintf (stderr, "Unable to send packet: %s\n",
			   strerror (errno));
		  fprintf (stderr, "Send packets called with %s[%d]\n",
			   inet_ntoa (play_args->to.sin_addr),
			   ntohs (play_args->to.sin_port));
		  abort ();
		}
	    }
	  rtp_pckts++;
	  rtp_bytes += pktlen;
	}
      while (ret == -1);

      memcpy (&last, &pkthdr->ts, sizeof (struct timeval));
    }
  pcap_close (pcap);
  libnet_destroy (l);
}

/*
 * Given the timestamp on the current packet and the last packet sent,
 * calculate the appropriate amount of time to sleep and do so.
 */
void
do_sleep (struct timeval *time, struct timeval *last, int len,
	  struct timeval *didsleep, struct timeval *start)
{
  struct timeval nap, now, delta;
  struct timespec ignore, sleep;
  float n;
  static u_int32_t send = 0;	/* remember # of packets to send btw calls */

  if (gettimeofday (&now, NULL) < 0)
    {
      errx (1, "Error gettimeofday: %s", strerror (errno));
    }

  /* First time through for this file */
  if (!timerisset (last))
    {
      *start = now;
      timerclear (&delta);
      timerclear (didsleep);
    }
  else
    {
      timersub (&now, start, &delta);
    }

  if (timerisset (last) && timercmp (time, last, >))
    {
      timersub (time, last, &nap);
    }
  else
    {
      /* 
       * Don't sleep if this is our first packet, or if the
       * this packet appears to have been sent before the 
       * last packet.
       */
      timerclear (&nap);
    }

  timeradd (didsleep, &nap, didsleep);

  if (timercmp (didsleep, &delta, >))
    {
      timersub (didsleep, &delta, &nap);

      sleep.tv_sec = nap.tv_sec;
      sleep.tv_nsec = nap.tv_usec * 1000;	/* convert ms to ns */

      while ((nanosleep (&sleep, &sleep) == -1) && (errno == -EINTR));
    }
}
