/***************************************************************************
*   Copyright (C) 2004 by Christoph Thielecke                             *
*   crissi99@gmx.de                                                       *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU General Public License     *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
//BEGIN INCLUDES
#include "networkinterface.h"
#include <iostream>
#include <qfile.h>
#include <qtextstream.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kglobal.h>
#include <kstddirs.h>
#include <qnetwork.h>
#include <qurloperator.h>
#include <kmessagebox.h>
//END INCLUDES

NetworkInterface::NetworkInterface( KVpncConfig* GlobalConfig,QApplication *app, QObject *parent, const char *name ) : QObject( parent, name )
{

	this->app = app;
	interfaceTest = false;
	retrieveAllNetworkInterfaces = false;
	retrieveInterfaceIP = false;
	retrieveInterfaceAddress = false;
	retrieveDefaultInterface = false;
	retrieveGatewayOfDefaultInterface=false;
	retrieveGatewayOfInterface=false;
	QPtrList<QString>*InterfaceList = new QPtrList<QString>();
	InterfaceList->setAutoDelete( TRUE ); // the list owns the objects
	QString InterfaceIP = "";
	QString InterfaceAddress = "";
	IPforInterface = "";
	tmpInterface = "";
	interfaceExists = false;
	defaultinterface="default";
	readOutput=false;
	env = new QStringList();
	*env << "LC_ALL=C" << "LANG=C";
	this->GlobalConfig = GlobalConfig;
}

NetworkInterface::~NetworkInterface()
{
	//delete proc;
	if (defaultinterface == "default")
		defaultinterface == "";
}

bool NetworkInterface::interfaceExist( QString Interface )
{
	if ( !Interface.isEmpty() )
	{

		proc = new QProcess (this);
		proc->addArgument( GlobalConfig->pathToIfconfig );
		proc->addArgument( Interface );

		connect( proc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout() ) );
		connect( proc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr() ) );
		connect( proc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );

		interfaceTest = true;

		if ( !proc->start() )
		{
			GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg("ifconfig"), KVpncConfig::error);
		}
	}
	while ( interfaceTest == true && proc->isRunning() )
		app->processEvents();

	disconnect( proc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout() ) );
	disconnect( proc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr() ) );
	disconnect( proc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );
	//delete proc;
	return interfaceExists;
}

QStringList NetworkInterface::getAllNetworkInterfaces()
{

	proc = new QProcess(this);
	proc->addArgument( GlobalConfig->pathToIfconfig );

	retrieveAllNetworkInterfaces = true;

	connect( proc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout() ) );
	connect( proc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr() ) );
	connect( proc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );

	if ( !proc->start() )
	{
		GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg("ifconfig"), KVpncConfig::error);
	}

	while ( retrieveAllNetworkInterfaces && proc->isRunning() )
		app->processEvents();


	disconnect( proc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout() ) );
	disconnect( proc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr() ) );
	disconnect( proc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );
	//delete proc;
	return InterfaceList;
}

QString NetworkInterface::getInterfaceIP( QString Interface )
{
	if ( !Interface.isEmpty() )
	{

		InterfaceIpProc = new QProcess(this);
		InterfaceIpProc->addArgument( GlobalConfig->pathToIp );
		InterfaceIpProc->addArgument("addr");
		InterfaceIpProc->addArgument("show");
		InterfaceIpProc->addArgument(Interface);

		retrieveInterfaceIP=true;
		readOutput=true;

		connect( InterfaceIpProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_interfaceip() ) );
		connect( InterfaceIpProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_interfaceip() ) );
		connect( InterfaceIpProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );

		if ( !InterfaceIpProc->start(env) )
		{
			GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("getting IP address from interface")), KVpncConfig::error);
		}
		else
		{
			while ( retrieveInterfaceIP && InterfaceIpProc->isRunning() )
			{
				app->processEvents();
				usleep(500);
			}
			/*
			while ( readOutput)
				app->processEvents();*/

			// 			disconnect( proc, SIGNAL( InterfaceIpProc() ), this, SLOT( readFromStdout() ) );
			// 			disconnect( proc, SIGNAL( InterfaceIpProc() ), this, SLOT( readFromStderr() ) );
			// 			disconnect( proc, SIGNAL( InterfaceIpProc () ), this, SLOT( processHasFinished() ) );
			delete InterfaceIpProc;

		}
	}
	return InterfaceIP;
}

QString NetworkInterface::getInterfaceAddress( QString IPforInterface )
{
	// TODO fixme
	if ( !IPforInterface.isEmpty() )
	{
		this->IPforInterface = IPforInterface;
		QStringList devlist = getAllNetworkInterfaces();
		tmpfile = new KTempFile();
		QString tmpPath = locateLocal ( "data", "kvpnc/" );
		QString GetIpForInterfaceScript = tmpPath + "get_interface_for_ip_"+IPforInterface+".sh";

		QFile file ( GetIpForInterfaceScript );
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
		{
			stream << "# generated by kvpnc. Do not edit it." << "\n";
			stream << "\n";
			stream << GlobalConfig->pathToIfconfig +" | grep -B1 "+IPforInterface+" | head -n1 |awk {'print $1'} > "+ tmpfile->name()+"\n";
			file.close();



			InterfaceAddressProc = new QProcess(this);
			InterfaceAddressProc->addArgument( "/bin/sh" );
			InterfaceAddressProc->addArgument(GetIpForInterfaceScript);
			retrieveInterfaceAddress=true;
			readOutput=true;

			//connect( InterfaceAddressProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_interfaceaddress() ) );
			//	connect( InterfaceAddressProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_interfaceaddress() ) );
			connect( InterfaceAddressProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );


			if ( !InterfaceAddressProc->start(env) )
			{
				GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("script for get interface from IP address")), KVpncConfig::error);
			}

			else
			{
				while (  InterfaceAddressProc->isRunning() )
					app->processEvents();

				while ( readOutput && retrieveInterfaceAddress == true )
					app->processEvents();

				// 		disconnect( InterfaceAddressProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_interfaceaddress() ) );
				// 		disconnect( InterfaceAddressProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_interfaceaddress() ) );
				disconnect( InterfaceAddressProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );
				//delete InterfaceAddressProc;
			}
		}
	}
	return InterfaceAddress;

}

QString NetworkInterface::getDefaultInterface()
{
	retrieveDefaultInterface = true;
	// 	readOutput=true;
	defaultinterface="";
	DefaultInterfaceProc = new QProcess(this);
	DefaultInterfaceProc->addArgument( GlobalConfig->pathToIp );
	DefaultInterfaceProc->addArgument( "route");
	DefaultInterfaceProc->addArgument( "show");
	DefaultInterfaceProc->addArgument( "default");

	connect( DefaultInterfaceProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_defaultinterface() ) );
	connect( DefaultInterfaceProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_defaultinterface() ) );
	connect( DefaultInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );

	if ( !DefaultInterfaceProc->start(env) )
	{
		GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("getting interface to which default route points")), KVpncConfig::error);
		//KMessageBox::information( 0,i18n("unable to start proc (%1)!").arg(QString("route "+i18n("defaultinterface")+")")),i18n("Start Failed"));
		return "none";
	}
	else
	{
		// 		std::cout << "getDefaultInterface() started." << std::endl;
		while ( DefaultInterfaceProc->isRunning())
		{
			app->processEvents();
			usleep(500);
		}

		disconnect( DefaultInterfaceProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_defaultinterface() ) );
		disconnect( DefaultInterfaceProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_defaultinterface() ) );
		disconnect( DefaultInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );
		//		delete DefaultInterfaceProc;

		// special case: 2 or more default routes gives multiple line of interfaces
		if (defaultinterface.find('\n') > -1 )
		{

			GlobalConfig->appendLogEntry(i18n("2 or more default routes found! This is wrong and must be fixed."), KVpncConfig::error);

			// try to fix that

			tmpfile = new KTempFile();
			//QString firstdefaultinterface=defaultinterface.left(defaultinterface.find("\n")+1).stripWhiteSpace(); // eth0\neth1 -> eth0
			QString firstdefaultinterface=defaultinterface.section('\n',0,0); // eth0 eth1 -> eth0
			//GlobalConfig->appendLogEntry(QString("firstdefaultinterface: "+firstdefaultinterface), KVpncConfig::debug);
			QString firstgateway=getGatewayOfDefaultInterface();
			GlobalConfig->appendLogEntry(QString("firstgateway: "+firstgateway), KVpncConfig::debug);
			QString tmpPath = locateLocal ( "data", "kvpnc/" );
			QString FixDefaultRouteScript = tmpPath+"fixdefaultroutescript.sh";
			QFile file ( FixDefaultRouteScript );
			QTextStream stream( &file );
			if ( file.open( IO_WriteOnly ) )
			{
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "\n";

				// FIXME we stupidly try to remove default route 4 times: works wrong if more than 4 default routes exist (nearly 0%)
				stream << GlobalConfig->pathToRoute +" del default 2>/dev/null\n";
				stream << GlobalConfig->pathToRoute +" del default 2>/dev/null\n";
				stream << GlobalConfig->pathToRoute +" del default 2>/dev/null\n";
				stream << GlobalConfig->pathToRoute +" del default 2>/dev/null\n";
				stream << GlobalConfig->pathToRoute +" add default gw "+firstgateway+" "+firstdefaultinterface+" 2>/dev/null\n";
				file.close();
			}

			DefaultInterfaceProc = new QProcess(this);
			DefaultInterfaceProc->addArgument( "/bin/sh" );
			DefaultInterfaceProc->addArgument(FixDefaultRouteScript);

			connect( DefaultInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );

			if ( !DefaultInterfaceProc->start(env) )
			{
				GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("script for fixing default route")), KVpncConfig::error);
				//KMessageBox::information( 0,i18n("unable to start proc (%1)!").arg(QString("route "+i18n("defaultinterface")+")")),i18n("Start Failed"));
				return "none";
			}
			else
			{

				//std::cout << "getDefaultInterface() started." << std::endl;
				GlobalConfig->appendLogEntry(i18n("Try to fix multiple default routes: delete all and add to first interface with gateway to which a default route has pointed. Note: This can be wrong."), KVpncConfig::debug);


				while ( DefaultInterfaceProc->isRunning())
				{
					app->processEvents();
				}
				disconnect( DefaultInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );

				defaultinterface=firstdefaultinterface;
			}
		}
		else
			return defaultinterface;
	}
	return defaultinterface;
}

QString NetworkInterface::getGatewayOfInterface(QString interface)
{
	QString gateway;
	// TODO fixme
	if ( !interface.isEmpty() )
	{

		tmpfile = new KTempFile();
		QString tmpPath = locateLocal ( "data", "kvpnc/" );
		QString GetGatewayOfInterfaceScript = tmpPath + "get_gateway_of_interface_script_"+interface+".sh";

		QFile file ( GetGatewayOfInterfaceScript );
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
		{
			stream << "# generated by kvpnc. Do not edit it." << "\n";
			stream << "\n";
			stream << GlobalConfig->pathToRoute +" -n | grep '"+interface+"' | grep -v 'UG' | grep '0.0.0.0' |  awk {'print $2'} > "+ tmpfile->name()+"\n";
			file.close();
		}


		GatewayOfInterfaceProc = new QProcess(this);
		GatewayOfInterfaceProc->addArgument( "/bin/sh" );
		GatewayOfInterfaceProc->addArgument(GetGatewayOfInterfaceScript);
		retrieveGatewayOfInterface=true;
		readOutput=true;

		//connect( GatewayOfInterfaceProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_gatewayofinterface() ) );
		//	connect( GatewayOfInterfaceProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_gatewayofinterface() ) );
		connect( GatewayOfInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );


		if ( !GatewayOfInterfaceProc->start(env) )
		{
			GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("script for get gateway from interface")), KVpncConfig::error);
		}
	}
	while ( retrieveGatewayOfInterface == true && GatewayOfInterfaceProc->isRunning() )
		app->processEvents();

	while ( readOutput)
		app->processEvents();

	// 		disconnect( GatewayOfInterfaceProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_gatewayofinterface() ) );
	// 		disconnect( GatewayOfInterfaceProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_gatewayofinterface() ) );
	disconnect( GatewayOfInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );
	//delete proc;

	gateway=GatewayAddress;

	gateway= gateway.stripWhiteSpace();

	if (gateway == "0.0.0.0")
		gateway="none";

	return gateway;
}

QString NetworkInterface::getGatewayOfDefaultInterface()
{
	QString gateway="";

	GatewayOfDefaultInterfaceProc = new QProcess(this);
	GatewayOfDefaultInterfaceProc->addArgument( GlobalConfig->pathToIp );
	GatewayOfDefaultInterfaceProc->addArgument("route");
	GatewayOfDefaultInterfaceProc->addArgument("show");
	GatewayOfDefaultInterfaceProc->addArgument("default");
	retrieveGatewayOfDefaultInterface=true;

	connect( GatewayOfDefaultInterfaceProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_gatewayofdefaultinterface() ) );
	connect( GatewayOfDefaultInterfaceProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_gatewayofdefaultinterface() ) );
	connect( GatewayOfDefaultInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );


	if ( !GatewayOfDefaultInterfaceProc->start(env) )
	{
		GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("script for get gateway from default interface")), KVpncConfig::error);
	}

	while ( retrieveGatewayOfDefaultInterface == true && GatewayOfDefaultInterfaceProc->isRunning() )
	{
		app->processEvents();
		usleep(500);
	}

	// 	while ( readOutput)
	// 		app->processEvents();

	disconnect( GatewayOfDefaultInterfaceProc, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_gatewayofdefaultinterface() ) );
	disconnect( GatewayOfDefaultInterfaceProc, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_gatewayofdefaultinterface() ) );
	disconnect( GatewayOfDefaultInterfaceProc, SIGNAL( processExited () ), this, SLOT( processHasFinished() ) );
	//delete GatewayOfDefaultInterfaceProc;

	gateway= GatewayOfDefaultInterfaceAddress;

	//KMessageBox::information( 0,gateway,"gateway2");


	//gateway= gateway.stripWhiteSpace();
	if (gateway.find('\n') > -1)
	{
		//GlobalConfig->appendLogEntry(i18n("2 or more default routes found! This unusual and must be fixed by the administrator."), KVpncConfig::error);


		// try to fix that
		GlobalConfig->appendLogEntry(i18n("Warning: Multiple default routes on a network interface found. KVpnc will use the first one. This can be wrong."), KVpncConfig::debug);
		//gateway=gateway.left(gateway.find("\n")+1).stripWhiteSpace(); // 1.2.3.4\n6.7.8.9 -> 1.2.3.4
		gateway = gateway.section('\n',0,0);
	}

	if (gateway == "0.0.0.0")
		gateway="none";
	return gateway;
}

QString  NetworkInterface::getExternalIpAddress()
{
	qInitNetworkProtocols();
	ExternalIpAddress="";
	getExternalIpAddressRunning=true;
	http = new QHttp();
	connect (http,SIGNAL(readyRead(const QHttpResponseHeader &)), this, SLOT(externalIpDataRecieved(const QHttpResponseHeader &)));

	// FIXME how it could be better?
	http->setHost( "checkip.dyndns.org" );

	http->get
	( "/" );
	while ( getExternalIpAddressRunning )
		app->processEvents();
	return ExternalIpAddress;
}

void NetworkInterface::readFromStdout()
{
	while ( proc->canReadLineStdout() )
	{
		QString line = proc->readLineStdout() ;
		//		QString line = QString(proc->readStdout());


		/*
		example for one interface

		eth0      Protokoll:Ethernet  Hardware Adresse 00:10:4B:B2:19:00
		          inet Adresse:192.168.0.99  Bcast:192.168.0.255  Maske:255.255.255.0
		          inet6 Adresse: fe80::210:4bff:feb2:1900/64 Gltigkeitsbereich:Verbindung
		          UP BROADCAST NOTRAILERS RUNNING MULTICAST  MTU:1500  Metric:1
		          RX packets:31549 errors:0 dropped:0 overruns:0 frame:0
		          TX packets:34046 errors:0 dropped:0 overruns:0 carrier:0
		          Kollisionen:0 Sendewarteschlangenlï¿œge:1000
		          RX bytes:11308743 (10.7 Mb)  TX bytes:3701511 (3.5 Mb)
		          Interrupt:10 Basisadresse:0xdc00
		*/

		if ( interfaceTest )
		{
			if ( line.find( "proto", 0 , FALSE ) != -1 )
			{
				interfaceExists = true;
				interfaceTest = false;
			}
		}
		if ( retrieveAllNetworkInterfaces )
		{
			QString interface = line.simplifyWhiteSpace().section( ' ', 0, 0 ); // eth0
			InterfaceList.append( interface );
			//	std::cout << "dbg: found interface: " << interface << std::endl;
		}

		if ( retrieveDefaultInterface)
		{
			std::cout << "line: " << line.ascii() << std::endl;
			if (line.find( "default", 0 , FALSE ) != -1 )
			{
				if(!defaultinterface.isEmpty())
					defaultinterface+="\n";
				defaultinterface += line.simplifyWhiteSpace().section(' ', -1,-1); // default via 192.168.10.1 dev eth2
				std::cout << "defaultinterface: " << defaultinterface.ascii() << std::endl;
				retrieveDefaultInterface=false;
			}
		}
		if ( retrieveInterfaceIP)
		{
			if (line.find( "inet", 0 , FALSE ) != -1 )
			{

				InterfaceIP = line.simplifyWhiteSpace().section(' ', 1,1).section('/',0,0); // inet 192.168.10.100/24 brd 192.168.10.255 scope global eth2
				retrieveInterfaceIP=false;
			}
		}


	}
}

void NetworkInterface::readFromStderr()
{
	//while ( proc->canReadLineStderr() ) {
	//	QString line = proc->readLineStderr() ;
	QString line = QString( proc->readStderr() );

	if ( interfaceTest )
	{
		interfaceExists = false;
		interfaceTest = false;
	}
	//std::cerr << "dbg err: " << line << std::endl;
	//}
}

void NetworkInterface::readFromStdout_defaultinterface()
{
	while ( DefaultInterfaceProc->canReadLineStdout() )
	{
		QString line = DefaultInterfaceProc->readLineStdout() ;
		//		QString line = QString(DefaultInterfaceProc->readStdout());

		// 		std::cout << "line: " << line.ascii() << std::endl;
		if (line.find( "default", 0 , FALSE ) != -1 )
		{
			if(!defaultinterface.isEmpty())
				defaultinterface+="\n";
			defaultinterface += line.simplifyWhiteSpace().section(' ', -1,-1); // default via 192.168.10.1 dev eth2
			// 			std::cout << "defaultinterface: " << defaultinterface.ascii() << std::endl;
			retrieveDefaultInterface=false;
		}

	}
}

void NetworkInterface::readFromStderr_defaultinterface()
{
	while ( DefaultInterfaceProc->canReadLineStderr() )
	{
		QString line = DefaultInterfaceProc->readLineStderr() ;
		// 	QString line = QString( DefaultInterfaceProc->readStderr() );

		//std::cerr << "dbg err: " << line << std::endl;
	}
}

void NetworkInterface::readFromStdout_interfaceip()
{
	while ( InterfaceIpProc->canReadLineStdout() )
	{
		QString line = InterfaceIpProc->readLineStdout() ;
		//		QString line = QString(InterfaceIpProc->readStdout());

		if (line.find( "inet", 0 , FALSE ) != -1 )
		{

			InterfaceIP = line.simplifyWhiteSpace().section(' ', 1,1).section('/',0,0); // inet 192.168.10.100/24 brd 192.168.10.255 scope global eth2
			retrieveInterfaceIP=false;
		}
	}
}

void NetworkInterface::readFromStderr_interfaceip()
{
	while ( InterfaceIpProc->canReadLineStderr() )
	{
		QString line = InterfaceIpProc->readLineStderr() ;
		// 	QString line = QString( InterfaceIpProc->readStderr() );

		if ( interfaceTest )
		{
			interfaceExists = false;
			interfaceTest = false;
		}
		//std::cerr << "dbg err: " << line << std::endl;
	}
}

void NetworkInterface::readFromStdout_interfaceaddress()
{
	while ( InterfaceAddressProc->canReadLineStdout() )
	{
		QString line = InterfaceAddressProc->readLineStdout() ;
		//		QString line = QString(retrieveInterfaceAddress->readStdout());

		if (line.find( "inet", 0 , FALSE ) != -1 )
		{

			InterfaceIP = line.simplifyWhiteSpace().section(' ', 1,1).section('/',0,0); // inet 192.168.10.100/24 brd 192.168.10.255 scope global eth2
			retrieveInterfaceAddress=false;
		}

	}
}

void NetworkInterface::readFromStderr_interfaceaddress()
{
	while ( InterfaceAddressProc->canReadLineStderr() )
	{
		QString line = InterfaceAddressProc->readLineStderr() ;
		// 	QString line = QString( InterfaceAddressProc->readStderr() );

		if ( interfaceTest )
		{
			retrieveInterfaceAddress = false;
		}
		//std::cerr << "dbg err: " << line << std::endl;
	}
}

void NetworkInterface::readFromStdout_gatewayofdefaultinterface()
{
	while ( GatewayOfDefaultInterfaceProc->canReadLineStdout() )
	{
		QString line = GatewayOfDefaultInterfaceProc->readLineStdout() ;
		//		QString line = QString(GatewayOfDefaultInterfaceProc->readStdout());

		if (line.find( "default", 0 , FALSE ) != -1 )
		{

			GatewayOfDefaultInterfaceAddress = line.simplifyWhiteSpace().section(' ', 2,2); // default via 192.168.1.1 dev eth2 => 192.168.1.1
			retrieveGatewayOfDefaultInterface=false;
		}

	}
}

void NetworkInterface::readFromStderr_gatewayofdefaultinterface()
{
	while ( GatewayOfDefaultInterfaceProc->canReadLineStderr() )
	{
		QString line = GatewayOfDefaultInterfaceProc->readLineStderr() ;
		// 	QString line = QString( retrieveInterfaceAddress->readStderr() );

		if ( interfaceTest )
		{
			retrieveGatewayOfDefaultInterface = false;
		}
		//std::cerr << "dbg err: " << line << std::endl;
	}
}

void NetworkInterface::readFromStdout_gatewayofinterface()
{

	while ( GatewayOfInterfaceProc->canReadLineStdout() )
	{
		QString line = GatewayOfInterfaceProc->readLineStdout() ;
		//		QString line = QString(GatewayOfInterfaceProc->readStdout());

		if (line.find( "default", 0 , FALSE ) != -1 )
		{

			GatewayOfInterfaceAddress = line.simplifyWhiteSpace().section(' ', 2,2); // default via 192.168.1.1 dev eth2 => 192.168.1.1
			retrieveGatewayOfInterface=false;
		}

	}

}

void NetworkInterface::readFromStderr_gatewayofinterface()
{

	while ( GatewayOfInterfaceProc->canReadLineStderr() )
	{
		QString line = GatewayOfInterfaceProc->readLineStderr() ;
		// 	QString line = QString( GatewayOfInterfaceProc->readStderr() );

		if ( interfaceTest )
		{
			retrieveGatewayOfInterface = false;
		}
		//std::cerr << "dbg err: " << line << std::endl;
	}

}

void NetworkInterface::processHasFinished()
{

// 	std::cout << "dbg: processHasFinished():" << std::endl;// << proc->exitStatus() << std::endl;;
	if ( retrieveAllNetworkInterfaces )
		retrieveAllNetworkInterfaces = false;

	if (retrieveDefaultInterface)
		retrieveDefaultInterface=false;

	if (retrieveInterfaceAddress )
	{
// 		std::cout << "tmp file: " << tmpfile->name() << std::endl;
		InterfaceAddress = QString(tmpfile->file()->readAll()).stripWhiteSpace();
// 		KMessageBox::information( 0,this->defaultinterface,"default if");
		// 		tmpfile->unlink();
		retrieveInterfaceAddress=false;
	}

	if (retrieveGatewayOfInterface )
	{
		//std::cout << "tmp file: " << tmpfile->name() << std::endl;
		GatewayAddress = QString(tmpfile->file()->readAll()).stripWhiteSpace();
		//KMessageBox::information( 0,GatewayAddress,"GatewayAddress");

		// 		tmpfile->unlink();
		retrieveGatewayOfInterface=false;
	}

	if (retrieveGatewayOfDefaultInterface )
	{
		//std::cout << "tmp file: " << tmpfile->name() << std::endl;
		GatewayAddress = QString(tmpfile->file()->readAll());
		//KMessageBox::information( 0,this->defaultinterface,"default if");
		tmpfile->unlink();
		retrieveGatewayOfDefaultInterface=false;
	}

	readOutput=false;
}

void NetworkInterface::externalIpDataRecieved(const QHttpResponseHeader &)
{
	ExternalIpAddress=QString(http->readAll()).stripWhiteSpace().remove ("Current IP Address: ").stripWhiteSpace();
	getExternalIpAddressRunning=false;
}

#include "networkinterface.moc"
