/* A Small program that loggs downtime *
 *		0.0.1		       *
 * 	pingvin@varberg.se	       */

#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/timeb.h>

#define LOG_PATH "/var/log/dt.log"
#define MAXBUFFER 1024
#define MAXTIME 15	/* Seconds before logging */

int main (int argc, char *argv[])
{
	struct sockaddr_in *to;
	struct sockaddr_in from;
	struct icmphdr *pkt;
	struct timeval totval, before;
	struct timespec t1, t2;
	struct tm lt;
	unsigned char outpacket[sizeof (struct icmphdr)];
	unsigned char inpacket[IP_MAXPACKET];
	char buffer[MAXBUFFER],ipfrom[MAXBUFFER];
	int nw,rawfd;
	int flag = 0;
	int tot = 0;
	int sek = 0;
	FILE *utfil;
	fd_set fdset;
	socklen_t fromlen = sizeof (from);

	if (argc != 2)
	{
		fprintf (stderr, "Usage: %s ip\n", argv[0]);
		exit (1);
	}
	strncpy(ipfrom,argv[1],MAXBUFFER);
	rawfd = socket (PF_INET, SOCK_RAW, IPPROTO_ICMP);
	to->sin_port = 0;
	to->sin_family = AF_INET;
	inet_aton (argv[1], &to->sin_addr);

	pkt = (struct icmphdr *) outpacket;
	pkt->type = ICMP_ECHO;
	pkt->code = 0;
	pkt->checksum = 0;
	pkt->un.echo.sequence = 0;
	pkt->un.echo.id = getpid () & 0xFFFF;
	pkt->checksum = 1;	// I know, way wrong!

	t1.tv_sec = 1;
	t1.tv_nsec = 0;
	totval.tv_sec = 1;
	totval.tv_usec = 0;

	while (1 == 1) // No exit 8)
	{
		nanosleep (&t1, &t2);
		if (flag == 0)
			sek++;

		if (tot == 0)
		{
			gettimeofday (&before, NULL);
			tot = 1;
		}

		nw =
			sendto (rawfd, outpacket, sizeof (outpacket), 0, to,
				sizeof (*to));
		FD_ZERO (&fdset);
		FD_SET (rawfd, &fdset);
		select (rawfd + 1, &fdset, NULL, NULL, &totval);
		if (FD_ISSET (rawfd, &fdset))
		{
			recvfrom (rawfd, inpacket, sizeof (inpacket), 0,
				  &from, &fromlen);
			flag = 1;
			if (sek >= MAXTIME)
			{
				utfil = fopen (LOG_PATH, "a");
				lt = *localtime ((time_t *) & before);
				strftime (buffer, MAXBUFFER,
					  "%a, %d %b %Y %H:%M:%S", &lt);
				fprintf (utfil,
					 "Lost connection to %s at %s, but got connected after %i seconds\n",
					 ipfrom, buffer, sek);
				fclose (utfil);
				tot = 0;
			}
			sek = 0;
		}
		else
		{
			flag = 0;
		}
	}

}

