/*
  findgw.c

  Determine local gateway via passive sniffing.
  
  Copyright (c) 1999 Dug Song <dugsong@monkey.org>
  All rights reserved, all wrongs reversed.

  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. The name of author may not 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 AUTHOR 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.

  $Id: findgw.c,v 1.7 2000/01/24 17:59:09 dugsong Exp $
*/

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
#include <string.h>
#include <libnet.h>
#include <pcap.h>

#include "version.h"

#define MAC_TAB_SIZE		256
#define DEFAULT_TIMEOUT		10

#define MAC_EQ(a, b)		(memcmp(a, b, ETHER_ADDR_LEN) == 0)
#define MAC_ISNULL(a)		(*((u_long *)a) + *((u_short *)(a + 4)) == 0)
#define int_ntoa(x)		inet_ntoa(*((struct in_addr *)&(x)))

extern char *ether_ntoa(struct ether_addr *);

struct mac_info {
  u_char mac[ETHER_ADDR_LEN];
  
  struct ip_list {
    u_long addr;
    struct ip_list *next;
  } ips;
};

/* Globals. */
struct mac_info MAC_tab[MAC_TAB_SIZE];
jmp_buf env_buf;

void
usage(void)
{
  fprintf(stderr, "Usage: findgw [-i interface] [-t timeout]\n");
  exit(1);
}

void
print_spin_thing(void)
{
  static int i = 0;
  char *spin_chars = "|/-\\|/-\\";
  
  if (i > 7) i = 0;
  fprintf(stderr, "\b%c", spin_chars[i++]);
  fflush(stderr);
}

/* Add MAC, IP address info to MAC table. */
void
mac_tab_add(u_char *pkt, int len)
{
  u_long addr;
  u_char *mac;
  struct ip_list *ipl;
  int i;
  
  if (len < ETH_H + IP_H) return;
  
  mac = /*((struct ether_header *)*/ pkt /*)->ether_dhost*/;	/* XXX */
  addr = ((struct ip *)(pkt + ETH_H))->ip_dst.s_addr;
  
  for (i = 0; i < MAC_TAB_SIZE; i++) {
    if (MAC_EQ(mac, MAC_tab[i].mac)) {
      for (ipl = &MAC_tab[i].ips; ipl->next != NULL; ipl = ipl->next) {
	if (ipl->addr == addr)
	  break;
      }
      if (ipl->addr != addr) {
	if ((ipl->next = malloc(sizeof(*ipl))) == NULL) return;
	ipl->next->addr = addr;
	ipl->next->next = NULL;
      }
      break;
    }
    else if (MAC_ISNULL(MAC_tab[i].mac)) {
      memcpy(MAC_tab[i].mac, mac, ETHER_ADDR_LEN);
      MAC_tab[i].ips.addr = addr;
      break;
    }
  }
}

/* Find the most popular router from the MAC table. */
u_char *
mac_tab_gateway(void)
{
  int i, num, min = 1;
  u_char *mac = NULL;
  struct ip_list *ipl;
  
  for (i = 0; i < MAC_TAB_SIZE; i++) {
    if (MAC_ISNULL(MAC_tab[i].mac)) break;
    for (ipl = &MAC_tab[i].ips, num = 0; ipl != NULL; ipl = ipl->next, num++) ;
    if (num > min) {
      min = num;
      mac = MAC_tab[i].mac;
    }
  }
  return (mac);
}

#ifdef DEBUG
/* Print MAC table. */
void
mac_tab_print(void)
{
  int i;
  struct ip_list *ipl;

  for (i = 0; i < MAC_TAB_SIZE; i++) {
    if (MAC_ISNULL(MAC_tab[i].mac)) break;
    fprintf(stderr, "%s\n", ether_ntoa((struct ether_addr *)MAC_tab[i].mac));
    for (ipl = &MAC_tab[i].ips; ipl != NULL; ipl = ipl->next)
      fprintf(stderr, "\t%s\n", int_ntoa(ipl->addr));
  }
}
#endif

/* Start sniffing on an interface. */
pcap_t *
pcap_init(char *intf, char *filter, int snaplen)
{
  pcap_t *pd;
  u_int net, mask;
  struct bpf_program fcode;
  char ebuf[PCAP_ERRBUF_SIZE];

  if ((pd = pcap_open_live(intf, snaplen, 1, 1024, ebuf)) == NULL)
    return (NULL);
  
  if (pcap_lookupnet(intf, &net, &mask, ebuf) == -1)
    return (NULL);
  
  if (pcap_compile(pd, &fcode, filter, 1, mask) < 0)
    return (NULL);
  
  if (pcap_setfilter(pd, &fcode) == -1)
    return (NULL);
  
  return (pd);
}

void handle_timeout(int sig)
{
  alarm(0);
  longjmp(env_buf, 1);
}

/* Watch IP traffic to determine the most likely gateway. */
u_char *
sniff_gateway_mac(char *intf, int seconds)
{
  pcap_t *pd;
  struct pcap_pkthdr pkthdr;
  u_char *pkt;

  memset(&MAC_tab, 0, sizeof(MAC_tab));

  if ((pd = pcap_init(intf, "ip and not ip broadcast and not "
		      "ether broadcast", ETH_H + IP_H)) == NULL) {
    fprintf(stderr, "couldn't initialize sniffing\n");
    return (NULL);
  }
  fprintf(stderr, "sniffing traffic for %d seconds...  ",
	  seconds);
  
  if (!setjmp(env_buf)) {
    signal(SIGALRM, handle_timeout);
    alarm(seconds);
    for (;;) {
      if ((pkt = (char *)pcap_next(pd, &pkthdr)) != NULL)
	mac_tab_add(pkt, pkthdr.caplen);
      print_spin_thing();
    }
    alarm(0);
  }
  pcap_close(pd);
  fprintf(stderr, "\b \n");

  return (mac_tab_gateway());
}

/* Watch ARP replies from a MAC to determine a host's IP address. */
u_long
sniff_arp_for_ip(char *intf, u_char *mac)
{
  char filter[128];
  pcap_t *pd;
  struct pcap_pkthdr pkthdr;
  u_char *pkt = NULL;

  snprintf(filter, sizeof(filter) - 1, "arp[6:2] = 2 and ether src %s",
	   ether_ntoa((struct ether_addr *)mac));
  
  if ((pd = pcap_init(intf, filter, 60)) == NULL) {
    fprintf(stderr, "couldn't initialize sniffing\n");
    return (0);
  }
  fprintf(stderr, "waiting for ARP reply from %s...  ",
	  ether_ntoa((struct ether_addr *)mac));

  for (;;) {
    if ((pkt = (char *)pcap_next(pd, &pkthdr)) != NULL) {
      if (pkthdr.caplen == 60) break;
    }
    print_spin_thing();
  }
  pcap_close(pd);
  fprintf(stderr, "\b \n");

  return (*(u_long *)(pkt + ETH_H + 14)); /* XXX - ar_spa */
}
    
int
main(int argc, char *argv[])
{
  int c, timeout;
  char *intf;
  char ebuf[PCAP_ERRBUF_SIZE];
  u_char *mac;
  u_long addr;
  
  intf = NULL;
  timeout = 0;
  
  while ((c = getopt(argc, argv, "i:t:h?V")) != -1) {
    switch (c) {
    case 'i':
      intf = optarg;
      break;
    case 't':
      timeout = atoi(optarg);
      break;
    case 'V':
      fprintf(stderr, "Version: %s\n", VERSION);
      usage();
      break;
    default:
      usage();
      break;
    }
  }
  if (argc - optind != 0)
    usage();

  if (intf == NULL && (intf = pcap_lookupdev(ebuf)) == NULL) {
    fprintf(stderr, "%s\n", ebuf);
    exit(1);
  }
  if (timeout == 0)
    timeout = DEFAULT_TIMEOUT;

  if ((mac = sniff_gateway_mac(intf, timeout)) == NULL) {
    fprintf(stderr, "couldn't determine gateway MAC\n");
    exit(1);
  }
  printf("gateway MAC: %s\n", ether_ntoa((struct ether_addr *)mac));

  /* XXX - don't timeout here, just sniff until we get the goods. */
  addr = sniff_arp_for_ip(intf, mac);
  
  printf("gateway IP: %s\n", int_ntoa(addr));
  
  exit(0);
}

/* 5000 */
