/* A test program for IP Queue functionality */

#include <stdio.h>
#include <linux/netfilter.h>
#include <libipq.h>

#define BUFFER_SIZE 4096

int main( int argv, char** argc ){
	struct ipq_handle * qhandle;
	char buffer[BUFFER_SIZE]; /* This buffer stores packets from ipq */
	int i;
	int msg_type;
	struct ipq_packet_msg * packet;
	
	/* Create the queue handle so we can begin processing packets */
	qhandle = ipq_create_handle( 0 );
	if ( qhandle == NULL )
	{
		ipq_perror( "ipq_create_handle" );
		return 1;
	}
	
	/* Tell netfilter that we want metadata only */
	if ( ipq_set_mode( qhandle, IPQ_COPY_META, 0 ) == -1 )
	{
		ipq_perror( "ipq_set_mode" );
		return 2;
	}

	for ( i = 0; i < 100; ++ i )
	{
		if ( ipq_read( qhandle, buffer, BUFFER_SIZE, 0 ) == -1 )
		{
			ipq_perror( "ipq_read" );
			return 3;
		}
		
		/* We got a message, handle it */
		msg_type = ipq_message_type( buffer );
		if ( msg_type == IPQM_PACKET )
		{
			packet = ipq_get_packet( buffer );
			ipq_set_verdict( qhandle, packet->packet_id, NF_ACCEPT, 0, NULL );
			printf( "Got a packet id = %lx iface = %s oface = %s data_len = %u\n",
				packet->packet_id, packet->indev_name, packet->outdev_name, packet->data_len );
		}
		else if ( msg_type == NLMSG_ERROR )
		{
			printf( "Got an error!\n" );
			errno = ipq_get_msgerr( buffer );
			perror( "ipq_read" );
			return 4;
		}
		else
		{
			printf( "Got an unhandled message_type: %d\n", msg_type );
		}
	}
	
	/* We are done processing packets */
	if ( ipq_destroy_handle( qhandle ) != 0 )
	{
		ipq_perror( "ipq_destroy_handle" );
		return 100;
	}
	
	return 0;
}

