/*
 * Scan for the existance of a specific peer using fake ARP requests
 *
 * Copyright (C) 2003--2007  Enrico Zini <enrico@debian.org>
 * Originally based on laptop-netconf.c by Matt Kern <matt@debian.org>
 * Which in turn was nased on divine.c by Felix von Leitner <felix@fefe.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "scanner/peer.h"
#include "util/netsender.h"
#include "util/packetmaker.h"
#include "util/output.h"

#include <netinet/in.h> // ntohs, htons, ...

#include <memory>

/*
extern "C" {
#include <libnet.h>
}
*/

using namespace std;
using namespace wibble::sys;
using namespace util;

namespace scanner {

PeerScan::PeerScan(const std::string& name)
	: Scan(name), _ip("0.0.0.0"), _source("0.0.0.0")
{
	bzero(&_mac, sizeof(struct ether_addr));
}

void PeerScan::startableStart()
{
	// Enqueue the probe packets for sending
	NetSender& sender = NetSender::get();

	// Build and send the arp probe
	Buffer pkt;
	
	if (hasIP())
	{
		pkt = PacketMaker::makeARPRequest(ip(), source());
		verbose("Sending 10 ARP probes, 1 every second...\n");
	}
	else
	{
		pkt = PacketMaker::makePingRequest(mac(), source());
		verbose("Sending 10 Ping probes, 1 every second...\n");
	}

	// Enqueue the packet for sending
	sender.post(pkt, 1000, 10000);
}

void PeerScan::startableStop()
{
}

bool PeerScan::hasMAC() const
{
	struct ether_addr zeromac;
	bzero(&zeromac, sizeof(struct ether_addr));
	return !MAC_MATCHES(&_mac, &zeromac);
}

string PeerScan::signature() const
{
	return "peer " + fmt(ip()) + " " + fmt(mac());
}

void PeerScan::handleEthernet(const NetBuffer& pkt)
{
	// Parse and check the ethernet header
	const libnet_ethernet_hdr* packet_header = pkt.cast<struct libnet_ethernet_hdr>();

	//debug("Got eth packet\n");

	// Just check that it comes from the MAC we're looking for
	if (!hasIP() && MAC_MATCHES(&mac(), packet_header->ether_shost))
	{
		debug("Got reply from %s\n", fmt(mac()).c_str());
		success();
	}
}

void PeerScan::handleARP(const NetBuffer& arp)
{
	// Parse and check the arp header
	const libnet_arp_hdr* arp_header = arp.cast<libnet_arp_hdr>();
	if (ntohs (arp_header->ar_op) == ARPOP_REPLY)
	{
		//in_addr* ipv4_him = arp_get_tip(arp_header);
		in_addr* ipv4_him = arp_get_sip(arp_header);
		ether_addr* mac_him = arp_get_sha(arp_header);

		debug("Got ARP reply from %s %s\n", fmt(IPAddress(*ipv4_him)).c_str(), fmt(*mac_him).c_str());

		//IPv4_FROM_LIBNET(ipv4_me, arp_header->ar_tpa);
		//IPv4_FROM_ARP(ipv4_him, arp_header->ar_spa);

		bool match = true;

		// Check if IP matches
		if (hasIP() && ! IPv4_MATCHES(&ip(), ipv4_him))
			match = false;

		// Check if MAC matches
		if (hasMAC() && ! MAC_MATCHES(&mac(), mac_him))
			match = false;

		if (match)
		{
			debug("ARP reply from %s %s matches\n",
					fmt(IPAddress(*ipv4_him)).c_str(), fmt(*mac_him).c_str());
			success();
		}
	}
}

void PeerScan::finaliseInit()
{
	// Register with the NetWatcher
	NetWatcher& watcher = NetWatcher::get();

	if (hasIP())
	{
		//debug("Listen ARP\n");
		watcher.addARPListener(this);
	}
	else
	{
		//debug("Listen Ethernet\n");
		watcher.addEthernetListener(this);
	}

	// Access the NetSender to show that we depend on it
	NetSender& sender = NetSender::get();

	util::Starter::get().add(this);
}

Scan* Peer::createScan(const std::string& name, const ether_addr& mac, const IPAddress& ip)
{
	auto_ptr<PeerScan> res(new PeerScan(name, mac, ip));
	res->finaliseInit();
	return res.release();
}

Scan* Peer::createScan(const std::string& name, const ether_addr& mac, const IPAddress& ip, const IPAddress& source)
{
	auto_ptr<PeerScan> res(new PeerScan(name, mac, ip, source));
	res->finaliseInit();
	return res.release();
}

}

// vim:set ts=4 sw=4:
