/**************************************************************************** 
**
** File: open_pcap()
**
** Author: Mike Borella
**
** Comments: Set up pcap to sniff the packets we want.  Most of these 
** commands are listed in the pcap(3) man page.
**
** $Log: open_pcap.c,v $
** Revision 1.2  1998/06/12 21:01:10  mborella
** Added log tag
**
*****************************************************************************/

#include <stdio.h>
#include <pcap.h>
#include "config.h"

extern struct arg_t *my_args;

/*----------------------------------------------------------------------------
 *
 * pcap_open()
 *
 *----------------------------------------------------------------------------
 */

void open_pcap(void)
{
  extern char *pcap_cmd;
  extern pcap_t *pd;
  extern int datalink;
  bpf_u_int32 localnet, netmask;
  struct bpf_program fcode;
  char errorbuf[PCAP_ERRBUF_SIZE];
  void ftlerr(char *, ...);

  /*
   * Look up the device and get a handle to it
   */

  if (my_args->i == NULL) 
    {
      my_args->i = pcap_lookupdev(errorbuf);
      if (my_args->i == NULL) 
	ftlerr("open_pcap: pcap_lookupdev() failed for %s: %s", my_args->i, 
	       errorbuf);
    }

  /*
   * Get a file descriptor to the device
   */

  pd = pcap_open_live(my_args->i, SNAPLEN, PROMISC, READ_TIMEOUT, errorbuf);
  if (pd == NULL) ftlerr("open_pcap: pcap_open_live() failed for %s: %s", 
			 my_args->i, errorbuf);

  /*
   * Determine local net and netmask
   */

  if (pcap_lookupnet(my_args->i, &localnet, &netmask, errorbuf) < 0)
    ftlerr("open_pcap: pcap_lookupnet() failed for %s: %s", my_args->i, 
	   errorbuf);
  
  /*
   * Compile command line filter spec info fcode FSM
   */

  if (pcap_compile(pd, &fcode, pcap_cmd, 0, netmask) < 0)
    ftlerr("pcap_compile: %s", pcap_geterr(pd));

  /*
   * Set the pcap filter with our fcode FSM.  That should do it...
   */

  if (pcap_setfilter(pd, &fcode) < 0)
    ftlerr("pcap_setfilter: %s", pcap_geterr(pd));

  /*
   * Get the data link type 
   */

  datalink = pcap_datalink(pd);
  if (datalink < 0) ftlerr("pcap_datalink: %s", pcap_geterr(pd));

}
