
/**
 @Name:		dumphdr.c
 @Purpose:	@User:  Fill in purpose

 Message Types:
	@User:  Document messages (requests and replies) here
	Op	Short Descr	Request			Reply
	-----------------------------------------------------------
	0	Hello		[0]  instance #		plugin id
				[1]  command = 0	instance #
 Notation:
	- this:  struct rp_instance * (ptr to plugin instance)
 Post-Conditions:
   dumphdr_load
	- Plugin class (dumphdr_class) structure is initialized
	- dumphdr_get_class() is registered with PCU
   dumphdr_create_instance
	- Plugin instance memory is allocated and initialized
	  (base class and its extension):
	  this->rpclass = &dumphdr_class
	  ... other members of base class ...
   dumphdr_bind_instance
   
   dumphdr_handle_packet
   
   dumphdr_handle_message
   
   dumphdr_unbind_instance
   
   dumphdr_free_instance
	- Plugin instance memory is free
   dumphdr_unload
	- All instances are free
	- Class is not registered with PCU
*/

#include "stdinc.h"

#include "dumphdr.h"
#include "utils.h"

MOD_MISC("dumphdr")

// Static plugin class structure.
// Each kernel module has one class structure that is initialized by
// the plugin and a pointer to it is returned. The class structure can then
// be used to create plugin instances. Note that this is a structure and 
// not a pointer.
static struct rp_class dumphdr_class;

// @User:  Add class-wide global variables here

void
dumphdr_init_class() {		// initialize plugin class
//
// Initialize class struct:
//   classid - user defined
//   itype   - RP_INTERFACE_TYPE_PKT - for read-only plugins. The handle packet
//             signature is <handle_packet(struct rp_instance *this, void *pkt)>
//             RP_INTERFACE_TYPE_HLIST for plugins that will modify pkts or want
//             to source or sink data. The signature is
//              <handle_packet(struct rp_instance *this, void *plist)>
//   create_instance = function pointer to your create instance method.

  dumphdr_class.classid = dumphdr_ID;
  dumphdr_class.itype   = RP_INTERFACE_TYPE_HLIST;
  dumphdr_class.create_instance = dumphdr_create_instance;
  return;
}

// --| create and initialize an instance of dumphdr |--
struct rp_instance *
dumphdr_create_instance(
  struct rp_class *myclass,		// points to class structure
  u_int32_t instanceid)			// new instance identifier
{
  struct dumphdr_instance *myinst; 

  // allocate memory for local instance struct
  MSR_PLUGIN_MALLOC(myinst,struct dumphdr_instance *, 
                    sizeof(struct dumphdr_instance),
                    M_MSR, 
                    M_WAITOK);
  if (myinst == NULL)	return NULL;

  // fill in instance pointers to local methods
  myinst->rootinstance.rpclass         = &dumphdr_class;
  myinst->rootinstance.handle_packet   = dumphdr_handle_packet;
  myinst->rootinstance.free_instance   = dumphdr_free_instance;
  myinst->rootinstance.bind_instance   = dumphdr_bind_instance;
  myinst->rootinstance.unbind_instance = dumphdr_unbind_instance;
  myinst->rootinstance.handle_msg      = dumphdr_handle_msg;

  myinst->rootinstance.instanceid = instanceid;

  // @User:  Initialize instance variables here
  myinst->pkt_count = 0;
  myinst->hlen	= 0;
  myinst->tos	= 0;
  myinst->len	= 0;
  myinst->id	= 0;
  myinst->ttl	= 0;
  myinst->proto	= 0;
  myinst->saddr	= 0;
  myinst->daddr	= 0;
  myinst->sport	= 0;
  myinst->dport	= 0;

  return (struct rp_instance *)myinst;
}

// --| handle packet |--
void
dumphdr_handle_packet(
  struct rp_instance *this,		// points to instance structure
  void *bufferList)			// points to list of pkt buffers
{
  struct dumphdr_instance
  		*inst	= (struct dumphdr_instance *)this;
  struct ip	*iph;
  msr_bufhdr_t	*buffer;

  // @User:  Add code to handle packets here
  inst->pkt_count++;

  buffer = msr_firstBuffer(bufferList);
  iph = msr_pkt_iph(buffer);

  inst->hlen	= msr_iphlen(iph);
  inst->tos	= msr_iptos(iph);
  inst->len	= msr_iplen(iph);
  inst->id	= msr_ipid(iph);
  inst->ttl	= msr_ipttl(iph);
  inst->proto	= msr_ipproto(iph);
  inst->saddr	= msr_ipsaddr(iph);
  inst->daddr	= msr_ipdaddr(iph);
  if ((inst->proto == IPPROTO_UDP) || (inst->proto == IPPROTO_TCP)) {
    inst->sport	= msr_ipsport(iph);
    inst->dport	= msr_ipdport(iph);
  } else {
    inst->sport	= 0;
    inst->dport	= 0;
  }

  MSR_DEBUG( (MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
  	"dumphdr_handle_packet:  pkt_count %d\n", inst->pkt_count) );
  MSR_DEBUG( (MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
	"dumphdr_handle_packet:  proto x%x, saddr x%x, daddr x%x, sport x%x, dport x%x\n",
	inst->proto, inst->saddr, inst->daddr, inst->sport, inst->dport) );
  MSR_DEBUG( (MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
	"dumphdr_handle_packet:  hlen x%x, tos x%x, len x%x, id x%x, ttl x%x\n",
	inst->hlen, inst->tos, inst->len, inst->id, inst->ttl) );

}

/*
 @Purpose: Handle control messages.
	The request buffer 'buf' is 44 Bytes (11 ints) long. The same array
	will be used for the reply msg (i.e., request buffer is reused for
	the reply buffer and is overwritten).
 	Request Buffer (1 word = 1 int):
		Word 0	Instance number of receiver
		Word 1	Command (Operation Code)
		Word 2	Arg 0 (if any)
		...
		Word 10	Arg 8 (if any)
	Note 1:	By convention, command 0 is the 'hello' command which returns
		the plugin id and the instance number.  All other commands are
		at the discretion of the user.
	Note 2: The word preceding buf[0] contains the message header and
		contains the values of 'flags', 'seq' and '*len' which are
		passed to this routine.
 @User: Append request codes and reply args to the list below.
 Request Codes:		Reply (#: args):
	0: Hello	2: dumphdr_ID, id
	*: Hello	2: dumphdr_ID, id
*/
int
dumphdr_handle_msg(
  struct rp_instance *this,	// points to instance structure
  void *buf,			// points to request/reply buffer
  u_int8_t flags,		// flags
  u_int8_t seq,			// sequence number
  u_int8_t *len)		// IN:  request is in buf[0] thru buf[*len/4-1]
				// OUT:	reply is in buf[0] thru buf[*len/4-1]
{
  struct dumphdr_instance *inst = (struct dumphdr_instance *)this;
  u_int32_t *vals	= (u_int32_t *)buf;
  u_int32_t id		= (u_int32_t)ntohl(*vals);
  u_int32_t cmnd	= (u_int32_t)ntohl(*(vals + 1));
  struct msr_bufhdr_t *hdr;

  switch (cmnd) {
  case 0:	// hello
    *vals++ = (u_int32_t)htonl(dumphdr_ID);
    *vals++ = (u_int32_t)htonl(id);
    break;
  case 1:	// get count
    *vals++ = (u_int32_t)htonl(inst->pkt_count);
    break;
  case 2:	// get major hdr fields:  saddr, daddr, sport, dport
    vals	= (u_int32_t *)buf;
    *vals++	= (u_int32_t) htonl( (inst->saddr)>>24 );
    *vals++	= (u_int32_t) htonl( ((inst->saddr) & 0xff0000) >> 16 );
    *vals++	= (u_int32_t) htonl( ((inst->saddr) & 0xff00) >> 8 );
    *vals++	= (u_int32_t) htonl( (inst->saddr) & 0xff );
    *vals++	= (u_int32_t) htonl( (inst->daddr)>>24 );
    *vals++	= (u_int32_t) htonl( ((inst->daddr) & 0xff0000) >> 16 );
    *vals++	= (u_int32_t) htonl( ((inst->daddr) & 0xff00) >> 8 );
    *vals++	= (u_int32_t) htonl( (inst->daddr) & 0xff );
    *vals++	= (u_int32_t) htonl(inst->sport);
    *vals++	= (u_int32_t) htonl(inst->dport);
    break;
  case 3:	// get minor hdr fields:  proto, hlen, tos, len, id, ttl
    vals	= (u_int32_t *)buf;
    *vals++	= (u_int32_t) htonl(inst->proto);
    *vals++	= (u_int32_t) htonl(inst->hlen);
    *vals++	= (u_int32_t) htonl(inst->tos);
    *vals++	= (u_int32_t) htonl(inst->len);
    *vals++	= (u_int32_t) htonl(inst->id);
    *vals++	= (u_int32_t) htonl(inst->ttl);
  case 4:	// reset count, etc.
    inst->pkt_count = 0;
    inst->hlen	= 0;
    inst->tos	= 0;
    inst->len	= 0;
    inst->id	= 0;
    inst->ttl	= 0;
    inst->proto	= 0;
    inst->saddr	= 0;
    inst->daddr	= 0;
    inst->sport	= 0;
    inst->dport	= 0;
    break;
  default:
    MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
		   "Default:  command %d\n", cmnd));
    break;
  }

  *len = ((char *)vals) - ((char *)buf);
  return 0;

}

// --| Free instance structure |--
void
dumphdr_free_instance(
  struct rp_instance *this)	// points to instance structure
{
  if (this) {
    MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
          "dumphdr_free_instance: Freeing instance id %d ((class id %d)\n",
          this->instanceid, this->rpclass->classid));
    MSR_PLUGIN_FREE(this, M_MSR);
  } else {
    MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_WARNING,
          "dumphdr_free_instance: Passing a NULL this pointer\n"));
  }
}

// --| Bind plugin instance to filter |--
void
dumphdr_bind_instance(
  struct rp_instance *this)	// points to instance structure
{
  struct dumphdr_instance *inst = (struct dumphdr_instance *)this;

  MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
	"dumphdr_bind_instance: Binding instance id %d (class id %d, type %d) to filter id %d\n",
        this->instanceid, this->rpclass->classid,
	this->rpclass->itype, this->bound_fid));

  // @User:  Define what occurs when binding your plugin here
}

// --| Unbind plugin instance from filter
void
dumphdr_unbind_instance(
  struct rp_instance *this)	// points to instance structure
{
  struct dumphdr_instance *inst = (struct dumphdr_instance *)this;

  MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
	"dumphdr_unbind_instance: Unbinding instance id %d (class id %d, Type %d) to filter id %d\n",
        this->instanceid, this->rpclass->classid,
	this->rpclass->itype, this->bound_fid));
  // @User:  Define what occurs when unbinding your plugin here
}

/**
	----------------------------------------------------------------
 @User: YOU SHOULD NOT NEED TO MAKE ANY CHANGES TO THE REST OF THIS FILE
	----------------------------------------------------------------
*/

struct rp_class *
dumphdr_get_class() {	// return class structure
  return &dumphdr_class;
}

// External kernel module entry point.
//
// This function must match the name of the .o file.
// It is called each time the module is loaded or unloaded.
// The stat information is not needed here, so we will 
// leave it lkm_nofunc().
//

int
dumphdr  (
  struct lkm_table *lkmtp,	// points to loadable kernel module table
  int cmd,			// command:  load or unload
  int ver,			// version
  struct kernel_plugin_fct_struct *fctPtr)
				// points to table of kernel functions
{
  // Do NOT put anything before the kernel_plugin_fcts is set, especially if
  // it uses any of the MSR_ macros!!!
  if (kernel_plugin_fcts == NULL) {
    kernel_plugin_fcts = fctPtr;
    kernel_plugin_variables = fctPtr->pluginVariables;
  }

  MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_VERBOSE,
        "dumphdr: Entry function -- initialized plugin_fcts pointers\n"));

  MSR_PLUGIN_DISPATCH(lkmtp, cmd, ver, dumphdr_load, dumphdr_unload,
							PLUGIN_LKM_NOFUNC_FCT);
}

// This function is called each time the module is loaded
int
dumphdr_load(
  struct lkm_table *lkmtp,	// points to loadable kernel module table
  int cmd)			// command (should be load)
{
  int err;

  MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_VERBOSE,
        "dumphdr_load: Loading dumphdr ...\n"));

  if (PLUGIN_LKM_EXISTS_FCT(lkmtp)) {	// avoid loading twice
    MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_INFO,
      "dumphdr_load: plugin already exists! Returing EEXIST\n"));
    return (EEXIST);
  }
  dumphdr_init_class();

  err = PLUGIN_PCU_REGISTER_CLASS_FCT(dumphdr_get_class());
  if (err != RP_OK) {
    MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_ERROR,
	"dumphdr_load: Error (err = %d) encountered registering class.\n",
	err));
    return -1;
  }

  return 0;
}

// This function is called each time the module is unloaded.
// Remove all existing instances and then remove class.
int
dumphdr_unload(
  struct lkm_table *lkmtp,	// points to loadable kernel module table
  int cmd)			// command (should beunload)
{
  struct rp_class *rpclass;
  u_int32_t cid;

  rpclass = dumphdr_get_class();
  cid = rpclass->classid;

  MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_VERBOSE,
        "dumphdr_unload: my rpclass id = %d, Struct Address = 0x%08x\n",
        cid, (u_int32_t)rpclass));
  if (PLUGIN_PCU_FREE_ALL_INSTANCES_FCT(rpclass) != RP_OK) {
    MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_ERROR,
          "dumphdr_unload: Error freeing all instances for class %d\n", cid));
    return -1;
  }

  if (PLUGIN_PCU_DEREGISTER_CLASS_FCT(rpclass) != RP_OK) {
    MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_ERROR,
          "dumphdr_unload: Error deregistering class %d\n", cid));
  }

  MSR_DEBUG((MSR_DEBUG_PLUGIN | MSR_DEBUG_LEVEL_VERBOSE,
        "dumphdr_unload: Unloaded class %d\n", cid));

  return 0;
}

