/* 
 * $smu-mark$ 
 * $name: listen.c$ 
 * $author: Salvatore Sanfilippo <antirez@invece.org>$ 
 * $copyright: Copyright (C) 1999 by Salvatore Sanfilippo$ 
 * $license: This software is under GPL version 2 of license$ 
 * $date: Fri Nov  5 11:55:48 MET 1999$ 
 * $rev: 8$ 
 */ 

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include "hping2.h" /* hping2.h includes hcmp.h */
#include "globals.h"

void listenmain(void)
{
	int size;
	int stdoutFD = fileno(stdout);
	char packet[LINK_PACKETSIZE];
	char *p;
	struct myiphdr *ip = (struct myiphdr*) (packet+ABS_OFFSETIP);
	__u16 id;
	static __u16 exp_id; /* expected id */

	exp_id = 1;

	while(1)
	{
#if (!defined OSTYPE_LINUX) || (defined FORCE_LIBPCAP)
		size = pcap_recv(packet, LINK_PACKETSIZE);
		if (size == -1) {
			perror("[wait_packet] pcap_recv()");
			return;
		}
#else
		size = recv(sockpacket, packet, LINK_PACKETSIZE, 0);
		if (size == -1)
			continue;
#endif /* !OSTYPE_LINUX || FORCE_LIBPCAP */

		id = ntohs(ip->id);

		if ((p = memstr(packet, sign, size)))
		{
			if (opt_verbose)
				fprintf(stderr, "packet %d received\n", id);

			if (opt_safe)
			{
				if (id == exp_id)
					exp_id++;
				else
				{
					if (opt_verbose)
						fprintf(stderr, "packet not in sequence (id %d) received\n", id);
					send_hcmp(HCMP_RESTART, exp_id);
					if (opt_verbose)
						fprintf(stderr, "HCMP restart from %d sent\n", exp_id);
					continue; /* discard this packet */
				}
			}

			p+=strlen(sign);
			write(stdoutFD, p, size-(p-packet));
		}
	}
}
