#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "ars.h"

int main(int argc, char **argv)
{
	struct ars_packet p;
	struct ars_iphdr *ip, *ip2;
	struct ars_ipopt *ipopt;
	struct ars_tcphdr *tcp;
	struct ars_icmphdr *icmp;
	struct ars_tcpopt *tcpopt;
	int s, j;
	void *data;

	ars_init(&p);

	s = ars_open_rawsocket(&p);
	if (s == -ARS_ERROR) {
		perror("Opening raw socket");
		exit(1);
	}

	/* IP layer */
	ip = ars_add_iphdr(&p, 0);
	ip->id = htons(1);
	ip->ttl = 0;
	ars_resolve(&p, &ip->saddr, "192.168.2.1");
	ars_resolve(&p, &ip->daddr, "192.168.2.2");

	/* IP options */
	ipopt = ars_add_ipopt(&p, ARS_IPOPT_RR);

	/* ICMP layer */
	icmp = ars_add_icmphdr(&p, 0);
	icmp->type = ARS_ICMP_TIME_EXCEEDED;
	icmp->code = ARS_ICMP_EXC_TTL;

	/* Second IP layer */
	ip2 = ars_add_iphdr(&p, 0);
	ip2->id = htons(1);
	ip2->ttl = 64;
	ars_resolve(&p, &ip2->saddr, "1.2.3.4");
	ars_resolve(&p, &ip2->daddr, "5.6.7.8");

	/* TCP layer */
	tcp = ars_add_tcphdr(&p, 0);
	tcp->th_win = htons(512);
	tcp->th_flags = ARS_TCP_TH_SYN;
	tcp->th_dport = htons(21);

	/* TCP options */
	tcpopt = ars_add_tcpopt(&p, ARS_TCPOPT_WINDOW);
	tcpopt->un.win.shift = 2;

	/* TCP data, 10 bytes */
	data = ars_add_data(&p, 10);
	memset(data, 'A', 10);

	/* Compile the packet and send it, using 10 different TTLs */
	while(ip->ttl < 10) {
		if (ars_compile(&p) != -ARS_OK) {
			printf("Error compiling\n");
			exit(0);
		}
		ars_send(s, &p, NULL, 0);
		ip->ttl++;
	}

	/* Print some information about the layers */
	for (j = 0; j < ARS_MAX_LAYER; j++) {
		if (p.p_layer[j].l_type == ARS_TYPE_NULL)
			break;
		printf("layer %d rel_size: %d type: %s\n", j, ars_relative_size(&p, j), ars_linfo[p.p_layer[j].l_type].li_name);
	}
	return 0;
}
