/*
 * 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 <unistd.h>
#include <assert.h>
#include <stdlib.h>
#include <netinet/udp.h>
#include <errno.h>
#include <string.h>

#include "send_packets.h"
#include "prepare_pcap.h"

extern volatile unsigned long rtp_pckts;
extern volatile unsigned long rtp_bytes;
extern int media_ip_is_ipv6;

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_name" */
int
parse_play_args (char *buffer, pcap_pkts *pkts)
{
  pkts->file = strdup (buffer);
  prepare_pkts(pkts->file, pkts);
  return 1;
}

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

int
send_packets (play_args_t * play_args)
{
  int ret, sock, port_diff;
  pcap_pkt *pkt_index, *pkt_max;
  uint16_t from_port, to_port;
  struct timeval didsleep = { 0, 0 };
  struct timeval start = { 0, 0 };
  struct timeval last = { 0, 0 };
  pcap_pkts *pkts = play_args->pcap;
  struct sockaddr_storage to = play_args->to;
  struct sockaddr_storage from = play_args->from;
  struct udphdr *udp;
  char buffer[PCAP_MAXPACKET];

  if (media_ip_is_ipv6) {
    sock = socket(PF_INET6, SOCK_RAW, IPPROTO_UDP);
    assert(sock >= 0);
    from_port = ((struct sockaddr_in6 *) (&(from)) )->sin6_port;
    to_port = ((struct sockaddr_in6 *) (&(to)) )->sin6_port;
  }
  else {
    sock = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
    assert(sock >= 0);
    from_port = ((struct sockaddr_in *) (&(from)) )->sin_port;
    to_port = ((struct sockaddr_in *) (&(to)) )->sin_port;
  }

  udp = (struct udphdr *)buffer;

  pkt_index = pkts->pkts;
  pkt_max = pkts->max;
  fprintf(stderr, "S IP: %08x\n", ((struct sockaddr_in *)&from)->sin_addr.s_addr);
  fprintf(stderr, "D IP: %08x\n", ((struct sockaddr_in *)&to)->sin_addr.s_addr);

  while (pkt_index < pkt_max) {
    memcpy(buffer, pkt_index->data, pkt_index->pktlen);
#ifndef __HPUX
    port_diff = ntohs (udp->dest) - pkts->base;
    udp->source = htons(port_diff + from_port);
    udp->dest = htons(port_diff + to_port);
#else
    port_diff = ntohs (udp->uh_dport) - pkts->base;
    udp->uh_sport = htons(port_diff + from_port);
    udp->uh_dport = htons(port_diff + to_port);
#endif
    // mangle udp ports
// check ipv6!!!!!
    if (!media_ip_is_ipv6) {
#ifndef __HPUX
      udp->check = checksum_carry(pkt_index->partial_check + check((u_int16_t *) &(((struct sockaddr_in *)&from)->sin_addr.s_addr), 4) + check((u_int16_t *) &(((struct sockaddr_in *)&to)->sin_addr.s_addr), 4) + check((u_int16_t *) &udp->source, 4));
#else
      udp->uh_sum = checksum_carry(pkt_index->partial_check + check((u_int16_t *) &(((struct sockaddr_in *)&from)->sin_addr.s_addr), 4) + check((u_int16_t *) &(((struct sockaddr_in *)&to)->sin_addr.s_addr), 4) + check((u_int16_t *) &udp->uh_sport, 4));
#endif
      }

    do_sleep ((struct timeval *) &pkt_index->ts, &last, &didsleep,
		&start);
#ifdef MSG_DONTWAIT
 // OJAOJA return send(s, msg, len, flags | MSG_DONTWAIT);

    ret = sendto(sock, buffer, pkt_index->pktlen, MSG_DONTWAIT,
      (struct sockaddr *)&to, sizeof(to));
#else
    int fd_flags = fcntl(sock, F_GETFL , NULL);
    int initial_fd_flags;
    initial_fd_flags = fd_flags;
    fd_flags |= O_NONBLOCK;
    fcntl(sock, F_SETFL , fd_flags);
    ret = sendto(sock, buffer, pkt_index->pktlen, 0,
      (struct sockaddr *)&to, sizeof(to));
    fcntl(sock, F_SETFL , initial_fd_flags);
#endif
    if (ret < 0) {
      fprintf(stderr, "Send: failed with %s\n", strerror(errno));
      abort();
	    }

	  rtp_pckts++;
    rtp_bytes += pkt_index->pktlen - sizeof(*udp);
    memcpy (&last, &(pkt_index->ts), sizeof (struct timeval));
    pkt_index++;
	}

  close(sock);
  return 0;
}

/*
 * 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,
	  struct timeval *didsleep, struct timeval *start)
{
  struct timeval nap, now, delta;
  struct timespec ignore, sleep;
  float n;

  if (gettimeofday (&now, NULL) < 0)
    {
      fprintf (stderr, "Error gettimeofday: %s\n", 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));
    }
}


