//
// C++ Implementation: kmfiptablesscriptgenerator
//
// Description: 
//
//
// Author: Christian Hubinger <chubinger@irrsinnig.org>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
// License: GPL
//
#include "kmfiptablesscriptgenerator.h"

// TQt includes
#include <tqptrlist.h>
#include <tqstringlist.h>
#include <tqmultilineedit.h>
#include <tqtabwidget.h>

// KDE includes
#include <kdebug.h>
#include <tdelocale.h>
#include <kstandarddirs.h>
#include <tdefiledialog.h>
#include <tdetempfile.h>
#include <tdeio/netaccess.h>
#include <tdemessagebox.h>
#include <tdeapplication.h>

// Project includes
#include "../../version.h"
#include "../../core/xmlnames.h"
#include "../../core/kmfgenericdoc.h"
#include "../../core/kmfiptdoc.h"
#include "../../core/kmfnetzone.h"
#include "../../core/kmfnethost.h"
#include "../../core/kmfprotocol.h"
#include "../../core/iptable.h"
#include "../../core/iptchain.h"
#include "../../core/iptrule.h"
#include "../../core/iptruleoption.h"
#include "../../core/kmferror.h"
#include "../../core/kmferrorhandler.h"
#include "../../core/kmfconfig.h"
#include "../../core/kmftarget.h"
#include "../../core/kmftargetconfig.h"
#include "../../kmfwidgets/kmflistview.h"



namespace KMF {
KMFIPTablesScriptGenerator::KMFIPTablesScriptGenerator()
{
}


KMFIPTablesScriptGenerator::~KMFIPTablesScriptGenerator()
{
}

const TQString& KMFIPTablesScriptGenerator::compile( KMFIPTDoc* doc ) {
	m_iptDoc = doc;
	TQString script;
	m_stream = new TQTextOStream( &script );
	printScriptHeader();
	printScriptStartFunction();
	printScriptStopFunction();
	printScriptExecLogic();
	return *(new TQString( script ) );
}



void KMFIPTablesScriptGenerator::printScriptExecLogic() {
	*m_stream <<
	"IPT=\"" + m_iptDoc->target()->config()->IPTPath() + "\"\n"
	"MOD=\"" + m_iptDoc->target()->config()->modprobePath() + "\"\n"
	
	"status=\"0\"\n"
	"verbose=\"0\"\n"
	"action=\"$1\"\n"

	"if [ \"$1\" = \"-v\" ]; then\n  "
	"  verbose=\"1\"\n"
	"fi\n\n"
	"if [ \"$1\" = \"--verbose\" ]; then\n  "
	"  verbose=\"1\"\n"
	"fi\n\n"

	"if [ \"$verbose\" = \"1\" ]; then\n  "
	"  if [ \"$2\" = \"\" ]; then\n"
	"    echo \"Usage: sh kmyfirewall.sh [-v|--verbose] { start | stop | restart }\"\n"
	"    exit 1\n"
	"  fi\n"
	"action=\"$2\"\n"
	"fi\n\n"

	"case $action in\n"
	"  start)\n"
	"  stopFirewall\n"
	"  startFirewall\n"
	"  ;;\n"
	"  stop)\n"
	"  stopFirewall\n"
	"  ;;\n"
	"  restart)\n"
	"  stopFirewall\n"
	"  startFirewall\n"
	"  ;;\n"
	"  *)\n"
	"  echo \"Invalid action!\nUsage: sh kmyfirewall.sh [-v|--verbose] { start | stop | restart }\"\n"
	"  ;;\n"
	"  esac\n\n"

	"if [ \"$status\" = \"1\" ]; then\n"
	"  exit 1\n"
	"else\n"
	"  exit 0\n"
	"fi\n" << endl;
}

void KMFIPTablesScriptGenerator::printScriptStartFunction() {
	*m_stream << "startFirewall() {\n"
	"\necho -n \"Starting iptables (created by KMyFirewall)...       \"";
	if ( m_iptDoc->useModules() ) {
		printScriptModuleLoad(); 
		*m_stream << endl;
	}
	*m_stream << "#  Define all custom chains" << endl;
	*m_stream << printScriptDebug( "Create custom chains...       ", false) << endl;
	if ( m_iptDoc->useFilter() ) {
		printScriptTableChainDefinition(  m_iptDoc->table( Constants::FilterTable_Name  ) );
		*m_stream << endl;
	}
	if ( m_iptDoc->useNat() ) {
		printScriptTableChainDefinition(  m_iptDoc->table( Constants::NatTable_Name  ) );
		*m_stream << endl;
	}
	if ( m_iptDoc->useMangle() ) {
		printScriptTableChainDefinition(  m_iptDoc->table( Constants::MangleTable_Name  ) );
		*m_stream << endl;
	}

	*m_stream << printScriptDebug( "  Done." ) << endl;
	*m_stream << "\n#  Rules:" << endl;
	if ( m_iptDoc->useFilter() ) {
		printScriptTableRules(  m_iptDoc->table( Constants::FilterTable_Name ) );
		*m_stream << endl;
	}
	if ( m_iptDoc->useNat() ) {
		printScriptTableRules(  m_iptDoc->table( Constants::NatTable_Name ) );
		*m_stream << endl;
	}
	if ( m_iptDoc->useMangle() ) {
		printScriptTableRules(  m_iptDoc->table( Constants::MangleTable_Name ) );
		*m_stream << endl;
	}

	if ( m_iptDoc->useIPFwd() ) {
		*m_stream << "\n"<< printScriptDebug( "Enable IP Forwarding.                ", false ) << endl;
		*m_stream << "echo 1 > /proc/sys/net/ipv4/ip_forward" << endl;
		*m_stream << printScriptDebug( "Done." ) << endl;
	} else {
		*m_stream << printScriptDebug( "Disable IP Forwarding.              ", false ) << endl;
		*m_stream << "echo 0 > /proc/sys/net/ipv4/ip_forward" << endl;
		*m_stream << printScriptDebug( "Done.") << endl;
	}

	if ( m_iptDoc->useRPFilter() ) {

		*m_stream << "\n" << printScriptDebug( "Enable Reverse Path Filtering      ", false ) << endl;
		*m_stream << "for i in /proc/sys/net/ipv4/conf/*/rp_filter ; do" << endl;
		*m_stream << "echo 2 > $i " << endl;
		*m_stream << "done" << endl;
		*m_stream <<  printScriptDebug( "Done." ) << endl;
	} else {
		*m_stream << printScriptDebug( "Disable Reverse Path Filtering       ", false ) << endl;
		*m_stream << "for i in /proc/sys/net/ipv4/conf/*/rp_filter ; do" << endl;
		*m_stream << "echo 0 > $i " << endl;
		*m_stream << "done" << endl;
		*m_stream << printScriptDebug( "Done." ) << endl;
	}

	if ( m_iptDoc->useMartians() ) {
		*m_stream << "\n" << printScriptDebug( "Enable log_martians (logging).             ", false ) << endl;
		*m_stream << "for i in /proc/sys/net/ipv4/conf/*/log_martians ; do" << endl;
		*m_stream << "echo 1 > $i " << endl;
		*m_stream << "done" << endl;
		*m_stream << printScriptDebug( "Done." ) << endl;
	} else {
		*m_stream << printScriptDebug( "Disable log_martians (logging).           ", false ) << endl;
		*m_stream << "for i in /proc/sys/net/ipv4/conf/*/log_martians ; do" << endl;
		*m_stream << "echo 0 > $i " << endl;
		*m_stream << "done" << endl;
		*m_stream << printScriptDebug( "Done." ) << endl;
	}

	if ( m_iptDoc->useSynCookies() ) {
		*m_stream << "\n" <<  printScriptDebug( "Enable Syn Cookies.          ", false ) << endl;
		*m_stream << "echo 1 > /proc/sys/net/ipv4/tcp_syncookies" << endl;
		*m_stream << printScriptDebug( "Done." )<< endl;
	} else {
		*m_stream <<  printScriptDebug( "Disable Syn Cookies.          ", false ) << endl;
		*m_stream << "echo 0 > /proc/sys/net/ipv4/tcp_syncookies" << endl;
		*m_stream << printScriptDebug( "Done." ) << endl;
	}
	*m_stream << "echo Done." << endl;
	*m_stream << "}" << endl;
}

void KMFIPTablesScriptGenerator::printScriptStopFunction() {
	*m_stream << "stopFirewall() {\n"
	"  echo -n \"Clearing iptables (created by KMyFirewall)...       \"\n" << endl;
	if ( m_iptDoc->useFilter() ) {
		*m_stream << "  $IPT -t filter -F || status=\"1\"\n"
		"  $IPT -t filter -X || status=\"1\"\n"
		"  $IPT -t filter -P INPUT ACCEPT || status=\"1\"\n"
		"  $IPT -t filter -P OUTPUT ACCEPT || status=\"1\"\n"
		"  $IPT -t filter -P FORWARD ACCEPT || status=\"1\"\n"<< endl;
	}
	if ( m_iptDoc->useNat() ) {
		*m_stream << "  $IPT -t nat -F || status=\"1\"\n"
		"  $IPT -t nat -X || status=\"1\"\n"
		"  $IPT -t nat -P OUTPUT ACCEPT || status=\"1\"\n"
		"  $IPT -t nat -P PREROUTING ACCEPT || status=\"1\"\n"
		"  $IPT -t nat -P POSTROUTING ACCEPT || status=\"1\"\n"<< endl;
	}
	if ( m_iptDoc->useMangle() ) {
		*m_stream << "  $IPT -t mangle -F || status=\"1\"\n"
		"  $IPT -t mangle -X || status=\"1\"\n"
		"  $IPT -t mangle -P INPUT ACCEPT || status=\"1\"\n"
		"  $IPT -t mangle -P OUTPUT ACCEPT || status=\"1\"\n"
		"  $IPT -t mangle -P OUTPUT ACCEPT || status=\"1\"\n"
		"  $IPT -t mangle -P PREROUTING ACCEPT || status=\"1\"\n"
		"  $IPT -t mangle -P POSTROUTING ACCEPT || status=\"1\"\n" << endl;
	}
	*m_stream << "  echo \"Done.\"\n" << endl;
	*m_stream << "}" << endl;
}




void KMFIPTablesScriptGenerator::printScriptTableChainDefinition( IPTable *tbl ) {
	for ( uint i = 0;i < tbl->chains().count();i++ ) {
		IPTChain* c = tbl->chains().at( i );
		if ( !c->isBuildIn() ) {
			*m_stream << "\n#  Create Chain: " + c->name() << endl;
			TQString s2 = c->createIPTablesChainDefinition();
			if ( !s2.isEmpty() ) {
				*m_stream << s2 << " || { status=\"1\"; echo \"Setting up Chain: " + c->name() + " FAILED !!!\"; echo \"Ann Error occoured! Clearing rules\"; stopFirewall; exit 1; }\n";
			}
		}
	}
}

void KMFIPTablesScriptGenerator::printScriptTableRules( IPTable *tbl ) {
	*m_stream << printScriptDebug(  "Settup Rules in Table " + tbl->name().upper() + ":" ) << "\n" << endl;
	for ( uint i = 0;i < tbl->chains().count();i++ ) {
		IPTChain* c = tbl->chains().at( i );
		*m_stream << "\n#  Define Rules for Chain: " + c->name() << endl ;
		*m_stream << printScriptDebug( "Create Rules for Chain: " + c->name() ) + "                    " << endl;
		TQPtrList<TQStringList> rules = c->createIPTablesChainRules();
		TQStringList* curr_rule;
		TQString rule_name;
		for ( curr_rule = rules.first(); curr_rule; curr_rule = rules.next() ) {
			rule_name = *curr_rule->at( 0 );
			TQString s = *curr_rule->at( 1 );
			if ( !s.isEmpty() ) {
				*m_stream << s << " || { status=\"1\"; echo \" Setting up Rule: " + rule_name + " FAILED! Clearing Rules!\";  stopFirewall; exit 1; }\n" << endl;
			}
		}
	}
}

void KMFIPTablesScriptGenerator::printScriptModuleLoad() {
	*m_stream << "\n";
	*m_stream << printScriptDebug( "\nLoading needed modules...          ", false ) << endl;
	*m_stream <<
	"$MOD ip_tables \n"
	"$MOD ip_conntrack \n"
	"$MOD ipt_LOG \n"
	"$MOD ipt_limit \n"
	"$MOD ipt_state \n"
	"$MOD ip_conntrack_ftp\n"
	"$MOD ip_conntrack_irc\n"
	<< endl;
	if ( m_iptDoc->useFilter() ) {
		*m_stream << "$MOD iptable_filter" << endl;
	}
	if ( m_iptDoc->useNat() ) {
		*m_stream << "$MOD iptable_nat" << endl;

	}
	if ( m_iptDoc->useMangle() ) {
		*m_stream << "$MOD iptable_mangle" << endl;
	}
	*m_stream << printScriptDebug( "Done.") << endl;
}

void KMFIPTablesScriptGenerator::printScriptHeader() {
	KMFTarget *tg = m_iptDoc->target();
	TQString version = KMYFIREWALL_VERSION;
	TQString copyright_string = COPYRIGHT_STRING;
	TQString maintainer = MAINTAINER;
	TQString license = LICENSE;
	*m_stream <<
	"#!/bin/sh\n"
	"#\n"
	"# " + copyright_string + "\n"
	"# Please report bugs to: " + maintainer + "\n"
	"#\n"
	"# " + license + "\n"
	"#\n"
	"# KMyFirewall v" + version + "\n"
	"# This is an automatic generated file DO NOT EDIT\n" +
	"#\n" +
	"# Configuration created for " + tg->toFriendlyString() + "\n" +
	"#\n" << endl;
}


const TQString& KMFIPTablesScriptGenerator::printScriptDebug( const TQString& msg, bool newLine ) {
	TQString script;
	*m_stream << "if [ \"$verbose\" = \"1\" ]; then\n" ;
	*m_stream << "echo " ;
	if ( ! newLine )
		*m_stream << "-n " ;
	*m_stream << "\"" + msg +"\"\n";
	*m_stream << "fi\n" << endl;
	return *(new TQString( script ) );
}

}

