/***************************************************************************
*  Copyright (C) 2004 by Christoph Thielecke               *
*  crissi99@gmx.de                            *
*                                     *
*  Contains parts of code from klcc project               *
*  (Peter Simonsson <psn@linux.se>.                   *
*                                     *
*  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 <time.h>
#include <iomanip>
#include <stdlib.h>
#include <qstringlist.h>
#include <qcstring.h>
#include <qptrlist.h>
#include <qcolor.h>
#include <qcheckbox.h>
#include <qspinbox.h>
#include <qtextedit.h>
#include "debugoutputtextedit.h"
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qtimer.h>
#include <qdir.h>
#include <qspinbox.h>
#include <qdns.h>
#include <qstringlist.h>
#include <qcombobox.h>
#include <qfile.h>
#include <qdatetime.h>
#include <qtextstream.h>
#include <qsocket.h>
#include <qstatusbar.h>
#include <qstringlist.h>
#include <qcolor.h>
#include <qregexp.h>
#include <qmenudata.h>
#include <kaboutdata.h>
#include <kstdaction.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kpassdlg.h>
#include <knotifyclient.h>
#include <kstatusbar.h>
#include <kdebug.h>
#include <krun.h>
#include <kkeydialog.h>
#include <kedittoolbar.h>
#include <knotifydialog.h>
#include <kapplication.h>
#include <klineedit.h>
#include <kpassdlg.h>
#include <kurlrequester.h>
#include <kcombobox.h>
#include <kstddirs.h>
#include <klineeditdlg.h>
#include <kmessagebox.h>
#include <kio/netaccess.h>
#include <ktempfile.h>
#include <klistview.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <knuminput.h>
#include <kwallet.h>
#include <kinputdialog.h>
#include <kactioncollection.h>

#include "kvpnc.h"
#include "mainview.h"
#include "mainviewbase.h"
#include "helpdialog.h"
#include "advancedsettingsdialog.h"
#include "importprofiledialog.h"
#include "importopenvpnprofiledialog.h"
#include "networkinterface.h"
#include "newprofiledialog.h"
#include "importcertificatedialog.h"
#include "vpnaccountdata.h"
#include "enterpassworddialog.h"
#include <ktempfile.h>
#include <iostream>
#include "utils.h"
#include "toolsinfodialog.h"
#include "logviewerdialog.h"
#include "generateopenvpnkeydialog.h"
#include "newprofilewizard.h"

//END includes

KVpnc::KVpnc( KApplication *parent, QWidget*, const char *name ) : KMainWindow( 0, name ),   DCOPObject("KVpncInterface")
{
	this->parent = parent;
	setCaption( i18n( "KVpnc" ) );

	GlobalConfig = new KVpncConfig(this);
	GlobalConfig->appPointer = parent;
	GlobalConfig->config = kapp->config();

	this->initStatusbar();
	this->initAction();
	this->initDockWindow();
	this->initView();
	mw->buttonConnect->setEnabled( false );
	mw->buttonDisconnect->setEnabled( false );

	GlobalConfig->setLogOutput(mw->DebugOutput);
	GlobalConfig->status = GlobalConfig->disconnected;

	VpncConnectScript = "";
	VpncDisconnectScript = "";
	OldDefaultroute = "";

	TunnelInterfaceIP="";

	connectCounter = 0;

	ConnectProcess = 0;
	DisconnectProcess = 0;
	RacoonProcess = 0;
	FreeswanProcess = 0;
	PingProcess = 0;
	TailProcess = 0;
	X509CertificateExtractProcess = 0;
	PptpProcess = 0;
	OpenvpnProcess = 0;
	CmdAfterConnectProcess = 0;
	CmdAfterDisconnectProcess = 0;
	RouteProcess = 0;
	SetVirtualIPProcess = 0;
	ReplaceDefaultRouteProcess = 0;
	ConnectionStatusCheckProcess = 0;
	env = new QStringList();
	*env << "LC_ALL=C" << "LANG=C";

	AuthRetry=false;
	GlobalConfig->doAutoConnectAtStartup=false;
	quitFromKicker=false;
	oldPppdStyle=false;
	pppdHasMppeSupport = true;
	testOldPppdStyle = false;

	TmpPassword="";
	TmpUsername="";

	GlobalConfig->loadOptions();

	toolBar( "mainToolBar" )->applySettings( GlobalConfig->config, "ToolBar Settings" );
	// 	showToolbarAction->setChecked( GlobalConfig->showToolBar );

	showStatusbarAction->setChecked( GlobalConfig->showStatusBar );
	slotShowStatusbar();

	if ( GlobalConfig->showDebugConsole )
	{
		mw->DebugOutput->show();
	}
	else
	{
		mw->DebugOutput->hide();
		// 		setMinimumSize(0,0);
		// 		this->resize( minimumSizeHint() );
	}
	debugconsoleAction ->setChecked( GlobalConfig->showDebugConsole );

	if ( GlobalConfig->WindowSize.width() < 50 || 	GlobalConfig->WindowSize.height() < 50 )
	{
		GlobalConfig->WindowSize = QSize( minimumWidth(), minimumHeight() );
	}

	if ( GlobalConfig->WindowPos.x() < 0 || GlobalConfig->WindowPos.y() < 0 )
		GlobalConfig->WindowPos = QPoint ( 0, 0 );

	resize( GlobalConfig->WindowSize );
	move ( GlobalConfig->WindowPos );

	//Failsafe
	if ( isHidden() && KVpncDock->isHidden() )
	{
		this->show();
	}

	QuickConnectMenu = new QPopupMenu(KVpncDock->menu());
	connect (QuickConnectMenu, SIGNAL(activated(int)), this, SLOT(doQuickConnect(int)));

	connect (parent, SIGNAL(shutDown()), this, SLOT(shutdownCalled()));

	for (uint i=0; i < GlobalConfig->AccountList->count();i++)
	{
		QuickConnectMenu->insertItem( GlobalConfig->AccountList->at(i)->getName());
		mw->SessionCombo->insertItem( GlobalConfig->AccountList->at(i)->getName());
	}

	if (!GlobalConfig->AccountList->isEmpty())
		mw->SessionCombo->setEnabled(true);

	KVpncDock->menu()->insertItem(i18n("Connecting To..."),QuickConnectMenu,0,3);
	KVpncDock->menu()->insertSeparator(3);

	if ( !GlobalConfig->lastProfile.isEmpty() )
	{
		if (GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry(i18n("Last used profile found: %1").arg(GlobalConfig->lastProfile),KVpncConfig::debug);
		VpnAccountData * it;
		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			if (it->getName() == GlobalConfig->lastProfile)
			{
				GlobalConfig->currentProfile = it;
				mw->SessionCombo->setCurrentText( GlobalConfig->lastProfile );
				sessionToggled( GlobalConfig->lastProfile );
				break;
			}
		}
	}
	else
	{
		if (GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry(i18n("No last used profile found."),KVpncConfig::info);
		if ( !GlobalConfig->AccountList->isEmpty() )
		{
			this->connectAction->setEnabled( true );
			this->mw->buttonConnect->setEnabled( true );
			mw->SessionCombo->setCurrentItem( 1 );
			GlobalConfig->currentProfile = GlobalConfig->AccountList->first();
			mw->SessionCombo->setEnabled(true);
		}
		else
		{
			deleteSessionAction->setEnabled ( FALSE );
			connectAction->setEnabled ( FALSE );
		}
	}

	preserveNetworkEnvironment();

	// auto connect
	if (GlobalConfig->doAutoConnectAtStartup)
	{
		bool profileInList=false;
		for (uint i=0; i < GlobalConfig->AccountList->count();i++)
		{
			if ( GlobalConfig->AccountList->at(i)->getName() == GlobalConfig->AutoConnectProfile)
			{
				profileInList=true;
				if (GlobalConfig->KvpncDebugLevel > 0)
					GlobalConfig->appendLogEntry(i18n("Automatic connection at startup to \"%1\" requested.").arg(GlobalConfig->AutoConnectProfile),GlobalConfig->info);

				sessionToggled( GlobalConfig->AutoConnectProfile );
				mw->SessionCombo->setCurrentText( GlobalConfig->AutoConnectProfile );
				GlobalConfig->currentProfile = GlobalConfig->AccountList->at(i);
				connectClicked();
				break;
			}
		}

		if (!profileInList)
		{
			GlobalConfig->doAutoConnectAtStartup=false;
		}
	}
}

KVpnc::~KVpnc()
{
	delete env;
	delete QuickConnectMenu;
	delete GlobalConfig;
	delete saveSessionAction;
	delete deleteSessionAction;
	delete newSessionAction;
	delete importSessionAction;
	delete importOpenvpnProfileAction;
	delete importCertAction;
	delete connectAction;
	delete disconnectAction;
	delete profileManagerAction;
	delete NewProfileWizardAction;
	delete donateAction;
	delete debugconsoleAction;
	delete toolsInfoAction;
	delete LogViewerAction;
	delete GenerateOpenvpnKeyAction;
}

void KVpnc::initAction()
{
	disconnectedIcon = KGlobal::iconLoader()->loadIcon( "disconnected", KIcon::NoGroup, 22 );
	connectedIcon = KGlobal::iconLoader()->loadIcon( "connected", KIcon::NoGroup, 22 );
	connectingIcon = KGlobal::iconLoader()->loadIcon( "connecting", KIcon::NoGroup, 22 );
	setIcon( disconnectedIcon );

	( void* ) KStdAction::quit( this, SLOT( quitCalled() ), actionCollection() );

	saveSessionAction = new KAction( i18n( "&Save Profile..." ), "fileexport", Key_S, this, SLOT( saveSessionClicked() ), actionCollection(), "saveSession" );
	deleteSessionAction = new KAction( i18n( "&Delete Profile..." ), "editdelete", Key_D, this, SLOT( deleteSessionClicked() ), actionCollection(), "deleteSession" );
	newSessionAction = new KAction( i18n( "&New Profile..." ), "profilenew", Key_N, this, SLOT( newSessionClicked() ), actionCollection(), "newSession" );
	//advancedSessionAction = new KAction( i18n( "&Advanced..." ), "wizard", Key_A, this, SLOT( advancedSettingsClicked() ), actionCollection(), "advancedSettingsSession" );
	importSessionAction = new KAction( i18n( "&Import Cisco pcf File..." ), "pcfimport", Key_I, this, SLOT( importProfileClicked() ), actionCollection(), "importSession" );
	importOpenvpnProfileAction = new KAction( i18n( "Import &OpenVPN config File..." ), "openvpnimport", Key_O, this, SLOT( importOpenvpnProfileClicked() ), actionCollection(), "importOpenvpnConfig" );

	importCertAction = new KAction( i18n( "Import &P12 certificate..." ), "certimport", Key_C, this, SLOT( importCertClicked() ), actionCollection(), "importCert" );

	connectAction = new KAction( i18n( "&Connect" ), "connected", CTRL + Key_Up, this, SLOT( slotConnecting() ), actionCollection(), "serverConnect" );
	disconnectAction = new KAction( i18n( "&Disconnect" ), "disconnected", CTRL + Key_Down, this, SLOT( disconnectClicked() ), actionCollection(), "serverDisconnect" );

	profileManagerAction = new KAction( i18n( "&Manage Profiles" ), "view_detailed", CTRL + Key_M, this, SLOT( showProfileManagerClicked() ), actionCollection(), "profileManager" );

	NewProfileWizardAction = new KAction( i18n( "&new Profile (Wizard)" ), "wizard", CTRL + Key_W, this, SLOT( showNewProfileWizardClicked() ), actionCollection(), "NewProfileWizard" );

	donateAction = new KAction ( i18n("&Donate..."), "donate", CTRL + Key_D, this, SLOT( donateClicked() ), actionCollection(), "donate" );

	debugconsoleAction = new KToggleAction ( i18n("Toggle Debug &Console"), "text_center", CTRL + Key_C, this, SLOT(toggleDebugConsole() ), actionCollection(), "debugconsole" );

	toolsInfoAction = new KToggleAction ( i18n("Show &Tools Info"), "info", CTRL + Key_T, this, SLOT(toolsInfoClicked() ), actionCollection(), "toolsinfo" );

	// // tmp
	// 	toolsInfoAction = new KToggleAction ( i18n("Show &Tools Info"), "info", CTRL + Key_T, this, SLOT(helpClicked() ), actionCollection(), "toolsinfo" );

	LogViewerAction = new KToggleAction ( i18n("Show &Log"), "log", CTRL + Key_L, this, SLOT(showLogViewer() ), actionCollection(), "logviewer" );

	GenerateOpenvpnKeyAction = new KToggleAction ( i18n("Generate OpenVPN Key"), "key", CTRL + Key_G, this, SLOT(generateOpenvpnKey() ), actionCollection(), "genOpenvpncKey" );

	KStdAction::preferences( this, SLOT( slotSettings() ), actionCollection(), "preferences" );

	KStdAction::helpContents(this, SLOT( helpClicked () ), actionCollection(), "help" );

	KStdAction::configureNotifications(this, SLOT(slotConfigNotifications()), actionCollection());
	KStdAction::keyBindings   (  this, SLOT(slotKeyBindings()), actionCollection());

	this->connectAction->setEnabled( false );
	this->disconnectAction->setEnabled( false );

	// 	showToolbarAction = KStdAction::showToolbar( this, SLOT( slotShowToolbar() ), actionCollection() );
	createStandardStatusBarAction();
	showStatusbarAction = KStdAction::showStatusbar( this, SLOT( slotShowStatusbar() ), actionCollection() );
	preferencesAction = KStdAction::preferences( this, SLOT( slotSettings() ), actionCollection() );

	( void* ) KStdAction::keyBindings( this, SLOT( slotKeyBindings() ), actionCollection() );
	( void* ) KStdAction::configureToolbars( this, SLOT( slotConfigToolbars() ), actionCollection() );
	( void* ) KStdAction::configureNotifications( this, SLOT( slotConfigNotifications() ), actionCollection() );

	createGUI();

}

void KVpnc::initView()
{

	mw = new MainView( this, "mainView" );
	setCentralWidget( mw );


	connect ( mw->buttonConnect, SIGNAL( clicked() ), this, SLOT( slotConnecting() ) );
	connect ( mw->buttonDisconnect, SIGNAL( clicked() ), this, SLOT( disconnectClicked() ) );

	connect ( mw->SessionCombo, SIGNAL ( activated ( const QString & ) ), this, SLOT ( sessionToggled( const QString& ) ) );

	mw->SessionCombo->setEnabled( FALSE );

	statusColorLabel = new QLabel(this);
	disconnectedStatusPixmap = new QPixmap(15,15);
	disconnectedStatusPixmap->fill(QColor(Qt::red));
	connectedStatusPixmap  = new QPixmap(15,15);
	connectedStatusPixmap->fill(QColor(Qt::green));
	connectingStatusPixmap = new QPixmap(15,15);
	connectingStatusPixmap->fill(QColor(Qt::yellow));


	statusColorLabel->setPixmap(*disconnectedStatusPixmap);
	statusBar()->addWidget(statusColorLabel,0,true);

	KNotifyClient::startDaemon();


}

void KVpnc::initStatusbar()
{
	statusBar() ->insertItem( i18n( "Ready." ), 1, 100 );
	statusBar() ->setItemAlignment( 1, AlignLeft | AlignVCenter );
	statusBar() ->insertItem( i18n( "Disconnected" ), 2, 0, true );
}

void KVpnc::initDockWindow()
{
	KVpncDock = new KVpncKicker( this, "kickerIcon" );
	connectAction->plug( KVpncDock->menu(),1 );
	disconnectAction->plug( KVpncDock->menu(),2 );
	KVpncDock->menu()->insertSeparator(5);
	preferencesAction->plug( KVpncDock->menu(),6 );
}

bool KVpnc::queryExit()
{
	GlobalConfig->lastProfile = mw->SessionCombo->currentText();
	//GlobalConfig->saveOptions();
	//saveGuiOptions();
	return true;
}

void KVpnc::slotSettings()
{
	this->slotStatusMsg( i18n( "Setup KVpnc..." ), ID_FLASH_MSG );
	this->slotStatusMsg( i18n( "Ready." ), ID_STATUS_MSG );

	PreferencesDialog prefDlg( this,parent, mw->DebugOutput, GlobalConfig, false);
	prefDlg.setMinimumSize(800,600);

	VpnAccountData *oldProfile = GlobalConfig->currentProfile;

	prefDlg.exec();

	if (prefDlg.profileAddedOrDeleted)
	{
		GlobalConfig->saveOptions();
		saveGuiOptions();
		if (GlobalConfig->AccountList->isEmpty())
		{
			GlobalConfig->currentProfile=0L;
			mw->SessionCombo->setEnabled ( FALSE );
			connectAction->setEnabled(false);
			mw->buttonConnect->setEnabled ( FALSE );
			mw->SessionCombo->clear();
		}
		else
		{
			QString Name="";
			if ( GlobalConfig->currentProfile != 0 )
				Name = GlobalConfig->currentProfile->getName();
			if (Name != mw->SessionCombo->currentText())
				GlobalConfig->currentProfile=oldProfile; // restore from beforNme calling pref dialog

			if ( GlobalConfig->currentProfile != 0 )
			{
				mw->SessionCombo->setCurrentText(GlobalConfig->currentProfile->getName());
				sessionToggled(GlobalConfig->currentProfile->getName());
			}
			profileAddedOrDeleted();
			if (!prefDlg.NewProfileName.isEmpty())
			{
				mw->SessionCombo->setCurrentText(prefDlg.NewProfileName);
				sessionToggled(prefDlg.NewProfileName);
			}
		}

	}

	if ( GlobalConfig->showDebugConsole )
	{
		mw->DebugOutput->show();
		//resize( minimumSizeHint() );
	}
	else
	{
		mw->DebugOutput->hide();
		setMinimumSize(0,0);
		this->resize( minimumSizeHint() );
	}

	if ( GlobalConfig->writeLogFile )
	{
		if ( !GlobalConfig->logfile.isOpen() )
		{
			KStandardDirs *dirs = KGlobal::dirs();
			QString  logfileName = QString(dirs->saveLocation( "data" ));
			QString logfilePath = QString(logfileName + "/kvpnc/kvpnc.log");
			//KMessageBox::information( this, "info", logfileName );
			GlobalConfig->logfile.setName( logfileName );
			if ( !GlobalConfig->logfile.open( IO_WriteOnly | IO_Append ) )
			{
				KMessageBox::error( this, i18n( "Log file cannot be opened!" ) );
				GlobalConfig->appendLogEntry( i18n( "Log file cannot be opened!" ) ,GlobalConfig->error);
			}
			else
			{
				GlobalConfig->logFileStream << i18n( "Log session started at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
			}
		}
	}
	else
	{
		if ( GlobalConfig->logfile.isOpen() )
		{
			//QTextStream s( &logfile );
			GlobalConfig->logFileStream << i18n( "Log session ended at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
			GlobalConfig->logfile.close();
		}
	}
	GlobalConfig->saveOptions();
	saveGuiOptions();
}

void KVpnc::slotShowToolbar()
{
	// 	if ( !showToolbarAction->isChecked() )
	// 		toolBar( "mainToolBar" )->hide();
	// 	else
	// 		toolBar( "mainToolBar" )->show();
}

void KVpnc::slotShowStatusbar()
{

	if ( !showStatusbarAction->isChecked() )
	{
		statusBar()->hide();
		GlobalConfig->showStatusBar =false;
		showStatusbarAction->setChecked(false);
	}
	else
	{
		statusBar()->show();
		GlobalConfig->showStatusBar=true;
		showStatusbarAction->setChecked(true);
	}
}

void KVpnc::slotKeyBindings()
{

	//FIXME remove dublicate entries
	KKeyDialog::configure( actionCollection(), this );
}

void KVpnc::slotConfigToolbars()
{
	KEditToolbar dlg( actionCollection() );

	if ( dlg.exec() )
	{
		createGUI();
	}
}

void KVpnc::slotConfigNotifications()
{
	KNotifyDialog::configure(this);
}

void KVpnc::slotStatusMsg( const QString &text, int id )
{
	if ( id != ID_FLASH_MSG )
	{
		statusBar()->clear();
		statusBar()->changeItem( text, id );
	}
	else
	{
		statusBar()->message( text, 2000 );
	}

}

void KVpnc:: quitCalled()
{
	bool reallyQuit = false;

	QString TypeString="";

	if (GlobalConfig->currentProfile != 0 )
	{
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
			TypeString="Cisco";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
			TypeString="PPTP";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			TypeString = "racoon";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			TypeString = "freeswan";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
			TypeString = "OpenVPN";
		else
			TypeString = i18n("other");
	}

	GlobalConfig->WindowSize = QSize( QWidget::width(), QWidget::height() );
	GlobalConfig->WindowPos = QPoint( this->x(), this->y() );

	if ( GlobalConfig->status == GlobalConfig->connected )
	{
		int res;
		if ( !GlobalConfig->shutdownIsCalled && !GlobalConfig->useSilentQuit )
		{
			res = KMessageBox::questionYesNo ( this, i18n( "You are still connected to \"%1\" (%2) Do you really want to quit?" ).arg(GlobalConfig->currentProfile->getName()).arg(TypeString), i18n( "Quit?" ), KStdGuiItem::quit(), KStdGuiItem::cancel() );
			if ( res != 4 )
			{
				disconnectClicked();
				reallyQuit = true;
				GlobalConfig->skipKwalletStoring = true;
				if (!GlobalConfig->AccountList->isEmpty() && GlobalConfig->currentProfile != 0)
					GlobalConfig->lastProfile = GlobalConfig->currentProfile->getName();
				if ( GlobalConfig->writeLogFile )
				{
					if ( GlobalConfig->logfile.isOpen() )
					{
						//						QTextStream s( &logfile );
						GlobalConfig->logFileStream << i18n( "Log session ended at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
						GlobalConfig->logfile.flush();
						GlobalConfig->logfile.close();
						GlobalConfig->appPointer->processEvents();
					}
				}
				saveGuiOptions();
				GlobalConfig->saveOptions();
				restoreNetworkEnvironment();
				kapp->quit();
			}
		}
		else
		{
			disconnectClicked();
			reallyQuit = true;
			GlobalConfig->skipKwalletStoring = true;
			if (!GlobalConfig->AccountList->isEmpty() && GlobalConfig->currentProfile != 0)
				GlobalConfig->lastProfile = GlobalConfig->currentProfile->getName();
			if ( GlobalConfig->writeLogFile )
			{
				if ( GlobalConfig->logfile.isOpen() )
				{
					//						QTextStream s( &logfile );
					GlobalConfig->logFileStream << i18n( "Log session ended at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
					GlobalConfig->logfile.flush();
					GlobalConfig->logfile.close();
					GlobalConfig->appPointer->processEvents();
				}
			}
			saveGuiOptions();
			GlobalConfig->saveOptions();
			restoreNetworkEnvironment();
			kapp->quit();
		}
	}
	else
	{
		reallyQuit = true;
		if ( reallyQuit )
		{
			if (!GlobalConfig->AccountList->isEmpty())
				if (GlobalConfig->currentProfile != 0 )
					GlobalConfig->lastProfile = GlobalConfig->currentProfile->getName();

			if ( GlobalConfig->writeLogFile )
			{
				if ( GlobalConfig->logfile.isOpen() )
				{
					//					QTextStream s( &logfile );
					GlobalConfig->logFileStream << i18n( "Log session ended at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
					GlobalConfig->logfile.flush();
					GlobalConfig->logfile.close();
					GlobalConfig->appPointer->processEvents();
				}
			}
			saveGuiOptions();
			GlobalConfig->saveOptions();
			restoreNetworkEnvironment();
			kapp->quit();
		}
	}
}

void KVpnc::quitCalledKicker()
{
	quitFromKicker=true;
	quitCalled();
	//KMessageBox::information( this, "kicker quit", "info" );
}

void KVpnc::shutdownCalled()
{
	GlobalConfig->shutdownIsCalled=true;
	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( i18n( "shutdown called!" ), GlobalConfig->debug );
}

void KVpnc::closeEvent( QCloseEvent *e )
{

	QString TypeString="";
	if ( GlobalConfig->currentProfile != 0)
	{
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
			TypeString="Cisco";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
			TypeString="PPTP";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			TypeString = "racoon";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			TypeString = "freeswan";
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
			TypeString = "OpenVPN";
		else
			TypeString = i18n("other");
	}

	if ( GlobalConfig->dontQuitOnCloseEvent==false || quitFromKicker==true || kapp->sessionSaving())
	{
		bool reallyQuit = false;
		if ( GlobalConfig->status == GlobalConfig->connected )
		{
			int res;
			if (kapp->sessionSaving()) //KDE is going down, skip kwallet, disconnect and quit
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n( "Shutdown was called...exiting.\n" ), GlobalConfig->debug );
				reallyQuit = true;
				GlobalConfig->skipKwalletStoring = true;
				disconnectClicked();
			}
			else
			{
				if ( !GlobalConfig->useSilentQuit  )
				{
					res = KMessageBox::questionYesNo ( this, i18n( "You are still connected to \"%1\" (%2) Do you really want to quit?" ).arg(GlobalConfig->currentProfile->getName()).arg(TypeString), i18n( "Quit?" ), KStdGuiItem::quit(), KStdGuiItem::cancel() );
					//KMessageBox::error( this,QString().setNum(res) );
					if ( res != 4 )
					{
						reallyQuit = true;
						GlobalConfig->skipKwalletStoring = true;
						disconnectClicked();

						if ( reallyQuit )
						{
							GlobalConfig->saveOptions();
							saveGuiOptions();

							if ( GlobalConfig->writeLogFile )
							{
								if ( GlobalConfig->logfile.isOpen() )
								{
									//								QTextStream s( &logfile );
									GlobalConfig->logFileStream << i18n( "Log session ended at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
									GlobalConfig->logfile.close();
									GlobalConfig->appPointer->processEvents();
								}
							}
							KMainWindow::closeEvent( e );
						}
						else
						{
							e = 0L;
						}
					}
					else
					{
						e = 0L;
					}
				}
				else
				{
					//disconnect and quit silently
					GlobalConfig->skipKwalletStoring = true;
					disconnectClicked();
					reallyQuit = true;
				}
			}
		}
		else
		{
			reallyQuit = true;
			GlobalConfig->skipKwalletStoring = true;
		}

		if ( reallyQuit )
		{
			GlobalConfig->saveOptions();
			saveGuiOptions();
			if ( GlobalConfig->writeLogFile )
			{
				if ( GlobalConfig->logfile.isOpen() )
				{
					GlobalConfig->logFileStream << i18n( "Log session ended at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
					GlobalConfig->logfile.flush();
					GlobalConfig->logfile.close();
					GlobalConfig->appPointer->processEvents();
				}
			}
			//KMainWindow::closeEvent( e );
			disconnectClicked();
			e->accept();
			kapp->quit();
		}
	}
	else
	{
		if (!GlobalConfig->hideOnCloseInfo)
			KMessageBox::information( this,i18n( "<qt>Closing the main window will keep KVpnc running in the system tray. Use Quit from the File menu to quit the application.</qt>" ), i18n( "Docking in System Tray" ), "hideOnCloseInfo" );
		hide();
	}
}

void KVpnc::connectClicked()
{
	TunnelInterfaceIP=i18n("None");

	bool ok = true; // if ok we will run process

	if (GlobalConfig->KvpncDebugLevel > 0)
		GlobalConfig->appendLogEntry(i18n("Connect try requested"),GlobalConfig->info);

	if (GlobalConfig->currentProfile->getGateway().isEmpty())
	{
		KMessageBox::error( this, i18n( "No gateway for profile \"%1\" entered. STOP.").arg(GlobalConfig->currentProfile->getName()));
		GlobalConfig->appendLogEntry( i18n( "No gateway for profile \"%1\" entered. STOP.").arg(GlobalConfig->currentProfile->getName()), GlobalConfig->error);
		ok = false;
		setGuiStatus(disconnected);
		return;
	}

	// type selection
	/* ============ vpnc ================ */
	if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
	{

		//setGuiStatus(connecting);

		// looking for vpnc
		if (  GlobalConfig->useDefaultPaths )
		{
			GlobalConfig->pathToVpnc= KStandardDirs::findExe("vpnc",QString::null);
		}
		else if ( GlobalConfig->pathToVpnc.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToVpnc.section('/',-1,-1),GlobalConfig->pathToVpnc.section('/',0,-2)).isEmpty())
		{
			KMessageBox::error( this, i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("vpnc").arg(GlobalConfig->pathToVpnc) );
			GlobalConfig->appendLogEntry( i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("vpnc").arg(GlobalConfig->pathToVpnc), GlobalConfig->error);
			ok = false;
			setGuiStatus(disconnected);
			return;
		}

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "vpnc: %1" ) .arg( GlobalConfig->pathToVpnc ), GlobalConfig->debug );


		if ( !Utils( GlobalConfig, parent ).tunDevExists() )
		{
			if ( !Utils( GlobalConfig, parent ).createTunDev() )
			{
				KMessageBox::error( this, i18n( "Unable to create tunnel device file \"%1\"!" ).arg("/dev/net/tun") );
				GlobalConfig->appendLogEntry(i18n( "Unable to create tunnel device file \"%1\"!" ).arg("/dev/net/tun"), GlobalConfig->error);
				ok=false;
			}
			else
				ok=true;
		}

		TmpGatewayIP = Utils( GlobalConfig, parent ).resolveName(GlobalConfig->currentProfile->getGateway(), parent);
		if (TmpGatewayIP=="0.0.0.0" || TmpGatewayIP.isEmpty())
		{
			KMessageBox::error( this, i18n( "Host \"%1\" could not be resolved!" ).arg(GlobalConfig->currentProfile->getGateway()) );
			GlobalConfig->appendLogEntry(i18n( "Host \"%1\" could not be resolved!" ).arg(GlobalConfig->currentProfile->getGateway()),GlobalConfig->error);
			ok =false;
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "Gateway hostname (%1) resolved to \"%2\"." ).arg(GlobalConfig->currentProfile->getGateway()).arg(TmpGatewayIP), GlobalConfig->debug );
		}

		if (ok)
		{
			bool askUsernamePass=false;

			if (GlobalConfig->currentProfile->getSaveUserPassword() )
			{
				if (AuthRetry)
					askUsernamePass=true;
			}
			else if( !GlobalConfig->currentProfile->getSavePsk())
				askUsernamePass=true;
			else if( GlobalConfig->currentProfile->getAllowEmptyGroupPassword())
				askUsernamePass=true;

			if (GlobalConfig->currentProfile->getUserName().isEmpty())
				askUsernamePass=true;

			if (GlobalConfig->currentProfile->getUserPassword().isEmpty())
				askUsernamePass=true;

			if (AuthRetry)
				askUsernamePass=true;

			if ( askUsernamePass )
			{
				bool requestUsername = GlobalConfig->currentProfile->getUserPassword().isEmpty();
				EnterUsernamePasswordDialog dlg(this, i18n("Enter Account Data"), true, requestUsername);

				if (!GlobalConfig->currentProfile->getUserName().isEmpty())
					dlg.main->UsernameEdit->setText(GlobalConfig->currentProfile->getUserName());


				dlg.main->LabelGroupPassword->setText(i18n("Enter group password:"));

				if( !GlobalConfig->currentProfile->getUserPassword().isEmpty() )
					dlg.main->PasswordEdit->setText(GlobalConfig->currentProfile->getUserPassword());

				if ( !GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
				{
					dlg.main->PSKLineEdit->setText(GlobalConfig->currentProfile->getPreSharedKey());
				}

				if (!dlg.main->UsernameEdit->text().isEmpty()) //go straight to pw if username present
				{
					if (!dlg.main->PSKLineEdit->text().isEmpty())
						dlg.main->PasswordEdit->setFocus();
					else
						dlg.main->PSKLineEdit->setFocus();
				}

				dlg.main->SaveValuesCheckBox->setChecked(	GlobalConfig->currentProfile->getSaveUserPassword() || !GlobalConfig->currentProfile->getDontSaveUsername());

				if (dlg.exec())
				{

					if ( !GlobalConfig->currentProfile->getSaveUserPassword() || AuthRetry)
						TmpPassword= dlg.Password;

					TmpGroupPassword= dlg.GroupPassword;

					if ( TmpGroupPassword.isEmpty() && !GlobalConfig->currentProfile->getAllowEmptyGroupPassword())
					{
						GlobalConfig->appendLogEntry( i18n( "Password is empty" ), GlobalConfig->error );
						ok=false;
					}

					if( requestUsername && GlobalConfig->currentProfile->getUserName().isEmpty())
					{
						GlobalConfig->appendLogEntry( i18n( "Username is empty!" ), GlobalConfig->error );
						ok=false;
					}

					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "Some account data which is needed got from password enter dialog." ), GlobalConfig->debug );

					if (dlg.main->SaveValuesCheckBox->isChecked())
					{
						if (!GlobalConfig->currentProfile->getDontSaveUsername())
							GlobalConfig->currentProfile->setUserName(dlg.Username);
						else
							TmpUsername = dlg.Username;

						GlobalConfig->currentProfile->setSavePsk(true);
						GlobalConfig->currentProfile->setPreSharedKey(TmpGroupPassword);
						GlobalConfig->currentProfile->setSaveUserPassword(true);
						GlobalConfig->currentProfile->setUserPassword(TmpPassword);
						saveSessionClicked();
					}
				}
				else
				{
					ok=false;
					AuthRetry=false;
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "Connect canceled because account data dialog aborted." ), GlobalConfig->debug );
				}
			}
		}


		// here we go
		if ( ok )
		{
			if ( GlobalConfig->currentProfile->getExecuteCmdBeforeConnect() )
				executeCommandBeforeConnect();

			tmpPath = locateLocal ( "data", "kvpnc/" );

			QString tmpInterface;
			QString LocalIP;
			NetworkInterface iface(GlobalConfig ,parent);
			if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" )
			{
				tmpInterface = iface.getDefaultInterface();
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Default interface: \"%1\"." ).arg(tmpInterface) ,GlobalConfig->info);
				LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "IP address of default interface: \"%1\"." ).arg(LocalIP) ,GlobalConfig->info);
			}
			else
			{
				tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
				LocalIP = iface.getInterfaceIP( GlobalConfig->currentProfile->getNetworkDevice() );
			}
			if ( tmpInterface.isEmpty() )
			{
				tmpInterface = iface.getDefaultInterface();
				LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
				if ( tmpInterface.isEmpty() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
					{
						GlobalConfig->appendLogEntry( i18n( "No default interface found, using \"lo\"." ), GlobalConfig->debug );
						tmpInterface = "lo"; // no default interface found :(
						LocalIP="127.0.0.1";
					}
				}
				else
				{
					GlobalConfig->appendLogEntry( i18n( "No default interface given, tried default interface, got success, using \"%1\"." ).arg(tmpInterface), GlobalConfig->debug );
				}
			}

			if ( LocalIP.isEmpty() )
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "No IP for default interface found, using \"127.0.0.1\"." ), GlobalConfig->debug );
				LocalIP = "127.0.0.1"; // no IP for default interface found :(
			}

			//   QString tunneldevice = "tun0";
			int mtusize = 1412;
			OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
			VpncGateway = tmpPath + "gateway." + GlobalConfig->currentProfile->getName(); // gateway.<id>
			VpncConnectScript = tmpPath + "vpnc-connect." + GlobalConfig->currentProfile->getName() + ".sh"; // vpnc-connect.<id>.sh
			GlobalConfig->Vpnc_pid_file = tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getName() + ".pid"; // vpnc-pid.<id>.pid

			// define 0.2.1
			int vpnc_version_major=0;
			int vpnc_version_minor=2;
			int vpnc_version_subminor=1;

			ToolInfo *Tool= Utils(GlobalConfig).getToolInfo(GlobalConfig, "vpnc");
			if (!Tool->Version.isEmpty())
			{
				vpnc_version_major=(Tool->Version.section('.',0,0)).toInt();
				vpnc_version_minor=(Tool->Version.section('.',1,1)).toInt();
				vpnc_version_subminor=(Tool->Version.section('.',2,2)).toInt();
				if (GlobalConfig->KvpncDebugLevel > 0)
				{
					GlobalConfig->appendLogEntry ( i18n( "vpnc version (major): \"%1\"" ).arg( vpnc_version_major ) , GlobalConfig->info);
					GlobalConfig->appendLogEntry ( i18n( "vpnc version (minor): \"%1\"" ).arg( vpnc_version_minor ) , GlobalConfig->info);
					GlobalConfig->appendLogEntry ( i18n( "vpnc version (subminor): \"%1\"" ).arg( vpnc_version_subminor ) , GlobalConfig->info);
				}
			}

			// write vpnc connect script
			VpncScript = tmpPath + "vpnc-script." + GlobalConfig->currentProfile->getName(); // vpnc-script.<name>
			if (GlobalConfig->KvpncDebugLevel > 0)
				GlobalConfig->appendLogEntry( "VpncScript: " + VpncScript + "\n", GlobalConfig->debug );
			QFile file ( VpncScript );
			QTextStream stream( &file );
			if ( file.open( IO_WriteOnly ) )
			{
				stream << "#!/bin/bash" << "\n";
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + GlobalConfig->currentProfile->getID() << "\n";
				stream << "" << "\n";
				stream << "#* VPNGATEWAY             -- vpn gateway address (always present)\n";
				stream << "#* TUNDEV                 -- tunnel device (always present)\n";
				stream << "#* INTERNAL_IP4_ADDRESS   -- address (always present)\n";
				stream << "#* INTERNAL_IP4_NETMASK   -- netmask (often unset)\n";
				stream << "#* INTERNAL_IP4_DNS       -- list of dns serverss\n";
				stream << "#* INTERNAL_IP4_NBNS      -- list of wins servers\n";
				stream << "#* CISCO_DEF_DOMAIN       -- default domain name\n";
				stream << "#* CISCO_BANNER           -- banner from server\n";
				stream << "#* CISCO_SPLIT_INC              -- number of networks in split-network-list\n";
				stream << "#* CISCO_SPLIT_INC_%d_ADDR      -- network address\n";
				stream << "#* CISCO_SPLIT_INC_%d_MASK      -- subnet mask (for example: 255.255.255.0)\n";
				stream << "#* CISCO_SPLIT_INC_%d_MASKLEN   -- subnet masklen (for example: 24)\n";
				stream << "#* CISCO_SPLIT_INC_%d_PROTOCOL  -- protocol (often just 0)\n";
				stream << "#* CISCO_SPLIT_INC_%d_SPORT     -- source port (often just 0)\n";
				stream << "#* CISCO_SPLIT_INC_%d_DPORT     -- destination port (often just 0)\n";
				stream << "\n";
				stream << "fix_ip_get_output () {\n";
				stream << "	head -n 1 | sed 's/cache//;s/metric[0-9]\\+ [0-9]\\+//g' | xargs echo\n";
				stream << "}\n";
				// min 0.3.3
				if (vpnc_version_minor >= 3 && vpnc_version_subminor >= 3   )
				{
					stream << "do_connect() {\n";
				}
				stream << "test -e /proc/sys/kernel/modprobe && `cat /proc/sys/kernel/modprobe` tun 2>/dev/null\n";
				stream << "\n";
				stream << "if [ $? != 0 ]; then\n";
				stream << "# all this checks fail on a self-compiled kernel 2.4, though\n";
				stream << "( grep -q \" tun_init\" /proc/k*syms || test -e /sys/class/misc/tun || grep -q CONFIG_TUN=y /boot/config -`uname -r` ) 2>/dev/null || echo -e \"WARNING: failed to load the tun module\\n\"\n";
				stream << "fi\n";
				stream << "\n";
				stream << "ifconfig $TUNDEV inet $INTERNAL_IP4_ADDRESS pointopoint $INTERNAL_IP4_ADDRESS netmask 255.255.255.255 mtu " << mtusize << " up\n";
				stream << "ip route add $(ip route get $VPNGATEWAY | fix_ip_get_output)\n";
				stream << "if [ -n \"$CISCO_SPLIT_INC\" ]; then\n";
				stream << "	for ((i = 0 ; i < CISCO_SPLIT_INC ; i++ )) ; do\n";
				stream << "		eval NETWORK=\"\\${CISCO_SPLIT_INC_${i}_ADDR}\"\n";
				stream << "		eval NETMASK=\"\\${CISCO_SPLIT_INC_${i}_MASK}\"\n";
				stream << "		eval NETMASKLEN=\"\\${CISCO_SPLIT_INC_${i}_MASKLEN}\"\n";
				stream << "		ip route add \"$NETWORK/$NETMASKLEN\" dev \"$TUNDEV\"\n";
				stream << "	done\n";
				stream << "else\n";
				stream << "	true\n";
				if (!GlobalConfig->currentProfile->getKeepDefaultRoute())
				{
					stream << "	ip route | grep '^default' | fix_ip_get_output > \"" + OldDefaultroute + "\"\n";
					stream << "	echo \"$VPNGATEWAY\" > \"" + VpncGateway + "\"\n";
					stream << "	ip route del default\n";
					stream << "	ip route add default dev $TUNDEV\n";
				}
				stream << "fi\n";
				stream << "if [ \"$INTERNAL_IP4_DNS\" ] ; then\n";
				stream << "	if test -x /sbin/resolvconf && [ \"$(getvar \"${config}\" \"DNSUpdate\")\" != \"no\" ] ; then\n";
				stream << "		(\n";
				stream << "			if [ \"$CISCO_DEF_DOMAIN\" ] ; then\n";
				stream << "				echo domain \"$CISCO_DEF_DOMAIN\"\n";
				stream << "				echo search \"$CISCO_DEF_DOMAIN\"\n";
				stream << "			fi\n";
				stream << "			for ip in \"$INTERNAL_IP4_DNS\" ; do\n";
				stream << "				echo nameserver $ip\n";
				stream << "			done\n";
				stream << "			) | /sbin/resolvconf -a $TUNDEV\n";
				stream << "			echo $TUNDEV > $dnsdev\n";
				stream << "	else\n";
				stream << "	# in case we have no /sbin/resolvconf handle /etc/resolv.conf manually\n";
				stream << "	mv /etc/resolv.conf /etc/resolv.conf.before.kvpnc."+GlobalConfig->currentProfile->getName()+"\n";
				stream << "	if [ \"$CISCO_DEF_DOMAIN\" ] ; then" << "\n";
				stream << "		echo domain \"$CISCO_DEF_DOMAIN\"" << "\n";
				stream << "		echo search \"$CISCO_DEF_DOMAIN\"" << "\n";
				stream << "	fi" << "\n";
				stream << "	for i in $INTERNAL_IP4_DNS; do\n";
				stream << "		echo nameserver $i >> /etc/resolv.conf\n";
				stream << "	done\n";
				stream << "	fi\n";
				stream << "	for ip in $INTERNAL_IP4_DNS ; do\n";
				stream << "		ip route get $ip | grep -q \"dev $TUNDEV\" || ip route add $ip dev $TUNDEV\n";
				stream << "	done\n";
				stream << "fi\n";
				// end patch

				stream << "ip route flush cache\n";
				if (vpnc_version_minor >= 3 && vpnc_version_subminor >= 3   )
				{
					stream << "}\n";

					stream << "do_disconnect() {\n";
					stream << "	ip route del default > /dev/null 2>&1\n";
					stream << "	ip route add `cat \"" << OldDefaultroute << "\"`\n";
					stream << "	ip route flush cache\n";
					stream << "}\n";

					stream << "\n";
					stream << "case \"$reason\" in\n";
					stream << "	pre-init)\n";
					stream << " #	 do_pre_init\n";
					stream << "		;;\n";
					stream << "	connect)\n";
					stream << "		do_connect\n";
					stream << "		;;\n";
					stream << "	disconnect)\n";
					stream << "#		do_disconnect\n";
					stream << "		;;\n";
					stream << "	*)\n";
					stream << "		echo \"unknown reason '$reason'. Maybe vpnc-script is out of date\" 1>&2\n";
					stream << "		exit 1\n";
					stream << "		;;\n";
					stream << "esac\n";
					stream << "\n";
				}
			}

			file.close();

			// write vpnc.<profile>.conf # dummy!
			if (vpnc_version_minor > 2 )
			{
				file.setName( tmpPath + "vpnc." + GlobalConfig->currentProfile->getName() + ".conf" );
				stream.setDevice( &file );
				if ( file.open( IO_WriteOnly ))
				{
					stream << "# generated by kvpnc. Do not edit it." << "\n";
					stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
					stream << "" << "\n";
					stream << "IPSec gateway " << TmpGatewayIP <<"\n";
					stream << "IPSec ID " << GlobalConfig->currentProfile->getID() <<"\n";
					QString GrpPassStr="";
					if (!GlobalConfig->currentProfile->getSavePsk() || AuthRetry)
						GrpPassStr = TmpGroupPassword;
					else
						GrpPassStr = GlobalConfig->currentProfile->getPreSharedKey();
					stream << "IPSec secret " << GrpPassStr << "\n";
					stream << "Xauth username "<< GlobalConfig->currentProfile->getUserName() << "\n";
				}
				file.close();
				stream.unsetDevice();
			}

			ConnectProcess = new QProcess ( this );
			ConnectProcess->addArgument( "/bin/chmod" );
			ConnectProcess->addArgument( "+x" );
			ConnectProcess->addArgument( VpncScript );

			if ( ConnectProcess->start() )
			{

				//sleep ( 1 );

				if (!Utils( GlobalConfig, parent ).isValidNetworkDevice("tun0"))
				{
					QFile tundevfile("/dev/net/tun");
					if (!tundevfile.exists())
					{
						if (!Utils( GlobalConfig, parent ).createTunDev())
						{
							KMessageBox::error( this, i18n( "Creating of \"%1\" has been failed!" ).arg("/dev/net/tun"));
							GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating has been failed: stop."), GlobalConfig->error);
							disconnectClicked();
							setGuiStatus(disconnected);
							GlobalConfig->status=GlobalConfig->disconnected;
							return;
						}
						else
						{
							GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating has been succeded."),GlobalConfig->info);
						}
					}
					// load the module 'tun'
					bool tunsupportfound=false;
					QString procmisc="";
					QFile f("/proc/misc");
					if ( f.open( IO_ReadOnly ) )
					{
						QTextStream stream( &f );
						QString line = "";
						while ( !stream.atEnd() )
						{
							line = stream.readLine(); // line of text excluding '\n'
							if ( line.contains( "tun" ) )
							{
								tunsupportfound=true;
								break;
							}
						}
					}
					f.close();
					if (tunsupportfound)
					{
						if (GlobalConfig->KvpncDebugLevel > 0)
							GlobalConfig->appendLogEntry(i18n("Support for TUN/TAP found (compiled into kernel or kernel module already loaded)."), GlobalConfig->debug);
					}
					else
					{
						if (!Utils( GlobalConfig, parent ).loadKernelModule("tun",parent))
						{
							KMessageBox::information( this, i18n( "Loading of module \"%1\" failed!" ).arg("tun"));
							GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, loading module \"%1\" has failed: stop.").arg("tun"), GlobalConfig->error);
							disconnectClicked();
							setGuiStatus(disconnected);
							GlobalConfig->status=GlobalConfig->disconnected;
							return;
						}
						else
						{
							GlobalConfig->appendLogEntry(i18n("Loading of module \"%1\" was successful.").arg("tun"),GlobalConfig->info);
						}
					}
				}
				ConnectProcess = new QProcess ( this );

				ConnectProcess->addArgument( GlobalConfig->pathToVpnc );
				// ConnectProcess->addArgument("--no-detach");
				ConnectProcess->addArgument( "--script" );
				ConnectProcess->addArgument( VpncScript );
				if ( GlobalConfig->VpncDebugLevel > 0 )
				{

					ConnectProcess->addArgument( "--debug" );
					ConnectProcess->addArgument( QString().setNum( GlobalConfig->VpncDebugLevel ) );
				}
				ConnectProcess->addArgument( "--pid-file" );
				ConnectProcess->addArgument( GlobalConfig->Vpnc_pid_file );
				//    ConnectProcess->addArgument( "--gateway" );
				//    ConnectProcess->addArgument( GlobalConfig->currentProfile->getGateway() );
				//    ConnectProcess->addArgument( "--id" );
				//    ConnectProcess->addArgument( GlobalConfig->currentProfile->getID() );
				//    ConnectProcess->addArgument( "--username" );
				//    ConnectProcess->addArgument( GlobalConfig->currentProfile->getUserName() );


				if ( GlobalConfig->currentProfile->getUseAdvancedSettings() )
				{

					if ( GlobalConfig->currentProfile->getUseApplicationVersion() )
					{
						ConnectProcess->addArgument( "--application-version" );
						ConnectProcess->addArgument( GlobalConfig->currentProfile->getApplicationVersion() );
						GlobalConfig->appendLogEntry ( i18n( "Using userdefined application version \"%1\"." ).arg( GlobalConfig->currentProfile->getApplicationVersion() ) , GlobalConfig->debug);
					}

					if ( GlobalConfig->currentProfile->getUseLocalPort() )
					{
						ConnectProcess->addArgument( "--local-port" );
						ConnectProcess->addArgument( QString().setNum( GlobalConfig->currentProfile->getLocalPort() ) );
						GlobalConfig->appendLogEntry ( i18n( "Using userdefined local port \"%1\"." ).arg( QString().setNum( GlobalConfig->currentProfile->getLocalPort() ) ),GlobalConfig->info );
					}
					else
					{
						ConnectProcess->addArgument( "--local-port" );
						ConnectProcess->addArgument( "0" ); // random port
						GlobalConfig->appendLogEntry ( i18n( "Using random port." ), KVpncConfig::info);
					}

					if ( GlobalConfig->currentProfile->getUseNtDomainName() )
					{
						ConnectProcess->addArgument( "--domain" );
						ConnectProcess->addArgument( GlobalConfig->currentProfile->getNtDomainName() );
						GlobalConfig->appendLogEntry ( i18n( "Using (NT) domain name \"%1\"." ).arg( GlobalConfig->currentProfile->getNtDomainName() ),GlobalConfig->info );
					}

					if ( GlobalConfig->currentProfile->getUsePerfectForwardSecrety() )
					{
						ConnectProcess->addArgument( "--pfs" );
						ConnectProcess->addArgument( GlobalConfig->currentProfile->getPerfectForwardSecrety() );
						GlobalConfig->appendLogEntry ( i18n( "Using userdefined PFS \"%1\"." ).arg( GlobalConfig->currentProfile->getPerfectForwardSecrety() ),GlobalConfig->info );
					}

					if ( GlobalConfig->currentProfile->getUseIkeGroup() )
					{
						ConnectProcess->addArgument( "--dh" );
						ConnectProcess->addArgument( GlobalConfig->currentProfile->getIkeGroup() );
						GlobalConfig->appendLogEntry ( i18n( "Using userdefined IKE group \"%1\"." ).arg( GlobalConfig->currentProfile->getIkeGroup() ),GlobalConfig->info );
					}

					if ( GlobalConfig->currentProfile->getUseSingleDes() )
					{
						ConnectProcess->addArgument( "--enable-1des" );
						GlobalConfig->appendLogEntry ( i18n( "Using single DES." ),GlobalConfig->info );
					}

					if ( GlobalConfig->currentProfile->getUseUdp() )
					{
						ConnectProcess->addArgument( "--udp" );
						GlobalConfig->appendLogEntry ( i18n( "Using UDP." ),GlobalConfig->info );
					}

					if ( GlobalConfig->currentProfile->getUseUdpPort() )
					{
						ConnectProcess->addArgument( "--udp-port" );
						ConnectProcess->addArgument( QString().setNum(GlobalConfig->currentProfile->getUdpPort()) );
						GlobalConfig->appendLogEntry ( i18n( "Using userdefined UDP port \"%1.\"" ).arg(GlobalConfig->currentProfile->getUdpPort()),GlobalConfig->info );
					}

				}

				if (vpnc_version_minor > 2 )
				{
					ConnectProcess->addArgument(tmpPath + "vpnc." + GlobalConfig->currentProfile->getName() + ".conf");
				}
			}
			connect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_vpnc() ) );
			connect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_vpnc() ) );

			GlobalConfig->appendLogEntry ( i18n( "Trying to connect to server \"%1\" (%2) with user \"%3\" and IPSec ID \"%4\"...\n" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( TmpGatewayIP ).arg( GlobalConfig->currentProfile->getUserName() ).arg( GlobalConfig->currentProfile->getID() ),GlobalConfig->info );
			slotStatusMsg( i18n( "Connecting..." ), ID_CONNECTION_MSG );

			if ( !ConnectProcess->start() )
			{
				KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "vpnc" ) );
				GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "vpnc" ),GlobalConfig->error);
				disconnectClicked();
				setGuiStatus(disconnected);
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("vpnc"),GlobalConfig->info );
				ConnectingProcess = VpnAccountData::cisco;
				GlobalConfig->status = GlobalConfig->connecting;
				mw->buttonDisconnect->setEnabled( true );
				this->disconnectAction->setEnabled( true );

				connect ( ConnectProcess, SIGNAL( processExited () ), this, SLOT( vpncStarted() ) );
				connect( &timer, SIGNAL( timeout() ), this, SLOT( slotConnectTimedOut() ) );
				timer.start( GlobalConfig->tryConnectTimeout * 1000, FALSE );
			}
		}
		else
		{
			setGuiStatus(disconnected);
			return;
		}
	} // vpnc

	/* ============ racoon ================ */
	else if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
	{
		//setGuiStatus(connecting);
		// looking for racoon
		if (  GlobalConfig->useDefaultPaths )
		{
			GlobalConfig->pathToRacoon= KStandardDirs::findExe("racoon",QString::null);
		}
		else if ( GlobalConfig->pathToRacoon.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToRacoon.section('/',-1,-1),GlobalConfig->pathToRacoon.section('/',0,-2)).isEmpty())
		{
			KMessageBox::error( this, i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("racoon").arg(GlobalConfig->pathToRacoon) );
			GlobalConfig->appendLogEntry( i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("racoon").arg(GlobalConfig->pathToRacoon), GlobalConfig->error);
			ok = false;
			setGuiStatus(disconnected);
			return;
		}

		// looking for setkey
		if (  GlobalConfig->useDefaultPaths )
		{
			GlobalConfig->pathToSetkey= KStandardDirs::findExe("setkey",QString::null);
		}
		else if ( GlobalConfig->pathToSetkey.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToVpnc.section('/',-1,-1),GlobalConfig->pathToSetkey.section('/',0,-2)).isEmpty())
		{
			KMessageBox::error( this, i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("setkey").arg(GlobalConfig->pathToSetkey) );
			GlobalConfig->appendLogEntry( i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("setkey").arg(GlobalConfig->pathToSetkey), GlobalConfig->error);
			ok = false;
			setGuiStatus(disconnected);
			return;
		}

		TmpGatewayIP = Utils( GlobalConfig, parent ).resolveName(GlobalConfig->currentProfile->getGateway(), parent);
		if (TmpGatewayIP=="0.0.0.0")
		{
			KMessageBox::error( this, i18n( "Host \"%1\" could not be resolved!" ).arg(GlobalConfig->currentProfile->getGateway()) );
			GlobalConfig->appendLogEntry(i18n( "Host \"%1\" could not be resolved!" ).arg(GlobalConfig->currentProfile->getGateway()), GlobalConfig->error) ;
			ok =false;
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "Gateway hostname (%1) resolved to \"%2\"." ).arg(GlobalConfig->currentProfile->getGateway()).arg(TmpGatewayIP), GlobalConfig->debug );
		}

		if (GlobalConfig->currentProfile->authtype == VpnAccountData::cert)
		{
			QFile CertTmpFile;
			CertTmpFile.setName(GlobalConfig->currentProfile->getX509Certificate());
			if (!CertTmpFile.exists())
			{
				KMessageBox::error(0,  i18n("Certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getCertPath()),i18n("File Not Found"));
				GlobalConfig->appendLogEntry(i18n("Certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getX509Certificate()),GlobalConfig->error);
				ok=false;
			}
		}

		if (!Utils( GlobalConfig, parent ).loadKernelModule("esp4",parent))
		{
			KMessageBox::information( this, i18n( "Loading of module \"%1\" failed!" ).arg("esp4"));
			GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" has failed: stop.").arg("esp4"), GlobalConfig->error);
			ok=false;
		}

		if (!Utils( GlobalConfig, parent ).loadKernelModule("ah4",parent))
		{
			KMessageBox::information( this, i18n( "Loading of module \"%1\" failed!" ).arg("ah4"));
			GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" has failed: stop.").arg("ah4"), GlobalConfig->error);
			ok=false;
		}

		// here we go
		if ( ok )
		{
			if ( GlobalConfig->currentProfile->getExecuteCmdBeforeConnect() )
				executeCommandBeforeConnect();

			NetworkInterface iface(GlobalConfig,parent);
			if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" )
			{
				tmpInterface = iface.getDefaultInterface();
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Default interface: \"%1\"." ).arg(tmpInterface) ,GlobalConfig->info);
				LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "IP address of default interface: \"%1\"." ).arg(LocalIP) ,GlobalConfig->info);
			}
			else
			{
				tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
				LocalIP = iface.getInterfaceIP( GlobalConfig->currentProfile->getNetworkDevice() );
			}
			if ( tmpInterface.isEmpty() )
				tmpInterface = "lo"; // no default interface found :(

			if ( LocalIP.isEmpty() )
				LocalIP = "127.0.0.1"; // no IP for default interface found :(

			if (GlobalConfig->KvpncDebugLevel > 0)
			{
				GlobalConfig->appendLogEntry( i18n( "Default interface: %1" ).arg( tmpInterface ), GlobalConfig->debug );
				GlobalConfig->appendLogEntry( i18n( "Local IP address: %1" ).arg( LocalIP ), GlobalConfig->debug );
			}

			QString Gateway = GlobalConfig->currentProfile->getGateway();
			QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
			QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
			QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;

			tmpPath = locateLocal ( "data", "kvpnc/" ); // should be
			// KTempDir tmpdir;
			// tmpPath = tmpdir.name();
			if (GlobalConfig->KvpncDebugLevel > 0)
				GlobalConfig->appendLogEntry( "tmppath: " + tmpPath, GlobalConfig->debug );
			QString ProfileName = GlobalConfig->currentProfile->getName();
			QString CertPath = GlobalConfig->currentProfile->getCertPath();

			// write setkey.conf
			QFile file( tmpPath + "setkey." + ProfileName + ".conf" );
			QTextStream stream( &file );
			if ( file.open( IO_WriteOnly ) )
			{
				stream << "spdadd " + LocalIP + " " + Gateway + " any -P out ipsec esp/tunnel/" + LocalIP + "-" + TmpGatewayIP + "/require;" << "\n";
				stream << "spdadd " + Gateway + " " + LocalIP + " any -P in ipsec esp/tunnel/" + TmpGatewayIP + "-" + LocalIP + "/require;" << "\n";
				stream << "spdadd " + LocalIP + " " + RemoteNet + " any -P out ipsec esp/tunnel/" + LocalIP + "-" + TmpGatewayIP + "/require;" << "\n";
				stream << "spdadd " + RemoteNet + " " + LocalIP + " any -P in ipsec esp/tunnel/" + TmpGatewayIP + "-" + LocalIP + "/require;" << "\n";
			}
			file.close();

			// write racoon.<profile>.conf
			file.setName( tmpPath + "racoon." + ProfileName + ".conf" );
			if ( file.open( IO_WriteOnly ) )
			{
				stream.setDevice( &file );
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + ProfileName << "\n";

				stream << "\n";
				stream << "log " + GlobalConfig->RacoonDebugLevel << ";" << "\n";

				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
					stream << "path certificate \"" + GlobalConfig->currentProfile->getCertPath() + "\";" << "\n";

				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
					stream << "path pre_shared_key \"" + tmpPath + "psk." + ProfileName + ".key" + "\";" << "\n";

				stream << "" << "\n";
				stream << "remote " + TmpGatewayIP + " {" << "\n";
				stream << "  exchange_mode " << GlobalConfig->currentProfile->getExchangeMode() << ";" << "\n";

				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
				{
					stream << "  certificate_type x509 \"" << GlobalConfig->currentProfile->getX509Certificate() << "\" \"" << GlobalConfig->currentProfile->getX509Certificate() + "\";" << "\n";
					stream << "  verify_cert on;" << "\n";
				}
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
				{
					if (GlobalConfig->currentProfile->getUseSpecialRemoteID())
						stream << "  peers_identifier asn1dn " << GlobalConfig->currentProfile->getSpecialRemoteID() << ";" << "\n";
					else
						stream << "  peers_identifier asn1dn;" << "\n";
					stream << "  my_identifier asn1dn;" << "\n";
				}
				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					stream << "   nat_traversal on;" << "\n";
					GlobalConfig->appendLogEntry ( i18n( "Using UDP." ),GlobalConfig->info );
				}
				if ( GlobalConfig->currentProfile->getUseModeConfig() )
				{
					stream << "   mode_cfg on;" << "\n";
					GlobalConfig->appendLogEntry ( i18n( "Using Mode Config." ),GlobalConfig->info );
				}
				stream << "  proposal {" << "\n";

				stream << "    # for phase 1" << "\n";
				stream << "    encryption_algorithm 3des;" << "\n"; //FIXME made it dynamiclly
				stream << "    hash_algorithm " << GlobalConfig->currentProfile->getHashAlgo() << ";" << "\n";

				// x509
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
					stream << "    authentication_method rsasig;" << "\n";
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
					stream << "    authentication_method pre_shared_key;" << "\n";

				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
					if (!GlobalConfig->currentProfile->getUseIkeGroup())
					{
						stream << "    dh_group modp1024;" << "\n";
					}
					else
					{
						stream << "    dh_group "+GlobalConfig->currentProfile->getIkeGroup()+";" << "\n";
					}

				else
				{
					if (GlobalConfig->currentProfile->getUseAdvancedSettings() && GlobalConfig->currentProfile->getUseIkeGroup())
						stream << "    dh_group " << GlobalConfig->currentProfile->getIkeGroup() << ";\n";
					else
						stream << "    dh_group 2;" << "\n";
				}
				stream << "  }" << "\n";
				stream << "}" << "\n";
				stream << "" << "\n";
				stream << "sainfo address " << LocalIP << " any address " << GlobalConfig->currentProfile->getRemoteNetAddr() << "/" <<GlobalConfig->currentProfile->getRemoteNetMask() << " any {" << "\n";

				if (GlobalConfig->currentProfile->getUseAdvancedSettings())
				{
					if (GlobalConfig->currentProfile->getUsePerfectForwardSecrety())
					{
						QString pfs_group="";
						if (GlobalConfig->currentProfile->getPerfectForwardSecrety() == "server")
							pfs_group = "";
						else if (GlobalConfig->currentProfile->getPerfectForwardSecrety() == "nopfs")
							pfs_group="";
						else if (GlobalConfig->currentProfile->getPerfectForwardSecrety() == "dh1")
							pfs_group="1";
						else if (GlobalConfig->currentProfile->getPerfectForwardSecrety() == "dh2")
							pfs_group="2";
						else if (GlobalConfig->currentProfile->getPerfectForwardSecrety() == "dh5")
							pfs_group="5";
						stream << "    pfs_group " << pfs_group << ";\n";
					}
					else
					{
						stream << "  pfs_group modp768;" << "\n";
					}
				}

				stream << "  encryption_algorithm 3des, blowfish, des, rijndael;" << "\n"; //FIXME made it dynamiclly
				stream << "  authentication_algorithm hmac_sha1, hmac_md5;" << "\n"; //FIXME made it dynamiclly
				stream << "  compression_algorithm deflate;" << "\n";
				stream << "}" << "\n";

				// 				if ( GlobalConfig->currentProfile->getUseUdp() )
				// 				{
				// 					stream << "listen {" << "\n";
				// 					//stream << "isakmp 192.168.1.37[500];" << "\n";
				// 					if ( GlobalConfig->currentProfile->getUseUdpPort() )
				// 						stream << "isakmp_natt " << LocalIP << "["<< GlobalConfig->currentProfile->getUdpPort() << "];" << "\n";
				// 					else
				// 						stream << "isakmp_natt " << LocalIP << "[4500]" << ";" << "\n";
				// 					stream << "}" << "\n";
				// 				}
			}
			file.close();
			stream.unsetDevice();

			// write setkey.<profile>.sh
			file.setName( tmpPath + "setkey." + ProfileName + ".sh" );
			stream.setDevice( &file );
			if ( file.open( IO_WriteOnly ) )
			{
				stream << "#!/bin/sh" << "\n";
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + ProfileName << "\n";
				stream << "" << "\n";
				stream << "# Flush rules" << "\n";
				//     stream << "#  AH" << "\n";
				stream << GlobalConfig->pathToSetkey << " -F" << "\n";
				//     stream << "#  ESP" << "\n";
				stream << GlobalConfig->pathToSetkey << " -PF" << "\n";
				stream << "" << "\n";
				stream << "# run setkey" << "\n";
				stream << GlobalConfig->pathToSetkey << " -f " << tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".conf" << "\n";
			}
			file.close();
			stream.unsetDevice();

			// iptables need the right interface (eth0:1 => eth0)
			QString tmpInterface2 = "";
			int pointPos = tmpInterface.find( ':', 0, FALSE );
			if ( pointPos > 1 )
			{
				tmpInterface2 = tmpInterface.left( pointPos );
			}
			else
				tmpInterface2 = tmpInterface;

			// write iptables.<profile>.sh
			file.setName( tmpPath + "iptables." + ProfileName + ".add_ipsec_racoon.sh" );
			stream.setDevice( &file );
			if ( file.open( IO_WriteOnly )
			   )
			{
				stream << "#!/bin/sh" << "\n";
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + ProfileName << "\n";
				stream << "" << "\n";
				stream << "#  AH" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p 50 -i " << tmpInterface2 << " -s " << TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 50 -d " << TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  ESP" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p 51 -i " << tmpInterface2 << " -s " << TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 51 -d " << TmpGatewayIP << " -j  ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  IKE" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 500 -i " << tmpInterface2 << " -s " << TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  NAT-T" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << TmpGatewayIP << " -j ACCEPT" << "\n";

			}
			file.close();
			stream.unsetDevice();

			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
			{
				// write iptables.<profile>.sh
				file.setName( tmpPath + "psk." + ProfileName + ".key" );
				stream.setDevice( &file );
				if ( file.open( IO_WriteOnly ) )
				{
					stream << "# generated by kvpnc. Do not edit it." << "\n";
					stream << "# profile: " + ProfileName << "\n";
					stream << TmpGatewayIP + "\t" + GlobalConfig->currentProfile->getPreSharedKey() << "\n";
					file.close();
					stream.unsetDevice();
				}
			}

			// 			if (GlobalConfig->currentProfile->useVirtualIP()){
			// 				if (!setVirtualIP()){
			// 					setGuiStatus(disconnected);
			// 					return;
			// 				}
			//
			// 			}

			ConnectProcess = new QProcess ( this );
			//
			ConnectProcess->addArgument( "/bin/sh" );
			ConnectProcess->addArgument( tmpPath + "/setkey." + GlobalConfig->currentProfile->getName() + ".sh" );

			connect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoon() ) );
			connect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoon() ) );
			connect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doRouteRacoon() ) );

			if ( !ConnectProcess->start() )
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n( "\"%1\" start failed!" ).arg( "setkey" ), GlobalConfig->error );
				KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "setkey."+ProfileName+".sh" ) );
				disconnectClicked();
				//setGuiStatus(disconnected);
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg( "setkey" ),GlobalConfig->info );
				ConnectingProcess = VpnAccountData::racoon;
				GlobalConfig->status = GlobalConfig->connecting;
				mw->buttonDisconnect->setEnabled( true );
				mw->buttonConnect->setEnabled(false);
			}
		}
		else
		{
			setGuiStatus(disconnected);
		}
	} // racoon

	/* ============ freeswan ================ */
	else if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
	{

		//setGuiStatus(connecting);

		// looking for ipsec
		if (  GlobalConfig->useDefaultPaths )
		{
			GlobalConfig->pathToFreeswan= KStandardDirs::findExe("ipsec",QString::null);
		}
		else if ( GlobalConfig->pathToFreeswan.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToFreeswan.section('/',-1,-1),GlobalConfig->pathToFreeswan.section('/',0,-2)).isEmpty())
		{
			KMessageBox::error( this, i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("freeswan (ipsec)").arg(GlobalConfig->pathToFreeswan) );
			GlobalConfig->appendLogEntry( i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("freeswan(ipsec)").arg(GlobalConfig->pathToFreeswan), GlobalConfig->error);
			ok = false;
			setGuiStatus(disconnected);
			return;
		}

		QString leftid = "";
		QString rightid = "";

		// x509
		if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
		{
			QFile CertTmpFile;
			CertTmpFile.setName(GlobalConfig->currentProfile->getCertPath());
			if (!CertTmpFile.exists())
			{
				KMessageBox::error(0,  i18n("Certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getCertPath()),i18n("File Not Found"));
				GlobalConfig->appendLogEntry(i18n("Certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getCertPath()),GlobalConfig->error);
				ok=false;
				setGuiStatus(disconnected);
				return;
			}

			if (ok)
			{

				leftid = getX509CertificateID( GlobalConfig->currentProfile->getX509Certificate(), true ); // local
				if ( GlobalConfig->currentProfile->getUseSpecialRemoteID() )
					rightid = GlobalConfig->currentProfile->getSpecialRemoteID();
				else
					rightid = getX509CertificateID( GlobalConfig->currentProfile->getX509Certificate(), false ); // remote

				if ( leftid.isEmpty() || rightid.isEmpty() )
				{
					KMessageBox::error( this, i18n( "Left or right ID is empty!" ) );
					GlobalConfig->appendLogEntry(i18n( "Left or right ID is empty!" ),GlobalConfig->error);
					ok = false;
				}
			}
		}

		TmpGatewayIP = Utils( GlobalConfig, parent ).resolveName(GlobalConfig->currentProfile->getGateway(), parent);
		if (TmpGatewayIP=="0.0.0.0")
		{
			KMessageBox::error( this, i18n( "Host \"%1\" could not be resolved!" ).arg(GlobalConfig->currentProfile->getGateway()) );
			GlobalConfig->appendLogEntry(i18n( "Host \"%1\" could not be resolved!" ).arg(GlobalConfig->currentProfile->getGateway()), GlobalConfig->error);
			ok =false;
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "Gateway hostname (%1) resolved to \"%2\"." ).arg(GlobalConfig->currentProfile->getGateway()).arg(TmpGatewayIP), GlobalConfig->debug );
		}

		//   // here we go
		if ( ok )
		{
			if ( GlobalConfig->currentProfile->getExecuteCmdBeforeConnect() )
				executeCommandBeforeConnect();

			QString tmpInterface;
			QString LocalIP;
			NetworkInterface iface(GlobalConfig,parent);
			if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" )
			{
				tmpInterface = iface.getDefaultInterface();
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Default interface: \"%1\"." ).arg(tmpInterface) ,GlobalConfig->info);
				LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "IP address of default interface: \"%1\"." ).arg(LocalIP) ,GlobalConfig->info);
			}
			else
			{
				tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
				LocalIP = iface.getInterfaceIP( GlobalConfig->currentProfile->getNetworkDevice() );
			}
			if ( tmpInterface.isEmpty() )
				tmpInterface = "lo"; // no default interface found :(

			if ( LocalIP.isEmpty() )
				LocalIP = "127.0.0.1"; // no IP for default interface found :(

			if (GlobalConfig->KvpncDebugLevel > 0)
			{
				GlobalConfig->appendLogEntry( "default interface: " + tmpInterface, GlobalConfig->debug );
				GlobalConfig->appendLogEntry( "LocalIP: " + LocalIP, GlobalConfig->debug );
			}

			QString Gateway = GlobalConfig->currentProfile->getGateway();
			QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
			QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
			QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;

			tmpPath = locateLocal ( "data", "kvpnc/" ); // should be
			// KTempDir tmpdir;
			// tmpPath = tmpdir.name();
			// 			if (GlobalConfig->KvpncDebugLevel > 0)
			// 				GlobalConfig->appendLogEntry( "tmppath: " + tmpPath, GlobalConfig->debug );

			QString ProfileName = GlobalConfig->currentProfile->getName();
			QString CertPath = GlobalConfig->currentProfile->getCertPath();
			QString PrivateKeyPass = GlobalConfig->currentProfile->getPrivateKeyPass();
			QString PrivateKey = GlobalConfig->currentProfile->getPrivateKey();



			// backup system files

			if (GlobalConfig->KvpncDebugLevel > 0)
				GlobalConfig->appendLogEntry( i18n("Backing up %1").arg("ipsec.conf, ipsec.secrets"), GlobalConfig->debug );


			QString IpsecPrefix="/etc"; // prefix where ipsec.conf and ipsec.secrets
			// ipsec.conf
			QFile originalIpsecConfFile("/etc/ipsec.conf");
			QTextStream stream(&originalIpsecConfFile);
			QString originalIpsecConfFileContent="";
			if (!originalIpsecConfFile.exists())
			{
				originalIpsecConfFile.setName("/etc/ipsec.d/ipsec.conf");
				if (originalIpsecConfFile.exists())
				{
					IpsecPrefix="/etc/ipsec.d";
				}
				else
				{
					originalIpsecConfFile.setName("/etc/ipsec/ipsec.conf");
					if (originalIpsecConfFile.exists())
					{
						IpsecPrefix="/etc/ipsec";
					}
				}
			}
			if (originalIpsecConfFile.exists())
			{
				if (originalIpsecConfFile.open(IO_ReadOnly))
				{
					originalIpsecConfFileContent = QString(originalIpsecConfFile.readAll());
					originalIpsecConfFile.close();
				}
				stream.unsetDevice();
			}
			QFile backupOriginalIpsecConfFile(IpsecPrefix+"/ipsec.conf.before.kvpnc");
			stream.setDevice(&backupOriginalIpsecConfFile);
			if ( backupOriginalIpsecConfFile.open( IO_WriteOnly ) )
			{
				stream << originalIpsecConfFileContent;
				backupOriginalIpsecConfFile.close();
			}
			stream.unsetDevice();

			if (GlobalConfig->KvpncDebugLevel > 0)
				GlobalConfig->appendLogEntry(i18n("%1 found in %2, assuming %3 as prefix for %4.").arg("ipsec.conf").arg(IpsecPrefix).arg(IpsecPrefix).arg("FreeSWAN"),GlobalConfig->debug);

			// ipsec.secret
			QFile originalIpsecSecretFile(IpsecPrefix+"/ipsec.secrets");
			stream.setDevice(&originalIpsecSecretFile);
			QString originalIpsecSecretFileContent="";
			if (originalIpsecSecretFile.open(IO_ReadOnly))
			{
				originalIpsecSecretFileContent = QString(originalIpsecSecretFile.readAll());
				originalIpsecSecretFile.close();
			}
			QFile backupOriginalIpsecSecretFile(IpsecPrefix+"/ipsec.secrets.before.kvpnc");
			stream.setDevice(&backupOriginalIpsecSecretFile);
			if ( backupOriginalIpsecSecretFile.open( IO_WriteOnly ) )
			{
				stream << originalIpsecSecretFileContent;
				backupOriginalIpsecSecretFile.close();
			}
			stream.unsetDevice();

			// write /etc/ipsec.secrets
			QFile file( IpsecPrefix+"/ipsec.secrets" ); // warning: static
			stream.setDevice(&file);
			if ( file.open( IO_WriteOnly ) )
			{
				// cert
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
				{
					stream << "# generated by kvpnc. Do not edit it." << "\n";
					stream << "# profile: " + ProfileName << "\n";
					stream << ": RSA " + PrivateKey + " \"" + PrivateKeyPass + "\"\n";
					//  mw->DebugOutput->append( "cert: private key: : RSA " + PrivateKey + " \"" + PrivateKeyPass );
				}
				// PSK
				else
				{
					stream << "# generated by kvpnc. Do not edit it." << "\n";
					stream << "# profile: " + ProfileName << "\n";

					if (!GlobalConfig->currentProfile->getPskIsInFile())
						stream << ": PSK \"" + GlobalConfig->currentProfile->getPreSharedKey() + "\"\n";
					else
					{
						QFile PskFile(GlobalConfig->currentProfile->getPreSharedKeyFile());
						if (PskFile.open(IO_ReadOnly))
						{
							QString PskFileContent = QString(PskFile.readAll());
							PskFile.close();
							stream << ": PSK \"" + PskFileContent + "\"\n";
						}
					}
				}

			}
			file.close();

			// write /etc/ipsec.conf
			//file.setName( tmpPath + "freeswan." + ProfileName + ".conf" )
			file.setName( IpsecPrefix+"/ipsec.conf" ); // warning: static
			if ( file.open( IO_WriteOnly ) )
			{

				stream.setDevice( &file );
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + ProfileName << "\n";
				stream << "" << "\n";

				ToolInfo *tool = Utils(GlobalConfig).getToolInfo(GlobalConfig, "ipsec");
				QString realversion=tool->Version.section(' ',1,1).section('/',0,0).right(tool->Version.section(' ',1,1).section('/',0,0).length()-1);
				QString realtype=tool->Version.section(' ',0,0).lower();

				if ( realversion.find("2.",0,-1) > -1)
				{
					stream << "version 2" << "\n";
				}

				stream << "config setup" << "\n";
				stream << "    interfaces=%defaultroute" << "\n";
				stream << "    klipsdebug=none" << "\n";
				stream << "    plutodebug=none" << "\n";

				// FIXME add detection for nat-t
				if ( GlobalConfig->currentProfile->getUseUdp() )
					stream << "    nat_traversal=yes" << "\n";

				if ( realversion.find("1.",0,-1) > -1)
				{
					stream << "    plutoload=%search" << "\n";
					stream << "    plutostart=%search" << "\n";
				}
				stream << "" << "\n";
				stream << "conn %default" << "\n";

				// x509
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
				{
					stream << "    authby=rsasig" << "\n";
					stream << "    leftrsasigkey=%cert" << "\n";
					stream << "    rightrsasigkey=%cert" << "\n";
				}
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
				{
					stream << "    authby=secret" << "\n";
				}
				stream << "    type=tunnel" << "\n"; //TODO make it dynamiclly
				stream << "    left=%defaultroute" << "\n";
				stream << "    keyingtries=1" << "\n";
				stream << "    #keylife=1200s" << "\n";
				stream << "    #ikelifetime=1200s" << "\n";
				stream << "\n";
				stream << "conn " << GlobalConfig->currentProfile->getName() << "\n";
				if( GlobalConfig->currentProfile->getExchangeMode() == "aggressive")
				{
					stream << "    aggrmode=yes" << "\n";
					stream << "    ike=3des-sha-modp1024" << "\n";//TODO make it dynamiclly
					stream << "    esp=3des-md5-96" << "\n"; //TODO make it dynamiclly
				}

				if (GlobalConfig->currentProfile->getPerfectForwardSecrety() == "false")
					stream << "    pfs=no" << "\n";
				else if (GlobalConfig->currentProfile->getPerfectForwardSecrety() == "true")
					stream << "    auto=yes" << "\n";

				stream << "    auto=start" << "\n";
				stream << "    left="+LocalIP << "\n"; // local ip
				// 				stream << "    leftnexthop="+LocalNet << "\n";
				// 				stream << "    leftsubnet=" << "\n"; // local network
				stream << "    leftnexthop="+GlobalConfig->currentProfile->getLeftNextHop() << "\n";
				//    stream << "    rightnexthop=" << "192.168.1.1"  << "\n";
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
				{
					stream << "    leftcert=" + GlobalConfig->currentProfile->getX509Certificate() << "\n";
					// 						else
					// 					stream << "    leftid = \"" + leftid + "\"" << "\n";

					if (GlobalConfig->currentProfile->getUseSpecialServerCertificate())
						stream << "    rightcert="+GlobalConfig->currentProfile->getSpecialServerCertificate() << "\n";
					else
						stream << "    rightid=\"" + rightid + "\"" << "\n";
				}
				//stream << "    right=" + GlobalConfig->currentProfile->getGateway() << "\n";
				stream << "    right=" + TmpGatewayIP << "\n";

				stream << "    rightnexthop="+GlobalConfig->currentProfile->getRightNextHop() << "\n";

				//stream << "    rightid=\"/C=DE/ST=Sachsen-Anhalt/O=Powersoft/OU=IT/CN=212.100.100.212\"" << "\n";

			}

			stream << "    rightsubnet=" << RemoteNet << "\n";

			if (GlobalConfig->currentProfile->getDisableOpportunisticEncryption())
			{
				stream << "\n";
				stream << "# disable opportunistic encryption" << "\n";
				stream << "conn block" << "\n";
				stream << "    auto=ignore" << "\n\n";

				stream << "conn private" << "\n";
				stream << "    auto=ignore" << "\n\n";

				stream << "conn private-or-clear" << "\n";
				stream << "    auto=ignore" << "\n\n";

				stream << "conn clear-or-private" << "\n";
				stream << "    auto=ignore" << "\n";

				stream << "conn clear" << "\n";
				stream << "    auto=ignore" << "\n\n";

				stream << "conn packetdefault" << "\n";
				stream << "    auto=ignore" << "\n";
			}

			file.close();
			stream.unsetDevice();

			// iptables need the right interface (eth0:1 => eth0)
			QString tmpInterface2 = "";
			int pointPos = tmpInterface.find( ':', 0, FALSE );
			if ( pointPos > 1 )
			{
				tmpInterface2 = tmpInterface.left( pointPos );
			}
			else
				tmpInterface2 = tmpInterface;

			// write iptables.<profile>_add_ipsec_freeswan.sh
			file.setName( tmpPath + "iptables." + ProfileName + ".add_ipsec_freeswan.sh" );
			stream.setDevice( &file );
			if ( file.open( IO_WriteOnly ) )
			{
				stream << "#!/bin/sh" << "\n";
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + ProfileName << "\n";
				stream << "" << "\n";
				stream << "#  AH" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p 50 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 50 -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  ESP" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p 51 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 51 -d " << GlobalConfig->currentProfile->getGateway() << " -j  ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  IKE" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  NAT-T" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";

			}
			file.close();
			stream.unsetDevice();

			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
			{
				// write psk.<profile>.key
				file.setName( tmpPath + "psk." + ProfileName + ".key" );
				stream.setDevice( &file );
				if ( file.open( IO_WriteOnly ) )
				{
					stream << GlobalConfig->currentProfile->getPreSharedKey() << "\n";
				}
				file.close();
				stream.unsetDevice();
			}


			// 			if (GlobalConfig->currentProfile->useVirtualIP()){
			// 				if (!setVirtualIP()){
			// 					setGuiStatus(disconnected);
			// 					return;
			// 				}
			// 			}


			if (GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry("[freeswan] "+i18n( "Starting setup..." ),GlobalConfig->debug);

			ConnectProcess = new QProcess ( this );
			//
			ConnectProcess->addArgument( GlobalConfig->pathToFreeswan );
			ConnectProcess->addArgument( "setup" );
			ConnectProcess->addArgument( "start" );

			connect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_freeswan() ) );
			connect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_freeswan() ) );
			// 			connect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doRouteFreeswan() ) );

			if ( !ConnectProcess->start() )
			{
				KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "freeswan (ipsec): setup" ) );
				GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "freeswan (ipsec):setup" ) ,GlobalConfig->error);
				disconnectClicked();
				setGuiStatus(disconnected);
			}
			else
			{
				freeswanStarted();
			}
		}
		else
		{
			setGuiStatus(disconnected);
		}
	} // freeswan

	/* ============ pptp ================ */
	else if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
	{
		//setGuiStatus(connecting);

		// looking for pppd
		if (  GlobalConfig->useDefaultPaths )
		{
			GlobalConfig->pathToPppd= KStandardDirs::findExe("pppd",QString::null);
		}
		else if ( GlobalConfig->pathToPppd.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToPppd.section('/',-1,-1),GlobalConfig->pathToPppd.section('/',0,-2)).isEmpty())
		{
			KMessageBox::error( this, i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("pppd").arg(GlobalConfig->pathToPppd) );
			GlobalConfig->appendLogEntry( i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("pppd").arg(GlobalConfig->pathToPppd), GlobalConfig->error);
			ok = false;
			setGuiStatus(disconnected);
			return;
		}
		if ( GlobalConfig->enableDebugPppd )
			GlobalConfig->appendLogEntry( i18n( "pppd: %1" ) .arg( GlobalConfig->pathToPppd ), GlobalConfig->debug );


		if ( GlobalConfig->currentProfile->getRemoteNetAddr().isEmpty() || GlobalConfig->currentProfile->getRemoteNetMask() .isEmpty() )
		{
			GlobalConfig->appendLogEntry( i18n( "Remote network is missing, please fill in in profile dialog." ), GlobalConfig->error );
			ok = false;
			setGuiStatus(disconnected);
			return;
		}

		// test mppe support of pppd

		// first: ndew style
		testOldPppdStyle=false;
		TestPppdProcess = new QProcess(this);
		TestPppdProcess->addArgument( GlobalConfig->pathToPppd );
		TestPppdProcess->addArgument("require-mppe");

		connect( TestPppdProcess, SIGNAL( readyReadStdout() ), this, SLOT( readPppdtestProcessOutput() ) );
		connect( TestPppdProcess, SIGNAL( readyReadStderr() ), this, SLOT( readPppdtestProcessOutput() ) );


		if ( !TestPppdProcess->start(env) )
		{
			GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("Test mppe support of pppd")), KVpncConfig::error);
			ok = false;
			setGuiStatus(disconnected);
			return;
		}
		else
		{
			while ( TestPppdProcess->isRunning() )
				parent->processEvents();

			disconnect( TestPppdProcess, SIGNAL( readyReadStdout() ), this, SLOT( readPppdtestProcessOutput() ) );
			disconnect( TestPppdProcess, SIGNAL( readyReadStderr() ), this, SLOT( readPppdtestProcessOutput() ) );

			if (pppdHasMppeSupport==false && oldPppdStyle==false)
			{
				// we have to try old style
				testOldPppdStyle=true;
				TestPppdProcess->clearArguments();
				TestPppdProcess->addArgument( GlobalConfig->pathToPppd );
				TestPppdProcess->addArgument("require-mppe");

				connect( TestPppdProcess, SIGNAL( readyReadStdout() ), this, SLOT( readPppdtestProcessOutput() ) );
				connect( TestPppdProcess, SIGNAL( readyReadStderr() ), this, SLOT( readPppdtestProcessOutput() ) );


				if ( !TestPppdProcess->start(env) )
				{
					GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("Test mppe support of pppd")), KVpncConfig::error);
					ok = false;
					setGuiStatus(disconnected);
					delete TestPppdProcess;
					return;
				}
				else
				{
					while ( TestPppdProcess->isRunning() )
						parent->processEvents();

					disconnect( TestPppdProcess, SIGNAL( readyReadStdout() ), this, SLOT( readPppdtestProcessOutput() ) );
					disconnect( TestPppdProcess, SIGNAL( readyReadStderr() ), this, SLOT( readPppdtestProcessOutput() ) );

					delete TestPppdProcess;

					if (pppdHasMppeSupport==false && oldPppdStyle==false)
					{
						// no mppe support :(
						GlobalConfig->appendLogEntry(i18n("%1 has no MPPE support which is needed.").arg("pppd"), KVpncConfig::error);
						ok = false;
						setGuiStatus(disconnected);
						return;
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry( i18n( " %1 has MPPE support and uses old style." ) .arg( GlobalConfig->pathToPppd ), GlobalConfig->debug );
					}
				}
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( " %1 has MPPE support and uses new style." ) .arg( GlobalConfig->pathToPppd ), GlobalConfig->debug );

				delete TestPppdProcess;
			}
		}

		if ( !GlobalConfig->currentProfile->getSaveUserPassword() || GlobalConfig->currentProfile->getUserPassword().isEmpty() || GlobalConfig->currentProfile->getUserName().isEmpty() )
		{
			bool requestUsername = GlobalConfig->currentProfile->getUserPassword().isEmpty();
			EnterUsernamePasswordDialog dlg(this, i18n("Enter Account Data"),false,requestUsername); // only password

			if( !GlobalConfig->currentProfile->getSaveUserPassword() )
				dlg.main->PasswordEdit->setText(GlobalConfig->currentProfile->getUserPassword());

			dlg.main->UsernameEdit->setText(GlobalConfig->currentProfile->getUserName());
			if (!dlg.main->UsernameEdit->text().isEmpty()) //go straight to pw if username present
				dlg.main->PasswordEdit->setFocus();
			dlg.main->SaveValuesCheckBox->setText(i18n("Save username and password"));

			if (dlg.exec())
			{
				if (dlg.main->SaveValuesCheckBox->isChecked())
				{
					GlobalConfig->currentProfile->setSaveUserPassword(true);
					GlobalConfig->currentProfile->setUserPassword(dlg.Password);
				}
				TmpPassword= dlg.Password;

				if ( !GlobalConfig->currentProfile->getDontSaveUsername())
					GlobalConfig->currentProfile->setUserName(dlg.Username);
				else
				{
					TmpUsername=dlg.Username;
					GlobalConfig->appendLogEntry( i18n( "Username from dlg: %1" ).arg(dlg.Username), GlobalConfig->debug );
				}

				if ( TmpPassword.isEmpty())
				{
					GlobalConfig->appendLogEntry( i18n( "Password is empty" ), GlobalConfig->error );
					ok=false;
				}

				if( !GlobalConfig->currentProfile->getDontSaveUsername() && ( requestUsername && GlobalConfig->currentProfile->getUserName().isEmpty() ) )
				{
					GlobalConfig->appendLogEntry( i18n( "Username is empty!" ), GlobalConfig->error );
					ok=false;
				}


				if ( GlobalConfig->KvpncDebugLevel > 0  && ok)
					GlobalConfig->appendLogEntry( i18n( "Some passwords which are need got from password enter dialog." ), GlobalConfig->debug );
			}
			else
			{
				ok=false;
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Connect canceled because password enter dialog aborted." ), GlobalConfig->debug );
			}
		}

		// here we go
		if ( ok )
		{
			if ( GlobalConfig->currentProfile->getExecuteCmdBeforeConnect() )
				executeCommandBeforeConnect();

			tmpPath = locateLocal ( "data", "kvpnc/" );

			QString tmpInterface;
			QString LocalIP;
			NetworkInterface iface(GlobalConfig,parent);
			if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" )
			{
				tmpInterface = iface.getDefaultInterface();
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Default interface: \"%1\"." ).arg(tmpInterface) ,GlobalConfig->info);
				LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "IP address of default interface: \"%1\"." ).arg(LocalIP) ,GlobalConfig->info);
			}
			else
			{
				tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
				LocalIP = iface.getInterfaceIP( GlobalConfig->currentProfile->getNetworkDevice() );
			}
			if ( tmpInterface.isEmpty() )
			{
				tmpInterface = iface.getDefaultInterface();
				LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
				if ( tmpInterface.isEmpty() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
					{
						GlobalConfig->appendLogEntry( i18n( "No default interface found, using \"lo\"." ), GlobalConfig->debug );
						tmpInterface = "lo"; // no default interface found :(
					}
				}
				else
				{
					GlobalConfig->appendLogEntry( i18n( "No default interface given, tried default interface, got success, using \"%1\"." ).arg(tmpInterface), GlobalConfig->debug );
				}
			}

			if ( LocalIP.isEmpty() )
			{
				if ( GlobalConfig->PppdDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "No IP for default interface found, using \"127.0.0.1\"." ), GlobalConfig->debug );
				LocalIP = "127.0.0.1"; // no IP for default interface found :(
			}

			OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
			PptpGateway = tmpPath + "gateway." + GlobalConfig->currentProfile->getName(); // gateway.<id>
			GlobalConfig->Pppd_pid_file = "/var/run/ppp-"+GlobalConfig->currentProfile->getName()+".pid"; // /var/run/ppp-<id>.pid


			// write pppd.<profile>.up


			QFile up1file( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up1" );
			QTextStream up1stream( &up1file );
			if ( up1file.open( IO_WriteOnly ) )
			{
				up1stream << "# generated by kvpnc. Do not edit it." << "\n";
				up1stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
				up1stream << "#!/bin/sh" << "\n";
				up1stream << "cp /etc/resolv.conf " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << "\n";
			}
			up1file.close();

			QProcess *pppdUpProcess= new QProcess(this);
			pppdUpProcess->addArgument("/bin/sh");
			pppdUpProcess->addArgument(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up");

			if ( !pppdUpProcess->start() )
			{
				KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "PppdUpScript" ) );
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("PppdUpScript") ,GlobalConfig->info);
				while(pppdUpProcess->isRunning())
					parent->QApplication::processEvents();
				GlobalConfig->appendLogEntry ( i18n( "\"%1\" finished." ).arg("PppdUpScript"),GlobalConfig->info );
			}


			// write pppd peer script
			QString PppdPeerScript = "/etc/ppp/peers/kvpnc."+GlobalConfig->currentProfile->getName(); // /etc/ppp/peers/<id>
			if (GlobalConfig->KvpncDebugLevel > 0)
				GlobalConfig->appendLogEntry( "pppd peer script: " + PppdPeerScript + "\n", GlobalConfig->debug );

			QFile file ( PppdPeerScript );
			QTextStream stream( &file );
			if ( file.open( IO_WriteOnly ) )
			{
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
				stream << "" << "\n";
				stream << "\n";
				stream << "# name of tunnel, used to select lines in secrets files\n";
				stream << "remotename "+GlobalConfig->currentProfile->getName()+"\n";
				stream << "\n";
				stream << "# name of tunnel, used to name /var/run pid file\n";
				stream << "linkname kvpnc."+GlobalConfig->currentProfile->getName()+"\n";
				stream << "\n";
				stream << "# name of tunnel, passed to ip-up scripts\n";
				stream << "ipparam kvpnc."+GlobalConfig->currentProfile->getName()+"\n";
				stream << "\n";
				stream << "# data stream for pppd to use\n";
				stream << "pty \"pptp --loglevel "+QString().setNum(GlobalConfig->PptpDebugLevel)+" "+GlobalConfig->currentProfile->getGateway()+" --nolaunchpppd\"\n";
				stream << "\n";
				stream << "# domain and username, used to select lines in secrets files\n";
				if (GlobalConfig->currentProfile->getUseAdvancedSettings() && GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty())
				{
					stream << "name "+GlobalConfig->currentProfile->getNtDomainName()+"\\\\"+GlobalConfig->currentProfile->getUserName()+"\n";
					GlobalConfig->appendLogEntry ( i18n( "Using (NT) domain name \"%1\"." ).arg( GlobalConfig->currentProfile->getNtDomainName() ), GlobalConfig->debug );
				}
				else
					stream << "name "+GlobalConfig->currentProfile->getUserName()+"\n";
				stream << "\n";

				if (GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty())
				{
					stream << "# set own dns server\n";
					stream << "ms-dns "+GlobalConfig->currentProfile->getDnsServer()+"\n";
					stream << "\n";
				}
				else
				{
					stream << "# retrieve DNS from peer\n";
					stream << "usepeerdns\n";
					stream << "\n";
				}

				if ( GlobalConfig->currentProfile->getRequireMppe())
				{
					stream << "# use MPPE encryption\n";

					if (!oldPppdStyle)
						stream << "require-mppe\n";
					else
						stream << "mppe required";

					if (!GlobalConfig->currentProfile->getAllowStatefulMode())
						if (!oldPppdStyle)
							stream << "nomppe-stateful\n";
						else
							stream << ",stateless\n";

					if (GlobalConfig->currentProfile->getRefuse128BitEncryption())
						if (!oldPppdStyle)
							stream << "nomppe-128\n";
						else
							stream << ",no128\n";

					if (GlobalConfig->currentProfile->getRefuse40BitEncryption())
						if (!oldPppdStyle)
							stream << "nomppe-40\n";
						else
							stream << ",no40\n";

					stream << "\n";
				}
				else
				{
					stream  << "# disable MPPE encryption\n";
					if (!oldPppdStyle)
						stream << "nomppe\n" ;
					else
						stream << "nomppe\n" ;
					stream << "\n";
				}


				if (GlobalConfig->enableDebugPppd)
				{
					stream << "# enable debug\n";
					stream << "debug\n";
					stream << "kdebug 1\n";
					stream << "\n";
				}
				stream << "# do not require the server to authenticate to our client\n";
				stream << "noauth\n";
				stream << "\n";

				stream << "# we want to see what happen\n";
				stream << "nodetach\n";
				stream << "\n";

				stream << "# lock the device\n";
				stream << "lock\n";
				stream << "\n";

				if (GlobalConfig->currentProfile->getUseNoBsdComp())
				{
					stream << "# Dont use BSD compression\n";
					stream << "nobsdcomp\n";
					stream << "\n";
				}
				else
				{
					stream << "# Use BSD compression\n";
					stream << "bsdcomp 9,15\n";
					stream << "\n";
				}

				if (GlobalConfig->currentProfile->getUseNoDeflate())
				{
					stream << "# Dont use deflate method\n";
					stream << "nodeflate\n";
					stream << "\n";
				}
				else
				{
					stream << "# Use deflate method\n";
					// FIXME make values dynamiclly
					stream << "deflate 9,15\n";
					stream << "\n";
				}

				if (GlobalConfig->currentProfile->getRefuseEap() )
				{
					stream << "# refuse to authenticate itself to the peer using EAP\n";
					stream << "refuse-eap\n";
				}


				if (GlobalConfig->currentProfile->getKeepDefaultRoute())
				{
					stream << "# dont set defaultroute\n";
					stream << "nodefaultroute";
					stream <<"\n";
				}
				else
				{
					if (GlobalConfig->currentProfile->getSetDefaultRoute())
					{
						stream << "# set defaultroute\n";
						stream << "defaultroute\n";
						if (GlobalConfig->currentProfile->getReplaceDefaultRoute())
							stream << "replacedefaultroute\n";
						stream <<"\n";
					}
				}


				if (GlobalConfig->currentProfile->getUseMtu())
				{
					stream << "# userdefined MTU\n";
					stream << "mtu "+QString().setNum(GlobalConfig->currentProfile->getMtu())+"\n";
					stream << "\n";
				}

				if (GlobalConfig->currentProfile->getUseNoIpDefault() )
				{
					stream << "# Use no IP by default\n";
					stream << "noipdefault\n";
					stream << "\n";
				}

				if (GlobalConfig->currentProfile->getDisableMPPEComp() )
				{
					stream << "# disable Microsoft Point-to-Point Compression (MPPC) (i.e. for compatibility with watchguard firebox)\n";
					if (!oldPppdStyle)
						stream << "nopcomp\n";
					else
						stream << "nomppc\n";
					stream << "\n";
				}

				file.close();

				// write pppd /etc/ppp/chap-secrets
				QString ChapSecrets = "/etc/ppp/chap-secrets"; // /etc/ppp/chap-secrets

				if (GlobalConfig->KvpncDebugLevel > 0)
					GlobalConfig->appendLogEntry( QString("pppd chat script: /etc/ppp/chap-secrets\n"), GlobalConfig->debug );
				file.setName ( ChapSecrets  );
				stream.setDevice( &file );
				if ( file.open( IO_WriteOnly | IO_Append ) )
				{
					stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
					stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";

					if (GlobalConfig->currentProfile->getSaveUserPassword())
						TmpPassword = GlobalConfig->currentProfile->getUserPassword();

					QString UsernameStr;
					if (!GlobalConfig->currentProfile->getDontSaveUsername())
						UsernameStr= GlobalConfig->currentProfile->getUserName();
					else
						UsernameStr = TmpUsername;

					GlobalConfig->appendLogEntry( i18n( "Username: %1" ).arg(UsernameStr),GlobalConfig->debug);

					if (GlobalConfig->currentProfile->getUseAdvancedSettings() && GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty())
					{
						stream << GlobalConfig->currentProfile->getName() + " " << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr + " " <<  TmpPassword << " *\n";
						stream << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << " "+GlobalConfig->currentProfile->getName() + " " <<  TmpPassword << " *\n";
					}
					else
					{
						stream << GlobalConfig->currentProfile->getName() + " " << UsernameStr + " " <<  TmpPassword << " *\n";
						stream << UsernameStr + " " << GlobalConfig->currentProfile->getName() + " "  <<  TmpPassword << " *\n";
					}
					stream << "# --- generated by kvpnc. Do not edit it." << "\n";
					file.close();


					Utils(GlobalConfig,this).doChmod("/etc/ppp/chap-secrets","go-rwx");

				}
				else
				{
					GlobalConfig->appendLogEntry( i18n( "Creating of %1 failed!" ).arg("pppd secrets file"),GlobalConfig->error);
				}

				// load the module 'ppp_mppe'
				QFile modprobe_confFile ("/etc/modprobe.conf");
				if ( modprobe_confFile.exists())
				{
					QString modprobe_confFileContent="";
					bool ppp_compress_18_found=false;
					if (modprobe_confFile.open(IO_ReadOnly))
					{
						QTextStream stream( &modprobe_confFile );
						QString line = "";
						while ( !stream.atEnd() )
						{
							line = stream.readLine(); // line of text excluding '\n'
							if ( line.contains( "ppp-compress-18" ) )
							{
								ppp_compress_18_found=true;
								break;
							}
						}
						modprobe_confFile.close();
						if (!ppp_compress_18_found)
						{
							if ( !modprobe_confFile.open( IO_WriteOnly | IO_Append ) )
							{
								GlobalConfig->appendLogEntry( i18n( "%1 cannot be opened for append!" ).arg("/etc/modprobe.conf") ,GlobalConfig->error);
							}
							else
							{
								stream.setDevice(&modprobe_confFile);
								stream << "\n" << "# added by kvpnc, do not edit it.\n" << "alias ppp-compress-18 ppp_mppe_mppc\n";
								modprobe_confFile.close();

								if (GlobalConfig->KvpncDebugLevel > 0)
									GlobalConfig->appendLogEntry( i18n( "%1 found \"%2\" alias missing. KVpnc has been added it." ).arg("/etc/modprobe.conf").arg("ppp-compress-18"),GlobalConfig->debug);
							}
						}
					}
				}

				if (!Utils( GlobalConfig, parent ).loadKernelModule("ppp-compress-18",parent))
				{
					//KMessageBox::information( this, i18n( "Loading of module \"%1\" failed!" ).arg("\"ppp-compress-18\" (ppp_mppe)"));

					if (GlobalConfig->KvpncDebugLevel > 0)
						GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" has been failed, trying \"%2\"...").arg("ppp-compress-18").arg("ppp_mppe"), GlobalConfig->debug);

					if (!Utils( GlobalConfig, parent ).loadKernelModule("ppp_mppe",parent))
					{
						GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" and \"%2\" has been failed: stop.").arg("ppp-compress-18").arg("ppp_mppe"), GlobalConfig->error);
						setGuiStatus(disconnected);
						disconnectClicked();
					}
					else
					{
						if (GlobalConfig->KvpncDebugLevel > 0)
							GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" has been failed, but \"%2\" succeded.").arg("ppp-compress-18").arg("ppp_mppe"), GlobalConfig->debug);
					}
				}
				else
				{

					//sleep(2);
					if (GlobalConfig->KvpncDebugLevel > 0)
						GlobalConfig->appendLogEntry( "pppd: " + GlobalConfig->pathToPppd + "\n", GlobalConfig->debug );
					PptpProcess = new QProcess(this);

					PptpProcess->addArgument( GlobalConfig->pathToPppd );
					PptpProcess->addArgument( "call" );
					PptpProcess->addArgument( QString ("kvpnc."+GlobalConfig->currentProfile->getName() ));

					//      PptpProcess->addArgument( "/bin/sh" );
					//      PptpProcess->addArgument( "/home/crissi/pppd.sh" );

					connect( PptpProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_pptp() ) );
					connect( PptpProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_pptp() ) );



					GlobalConfig->appendLogEntry ( i18n( "Trying to connect to server \"%1\" with user \"%2\"...\n" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ), GlobalConfig->debug );


					if ( !PptpProcess->start() )
					{
						KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "pppd" ) );
						GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("pppd"),GlobalConfig->error);
						disconnectClicked();
						setGuiStatus(disconnected);
					}
					else
					{
						GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("pppd"),GlobalConfig->info );
						ConnectingProcess = VpnAccountData::pptp;
						GlobalConfig->status = GlobalConfig->connecting;
						connect ( PptpProcess, SIGNAL( processExited () ), this, SLOT( pppdStarted() ) );

						//     connect( &timer, SIGNAL( timeout() ), this, SLOT( slotConnectTimedOut() ) );
						//     timer.start( tryConnectTimeout * 1000, FALSE );

					}
				}
			}
		}
		else
		{
			setGuiStatus(disconnected);
			return;
		}

	} // pptp

	/* ============ openvpn ================ */
	else if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
	{
		//setGuiStatus(connecting);

		QString OpenvpnSecrectFile="";

		// looking for openvpn
		if (  GlobalConfig->useDefaultPaths )
		{
			GlobalConfig->pathToOpenvpn= KStandardDirs::findExe("openvpn",QString::null);
		}
		else if ( GlobalConfig->pathToOpenvpn.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToOpenvpn.section('/',-1,-1),GlobalConfig->pathToOpenvpn.section('/',0,-2)).isEmpty())
		{
			KMessageBox::error( this, i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("openvpn").arg(GlobalConfig->pathToOpenvpn) );
			GlobalConfig->appendLogEntry( i18n( "Unable to find \"%1\" at \"%2\"!" ).arg("openvpn").arg(GlobalConfig->pathToOpenvpn), GlobalConfig->error);
			ok = false;
			setGuiStatus(disconnected);
			return;
		}

		if ( GlobalConfig->OpenvpnDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "openvpn: %1" ) .arg( GlobalConfig->pathToOpenvpn ) ,GlobalConfig->info);

		{

			if (GlobalConfig->currentProfile->authtype == VpnAccountData::cert)
			{
				QFile CertTmpFile;
				CertTmpFile.setName(GlobalConfig->currentProfile->getX509Certificate());
				if (!CertTmpFile.exists())
				{
					KMessageBox::error(0, i18n("Certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getX509Certificate()), i18n("File Not Found"));
					GlobalConfig->appendLogEntry(i18n("Certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getX509Certificate()),GlobalConfig->error);
					ok=false;
					setGuiStatus(disconnected);
					return;
				}

				CertTmpFile.setName(GlobalConfig->currentProfile->getPrivateKey());
				if (!CertTmpFile.exists())
				{
					KMessageBox::error(0, i18n("Private key file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getPrivateKey()),i18n("File Not Found") );
					GlobalConfig->appendLogEntry(i18n("Private key file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getPrivateKey()) ,GlobalConfig->error);
					ok=false;
					setGuiStatus(disconnected);
					return;
				}

				CertTmpFile.setName(GlobalConfig->currentProfile->getCaCertificate());
				if (!CertTmpFile.exists())
				{
					KMessageBox::error(0,  i18n("CA certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getCaCertificate()), i18n("File Not Found"));
					GlobalConfig->appendLogEntry( i18n("CA certificate file (%1) could not be found. Please check the path of it.").arg(GlobalConfig->currentProfile->getCaCertificate()) ,GlobalConfig->error);
					ok=false;
					setGuiStatus(disconnected);
					return;
				}
			}
			if (!Utils( GlobalConfig, parent ).isValidNetworkDevice("tun0"))
			{
				QFile tundevfile("/dev/net/tun");
				if (!tundevfile.exists())
				{
					if (!Utils( GlobalConfig, parent ).createTunDev())
					{
						KMessageBox::error( this, i18n( "Creating of \"%1\" has been failed!" ).arg("/dev/net/tun"));
						GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating has been failed: stop."), GlobalConfig->error);
						disconnectClicked();
						setGuiStatus(disconnected);
						GlobalConfig->status=GlobalConfig->disconnected;
						return;
					}
					else
					{
						GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating has been succeded."),GlobalConfig->info);
					}
				}
				// load the module 'tun'
				bool tunsupportfound=false;
				QString procmisc="";
				QFile f("/proc/misc");
				if ( f.open( IO_ReadOnly ) )
				{
					QTextStream stream( &f );
					QString line = "";
					while ( !stream.atEnd() )
					{
						line = stream.readLine(); // line of text excluding '\n'
						if ( line.contains( "tun" ) )
						{
							tunsupportfound=true;
							break;
						}
					}
				}
				f.close();
				if (tunsupportfound)
				{
					if (GlobalConfig->KvpncDebugLevel > 0)
						GlobalConfig->appendLogEntry(i18n("Support for TUN/TAP found (compiled into kernel or kernel module already loaded)."), GlobalConfig->debug);
				}
				else
				{
					if (!Utils( GlobalConfig, parent ).loadKernelModule("tun",parent))
					{
						KMessageBox::information( this, i18n( "Loading of module \"%1\" failed!" ).arg("tun"));
						GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, loading module \"%1\" has failed: stop.").arg("tun"), GlobalConfig->error);
						disconnectClicked();
						setGuiStatus(disconnected);
						GlobalConfig->status=GlobalConfig->disconnected;
						return;
					}
					else
					{
						GlobalConfig->appendLogEntry(i18n("Loading of module \"%1\" was successful.").arg("tun"),GlobalConfig->info);
					}
				}
			}

			bool askUsernamePass=false;



			if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
			{
				if (GlobalConfig->currentProfile->getUserPassword().isEmpty() || GlobalConfig->currentProfile->getUserName().isEmpty())
					askUsernamePass=true;

				if(AuthRetry)
					askUsernamePass=true;
			}
			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
			{
				if (!GlobalConfig->currentProfile->getPskIsInFile() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty())
					askUsernamePass=true;
			}

			if (askUsernamePass)
			{
				bool requestUsername = GlobalConfig->currentProfile->getUserName().isEmpty();
				bool requestGrouppassword=false;
				if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && !GlobalConfig->currentProfile->getPskIsInFile() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty())
					requestGrouppassword=true;

				EnterUsernamePasswordDialog dlg(this, i18n("Enter Account Data"),requestGrouppassword,requestUsername);

				if ((GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && !GlobalConfig->currentProfile->getPskIsInFile() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty() ) && !GlobalConfig->currentProfile->getUseTlsAuth())
				{
					dlg.main->UsernameEdit->hide();
					dlg.main->PasswordEdit->hide();
					dlg.main->SaveValuesCheckBox->setText(i18n("Save PSK"));

					if (dlg.exec())
					{
						if (dlg.main->SaveValuesCheckBox->isChecked())
						{
							GlobalConfig->currentProfile->setSavePsk(true);
							GlobalConfig->currentProfile->setPreSharedKey(dlg.GroupPassword);
						}
						TmpGroupPassword = dlg.GroupPassword;

						if ( TmpGroupPassword.isEmpty())
						{
							GlobalConfig->appendLogEntry( i18n( "PSK is empty" ), GlobalConfig->error );
							ok=false;
						}

					}
					else
					{
						ok=false;
						AuthRetry=false;
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry( i18n( "Connect canceled because password enter dialog aborted." ), GlobalConfig->debug );
					}
				}
				else
				{
					if( GlobalConfig->currentProfile->getSaveUserPassword() )
						dlg.main->PasswordEdit->setText(GlobalConfig->currentProfile->getUserPassword());

					dlg.main->UsernameEdit->setText(GlobalConfig->currentProfile->getUserName());
					if (!dlg.main->UsernameEdit->text().isEmpty()) //go straight to pw if username present
						dlg.main->PasswordEdit->setFocus();

					dlg.main->SaveValuesCheckBox->setText(i18n("Save username and password"));

					if (dlg.exec())
					{
						if (dlg.main->SaveValuesCheckBox->isChecked())
						{
							GlobalConfig->currentProfile->setSaveUserPassword(true);
							GlobalConfig->currentProfile->setUserPassword(dlg.Password);
							if (!GlobalConfig->currentProfile->getDontSaveUsername())
							{
								GlobalConfig->currentProfile->setUserName(dlg.Username);
							}
						}
						TmpUsername = dlg.Username;
						TmpPassword= dlg.Password;


						if ( TmpPassword.isEmpty())
						{
							GlobalConfig->appendLogEntry( i18n( "Password is empty" ), GlobalConfig->error );
							ok=false;
						}

						if( requestUsername && GlobalConfig->currentProfile->getUserName().isEmpty())
						{
							GlobalConfig->appendLogEntry( i18n( "Username is empty!" ), GlobalConfig->error );
							ok=false;
						}
					}
					else
					{
						ok=false;
						AuthRetry=false;
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry( i18n( "Connect canceled because password enter dialog aborted." ), GlobalConfig->debug );
					}

				}
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Some passwords which are need got from password enter dialog." ), GlobalConfig->debug );

				AuthRetry=false;
			}

			// here we go
			if ( ok )
			{

				if ( GlobalConfig->currentProfile->getExecuteCmdBeforeConnect() )
					executeCommandBeforeConnect();

				mw->buttonConnect->setEnabled( false );
				tmpPath = locateLocal ( "data", "kvpnc/" );

				QString tmpInterface;
				QString LocalIP;
				NetworkInterface iface(GlobalConfig,parent);
				if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" )
				{
					tmpInterface = iface.getDefaultInterface();
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "Default interface: \"%1\"." ).arg(tmpInterface) ,GlobalConfig->info);
					LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "IP address of default interface: \"%1\"." ).arg(LocalIP) ,GlobalConfig->info);
				}
				else
				{
					tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
					LocalIP = iface.getInterfaceIP( GlobalConfig->currentProfile->getNetworkDevice() );
				}
				if ( tmpInterface.isEmpty() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "No default interface found, using \"lo\"." ) ,GlobalConfig->info);
					tmpInterface = "lo"; // no default interface found :(
				}

				if ( LocalIP.isEmpty() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "No IP for default interface found, using \"127.0.0.1\"." ),GlobalConfig->info );
					LocalIP = "127.0.0.1"; // no IP for default interface found :(
				}

				// 				GlobalConfig->appendLogEntry( "debug: local virtual ip: "+GlobalConfig->currentProfile->getLocalVirtualIP(),GlobalConfig->info );
				// 				GlobalConfig->appendLogEntry( "debug: remote virtual ip: "+GlobalConfig->currentProfile->getRemoteVirtualIP(),GlobalConfig->info );

				// write openvpn.<profile>.conf
				QFile openvpn_file( tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".conf" );
				QTextStream openvpn_stream( &openvpn_file );
				if ( openvpn_file.open( IO_WriteOnly ) )
				{
					openvpn_stream << "# generated by kvpnc. Do not edit it." << "\n";
					openvpn_stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					openvpn_stream << "# verbosity" << "\n";
					openvpn_stream << "verb " << GlobalConfig->OpenvpnDebugLevel << "\n\n";

					openvpn_stream << "# change to prefix" << "\n";
					openvpn_stream << "cd " << GlobalConfig->currentProfile->getCertPath() << "\n";

					if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
					{
						openvpn_stream << "# use tun device" << "\n";
						openvpn_stream << "dev tun" << "\n\n";
					}
					else
					{
						openvpn_stream << "# use tap device" << "\n";
						openvpn_stream << "dev tap" << "\n\n";
					}

					// client mode
					openvpn_stream << "# dont listen" << "\n";
					openvpn_stream << "nobind" << "\n\n";

					openvpn_stream << "# keep the connection alive" << "\n";

					// TODO make it dynamiclly
					openvpn_stream << "keepalive 10 60" << "\n\n";

					if ( ! GlobalConfig->currentProfile->getDisableLzoCompression())
					{
						openvpn_stream << "# compression" << "\n";
						openvpn_stream << "comp-lzo" << "\n\n";
					}
					openvpn_stream << "" << "\n";

					openvpn_stream << "# try to resolve names infinite" << "\n";
					openvpn_stream << "resolv-retry infinite" << "\n\n";

					// TODO make it dynamiclly
					openvpn_stream << "" << "\n";
					if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::AuthenticationType(VpnAccountData::cert ))
					{
						openvpn_stream << "# client cert" << "\n";
						openvpn_stream << "cert " << GlobalConfig->currentProfile->getX509Certificate() << "\n\n";
						openvpn_stream << "" << "\n";
						openvpn_stream << "# client private key" << "\n";
						if (!GlobalConfig->currentProfile->getPskIsInFile())
							openvpn_stream << "key " << GlobalConfig->currentProfile->getPrivateKey() << "\n\n";
						else
							openvpn_stream << "key " << GlobalConfig->currentProfile->getPrivateKey() << "\n\n";
						openvpn_stream << "" << "\n";
						openvpn_stream << "# ca" << "\n";
						openvpn_stream << "ca " << GlobalConfig->currentProfile->getCaCertificate() << "\n\n";

						openvpn_stream << "# client side" << "\n";
						openvpn_stream << "tls-client" << "\n\n";
						openvpn_stream << "pull" << "\n\n";
						openvpn_stream << "# diffie hellman parameters" << "\n";
						openvpn_stream << "dh dh1024.pem" << "\n\n";

					}
					else if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::AuthenticationType(VpnAccountData::psk ))
					{
						openvpn_stream << "# client psk" << "\n";
						if ( GlobalConfig->currentProfile->getPskIsInFile())
						{
							openvpn_stream << "secret " << GlobalConfig->currentProfile->getPreSharedKeyFile() << "\n\n";
						}
						else
						{
							// write openvpn.<profile>.secret
							QFile openvpn_secretfile( tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".secret" );
							QTextStream openvpn_secretstream( &openvpn_secretfile );
							if ( openvpn_secretfile.open( IO_WriteOnly ) )
							{
								openvpn_secretstream << "# generated by kvpnc. Do not edit it." << "\n";
								openvpn_secretstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
								openvpn_secretstream << GlobalConfig->currentProfile->getPreSharedKey() << "\n\n";
							}
							openvpn_secretfile.close();
							openvpn_stream << "secret " << tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".secret" << "\n\n";
						}
					}

					if ( GlobalConfig->currentProfile->getUseUdp() )
					{
						openvpn_stream << "" << "\n";
						openvpn_stream << "# use udp" << "\n";
						openvpn_stream << "proto udp" << "\n\n";
					}
					else
					{
						openvpn_stream << "" << "\n";
						openvpn_stream << "# use tcp" << "\n";
						openvpn_stream << "proto tcp-client" << "\n\n";
					}
					openvpn_stream << "" << "\n";
					openvpn_stream << "# remote side" << "\n";
					openvpn_stream << "remote " << GlobalConfig->currentProfile->getGateway();
					if (GlobalConfig->currentProfile->getUseRemotePort())
						openvpn_stream << " " << GlobalConfig->currentProfile->getRemotePort();
					openvpn_stream << "\n\n";

					if (GlobalConfig->currentProfile->getUseVirtualIP())
					{
						openvpn_stream << "" << "\n";
						openvpn_stream << "# virtual ip addresses" << "\n";
						openvpn_stream << "ifconfig " << GlobalConfig->currentProfile->getLocalVirtualIP() << GlobalConfig->currentProfile->getRemoteVirtualIP() << "\n\n";


						QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
						int RemoteNetMaskNum = GlobalConfig->currentProfile->getRemoteNetMask().toInt();
						QString RemoteNetMask="255.255.255.0";
						if (RemoteNetMaskNum == 24 )
							RemoteNetMask="255.255.255.0";
						else if (RemoteNetMaskNum == 25 )
							RemoteNetMask="255.255.255.128";
						else if (RemoteNetMaskNum == 26 )
							RemoteNetMask="255.255.255.192";
						else if (RemoteNetMaskNum == 27 )
							RemoteNetMask="255.255.255.224";
						else if (RemoteNetMaskNum == 28 )
							RemoteNetMask="255.255.255.240";
						else if (RemoteNetMaskNum == 29 )
							RemoteNetMask="255.255.255.248";
						else if (RemoteNetMaskNum == 30 )
							RemoteNetMask="255.255.255.252";
						else if (RemoteNetMaskNum == 31 )
							RemoteNetMask="255.255.255.254";
						else if (RemoteNetMaskNum == 32 )
							RemoteNetMask="255.255.255.255";

						openvpn_stream << "" << "\n";
						openvpn_stream << "# route to remote network" << "\n";
						openvpn_stream << "route " << RemoteNetAddr << " " << RemoteNetMask << "\n";
					}
					//openvpn_stream << "" << "\n";
					//openvpn_stream << "# permissions" << "\n";
					// 					openvpn_stream << "user nobody" << "\n";
					// 					openvpn_stream << "group nogroup" << "\n";

					openvpn_stream << "" << "\n";
					openvpn_stream << "# port" << "\n";
					if ( GlobalConfig->currentProfile->getUseUserdefinedPort())
						openvpn_stream << "port " << GlobalConfig->currentProfile->getUserdefinedPort() << "\n\n";
					else
						openvpn_stream << "port 1194" << "\n";

					openvpn_stream << "" << "\n";
					openvpn_stream << "# don't re-read key files across SIGUSR1 or --ping-restart" << "\n";
					openvpn_stream << "persist-key" << "\n\n";

					openvpn_stream << "" << "\n";
					openvpn_stream << "# don't close and reopen TUN/TAP device across SIGUSR1 or --ping-restart restarts" << "\n";
					openvpn_stream << "persist-tun" << "\n\n";

					if (GlobalConfig->currentProfile->getUseNsCertType())
					{
						openvpn_stream << "" << "\n";
						if (GlobalConfig->currentProfile->getNsCertType() == "client")
						{
							openvpn_stream << "# Require that peer certificate was signed with an explicit nsCertType designation of \"client\"" << "\n";
							openvpn_stream << "ns-cert-type client" << "\n\n";
						}
						else
						{
							openvpn_stream << "# Require that peer certificate was signed with an explicit nsCertType designation of \"server\"" << "\n";
							openvpn_stream << "ns-cert-type server" << "\n\n";
						}
					}

					openvpn_stream << "# What happen if auth fails\n";
					// TODO made option for other types
					openvpn_stream << "auth-retry none\n\n";

					if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
					{
						openvpn_stream << "# we want to authenticate with username and password\n";
						openvpn_stream << "auth-user-pass\n\n";
					}

					if ( GlobalConfig->currentProfile->getUseUserdefiniedCipher() )
					{
						openvpn_stream << "# Use a userdefined cipher\n";
						openvpn_stream << "cipher " << GlobalConfig->currentProfile->getUserdefiniedCipher() << "\n\n";
					}

					if ( GlobalConfig->currentProfile->getUseRedirectGateway() )
					{
						openvpn_stream << "# Automatically execute routing commands to cause all outgoing IP traffic to be redirected over the VPN\n";
						openvpn_stream << "redirect-gateway\n\n";
					}

					if ( GlobalConfig->currentProfile->getUseTlsAuth() && !GlobalConfig->currentProfile->getTlsAuthFile().isEmpty() )
					{
						openvpn_stream << "# Add an additional layer of HMAC authentication on top of the TLS control channel to protect against DoS attacks\n";
						openvpn_stream << "tls-auth " << GlobalConfig->currentProfile->getTlsAuthFile() << "\n\n";

						if ( GlobalConfig->currentProfile->getUseTlsRemoteHost() )
						{
							openvpn_stream << "# Accept connections only from a host with X509 name or common name equal to host\n";
							openvpn_stream << "tls-remote "<< GlobalConfig->currentProfile->getTlsRemoteHost() << "\n\n";
						}

						if (GlobalConfig->currentProfile->getUseTlsRemoteHost()  && GlobalConfig->currentProfile->getUseTlsAuth())
							openvpn_stream << "tls-client" << "\n\n";

					}

					if ( GlobalConfig->currentProfile->getUseHttpProxy() )
					{
						openvpn_stream << "# Use a HTTP proxy\n";
						openvpn_stream << "http-proxy " << GlobalConfig->currentProfile->getHttpProxy() << " " << GlobalConfig->currentProfile->getHttpProxyPort() << "\n";
						openvpn_stream << "http-proxy-timeout " << GlobalConfig->currentProfile->getHttpProxyTimeout() << "\n\n";
					}

					openvpn_stream << "up " << tmpPath << "openvpn." << GlobalConfig->currentProfile->getName() << ".up" << "\n";
					openvpn_stream << "down " << tmpPath + "openvpn." << GlobalConfig->currentProfile->getName() << ".down" << "\n";
				}
				openvpn_file.close();

				// write openvpn.<profile>.up
				QFile upfile( tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".up" );
				QTextStream upstream( &upfile );
				if ( upfile.open( IO_WriteOnly ) )
				{
					upstream << "# generated by kvpnc. Do not edit it." << "\n";
					upstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					/* uses parts of http://www.smop.co.uk/node/69 */
					upstream << "#!/bin/sh" << "\n";
					upstream << "cp /etc/resolv.conf " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
					upstream << "echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";
					upstream << "set | sed -n \"s/^foreign_option_.* DNS \\(.*\\)'/nameserver \\1/; T next; p; :next; s/^foreign_option_.* DOMAIN \\(.*\\)'/domain \\1/; T; p;" ;
					upstream << "\" >> /etc/resolv.conf" << "\n";
					upstream << "cat  " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " | grep nameserver >> /etc/resolv.conf" << "\n";
				}
				upfile.close();

				Utils(GlobalConfig,this).doChmod(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".up","a+x");

				// write openvpn.<profile>.down
				QFile downfile( tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".down" );
				QTextStream downstream( &downfile );
				if ( downfile.open( IO_WriteOnly ) )
				{
					downstream << "# generated by kvpnc. Do not edit it." << "\n";
					downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					/* uses parts of http://www.smop.co.uk/node/69 */
					downstream << "cp " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " /etc/resolv.conf" << "\n";
				}
				downfile.close();

				Utils(GlobalConfig,this).doChmod(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".down","a+x");

				OpenvpnProcess = new QProcess ( this );
				OpenvpnProcess->setCommunication(QProcess::Stdin|QProcess::Stdout|QProcess::Stderr|QProcess::DupStderr);
				OpenvpnProcess->addArgument( GlobalConfig->pathToOpenvpn );

				OpenvpnProcess->addArgument( "--config" );
				OpenvpnProcess->addArgument( tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".conf" ); // default

				connect( OpenvpnProcess, SIGNAL( readyReadStdout() ), this, SLOT( readOutput_openvpn() ) );
				//         connect( OpenvpnProcess, SIGNAL( readyReadStderr() ), this, SLOT( readOutput_openvpn() ) );

				//GlobalConfig->appendLogEntry ( i18n( "Trying to connect to server \"%1\" with user \"%2\" and IPSec ID \"%3\"...\n" ).arg( GlobalConfig->currentProfile->getGateway() ). arg( GlobalConfig->currentProfile->getUserName() ).arg( GlobalConfig->currentProfile->getID() ) ,GlobalConfig->info);
				slotStatusMsg( i18n( "Connecting..." ), ID_CONNECTION_MSG );

				if ( !OpenvpnProcess->start() )
				{
					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "openvpn" ) );
					GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "openvpn" ) ,GlobalConfig->error);
					disconnectClicked();
				}
				else
				{
					ConnectingProcess = VpnAccountData::openvpn;
					GlobalConfig->status = GlobalConfig->connecting;
					mw->buttonDisconnect->setEnabled( true );
					this->disconnectAction->setEnabled( true );

					GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("openvpn"),GlobalConfig->info );

				}
			} // openvpn
			else
			{
				setGuiStatus(disconnected);
				return;
			}
		}
	}
}

void KVpnc::disconnectClicked()
{
	if (GlobalConfig->KvpncDebugLevel > 0)
		GlobalConfig->appendLogEntry(i18n("Disconnect requested"),GlobalConfig->info);
	if ( GlobalConfig->status == GlobalConfig->connected )
	{
		if (GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry(i18n("Disconnect requested, status connected"),GlobalConfig->debug);
		QString type_string = "";
		bool ok = true; // if ok we will run process

		if (ConnectionStatusCheckProcess != 0 )
			if ( ConnectionStatusCheckProcess->isRunning())
			{
				ConnectionStatusCheckProcess->kill();
				disconnect( ConnectionStatusCheckProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_connectionStatusCheck() ) );
				disconnect( ConnectionStatusCheckProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_connectionStatusCheck() ) );
			}

		// here we go
		if ( ok )
		{
			if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes())
				removeAdditionalNetworkRoutes();

			if ( GlobalConfig->currentProfile->getExecuteCmdBeforeDisconnect() )
				executeCommandBeforeDisconnect();

			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
			{

				tmpPath = locateLocal ( "data", "kvpnc/" );
				//Vpnc_pid_file = tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getID() + ".pid"; // vpnc-pid.<id>.pid
				VpncDisconnectScript = tmpPath + "vpnc-disconnect." + GlobalConfig->currentProfile->getID() + ".sh";
				// write vpnc connect script
				QFile pidFile( GlobalConfig->Vpnc_pid_file );
				QTextStream pidFileStream( &pidFile );
				QString Vpnc_pid = "";
				if ( pidFile.open( IO_ReadOnly ) )
				{
					Vpnc_pid = pidFileStream.readLine();
				}

				QFile file( VpncDisconnectScript );
				QTextStream stream( &file );
				if ( file.open( IO_WriteOnly ) )
				{
					//     stream << "#!/bin/bash\n";
					stream << "# generated by kvpnc. Do not edit it." << "\n";
					stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
					stream << "\n";

					if ( !Vpnc_pid.isEmpty() )
					{
						if ( GlobalConfig->VpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry( i18n( "Vpnc pid file found, killing process %1" ).arg( Vpnc_pid ) , GlobalConfig->debug);
						stream << GlobalConfig->pathToKill << " -3 " << Vpnc_pid << "\n";
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry( i18n( "No vpnc pid file found, using \"killall\" for killing vpnc." ), GlobalConfig->debug );
						stream << GlobalConfig->pathToKillall << " -3 vpnc" << "\n";
					}

					if (!GlobalConfig->currentProfile->getKeepDefaultRoute())
					{
						stream << "ip route del default > /dev/null 2>&1\n";
						stream << "ip route add $(cat \"" + OldDefaultroute + "\")\n";
					}
					stream << "ip route del $(cat \"" + VpncGateway + "\")\n";

					stream << "if [ -s \"$dnsdev\" ] && [ -e /sbin/resolvconf ] ; then\n";
					stream << "sbin/resolvconf -d `cat $dnsdev`\n";
					stream << "else\n";
					stream << "	mv /etc/resolv.conf.before.kvpnc."+GlobalConfig->currentProfile->getName()+" /etc/resolv.conf\n";
					stream << "fi\n";

					stream << "ip route flush cache\n";

				}
				file.close();

				DisconnectProcess = new QProcess ();
				DisconnectProcess->addArgument( "/bin/sh" );
				DisconnectProcess->addArgument( VpncDisconnectScript );

				if ( GlobalConfig->KvpncDebugLevel > 0 )
				{
					GlobalConfig->appendLogEntry ( i18n( "Setting %1 debug level %2." ).arg("vpnc").arg( QString().setNum( GlobalConfig->VpncDebugLevel ) ),GlobalConfig->info );
					DisconnectProcess->addArgument( "--debug" );
					DisconnectProcess->addArgument( QString().setNum( GlobalConfig->VpncDebugLevel ) );
				}

				connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
				connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );

				if ( !DisconnectProcess->start() )
				{
					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "vpnc_disconnect" ) );
				}
				setGuiStatus(disconnected);
				connectionEnded();
			}

			// racoon
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			{

				//     // looking for setkey
				//     if ( GlobalConfig->pathToSetkey.isEmpty() ) {
				//      QFile vpnc( "/usr/sbin/setkey" );
				//      if ( vpnc.exists() )
				//       GlobalConfig->pathToSetkey = "/usr/sbin/setkey";
				//      else {
				//       vpnc.setName( "/usr/local/sbin/setkey" );
				//       if ( vpnc.exists() )
				//        GlobalConfig->pathToSetkey = "/usr/local/sbin/setkey";
				//       else {
				//        vpnc.setName( "/usr/bin/setkey" );
				//        if ( vpnc.exists() )
				//         GlobalConfig->pathToSetkey = "/usr/bin/setkey";
				//        else {
				//         KMessageBox::error( this, i18n( "Unable to find \"%1\"!" ).arg("setkey") );
				//         ok = false;
				//        }
				//       }
				//      }
				//     }

				// iptables need the right interface (eth0:1 => eth0)
				QString tmpInterface2 = "";
				int pointPos = tmpInterface.find( ':', 0, FALSE );
				if ( pointPos > 1 )
				{
					tmpInterface2 = tmpInterface.left( pointPos );
				}
				else
					tmpInterface2 = tmpInterface;

				QFile file1( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_racoon.sh" );
				QTextStream stream1( &file1 );
				if ( file1.open( IO_WriteOnly ) )
				{
					stream1 << "#!/bin/sh" << "\n";
					stream1 << "# generated by kvpnc. Do not edit it." << "\n";
					stream1 << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
					stream1 << "" << "\n";
					stream1 << "#  AH" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p 50 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p 50 -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << "" << "\n";
					stream1 << "#  ESP" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p 51 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p 51 -d " << GlobalConfig->currentProfile->getGateway() << " -j  ACCEPT" << "\n";
					stream1 << "" << "\n";
					stream1 << "#  IKE" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << "" << "\n";
					stream1 << "#  NAT-T" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				}
				file1.close();

				QFile file2( tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh" );
				QTextStream stream2( &file2 );
				if ( file2.open( IO_WriteOnly ) )
				{
					stream2 << "#!/bin/sh" << "\n";
					stream2 << "# generated by kvpnc. Do not edit it." << "\n";
					stream2 << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
					stream2 << GlobalConfig->pathToSetkey << " -PF" << "\n";
					stream2 << GlobalConfig->pathToSetkey << " -F" << "\n";
				}
				file2.close();

				if ( RacoonProcess != 0 )
				{
					terminateConnection( TailProcess );
					terminateConnection( RacoonProcess );
				}

				removeSetkey();
				removeRouteRacoon();
				removeIptablesRacoon();

				connectionEnded();

				//     DisconnectProcess->clearArguments();
				//     DisconnectProcess->addArgument( GlobalConfig->pathToKillall );
				//     DisconnectProcess->addArgument( "-3" );
				//     DisconnectProcess->addArgument( "racoon" );
				//
				//     connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoon() ) );
				//     connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoon() ) );
				//     connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeSetkey() ) );
				//
				//     if ( !DisconnectProcess->start() )
				//      KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("killall -3 racoon") );
				//     else {
				//      TailProcess->tryTerminate();
				//      if ( GlobalConfig->RacoonDebugLevel > 0 )
				//       GlobalConfig->appendLogEntry( i18n( "\"%1\" was successful." ).arg("killall -3 racoon"), GlobalConfig->debug );
				//     }

			}

			// freeswan
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			{
				type_string = "freeswan";

				//     // looking for ipsec
				//     if ( GlobalConfig->pathToFreeswan.isEmpty() ) {
				//      QFile vpnc( "/usr/sbin/ipsec" );
				//      if ( vpnc.exists() )
				//       GlobalConfig->pathToRacoon = "/usr/sbin/ipsec";
				//      else {
				//       vpnc.setName( "/usr/local/sbin/ipsec" );
				//       if ( vpnc.exists() )
				//        GlobalConfig->pathToRacoon = "/usr/local/sbin/ipsec";
				//       else {
				//        vpnc.setName( "/usr/bin/ipsec" );
				//        if ( vpnc.exists() )
				//         GlobalConfig->pathToRacoon = "/usr/bin/ipsec";
				//        else {
				//         KMessageBox::error( this, i18n( "Unable to find \"%1\"!" ).arg("freeswan (ipsec)") );
				//         ok = false;
				//        }
				//       }
				//      }
				//     }

				// iptables need the right interface (eth0:1 => eth0)
				QString tmpInterface2 = "";
				int pointPos = tmpInterface.find( ':', 0, FALSE );
				if ( pointPos > 1 )
				{
					tmpInterface2 = tmpInterface.left( pointPos );
				}
				else
					tmpInterface2 = tmpInterface;

				QFile file1( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh" );
				QTextStream stream1( &file1 );
				if ( file1.open( IO_WriteOnly ) )
				{
					stream1 << "#!/bin/sh" << "\n";
					stream1 << "# generated by kvpnc. Do not edit it." << "\n";
					stream1 << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
					stream1 << "" << "\n";
					stream1 << "#  AH" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p 50 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p 50 -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << "" << "\n";
					stream1 << "#  ESP" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p 51 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p 51 -d " << GlobalConfig->currentProfile->getGateway() << " -j  ACCEPT" << "\n";
					stream1 << "" << "\n";
					stream1 << "#  IKE" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
					stream1 << "" << "\n";
					stream1 << "#  NAT-T" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				}
				file1.close();

				DisconnectProcess = new QProcess ( this );
				DisconnectProcess->addArgument( GlobalConfig->pathToFreeswan );
				DisconnectProcess->addArgument( "setup" );
				DisconnectProcess->addArgument( "stop" );

				connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_freeswan() ) );
				connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_freeswan() ) );
				// 				connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeRouteFreeswan() ) );

				if ( !DisconnectProcess->start() )
				{
					KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("ipsec setup stop") );
					GlobalConfig->appendLogEntry( i18n( "\"%1\" start failed!" ).arg("ipsec setup stop") ,GlobalConfig->error);
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "starting of \"%1\" was successful." ).arg("ipsec setup stop"), GlobalConfig->debug );

					setGuiStatus( disconnected );
					connectionEnded();

					// restore system files
					QString IpsecPrefix="/etc";
					// ipsec.conf
					QFile originalIpsecConfFile("/etc/ipsec.conf.before.kvpnc");
					QTextStream stream(&originalIpsecConfFile);
					QString originalIpsecConfFileContent="";

					if (!originalIpsecConfFile.exists())
					{
						originalIpsecConfFile.setName("/etc/ipsec.d/ipsec.conf.before.kvpnc");
						if (originalIpsecConfFile.exists())
						{
							IpsecPrefix="/etc/ipsec.d";
						}
						else
						{
							originalIpsecConfFile.setName("/etc/ipsec/ipsec.conf.before.kvpnc");
							if (originalIpsecConfFile.exists())
							{
								IpsecPrefix="/etc/ipsec";
							}
						}
					}
					if (originalIpsecConfFile.exists())
					{
						if (originalIpsecConfFile.open(IO_ReadOnly))
						{
							originalIpsecConfFileContent = QString(originalIpsecConfFile.readAll());
							originalIpsecConfFile.close();
						}
					}

					QFile backupOriginalIpsecConfFile(IpsecPrefix+"/ipsec.conf");
					stream.setDevice(&backupOriginalIpsecConfFile);
					if ( backupOriginalIpsecConfFile.open( IO_WriteOnly ) )
					{
						stream << originalIpsecConfFileContent;
						backupOriginalIpsecConfFile.close();
					}
					stream.unsetDevice();

					if (GlobalConfig->KvpncDebugLevel > 0)
						GlobalConfig->appendLogEntry(i18n("%1 found in %2, assuming %3 as prefix for %4.").arg("ipsec.conf.before.kvpnc").arg(IpsecPrefix).arg(IpsecPrefix).arg("FreeSWAN"), GlobalConfig->debug);

					// ipsec.secret
					QFile originalIpsecSecretFile(IpsecPrefix+"/ipsec.secrets.before.kvpnc");
					stream.setDevice(&originalIpsecSecretFile);
					QString originalIpsecSecretFileContent="";
					if (originalIpsecSecretFile.open(IO_ReadOnly))
					{
						originalIpsecSecretFileContent = QString(originalIpsecSecretFile.readAll());
						originalIpsecSecretFile.close();
					}

					QFile backupOriginalIpsecSecretFile(IpsecPrefix+"/ipsec.secrets");
					stream.setDevice(&backupOriginalIpsecSecretFile);
					if ( backupOriginalIpsecSecretFile.open( IO_WriteOnly ) )
					{
						stream << originalIpsecSecretFileContent;
						backupOriginalIpsecSecretFile.close();
					}
					stream.unsetDevice();

				}
			}
			// pptp
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
			{
				// write pppd.<profile>.down
				QFile downfile( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down" );
				QTextStream downstream( &downfile );
				if ( downfile.open( IO_WriteOnly ) )
				{
					downstream << "# generated by kvpnc. Do not edit it." << "\n";
					downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					downstream << "#!/bin/sh" << "\n";
					downstream << "cp " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " /etc/resolv.conf\n";
				}
				downfile.close();

				QProcess *pppdDownProcess= new QProcess(this);
				pppdDownProcess->addArgument("/bin/sh");
				pppdDownProcess->addArgument(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down");

				if ( !pppdDownProcess->start() )
				{
					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "PppdDownScript" ) );
				}
				else
				{
					GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("PppdDownScript") ,GlobalConfig->info);
					while(pppdDownProcess->isRunning())
						parent->QApplication::processEvents();
					GlobalConfig->appendLogEntry ( i18n( "\"%1\" finished." ).arg("PppdDownScript"),GlobalConfig->info );
				}

				disconnect( PptpProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_pptp() ) );
				disconnect( PptpProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_pptp() ) );
				GlobalConfig->appendLogEntry( i18n( "killing \"%1\"..." ).arg("pptp") , GlobalConfig->debug);
				DisconnectProcess = new QProcess(this);
				DisconnectProcess->addArgument( GlobalConfig->pathToKillall );
				DisconnectProcess->addArgument( "-3" );
				DisconnectProcess->addArgument( "pptp" );

				connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_pptp() ) );
				connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_pptp() ) );

				if ( !DisconnectProcess->start() )
				{
					KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("killall -3 pptp") );
					GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("killall -3 pptp") ,GlobalConfig->error);
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "\"%1\" was successful." ).arg("killall -3 pptp"), GlobalConfig->debug );
					while (DisconnectProcess->isRunning())
						parent->processEvents();
				}

				timer.stop();
				durationTimer.stop();
				GlobalConfig->status = GlobalConfig->disconnected;
				connectCounter = 0;
				connectionEnded();

				// remove kvpnc entries from chap-secerets
				QFile ChapSecretsFile ( "/etc/ppp/chap-secrets" );
				QTextStream stream( &ChapSecretsFile );
				if ( ChapSecretsFile.open( IO_ReadOnly ) )
				{
					QString line = "";
					QString chapsecret_content="";
					bool kvpnc_start_marker_found=false;
					while ( !stream.atEnd() )
					{
						line = stream.readLine(); // line of text excluding '\n'
						if ( line.contains( "# +++" ) )
							kvpnc_start_marker_found=true;
						if ( line.contains( "# ---" ) && kvpnc_start_marker_found )
							kvpnc_start_marker_found=false;

						if (!kvpnc_start_marker_found && !line.contains( "# ---" ) )
						{
							chapsecret_content+=line;
							chapsecret_content+='\n';
						}
					}
					ChapSecretsFile.close();
					if ( ChapSecretsFile.remove() )
					{
						GlobalConfig->appendLogEntry( i18n( "File %1 sucessfully removed" ).arg("/etc/ppp/chap-secrets"), GlobalConfig->info );
						ChapSecretsFile.open (IO_WriteOnly);
						stream.setDevice(&ChapSecretsFile);
						stream << chapsecret_content;
						ChapSecretsFile.close();
					}
					else
						GlobalConfig->appendLogEntry( i18n( "File %1 remove failed" ).arg("/etc/ppp/chap-secrets"), GlobalConfig->error );


				}
				else
				{
					GlobalConfig->appendLogEntry( i18n( "File %1 could not opened!" ).arg("/etc/ppp/chap-secrets"), GlobalConfig->error );
				}

				setGuiStatus ( disconnected );

			}
			// openvpn
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
			{
				disconnect( OpenvpnProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_openvpn() ) );
				disconnect( OpenvpnProcess, SIGNAL( readyReadStderr() ), this, SLOT( readOutput_openvpn() ) );
				GlobalConfig->appendLogEntry( i18n( "killing \"%1\"..." ).arg("openvpn"), GlobalConfig->debug );
				//     DisconnectProcess = new QProcess(this);
				//     DisconnectProcess->addArgument( GlobalConfig->pathToKill );
				//     DisconnectProcess->addArgument( "-3" );
				//     DisconnectProcess->addArgument( "openvpn" );
				//
				//     connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_pptp() ) );
				//     connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_pptp() ) );
				//
				//     if ( !DisconnectProcess->start() )
				//      KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("killall -3 openvpn") );
				//     else
				//     {
				//      if ( GlobalConfig->KvpncDebugLevel > 0 )
				//       GlobalConfig->appendLogEntry( i18n( "\"killall -3 %1\" successful." ).arg("openvpn"), GlobalConfig->debug );
				//     }

				terminateConnection(OpenvpnProcess);
				connectionEnded();
				setGuiStatus(disconnected);
			}
		}
		ConnectingProcess = 0L;

		if ( GlobalConfig->currentProfile->getExecuteCmdAfterDisconnect() )
			executeCommandAfterDisconnect();
	}
	else if (GlobalConfig->status == GlobalConfig->connecting)
	{
		if (GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry(i18n("Disconnect requested, status connecting"),GlobalConfig->debug);

		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry ( i18n( "Killing process while connecting.\n" ), GlobalConfig->debug );
		if (ConnectingProcess!= 0)
		{
			if (ConnectingProcess == VpnAccountData::cisco)
				ConnectProcess->kill();
			else if (ConnectingProcess == VpnAccountData::freeswan)
				FreeswanProcess->kill();
			else if (ConnectingProcess == VpnAccountData::racoon)
				RacoonProcess->kill();
			else if (ConnectingProcess == VpnAccountData::pptp)
				PptpProcess->kill();
			else if (ConnectingProcess == VpnAccountData::openvpn)
				OpenvpnProcess->kill();

		}
		//connectionEnded();
		setGuiStatus(disconnected);
		ConnectingProcess = -1;
	}
	else
	{
		GlobalConfig->appendLogEntry ( i18n( "Not connected.\n" ),GlobalConfig->info );
		setGuiStatus(disconnected);
		ConnectingProcess = -1;
	}

}

void KVpnc::helpClicked()
{

	/*
	mw->DebugOutput->append( "getting userID:\n" );
	QString leftid = getX509CertificateID( "/etc/racoon/certs/mykeys_thielecke.pem", true ); // we
	mw->DebugOutput->append( "getting issuerID:\n" );
	QString rightid = getX509CertificateID( "/etc/racoon/certs/mykeys_thielecke.pem", false ); // remote
	*/
	//doPingTest();

	// 	QString buggystring= "aaaaa::::bbbb    cccc$$$***//////";
	// 	mw->DebugOutput->append(QString("Buggy string: "+buggystring));
	// 	buggystring.replace(QRegExp("[*]+"),"_");
	// 	buggystring.replace(QRegExp("[+] +"),"_");
	// 	buggystring.replace(QRegExp("[$]+"),"_");
	// 	buggystring.replace(QRegExp(":+"),"_");
	// 	buggystring.replace(QRegExp("Ã¯Â¿Å"),"_");
	// 	buggystring.replace(QRegExp("Ã¯Â¿Å"),"_");
	// 	buggystring.replace(QRegExp("+"),"_");
	// 	buggystring.replace(QRegExp("Ã¯Â¿Å"),"_");
	// 	buggystring.replace(QRegExp("Ã¯Â¿Å"),"_");
	// 	buggystring.replace(QRegExp("Ã¯Â¿Å"),"_");
	// 	buggystring.replace(QRegExp("Ã¯Â¿Å"),"_");
	// 	buggystring.replace(QRegExp("\\+"),"_");
	// 	buggystring.replace(QRegExp("/+"),"_");
	// 	buggystring.replace(QRegExp(";+"),"_");
	// 	buggystring.replace(QRegExp(" "),"_");
	// 	buggystring.replace(QRegExp("_+"),"_");
	//
	// 	mw->DebugOutput->append(QString("Buggy string fixed: "+buggystring));

	// 		HelpDialog d1;
	// 		d1.exec();

	//	slotStatusMsg ( i18n( "Help dialog called." ), ID_FLASH_MSG );

	// 	QString host = "www.fdkldghgfdsfjhsjfgdjhsgfds.de";
	// 	QString ip = Utils( GlobalConfig, parent ).resolveName(host, parent);
	// 	if (ip=="0.0.0.0")
	// 		KMessageBox::error( this, i18n( "Host \"%1\" could not be resolved!" ).arg(host) );
	// 	else
	// 		mw->DebugOutput->append( QString("first ip of "+host+": "+ip ));
	//
	// 	QString host2 = "www.hs-harz.de";
	// 	QString ip2 = Utils( GlobalConfig, parent ).resolveName(host2, parent);
	// 	if (ip2=="0.0.0.0")
	// 		KMessageBox::error( this, i18n( "Host \"%1\" could not be resolved!" ).arg(host2) );
	// 	else
	// 		mw->DebugOutput->append( QString("first ip of "+host2+": "+ip2 ));

	// 	if (Utils( GlobalConfig, parent ).loadKernelModule("parport_pc",parent))
	// 		mw->DebugOutput->append( "Loading module ok" );
	// 	else
	// 		mw->DebugOutput->append( "Loading module failed." );


	appHelpActivated ();


	// QString bin="/a/b/c/myexe";
	// kdDebug() << "bin: " << bin.section('/',-1,-1) << endl;
	// kdDebug() << "path: " << bin.section('/',0,-2)  << endl;

	// 		// looking for vpnc
	// 		if (  GlobalConfig->useDefaultPaths ){
	// 			GlobalConfig->pathToVpnc= KStandardDirs::findExe("vpnc",QString::null);
	// 			 kdDebug() << "vpnc found at; " << GlobalConfig->pathToVpnc << endl;
	// 		}
	// 		if ( GlobalConfig->pathToVpnc.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToVpnc.section('/',-1,-1),GlobalConfig->pathToVpnc.section('/',0,-2)).isEmpty())
	// 		{
	// 				kdDebug() << "vpnc not found!" << endl;
	// 		}
	// 		else
	// 				kdDebug() << "vpnc (2) found at; " << GlobalConfig->pathToVpnc << endl;


	/* network tests */

	// 		NetworkInterface iface(GlobalConfig,parent);

	/*
	bool success = iface.interfaceExist( "eth0" );
	QString succString;
	if ( success == true )
		mw->DebugOutput->append( "Testing interface eth0: success" );
	else
		mw->DebugOutput->append( "Testing interface eth0: failed" );

	QStringList list = iface.getAllNetworkInterfaces();
	mw->DebugOutput->append( "All network interfaces:" );

	for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
		QString aa = QString( "Interface: " + *it );
		mw->DebugOutput->append( aa );
	}

	QString defaultinterface = iface.getDefaultInterface();
	if ( defaultinterface.isEmpty() )
		defaultinterface += "none";
	mw->DebugOutput->append( "Defaultinterface: "+defaultinterface );

	QString interfaceaddress = "Interface address: " + iface.getInterfaceAddress( "127.0.0.1" );
	if ( interfaceaddress.isEmpty() )
	interfaceaddress += "none";
	mw->DebugOutput->append( interfaceaddress );

	QString interfaceip = "Interface IP: " + iface.getInterfaceIP( "eth0" );
	if ( interfaceip.isEmpty() )
	interfaceip += "none";
	mw->DebugOutput->append( interfaceip );

	QString gatewayofdefaultinterface = "GW IP of default interface: " + iface.getGatewayOfDefaultInterface();
	mw->DebugOutput->append( gatewayofdefaultinterface );

	QString gatewayofinterface = "GW IP of interface eth0: " + iface.getGatewayOfInterface("eth0");
	mw->DebugOutput->append( gatewayofinterface );

	*/
	/*
	QString ipstring = "aaa\ngot address 194.95.192.28\nbbbb\ncccc";
	mw->DebugOutput->append(QString("Ipstring: \n"+ipstring));
	QString ip = ipstring.section('\n',1,1);
	ip = ip.right(ip.length()-12);
	mw->DebugOutput->append(QString("Ip: "+ip));
	*/
	// 	NetworkInterface iface(parent);
	// 		QString extIP = iface.getExternalIpAddress();
	// 	if ( extIP.isEmpty() )
	// 		extIP += "none";
	//
	// 	KMessageBox::information(0,extip,"ext ip" );

	// 	/* passwords with kwallet */
	// 	if (GlobalConfig->useKwallet && KWallet::Wallet::isEnabled())
	// 	{
	// 		// Open local wallet
	// 		GlobalConfig->wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet());
	// 		if (GlobalConfig->wallet != 0)
	// 		{
	//
	// 			QString walletname="kvpnc";
	// 			// Check if folder exists, otherwise create it
	//
	// 			if (!GlobalConfig->wallet->hasFolder(walletname))
	// 			{
	// 				bool walletOK = GlobalConfig->wallet->createFolder(walletname);
	// 				GlobalConfig->wallet->setFolder(walletname);
	// 				QString account="HS";
	//
	// 				QString loginname="masta";
	// 				QString pwd="secret";
	// 				std::cout << "[set] account: " << account << ", loginname: " << loginname << ", password: " << pwd << std::endl;
	//
	// 				bool pwdOK = (GlobalConfig->wallet->writePassword (QString(account+"_"+loginname), pwd) == 0);
	// 				std::cout << "success: " << pwdOK << std::endl;
	// 			}
	// 			// Read password entry
	//
	// 			{
	// 				GlobalConfig->wallet->setFolder(walletname);
	// 				QString loginname="masta";
	// 				QString pwd="";
	// 				QString account="HS";
	// 				bool pwdOK = (GlobalConfig->wallet->readPassword(QString(account+"_"+loginname), pwd) == 0);
	// 				std::cout << "success: " << pwdOK << std::endl;
	// 				std::cout << "[get]: loginname: " << loginname << ", password: " << pwd << std::endl;
	//
	// 			}
	// 		}
	// 	}

	// QStringList ciphers = Utils(GlobalConfig).getOpenvpnCiphers();
	//
	// std::cout << "ciphers: " << std::endl ;
	//
	// for ( QStringList::Iterator it = ciphers.begin(); it != ciphers.end(); ++it ) {
	//         std::cout << QString(*it).ascii() << "\n";
	//     }
	//     std::cout << std::endl;
}

void KVpnc::toolsInfoClicked()
{
	ToolsInfoDialog infodlg(GlobalConfig);
	toolsInfoAction->setChecked(true);
	infodlg.exec();
	toolsInfoAction->setChecked(false);
}

void KVpnc::donateClicked()
{
	KRun *run=new KRun(KURL("http://home.gna.org/kvpnc/paypal.html"));
	if (run)
		;
}

void KVpnc::readFromStderr_vpnc()
{
	//mw->DebugOutput->append( "readFromStderr_vpnc!\n" );
	// while ( ConnectProcess->canReadLineStderr() ) {
	//  ProcessMsg_connect = ConnectProcess->readLineStderr();
	ProcessMsg_connect = QString( ConnectProcess->readStderr() );

	/* TMP !!!! */
	// requesting group password
	if ( ProcessMsg_connect.find( "Enter IPSec secret", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Group password requested, send it...\n" ), GlobalConfig->debug );



		QString GrpPassStr="";
		if (!GlobalConfig->currentProfile->getSavePsk() || AuthRetry)
			GrpPassStr = TmpGroupPassword;
		else
			GrpPassStr = GlobalConfig->currentProfile->getPreSharedKey();

		ConnectProcess->writeToStdin( GrpPassStr );
		ConnectProcess->writeToStdin( "\n" );

	}

	// requesting password
	if ( ProcessMsg_connect.find( "Enter password", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "User password requested, send it...\n" ), GlobalConfig->debug );

		QString UserPassStr="";
		if (!GlobalConfig->currentProfile->getSaveUserPassword() || AuthRetry)
			UserPassStr = TmpPassword;
		else
			UserPassStr = GlobalConfig->currentProfile->getUserPassword();


		ConnectProcess->writeToStdin( UserPassStr );
		ConnectProcess->writeToStdin( "\n" );
	}

	// requesting gatway
	if ( ProcessMsg_connect.find( "Enter IPSec gateway address", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "IPSec gateway address requested, send it...\n" ), GlobalConfig->debug );
		//QString GatewayStr = GlobalConfig->currentProfile->getGateway();
		QString GatewayStr = TmpGatewayIP;
		ConnectProcess->writeToStdin( GatewayStr );
		ConnectProcess->writeToStdin( "\n" );
	}

	// requesting IPSec ID
	if ( ProcessMsg_connect.find( "Enter IPSec ID", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "IPSec ID requested, send it...\n" ), GlobalConfig->debug );
		QString IpsecIDStr = GlobalConfig->currentProfile->getID();
		ConnectProcess->writeToStdin( IpsecIDStr );
		ConnectProcess->writeToStdin( "\n" );
	}

	// requesting username
	if ( ProcessMsg_connect.find( "Enter username", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Username requested, send it...\n" ), GlobalConfig->debug );

		QString UsernameStr;
		if (!GlobalConfig->currentProfile->getDontSaveUsername())
			UsernameStr= GlobalConfig->currentProfile->getUserName();
		else
			UsernameStr = TmpUsername;

		ConnectProcess->writeToStdin( UsernameStr );
		ConnectProcess->writeToStdin( "\n" );
	}

	// 	//got address 194.95.192.28
	// 		if ( ProcessMsg_connect.find( "got address", 0, FALSE ) > -1 )
	// 	{
	// 		// "got address 194.95.192.28" => "194.95.192.28"
	// 		TunnelInterfaceIP = ProcessMsg_connect.section('\n',1,1);
	// 		TunnelInterfaceIP = TunnelInterfaceIP.right(TunnelInterfaceIP.length()-12);
	//
	// 		if ( GlobalConfig->VpncDebugLevel > 0 )
	// 			GlobalConfig->appendLogEntry ( i18n( "Tunnel IP: %1\n" ).arg(TunnelInterfaceIP), GlobalConfig->debug );
	// 	}

	if ( !ProcessMsg_connect.isEmpty() )
		GlobalConfig->appendLogEntry ( ProcessMsg_connect , GlobalConfig->error);

	bool connectSuccess = false;
	if ( ProcessMsg_connect.find( "started in background", 0, FALSE ) > -1 )
		connectSuccess = true;

	if ( ProcessMsg_connect.find( "started in foreground", 0, FALSE ) > -1 )
		connectSuccess = true;

	if ( connectSuccess )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( "[vpnc] "+i18n( "Connection established." ) ,GlobalConfig->info);

		//connectionTime.restart();
		//uint duration = connectionTime.elapsed();

		sec = hour = min = 0;

		GlobalConfig->status = GlobalConfig->connected;
		timer.stop();
		connectionTime.start();
		connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		durationTimer.start( 1000, FALSE );
		setGuiStatus(connected);
		connectSuccess = false;

		NetworkInterface iface(GlobalConfig,parent);
		TunnelInterfaceIP = iface.getInterfaceIP( "tun0" );
		if (GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( "[vpnc] "+i18n( "Tunnel IP:" ).arg(TunnelInterfaceIP) , GlobalConfig->debug);

		if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
			executeCommandAfterConnect();

		if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
		{
			addAdditionalNetworkRoutes();
			//sleep (2);
		}

		if ( GlobalConfig->currentProfile->getUseConnectionStatusCheck())
		{
			startConnectionStatusCheck();
		}
	}

	bool abort = false;
	bool doContinue=true;
	//ProcessMsg_connect = QString(ConnectProcess->readStdout());
	if ( this->GlobalConfig->VpncDebugLevel > 0 )
		this->GlobalConfig->appendLogEntry ( QString ( "[vpnc err] " + ProcessMsg_connect ) , GlobalConfig->error);


	if ( ProcessMsg_connect.find( "AUTHENTICATION_FAILED", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Authentication failed (%1)!" ).arg(i18n("group password") ));
		GlobalConfig->appendLogEntry(i18n( "Authentication failed (%1)!" ).arg(i18n("group password") ) ,GlobalConfig->error);
		//abort = true;
		AuthRetry=true;
		disconnect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_vpnc() ) );
		disconnect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_vpnc() ) );
		connectClicked();
	}
	if ( ProcessMsg_connect.find( "authentication unsuccessful", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Authentication failed (%1)!" ).arg(i18n("user password")) );
		GlobalConfig->appendLogEntry( i18n( "Authentication failed (%1)!" ).arg(i18n("user password")) ,GlobalConfig->error);
		//abort = true;
		AuthRetry=true;
		disconnect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_vpnc() ) );
		disconnect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_vpnc() ) );
		connectClicked();
	}

	// no ip for gateway
	if ( ProcessMsg_connect.find( "vpnc: unknown host `<Replace with your gateway IP address>' ", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "You have to enter a IP address for the remote gateway!" ) );
		GlobalConfig->appendLogEntry( i18n( "You have to enter a IP address for the remote gateway!" )  ,GlobalConfig->error);
		abort = true;
	}

	// no answer
	if ( ProcessMsg_connect.find( "no response from target", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "No response from VPN server" ) );
		GlobalConfig->appendLogEntry(i18n( "No response from VPN server" ) ,GlobalConfig->error);
		abort = true;
	}

	// initalizing tunnel interface failed
	if ( ProcessMsg_connect.find( "can't initialise tunnel interface", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Tunnel interface can't be initalized" ) );
		GlobalConfig->appendLogEntry(i18n( "Tunnel interface can't be initalized" ) ,GlobalConfig->error);
		abort = true;
		doContinue=false;
	}


	// /dev/net/tun doesnt exist
	if ( ProcessMsg_connect.find( "can't open /dev/net/tun", 0, FALSE ) > -1 )
		if (doContinue)
		{
			KMessageBox::error( this, i18n( "Device file \"%1\" can't be opened" ).arg("/dev/net/tun") );
			GlobalConfig->appendLogEntry(i18n( "Device file \"%1\" can't be opened" ).arg("/dev/net/tun")  ,GlobalConfig->error);
			abort = true;
		}

	// host unknown
	if ( ProcessMsg_connect.find( "unknown host" , 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Host unknown" ) );
		GlobalConfig->appendLogEntry(i18n( "Host unknown" )  ,GlobalConfig->error);
		abort = true;
	}

	//socket creation failed
	if ( ProcessMsg_connect.find( "making socket", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Socket creation failed" ) );
		GlobalConfig->appendLogEntry(i18n( "Socket creation failed" ) ,GlobalConfig->error);
		abort = true;
	}


	// binding to port failed
	if ( ProcessMsg_connect.find( "binding to port", 0 , FALSE ) > -1 )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Binding to port failed. Another vpnc is running, terminate it and try reconnect ." ), GlobalConfig->debug );

		QFile oldpidfile( tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getName() + ".pid" );
		if (oldpidfile.exists())
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "Old pid file found: %1" ).arg(oldpidfile.name()), GlobalConfig->debug );
			QTextStream pidFileStream( &oldpidfile );
			QString Vpnc_pid = "";
			if ( oldpidfile.open( IO_ReadOnly ) )
			{
				Vpnc_pid = pidFileStream.readLine();
				oldpidfile.close();
			}
			QProcess killvpncprocess(this);
			if ( !Vpnc_pid.isEmpty() )
			{

				if ( GlobalConfig->VpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Vpnc pid file contains a pid: %1, try to terminate the process with this pid." ).arg( Vpnc_pid ) , GlobalConfig->debug);
				killvpncprocess.addArgument(GlobalConfig->pathToKill);
				killvpncprocess.addArgument("-3");
				killvpncprocess.addArgument(Vpnc_pid);
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "No vpnc pid file found, using \"killall\" for killing vpnc." ), GlobalConfig->debug );
				killvpncprocess.addArgument("-3");

			}

			killvpncprocess.addArgument("vpnc");

			if (!killvpncprocess.start())
				GlobalConfig->appendLogEntry( i18n( "%1 could not be killed." ).arg("vpnc") ,GlobalConfig->error);

			while (killvpncprocess.isRunning())
				parent->processEvents();
		}
		else
		{
			//kill vpnc
			QProcess killvpncprocess(this);
			killvpncprocess.addArgument(GlobalConfig->pathToKillall);
			killvpncprocess.addArgument("vpnc");

			if (!killvpncprocess.start())
				GlobalConfig->appendLogEntry( i18n( "%1 could not be killed." ).arg("vpnc") ,GlobalConfig->error);

			while (killvpncprocess.isRunning())
				parent->processEvents();

			disconnectClicked();
			connectClicked();
		}

		VpncDisconnectScript = tmpPath + "vpnc-disconnect." + GlobalConfig->currentProfile->getID() + ".sh";

		QString OldDefaultroute="";
		QString oldProfileName="";

		QDir tmpDir(tmpPath);

		QStringList lst = tmpDir.entryList( "default-route.*" );
		if (!lst.isEmpty())
		{
			OldDefaultroute = lst.first(); // default-route.<id>

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "Old defaultroute file found: %1" ).arg(OldDefaultroute), GlobalConfig->debug );


			QFile file( VpncDisconnectScript );
			QTextStream stream( &file );
			if ( file.open( IO_WriteOnly ) )
			{
				//     stream << "#!/bin/bash\n";
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "\n";
				stream << "ip route del default > /dev/null 2>&1\n";
				stream << "ip route add $(cat \"" + OldDefaultroute + "\")\n";
				//stream << "ip route del $(cat \"" + VpncGateway + "\")\n";

				stream << "if [ -s \"$dnsdev\" ] && [ -e /sbin/resolvconf ] ; then\n";
				stream << "sbin/resolvconf -d `cat $dnsdev`\n";
				oldProfileName=OldDefaultroute.section('/',-2,-1); // /root/.kde/share/apps/kvpnc/default-route.<name> -> <name>
				if (!oldProfileName.isEmpty() &&QFile("/etc/resolv.conf.before.kvpnc."+oldProfileName).exists() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry( i18n( "Old resolv.conf file found, restore it." ), GlobalConfig->debug );

					stream << "else\n";
					stream << "	mv /etc/resolv.conf.before.kvpnc."+oldProfileName+" /etc/resolv.conf\n";
				}
				stream << "fi\n";

				stream << "ip route flush cache\n";
			}
			file.close();

			DisconnectProcess = new QProcess ();
			DisconnectProcess->addArgument( "/bin/sh" );
			DisconnectProcess->addArgument( VpncDisconnectScript );

			connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
			connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );

			if ( !DisconnectProcess->start() )
			{
				KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "vpnc_disconnect" ) );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( i18n( "Disconnect script started." ), GlobalConfig->debug );
			}
			setGuiStatus(disconnected);
			connectionEnded();
		}

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Trying reconnect..." ), GlobalConfig->debug );

		connectClicked();

		// 		KMessageBox::error( this, i18n( "Port binding failed" ) );
		// 		GlobalConfig->appendLogEntry(i18n( "Port binding failed" ) ,GlobalConfig->error);
		// 		abort = true;
	}


	if ( ProcessMsg_connect.find( "Network is unreachable", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "No network reachable" ) );
		GlobalConfig->appendLogEntry( i18n( "No network reachable" ) ,GlobalConfig->error);
		terminateConnection ( ConnectProcess );
	}

	if ( ProcessMsg_connect.find( "vpnc found running", 0 , FALSE ) > -1 )
	{
		//KMessageBox::sorry( this, i18n( "vpnc is already running, kill it manually" ) );
		//terminateConnection ( ConnectProcess );
		if ( GlobalConfig->KvpncDebugLevel > 0 )
		{
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Vpnc found running, killing it...\n" ) , GlobalConfig->debug);
		}
		disconnectClicked();
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Trying again...\n" ), GlobalConfig->debug );
		connectClicked();
	}

	if ( abort )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "There is a reason for stop connecting, terminating \"%1\" process." ).arg("vpnc") , GlobalConfig->debug);
		terminateConnection ( ConnectProcess );
	}

	// }
}

void KVpnc::readFromStdout_vpnc()
{
	//mw->DebugOutput->append( "readFromStdout_vpnc!\n" );

	//while ( ConnectProcess->canReadLineStdout() ) {
	// ProcessMsg_connect = ConnectProcess->readLineStdout();
	ProcessMsg_connect = QString( ConnectProcess->readStdout() );
	if ( !ProcessMsg_connect.isEmpty() )
		//    GlobalConfig->appendLogEntry ( ProcessMsg_connect + "\n", GlobalConfig->debug );
		if (GlobalConfig->VpncDebugLevel > 0)
			GlobalConfig->appendLogEntry ( QString("[vpnc] ")+ProcessMsg_connect , GlobalConfig->debug);


	if ( ProcessMsg_connect.find( "got address", 0, FALSE ) > -1 )
	{
		// "got address 194.95.192.28" => "194.95.192.28"
		QString ipline="";
		for (int i=0;i<5;i++)
		{
			ipline = ProcessMsg_connect.section('\n',i,i);
			if ( ipline.find( "got address", 0, FALSE ) > -1 )
			{
				//mw->DebugOutput->append(QString("line: "+ipline));
				//TunnelInterfaceIP = ipline.section(' ',2,2);
				NetworkInterface iface(GlobalConfig,parent);
				TunnelInterfaceIP = iface.getInterfaceIP( "tun0" ); // FIXME make it dynamiclly
				if (GlobalConfig->VpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry( "[vpnc] "+i18n( "Tunnel IP:" ).arg(TunnelInterfaceIP) , GlobalConfig->debug);
				break;
			}
		}
	}

	bool connectSuccess = false;
	if ( ProcessMsg_connect.find( "started in background", 0, FALSE ) > -1 )
		connectSuccess = true;

	if ( ProcessMsg_connect.find( "started in foreground", 0, FALSE ) > -1 )
		connectSuccess = true;

	// success
	// background -> normal but no check if running :(
	// foreground -> stays in foreground and we can test if running :)
	if ( connectSuccess )
	{

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( "[vpnc] "+i18n( "Connection established." ), GlobalConfig->debug );

		connectionTime.restart();
		uint duration = connectionTime.elapsed();

		sec = hour = min = 0;

		GlobalConfig->status = GlobalConfig->connected;
		timer.stop();

		connectionTime.start();
		connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		durationTimer.start( 1000, FALSE );
		setGuiStatus(connected);
		connectSuccess = false;

		NetworkInterface iface(GlobalConfig,parent);
		if (iface.interfaceExist( "tun0" ))
		{
			// 			TunnelInterfaceIP = iface.getInterfaceIP( "tun0" ); // FIXME make it dynamiclly
			if (GlobalConfig->VpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( "[vpnc] "+i18n( "Tunnel IP:" ).arg(TunnelInterfaceIP) , GlobalConfig->debug);
		}

		if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
			executeCommandAfterConnect();

		if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes()  && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
			addAdditionalNetworkRoutes();

		if ( GlobalConfig->currentProfile->getUseConnectionStatusCheck())
		{
			startConnectionStatusCheck();
		}
	}

	//ProcessMsg_connect = QString(ConnectProcess->readStdout());

	if ( this->GlobalConfig->KvpncDebugLevel > 0 )
		this->GlobalConfig->appendLogEntry ( QString ( "raw stdout: " + ProcessMsg_connect ), GlobalConfig->debug );

	if ( deviceaddrstr2addr )
	{
		deviceaddrstr = ProcessMsg_connect;
		//    this->GlobalConfig->appendLogEntry ( QString ( "deviceaddrstr: " + deviceaddrstr ),GlobalConfig->info );
		deviceaddr = "addr: " + QString( deviceaddrstr.simplifyWhiteSpace ().section( ' ', 1, 1 ) ).section( ':', 1, 1 );
		//    this->GlobalConfig->appendLogEntry ( deviceaddr,GlobalConfig->info ); //
		deviceaddrstr2addr = false;
		//disconnect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_vpnc() ) );
		//disconnect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_vpnc() ) );
	}

	// requesting group password
	if ( ProcessMsg_connect.find( "Enter IPSec secret", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Group password requested, send it...\n" ), GlobalConfig->debug );



		QString GrpPassStr="";
		if ( !GlobalConfig->currentProfile->getAllowEmptyGroupPassword() )
		{
			if (!GlobalConfig->currentProfile->getSavePsk() || AuthRetry)
				GrpPassStr = TmpGroupPassword;
			else
				GrpPassStr = GlobalConfig->currentProfile->getPreSharedKey();
		}

		ConnectProcess->writeToStdin( GrpPassStr );
		ConnectProcess->writeToStdin( "\n" );

	}

	// requesting password
	if ( ProcessMsg_connect.find( "Enter password", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "User password requested, send it...\n" ), GlobalConfig->debug );

		QString UserPassStr="";
		if (!GlobalConfig->currentProfile->getSaveUserPassword() || AuthRetry)
			UserPassStr = TmpPassword;
		else
			UserPassStr = GlobalConfig->currentProfile->getUserPassword();

		ConnectProcess->writeToStdin( UserPassStr );
		ConnectProcess->writeToStdin( "\n" );
	}

	// requesting gatway
	if ( ProcessMsg_connect.find( "Enter IPSec gateway address", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "IPSec gateway address requested, send it...\n" ), GlobalConfig->debug );
		//QString GatewayStr = GlobalConfig->currentProfile->getGateway();
		QString GatewayStr = TmpGatewayIP;
		ConnectProcess->writeToStdin( GatewayStr );
		ConnectProcess->writeToStdin( "\n" );
	}

	// requesting IPSec ID
	if ( ProcessMsg_connect.find( "Enter IPSec ID", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "IPSec ID requested, send it...\n" ), GlobalConfig->debug );
		QString IpsecIDStr = GlobalConfig->currentProfile->getID();
		ConnectProcess->writeToStdin( IpsecIDStr );
		ConnectProcess->writeToStdin( "\n" );
	}

	// requesting username
	if ( ProcessMsg_connect.find( "Enter username", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Username requested, send it...\n" ), GlobalConfig->debug );

		QString UsernameStr;
		if (!GlobalConfig->currentProfile->getDontSaveUsername())
			UsernameStr= GlobalConfig->currentProfile->getUserName();
		else
			UsernameStr = TmpUsername;
		ConnectProcess->writeToStdin( "\n" );
	}

	if ( ProcessMsg_connect.find( "vpnc found running", 0 , FALSE ) > -1 )
	{
		//KMessageBox::sorry( this, i18n( "vpnc is already running, kill it manually" ) );
		//terminateConnection ( ConnectProcess );
		if ( GlobalConfig->VpncDebugLevel > 0 )
		{
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Vpnc found running, killing it...\n" ), GlobalConfig->debug );
		}
		disconnectClicked();
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[vpnc] "+i18n( "Trying again...\n" ), GlobalConfig->debug );
		connectClicked();
	}

	slotStatusMsg ( i18n( "Ready." ), ID_STATUS_MSG );
	// }
}

void KVpnc::readFromStderr_disconnect()
{

	ProcessMsg_disconnect = DisconnectProcess->readLineStderr();
	if ( !ProcessMsg_disconnect.isEmpty() )
		GlobalConfig->appendLogEntry ( "[vpnc err] "+ProcessMsg_disconnect + "\n", GlobalConfig->error );
}

void KVpnc::readFromStdout_disconnect()
{
	ProcessMsg_disconnect = DisconnectProcess->readLineStdout();

	if ( !ProcessMsg_disconnect.isEmpty() )
		GlobalConfig->appendLogEntry ( QString("[vpnc] ")+ProcessMsg_disconnect + "\n",GlobalConfig->info );
}

void KVpnc::readFromStdout_racoon()
{
	//while ( ConnectProcess->canReadLineStdout() ) {
	//  ProcessMsg_connect = ConnectProcess->readLineStdout();
	QString ProcessMsg_connect = QString( ConnectProcess->readStdout() );

	if ( pingtest )
	{
		//   if ( GlobalConfig->KvpncDebugLevel > 0 )
		//    mw->DebugOutput->append( "raw out (pingtest): " + ProcessMsg_connect );

		if ( ProcessMsg_connect.find( "time=", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[ping] "+ProcessMsg_connect, GlobalConfig->success );
		}
		else if ( ProcessMsg_connect.find( "100 % packet loss", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[ping err] "+ProcessMsg_connect, GlobalConfig->error );
		}
		else
		{
			if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
			{
				KMessageBox::error( this, i18n( "Binding interface failed!" ) );
				GlobalConfig->appendLogEntry(i18n( "Binding interface failed!" ) ,GlobalConfig->error);
			}
			if ( ProcessMsg_connect.find( "Destination Host Unreachable", 0, FALSE ) > -1 )
			{
				KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
				GlobalConfig->appendLogEntry( i18n( "Destination host is unreachable!" ) ,GlobalConfig->error);
			}


			GlobalConfig->appendLogEntry( "[ping] " + ProcessMsg_connect,GlobalConfig->info );
		}
	}

	// normal
	else
	{
		GlobalConfig->appendLogEntry( "[racoon] "+ProcessMsg_connect, GlobalConfig->success );
	}
	//}
}

void KVpnc::readFromStderr_racoon()
{
	// while ( ConnectProcess->canReadLineStderr() ) {
	//  ProcessMsg_connect = ConnectProcess->readLineStderr();
	QString ProcessMsg_connect = QString( ConnectProcess->readStderr() );
	GlobalConfig->appendLogEntry( "[racoon err] " + ProcessMsg_connect, GlobalConfig->error );

	if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Binding interface failed!" ) );
		GlobalConfig->appendLogEntry(i18n( "Binding interface failed!" ) ,GlobalConfig->error);
	}

	if ( ProcessMsg_connect.find( "no default route, %defaultroute cannot cope!!!", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "No default route found, nesessary for freeswan!" ) );
		GlobalConfig->appendLogEntry(i18n( "No default route found, nesessary for freeswan!" )  ,GlobalConfig->error);
		disconnectClicked();
	}

	if ( ProcessMsg_connect.find( "SIOCADDRT: File exists", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[racoon err] "+i18n( "setting route failed: route still exists" ), GlobalConfig->error );
	}

	if ( ProcessMsg_connect.find( "SIOCDELRT: File exists", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[racoon err] "+i18n( "deleting route failed: route dont exists" ), GlobalConfig->error );
	}

	if ( ProcessMsg_connect.find( "fatal parse failure", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Error in generated configuration file for \%1\", please contact KVpnc team." ).arg("raccon") );
		GlobalConfig->appendLogEntry(i18n( "Error in generated configuration file for \%1\", please contact KVpnc team." ).arg("raccon")  ,GlobalConfig->error);
		disconnectClicked();
	}

	if ( ProcessMsg_connect.find( "failed to bind to address", 0, FALSE ) > -1 )
	{
		// FIXME kill and retry like vpnc
		KMessageBox::error( this, i18n( "Could not bind to listen socket (still %1 running?)" ).arg("raccon") );
		GlobalConfig->appendLogEntry( i18n( "Could not bind to listen socket (still %1 running?)" ).arg("raccon") ,GlobalConfig->error);
		disconnectClicked();
	}

	if ( pingtest )
	{
		// mw->DebugOutput->append( "raw err (pingtest): " + ProcessMsg_connect );
		if ( ProcessMsg_connect.find( "time=", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[ping] " + ProcessMsg_connect, GlobalConfig->success );
		}
		else if ( ProcessMsg_connect.find( "100 % packet loss", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[ping err] " + ProcessMsg_connect, GlobalConfig->error );
		}
		else
		{
			if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
			{
				KMessageBox::error( this, i18n( "Binding interface failed!" ) );
				GlobalConfig->appendLogEntry(i18n( "Binding interface failed!" ) ,GlobalConfig->error);
			}
			if ( ProcessMsg_connect.find( "Destination Host Unreachable", 0, FALSE ) > -1 )
			{
				KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
				GlobalConfig->appendLogEntry(i18n( "Destination host is unreachable!" ) ,GlobalConfig->error);
			}
		}
	}
}

void KVpnc::readFromStdout_freeswan()
{
	//while ( ConnectProcess->canReadLineStdout() ) {
	//  ProcessMsg_connect = ConnectProcess->readLineStdout();
	QString ProcessMsg_connect = QString( ConnectProcess->readStdout() );

	bool NormalMsg=true;

	if ( pingtest )
	{
		//   if ( GlobalConfig->KvpncDebugLevel > 0 )
		//    mw->DebugOutput->append( "raw out (pingtest): " + ProcessMsg_connect );

		if ( ProcessMsg_connect.find( "time=", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[ping] "+ProcessMsg_connect, GlobalConfig->success );
		}
		else if ( ProcessMsg_connect.find( "100 % packet loss", 0, FALSE ) > -1 )
		{
			NormalMsg=false;
			GlobalConfig->appendLogEntry( "[ping err] "+ProcessMsg_connect, GlobalConfig->error );
		}
		else
		{
			if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
			{
				NormalMsg=false;
				KMessageBox::error( this, i18n( "Binding interface failed!" ) );
				GlobalConfig->appendLogEntry( i18n( "Binding interface failed!" ),GlobalConfig->error);
			}
			if ( ProcessMsg_connect.find( "Destination Host Unreachable", 0, FALSE ) > -1 )
			{
				NormalMsg=false;
				KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
				GlobalConfig->appendLogEntry( i18n( "Destination host is unreachable!" ),GlobalConfig->error);
			}

		}
	}

	if ( ProcessMsg_connect.find( "IPsec apparently already running", 0, FALSE ) > -1 )
	{
		NormalMsg=false;
		GlobalConfig->appendLogEntry( i18n("IPsec seems to be already running"), GlobalConfig->error );
		GlobalConfig->appendLogEntry( i18n("Trying to kill %1 and restart it.").arg("FreeSWAN"), GlobalConfig->info );
		disconnectClicked();
		setGuiStatus(disconnected);

		KillProcess = new QProcess ( this );
		KillProcess->addArgument( GlobalConfig->pathToKillall );
		KillProcess->addArgument( "_plutorun" );

		// 			connect( KillProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_freeswan() ) );
		// 			connect( KillProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_freeswan() ) );

		if ( !KillProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "killall _plutorun" ) );
			GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "killall _plutorun" ) ,GlobalConfig->error);
		}
		else
		{
			while (KillProcess->isRunning())
				GlobalConfig->appPointer->processEvents();

			connectClicked();
		}
	}

	// normal
	if (NormalMsg)
	{
		GlobalConfig->appendLogEntry( "[freeswan] " + ProcessMsg_connect,GlobalConfig->info );
		// 		if (GlobalConfig->KvpncDebugLevel > 0)
		// 			GlobalConfig->appendLogEntry( "out: " + ProcessMsg_connect, GlobalConfig->debug );
	}

	//}
}

void KVpnc::readFromStderr_freeswan()
{
	// while ( ConnectProcess->canReadLineStderr() ) {
	//  ProcessMsg_connect = ConnectProcess->readLineStderr();
	QString ProcessMsg_connect = QString( ConnectProcess->readStderr() );


	if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Binding interface failed!" ) );
		GlobalConfig->appendLogEntry( i18n( "Binding interface failed!" ),GlobalConfig->error);
	}
	else if ( ProcessMsg_connect.find( "no default route, %defaultroute cannot cope!!!", 0, FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "No default route found, nesessary for freeswan!" ) );
		GlobalConfig->appendLogEntry(  i18n( "No default route found, nesessary for freeswan!" ) ,GlobalConfig->error);
		disconnectClicked();
	}
	else if ( ProcessMsg_connect.find( "SIOCADDRT: File exists", 0, FALSE ) > -1 )
	{
		// 		GlobalConfig->appendLogEntry( "[freeswan err] "+i18n( "setting route failed: route still exists" ), GlobalConfig->error );
	}
	else if ( ProcessMsg_connect.find( "SIOCDELRT: File exists", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[freeswan err] "+i18n( "deleting route failed: route dont exists" ), GlobalConfig->error );
	}
	else if ( ProcessMsg_connect.find( "we only support version 2", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[freeswan err] "+i18n( "only freeswan version 1.x is supported " ), GlobalConfig->error );
		disconnectClicked();
	}
	else if ( pingtest )
	{
		// mw->DebugOutput->append( "raw err (pingtest): " + ProcessMsg_connect );
		if ( ProcessMsg_connect.find( "time=", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[ping] " + ProcessMsg_connect, GlobalConfig->success );
		}
		else if ( ProcessMsg_connect.find( "100 % packet loss", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[ping err] " + ProcessMsg_connect, GlobalConfig->error );
		}
		else
		{
			if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
			{
				KMessageBox::error( this, i18n( "Binding interface failed!" ) );
				GlobalConfig->appendLogEntry(i18n( "Binding interface failed!" ) ,GlobalConfig->error);
			}
			if ( ProcessMsg_connect.find( "Destination Host Unreachable", 0, FALSE ) > -1 )
			{
				KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
				GlobalConfig->appendLogEntry( i18n( "Binding interface failed!" ) ,GlobalConfig->error);
			}
		}
	}
	else
	{
		GlobalConfig->appendLogEntry( "[freeswan err] " + ProcessMsg_connect, GlobalConfig->error );
	}
}

void KVpnc::readFromStdout_tail_racoon()
{
	//	QString ProcessMsg_connect = QString( TailProcess->readStdout() );
	while ( TailProcess->canReadLineStdout() )
	{
		QString ProcessMsg_connect = TailProcess->readLineStdout()+"\n";
		//        QString ProcessMsg_connect = TailProcess->readStdout();
		bool abort = false;

		// binding to port failed
		if ( ProcessMsg_connect.find( "ERROR: failed to bind to address", 0 , FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "Port binding failed" ) );
			GlobalConfig->appendLogEntry(i18n( "Port binding failed" ) ,GlobalConfig->error);

			//TODO
			// killall racoon

			abort = true;
		}


		//     if ( ProcessMsg_connect.find( "IPsec-SA established", 0 , FALSE ) > -1 ) {
		//         if ( GlobalConfig->KvpncDebugLevel > 0 )
		//             GlobalConfig->appendLogEntry( "[racoon] "+i18n( "Connection established." ), GlobalConfig->debug );
		//
		//         //connectionTime.restart();
		//         //uint duration = connectionTime.elapsed();
		//
		//         sec = hour = min = 0;
		//
		//         GlobalConfig->status = GlobalConfig->connected;
		//
		//         connectionTime.start();
		//         connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		//         durationTimer.start( 1000, FALSE );
		//         setGuiStatus(connected);
		//
		//
		//         if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
		//             executeCommandAfterConnect();
		//
		//         if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes()  && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
		//             addAdditionalNetworkRoutes();



		//      }

		if ( GlobalConfig->KvpncDebugLevel > 0 )

		{
			GlobalConfig->appendLogEntry( "[racoon] "+ProcessMsg_connect, GlobalConfig->debug );
		}
		if ( abort )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "There is a reason for stop connecting, terminating \"%1\" process." ).arg("vpnc") , GlobalConfig->debug);
			terminateConnection ( ConnectProcess );
		}

	}
}

void KVpnc::readFromStderr_tail_racoon()
{
	//	QString ProcessMsg_connect = QString( TailProcess->readStderr() );
	while ( TailProcess->canReadLineStderr() )
	{
		QString ProcessMsg_connect = TailProcess->readLineStderr()+"\n";
		//QString ProcessMsg_connect = TailProcess->readStderr();
		//		if ( GlobalConfig->KvpncDebugLevel > 0 )
		{
			GlobalConfig->appendLogEntry( "[racoon err] "  + ProcessMsg_connect, GlobalConfig->error );
		}
	}
}

void KVpnc::readFromStdout_pptp()
{
	ProcessMsg_connect = QString( PptpProcess->readStdout() );
	//if ( !ProcessMsg_connect.isEmpty() )
	GlobalConfig->appendLogEntry ( "[pppd]"+ProcessMsg_connect,GlobalConfig->info );

	bool abort = false;


	if ( ProcessMsg_connect.find( "could not find module", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Module not found." ) );
		GlobalConfig->appendLogEntry(i18n( "Module not found." ) ,GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "Connection terminated.", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Connection has been terminated." ) );
		abort = true;
	}

	if ( ProcessMsg_connect.find( "No route to host", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "No route to host." ) );
		GlobalConfig->appendLogEntry( i18n( "No route to host." ),GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "authentication failed", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Authentication has been failed." ) );
		GlobalConfig->appendLogEntry(i18n( "Authentication has been failed." ) ,GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "peer refused to authenticate", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "The peer refused to authenticate." ) );
		GlobalConfig->appendLogEntry(i18n( "The peer refused to authenticate." ) ,GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "Call manager exited with error", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Call manager exited with a error." ) );
		abort = true;
	}

	if ( ProcessMsg_connect.find( "Input/output error", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Input/output error" ) );
		GlobalConfig->appendLogEntry( i18n( "Input/output error" ) ,GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "Using interface", 0 , FALSE ) > -1 )
	{
		QString dev = ProcessMsg_connect.right(ProcessMsg_connect.length()-16);
		if ( GlobalConfig->PppdDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "device found: %1" ).arg(dev), GlobalConfig->debug );
		GlobalConfig->currentProfile->setNetworkDevice(dev);
		PppdDevice = dev;

		NetworkInterface iface(GlobalConfig,parent);
		TunnelInterfaceIP = iface.getInterfaceIP( dev );
		if (GlobalConfig->VpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( "[pppd] "+i18n( "Tunnel IP:" ).arg(TunnelInterfaceIP) , GlobalConfig->debug);

		abort = false;
	}

	if ( ProcessMsg_connect.find( "tcflush failed: Bad file descriptor", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Sending data has failed. Connection was terminated." ) );
		GlobalConfig->appendLogEntry(i18n( "Sending data has failed. Connection was terminated." )  ,GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "primary DNS address", 0 , FALSE ) > -1 )
	{
		// example: primary DNS address 132.210.*.2 secondary DNS address 132.210.**.2
		bool got2dns=false;
		QString DNS1= ProcessMsg_connect.section(' ',3,3);
		QString DNS2= ProcessMsg_connect.section(' ',7,7);

		got2dns=Utils(GlobalConfig).isValidIPv4Address(DNS2);

		if (got2dns)
		{
			TmpDns1=DNS1;
			TmpDns2=DNS2;
		}
		else
			TmpDns1=DNS2;

		if (GlobalConfig->KvpncDebugLevel > 0 )
			if (got2dns)
				GlobalConfig->appendLogEntry(i18n( "Got DNS1: %1, DNS2: %2" ).arg(DNS1).arg(DNS2)  ,GlobalConfig->debug);
			else
				GlobalConfig->appendLogEntry(i18n( "Got DNS1: %1" ).arg(DNS1)  ,GlobalConfig->debug);
		abort = false;
	}




	if ( abort )
	{
		if ( GlobalConfig->PppdDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "There is a reason for stop connecting, terminating \"%1\" process." ).arg("pppd") , GlobalConfig->debug);
		//terminateConnection ( PptpProcess );
		//disconnectClicked();
		GlobalConfig->status = GlobalConfig->disconnected;
		setGuiStatus(disconnected);

		// remove kvpnc entries from chap-secerets
		QFile ChapSecretsFile ( "/etc/ppp/chap-secrets" );
		QTextStream stream( &ChapSecretsFile );
		if ( ChapSecretsFile.open( IO_ReadOnly ) )
		{
			QString line = "";
			QString chapsecret_content="";
			bool kvpnc_start_marker_found=false;
			while ( !stream.atEnd() )
			{
				line = stream.readLine(); // line of text excluding '\n'
				if ( line.contains( "# +++" ) )
					kvpnc_start_marker_found=true;
				if ( line.contains( "# ---" ) && kvpnc_start_marker_found )
					kvpnc_start_marker_found=false;

				if (!kvpnc_start_marker_found && !line.contains( "# ---" ) )
				{
					chapsecret_content+=line;
					chapsecret_content+='\n';
				}
			}
			ChapSecretsFile.close();
			if ( ChapSecretsFile.remove() )
			{
				GlobalConfig->appendLogEntry( i18n( "File %1 sucessfully removed" ).arg("/etc/ppp/chap-secrets"), GlobalConfig->info );
				ChapSecretsFile.open (IO_WriteOnly);
				stream.setDevice(&ChapSecretsFile);
				stream << chapsecret_content;
				ChapSecretsFile.close();
			}
			else
				GlobalConfig->appendLogEntry( i18n( "File %1 remove failed" ).arg("/etc/ppp/chap-secrets"), GlobalConfig->error );
		}
	}


	bool connectSuccess = false;
	if ( ProcessMsg_connect.find( "remote IP address", 0, FALSE ) > -1 )
		connectSuccess = true;

	// success
	if ( connectSuccess )
	{

		if ( GlobalConfig->PppdDebugLevel > 0 )
			GlobalConfig->appendLogEntry( "[pppd]" +i18n( "Connection established." ), GlobalConfig->debug );

		//connectionTime.restart();
		//uint duration = connectionTime.elapsed();

		sec = hour = min = 0;

		GlobalConfig->status = GlobalConfig->connected;

		connectionTime.start();
		connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		durationTimer.start( 1000, FALSE );
		setGuiStatus(connected);
		connectSuccess = false;

		QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
		QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
		QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;

		// write pppd.<profile>.up
		QFile upfile( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up" );
		QTextStream upstream( &upfile );
		if ( upfile.open( IO_WriteOnly ) )
		{
			upstream << "# generated by kvpnc. Do not edit it." << "\n";
			upstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
			upstream << "#!/bin/sh" << "\n";
			if (!TmpDns1.isEmpty() && !TmpDns2.isEmpty())
			{
				upstream << "echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
				upstream << "echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";
				upstream << "echo \"nameserver " << TmpDns1 << "\" >> /etc/resolv.conf" << "\n";
				if (!TmpDns2.isEmpty())
					upstream << "echo \"nameserver " << TmpDns2 << "\" >> /etc/resolv.conf" << "\n";
			}
		}
		upfile.close();

		QProcess *pppdUpProcess= new QProcess(this);
		pppdUpProcess->addArgument("/bin/sh");
		pppdUpProcess->addArgument(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up");

		if ( !pppdUpProcess->start() )
		{
			KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "PppdUpScript" ) );
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("PppdUpScript") ,GlobalConfig->info);
			while(pppdUpProcess->isRunning())
				parent->QApplication::processEvents();
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" finished." ).arg("PppdUpScript"),GlobalConfig->info );
		}

		if (!RemoteNet.isEmpty())
			doRoutePptp();
		sleep(1);
		if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
			executeCommandAfterConnect();

		if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
			addAdditionalNetworkRoutes();

		if ( GlobalConfig->currentProfile->getUseConnectionStatusCheck())
		{
			startConnectionStatusCheck();
		}
	}
}

void KVpnc::readFromStderr_pptp()
{
	ProcessMsg_connect = QString( PptpProcess->readStderr() );
	//if ( !ProcessMsg_connect.isEmpty() )
	GlobalConfig->appendLogEntry ( "[pppd err] "+ProcessMsg_connect, GlobalConfig->error );

	bool abort = false;

	if ( ProcessMsg_connect.find( "authentication failed", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Authentication has been failed." ) );
		GlobalConfig->appendLogEntry(i18n( "Authentication has been failed." )  ,GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "could not find module", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Module not found." ) );
		GlobalConfig->appendLogEntry(  i18n( "Module not found." ),GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "Connection terminated.", 0 , FALSE ) > -1 )
	{
		//   KMessageBox::error( this, i18n( "Connection has been terminated." ) );
		abort = true;
	}

	if ( ProcessMsg_connect.find( "tcflush failed: Bad file descriptor", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Sending data has failed. Connection was terminated." ) );
		GlobalConfig->appendLogEntry( i18n( "Sending data has failed. Connection was terminated." ),GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "MPPE required, but kernel has no support", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "MPPE required, but kernel has no support. Please use a kernel with mppe support." ) );
		GlobalConfig->appendLogEntry( i18n( "MPPE required, but kernel has no support. Please use a kernel with mppe support." ) ,GlobalConfig->error);
		abort = true;
	}

	if ( ProcessMsg_connect.find( "unrecognized option 'mppe'", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "MPPE required, but pppd has no MPPE support. Please install a pppd with MPPE support." ) );
		GlobalConfig->appendLogEntry( i18n( "MPPE required, but pppd has no support. Please install a pppd with MPPE support." ) ,GlobalConfig->error);
		abort = true;
	}


	if ( ProcessMsg_connect.find( "Input/output error", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Input/output error" ) );
		GlobalConfig->appendLogEntry( i18n( "Input/output error" ) ,GlobalConfig->error);
		abort = true;
	}


	if ( abort )
	{
		if ( GlobalConfig->PppdDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "There is a reason for stop connecting, terminating \"%1\" process." ).arg("pppd") , GlobalConfig->debug);
		//terminateConnection ( PptpProcess );
		disconnectClicked();
		GlobalConfig->status = GlobalConfig->disconnected;
		setGuiStatus(disconnected);
	}
}

void KVpnc::readOutput_openvpn()
{

	QString ProcessMsg="";
	bool stderr=false;

	// 	while (OpenvpnProcess->canReadLineStdout())
	// 	{
	// 		ProcessMsg = QString( OpenvpnProcess->readLineStdout() );


	ProcessMsg = QString( OpenvpnProcess->readStdout() );

	// 	if (!ProcessMsg.isEmpty() )
	{

		// 		GlobalConfig->appendLogEntry ( "stdout openvpn: "+ProcessMsg, GlobalConfig->debug );
	}
	// 	else
	// 	{
	// 		stderr=true;
	//   	ProcessMsg = QString( OpenvpnProcess->readStderr() );
	// 		GlobalConfig->appendLogEntry ( "stderr openvpn: "+ProcessMsg, GlobalConfig->debug );
	// 	}


	if ( !ProcessMsg.find( "refused", 0 , FALSE ) > -1 && !stderr)
		GlobalConfig->appendLogEntry ( "[openvpn] "+ProcessMsg,GlobalConfig->info );
	else
		GlobalConfig->appendLogEntry ( "[openvpn] "+ProcessMsg, GlobalConfig->error );



	bool abort = false;

	if ( ProcessMsg.find( "Connection timed out", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Connection has been timed out. Terminate." ) );
		GlobalConfig->appendLogEntry( i18n( "Connection has been timed out. Terminate." )  ,GlobalConfig->error);
		abort = true;
	}


	else if ( ProcessMsg.find( "AUTH: Received AUTH_FAILED", 0, FALSE ) > -1 )
	{
		AuthRetry=true;
		disconnect( OpenvpnProcess, SIGNAL( readyReadStdout() ), this, SLOT( readOutput_openvpn() ) );
		//     disconnect( OpenvpnProcess, SIGNAL( readyReadStderr() ), this, SLOT( readOutput_openvpn() ) );
		connectClicked();
		// 		KMessageBox::error( this, i18n( "Authentication failed (%1)!" ).arg(i18n("user password") ));
		GlobalConfig->appendLogEntry(i18n( "Authentication failed (%1)!" ).arg(i18n("user password") ) ,GlobalConfig->error);
		// 		abort=true;
	}

	else if ( ProcessMsg.find( "Insufficient key material or header text not found", 0, FALSE ) > -1 )
	{
		AuthRetry=true;
		disconnect( OpenvpnProcess, SIGNAL( readyReadStdout() ), this, SLOT( readOutput_openvpn() ) );
		//     disconnect( OpenvpnProcess, SIGNAL( readyReadStderr() ), this, SLOT( readOutput_openvpn() ) );
		connectClicked();
		// 		KMessageBox::error( this, i18n( "Authentication failed (%1)!" ).arg(i18n("user password") ));
		GlobalConfig->appendLogEntry(i18n( "Insufficient key material or header text not found!"  ) ,GlobalConfig->error);
		abort=true;
	}

	else if ( ProcessMsg.find( "Cannot load private key file", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Auth username is empty." ) );
		GlobalConfig->appendLogEntry( i18n( "Private key file could not loaded!" ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "'dev-type' is used inconsistently, local='dev-type tun', remote='dev-type tap'", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n("Local network type is tun but remote network type is tap. This must be fixed.\nGo to OpenVPN settings and change it to %2." ).arg("tun").arg("tap"));
		GlobalConfig->appendLogEntry( i18n( "Local network type is tun but remote network type is tap. This must be fixed." ).arg("tun").arg("tap") ,GlobalConfig->error);
		abort = true;
	}


	else if ( ProcessMsg.find( "'dev-type' is used inconsistently, local='dev-type tap', remote='dev-type tun'", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n("Local network type is tap but remote network type is tun. This must be fixed.\nGo to OpenVPN settings and change it to tun." ) );
		GlobalConfig->appendLogEntry( i18n( "Local network type is tap but remote network type is tun. This must be fixed." ).arg("tap").arg("tun"),GlobalConfig->error);
		abort = true;
	}


	/*
	else if ( ProcessMsg.find( "authentication failed", 0 , FALSE ) > -1 )
	{
	 KMessageBox::error( this, i18n( "Authentication has been failed." ) );
	 abort = true;
	}
	*/

	else if ( ProcessMsg.find( "Enter Private Key Password", 0, FALSE ) > -1 )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n( "Private key password requested, send it...\n" ), GlobalConfig->debug );

		QString PrivKeyPassStr="";
		// 		if (GlobalConfig->currentProfile->getSavePsk())
		PrivKeyPassStr = GlobalConfig->currentProfile->getPrivateKeyPass();
		// 		else
		// 			PrivKeyPassStr = TmpPrivKeyPassStr;

		OpenvpnProcess->writeToStdin( PrivKeyPassStr );
		OpenvpnProcess->writeToStdin( "\n" );
		return;
	}

	else if ( ProcessMsg.find( "Enter Auth Username", 0 , FALSE ) > -1 )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n( "User name requested, send it...\n" ), GlobalConfig->debug );

		QString UsernameStr="";
		if (!GlobalConfig->currentProfile->getUserName().isEmpty())
			UsernameStr= GlobalConfig->currentProfile->getUserName();
		else
			UsernameStr = TmpUsername;

		// 		if ( GlobalConfig->KvpncDebugLevel > 0 )
		// 			GlobalConfig->appendLogEntry ( "User name: "+UsernameStr , GlobalConfig->debug );

		OpenvpnProcess->writeToStdin( UsernameStr );
		OpenvpnProcess->writeToStdin("\n");

		return;
	}

	else if ( ProcessMsg.find( "Enter Auth Password:", 0 , FALSE ) > -1 )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n( "User password requested, send it...\n" ), GlobalConfig->debug );

		if (!GlobalConfig->currentProfile->getSaveUserPassword() && !AuthRetry)
			OpenvpnProcess->writeToStdin( GlobalConfig->currentProfile->getUserPassword() );
		else
		{
			// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
			// 				GlobalConfig->appendLogEntry ( "Pass: "+TmpPassword , GlobalConfig->debug );


			OpenvpnProcess->writeToStdin( TmpPassword );
			OpenvpnProcess->writeToStdin("\n");
		}

	}

	else if ( ProcessMsg.find( "Cannot resolve host address", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Host could not be resolved." ) );
		GlobalConfig->appendLogEntry( i18n( "Host could not be resolved." ),GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "could not find module", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Module not found." ) );
		GlobalConfig->appendLogEntry(i18n( "Module not found." ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "Socket bind failed on local address", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Binding to socket on local address failed." ) );
		GlobalConfig->appendLogEntry( i18n( "Binding to socket on local address failed." ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "No route to host", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "No route to host found." ) );
		GlobalConfig->appendLogEntry( i18n( "No route to host found." ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "Connection terminated", 0 , FALSE ) > -1 )
	{
		//   KMessageBox::error( this, i18n( "Connection has been terminated." ) );
		abort = true;
	}

	else if ( ProcessMsg.find( "Cannot open file key file", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Cannot open the preshared key file." ) );
		GlobalConfig->appendLogEntry(i18n( "Cannot open the preshared key file." )  ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "Options error", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "OpenVPN configuration error." ) );
		GlobalConfig->appendLogEntry( i18n( "OpenVPN configuration error." ),GlobalConfig->error);
		GlobalConfig->currentProfile->setDoReconnectAfterConnectionLost(false);
		abort = true;
	}

	else if ( ProcessMsg.find( "refused", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Connection to OpenVPN server was refused." ) );
		abort = false;
	}

	else if ( ProcessMsg.find( "Connection timed out", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Connection has been timed out. Terminate." ) );
		GlobalConfig->appendLogEntry(i18n( "Connection has been timed out. Terminate." ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "Cannot load certificate file", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "Certificate file (%1) could not be load. Please check path of it." ).arg(GlobalConfig->currentProfile->getX509Certificate() ));
		GlobalConfig->appendLogEntry(i18n( "Certificate file (%1) could not be load. Please check path of it." ).arg(GlobalConfig->currentProfile->getX509Certificate() ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "ifconfig failed", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n( "ifconfig has been failed." ));
		GlobalConfig->appendLogEntry(i18n( "ifconfig has been failed." ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "Auth username is empty", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Auth username is empty." ) );
		GlobalConfig->appendLogEntry( i18n( "Auth username is empty." ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "Cannot load private key file", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "Auth username is empty." ) );
		GlobalConfig->appendLogEntry( i18n( "Private key file could not loaded!" ) ,GlobalConfig->error);
		abort = true;
	}

	else if ( ProcessMsg.find( "'dev-type' is used inconsistently, local='dev-type tun', remote='dev-type tap'", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n("Local network type is %1 but remote network type is %2. This must be fixed.\nGo to OpenVPN settings and change it to %2." ).arg("tun").arg("tap"));
		GlobalConfig->appendLogEntry( i18n( "Local network type is %1 but remote network type is %2. This must be fixed." ).arg("tun").arg("tap") ,GlobalConfig->error);
		abort = true;
	}


	else if ( ProcessMsg.find( "'dev-type' is used inconsistently, local='dev-type tap', remote='dev-type tun'", 0 , FALSE ) > -1 )
	{
		KMessageBox::error( this, i18n("Local network type is %1 but remote network type is %2. This must be fixed.\nGo to OpenVPN settings and change it to %2." ).arg("tap").arg("tun") );
		GlobalConfig->appendLogEntry( i18n( "Local network type is %1 but remote network type is %2. This must be fixed." ).arg("tap").arg("tun"),GlobalConfig->error);
		abort = true;
	}

	if ( abort )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "There is a reason for stop connecting, terminating \"%1\" process." ).arg("openvpn"), GlobalConfig->debug );

		terminateConnection ( OpenvpnProcess );
		disconnectClicked();

		return;
	}

	bool connectSuccess = false;
	if ( ProcessMsg.find( "Initialization Sequence Completed", 0, FALSE ) > -1 )
		connectSuccess = true;

	QString NetworkDevice="";
	if ( ProcessMsg.find( "TUN/TAP device", 0, FALSE ) > -1 )
	{
		if ( ProcessMsg.find( "opened", 0, FALSE ) > -1 )
		{
			// TUN/TAP device tun0 opened
			GlobalConfig->appendLogEntry( "Msg: "+ProcessMsg.section(' ',-3,-2), GlobalConfig->debug );
			NetworkDevice=ProcessMsg.section(' ',-2,-2); // tun0
		}
	}

	// success
	if ( connectSuccess )
	{

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Connection established." ), GlobalConfig->debug );

		//connectionTime.restart();
		//uint duration = connectionTime.elapsed();

		sec = hour = min = 0;

		timer.stop();
		GlobalConfig->status = GlobalConfig->connected;

		connectionTime.start();
		connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		durationTimer.start( 1000, FALSE );
		setGuiStatus(connected);
		connectSuccess = false;

		NetworkInterface iface(GlobalConfig,parent);
		if (NetworkDevice.isEmpty())
		{
			if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
				TunnelInterfaceIP = iface.getInterfaceIP( "tun0" );
			else
				TunnelInterfaceIP = iface.getInterfaceIP( "tap0" );
		}
		else
			TunnelInterfaceIP = iface.getInterfaceIP( NetworkDevice );

		GlobalConfig->appendLogEntry( "[openvpn] "+i18n( "Using %1 as tunnel device." ).arg(NetworkDevice) , GlobalConfig->info);
		GlobalConfig->appendLogEntry( "[openvpn] "+i18n( "Tunnel IP:" ).arg(TunnelInterfaceIP) , GlobalConfig->info);


		if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
			executeCommandAfterConnect();

		if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
		{
			addAdditionalNetworkRoutes();
			//	GlobalConfig->appendLogEntry( i18n( "Add additional network routes..." ), GlobalConfig->debug );
		}
		else
		{
			//	GlobalConfig->appendLogEntry( i18n( "No additional routes to add." ), GlobalConfig->debug );
		}
		if ( GlobalConfig->currentProfile->getUseConnectionStatusCheck())
		{
			startConnectionStatusCheck();
		}
	}
	// }
}

void KVpnc::readFromStdout_ping()
{
	//while ( ConnectProcess->canReadLineStdout() ) {
	//ProcessMsg_connect = ConnectProcess->readLineStdout();
	ProcessMsg_connect = QString( PingProcess->readStdout() );

	//mw->DebugOutput->append( "raw out (pingtest): " + ProcessMsg_connect );

	if ( ProcessMsg_connect.find( "time=", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[ping] " + ProcessMsg_connect, GlobalConfig->success );
		KNotifyClient::event( topLevelWidget()->winId(), "ping success",i18n("Ping was successful."));
	}
	else if ( ProcessMsg_connect.find( "100 % packet loss", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[ping err] " + ProcessMsg_connect, GlobalConfig->error );
		KNotifyClient::event( topLevelWidget()->winId(), "ping failed",i18n("Ping has failed."));
	}
	else
	{
		if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "Binding interface failed!" ) );
			GlobalConfig->appendLogEntry(i18n( "Binding interface failed!" ) ,GlobalConfig->error);
		}
		if ( ProcessMsg_connect.find( "Destination Host Unreachable", 0, FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
			GlobalConfig->appendLogEntry(i18n( "Destination host is unreachable!" ) ,GlobalConfig->error);
		}

		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry( "[ping]: " + ProcessMsg_connect, GlobalConfig->debug );
	}
	// }
}

void KVpnc::readFromStderr_ping()
{
	// while ( ConnectProcess->canReadLineStderr() ) {
	// ProcessMsg_connect = ConnectProcess->readLineStderr();
	ProcessMsg_connect = QString( PingProcess->readStderr() );

	//mw->DebugOutput->append( "raw err (pingtest): " + ProcessMsg_connect );
	if ( ProcessMsg_connect.find( "time=", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[ping] " + ProcessMsg_connect, GlobalConfig->success );
	}
	else if ( ProcessMsg_connect.find( "100 % packet loss", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry( "[ping err] " + ProcessMsg_connect, GlobalConfig->error);
	}
	else
	{
		if ( ProcessMsg_connect.find( "failed to bind", 0, FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "Binding interface failed!" ) );
			GlobalConfig->appendLogEntry( i18n( "Binding interface failed!" ) ,GlobalConfig->error);
		}
		if ( ProcessMsg_connect.find( "Destination Host Unreachable", 0, FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
			GlobalConfig->appendLogEntry(i18n( "Destination host is unreachable!" )  ,GlobalConfig->error);
		}
	}
	//}
}

void KVpnc::readFromStdout_route()
{
	//while ( RouteProcess->canReadLineStdout() ) {
	//ProcessMsg_connect = RouteProcess->readLineStdout();
	ProcessMsg_connect = QString( RouteProcess->readStdout() );

	if (GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry( "[route] " + ProcessMsg_connect, GlobalConfig->debug );

	// }
}

void KVpnc::readFromStderr_route()
{
	// while ( RouteProcess->canReadLineStderr() ) {
	// ProcessMsg_connect = RouteProcess->readLineStderr();
	ProcessMsg_connect = QString( RouteProcess->readStderr() );

	if (GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry( "[route err] " + ProcessMsg_connect, GlobalConfig->error );
	//}
}

void KVpnc::readFromStdout_setVirtualIP()
{
	QString msg = QString( SetVirtualIPProcess->readStdout() );
	if (GlobalConfig->KvpncDebugLevel > 0)
		GlobalConfig->appendLogEntry ( msg, GlobalConfig->debug );
}

void KVpnc::readFromStderr_setVirtualIP()
{
	QString msg = QString( SetVirtualIPProcess->readStderr() );
	GlobalConfig->appendLogEntry ( msg, GlobalConfig->error );
	setVirtualIPSuccess=false;
}

void KVpnc::readFromStdout_connectionStatusCheck()
{
	QString msg = QString( ConnectionStatusCheckProcess->readStdout() );

	if ( msg.find( "PING ok.", 0 , FALSE ) > -1 )
	{
		/* Connection alive */
		if (GlobalConfig->KvpncDebugLevel > 0)
		{
			if (GlobalConfig->currentProfile->getDoPingIP())
			{
				GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s was ok.").arg(GlobalConfig->currentProfile->getPingHostIP()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg(GlobalConfig->currentProfile->getConnectionStatusInterval()), GlobalConfig->debug );
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s was ok.").arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg(GlobalConfig->currentProfile->getConnectionStatusInterval()), GlobalConfig->debug );
			}
		}
	}
	if ( msg.find( "PING failed!", 0 , FALSE ) > -1 )
	{
		/* Connection dead?! */
		if (GlobalConfig->KvpncDebugLevel > 0)
		{
			if (GlobalConfig->currentProfile->getDoPingIP())
			{
				GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s has been failed!").arg(GlobalConfig->currentProfile->getPingHostIP()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg( GlobalConfig->currentProfile->getConnectionStatusInterval() ), GlobalConfig->error );
				KNotifyClient::event( topLevelWidget()->winId(), "connection lost",i18n("Ping to %1 within %2 checks every %3s has been failed!").arg(GlobalConfig->currentProfile->getPingHostIP()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg(GlobalConfig->currentProfile->getConnectionStatusInterval()) );
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s has been failed!").arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg( GlobalConfig->currentProfile->getConnectionStatusInterval() ), GlobalConfig->error );
				KNotifyClient::event( topLevelWidget()->winId(), "connection lost",i18n("Ping to %1 within %2 checks every %3s has been failed!").arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg(GlobalConfig->currentProfile->getConnectionStatusInterval()) );
			}
		}
		disconnect( ConnectionStatusCheckProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_connectionStatusCheck() ) );
		disconnect( ConnectionStatusCheckProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_connectionStatusCheck() ) );
		ConnectionStatusCheckProcess->kill();
		// kill connection
		disconnectClicked();

		if (GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
		{
			if (GlobalConfig->currentProfile->getUseReconnectDelay())
			{
				GlobalConfig->appendLogEntry ( i18n("Waiting %1s for reconnect...").arg(GlobalConfig->currentProfile->getReconnectDelay()), GlobalConfig->info );
				for (int time=0; time <= GlobalConfig->currentProfile->getReconnectDelay()*1000;time+=200)
				{
					usleep (200);
					GlobalConfig->appPointer->processEvents();
				}
			}
			//			if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry ( i18n("Reconnect after connection lost enabled, reconnecting..."), GlobalConfig->info );
			connectClicked();
		}
	}
}

void KVpnc::readFromStderr_connectionStatusCheck()
{
	QString msg = QString( ConnectionStatusCheckProcess->readStderr() );

	// 	if ( msg.find( "PING ok.", 0 , FALSE ) > -1 )
	// 	{
	// 		/* Connection alive */
	// 		if (GlobalConfig->KvpncDebugLevel > 0)
	// 			GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s was ok.").arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg(GlobalConfig->currentProfile->getConnectionStatusInterval()), GlobalConfig->debug );
	//
	// 	}
	// 	if ( msg.find( "PING failed!", 0 , FALSE ) > -1 )
	// 	{
	// 		/* Connection dead?! */
	// 		if (GlobalConfig->KvpncDebugLevel > 0)
	// 			GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s was ok.").arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg( GlobalConfig->currentProfile->getConnectionStatusInterval() ), GlobalConfig->error );
	// 		KNotifyClient::event( topLevelWidget()->winId(), "connection lost",i18n("Ping to %1 within %2 checks every %3s was ok.").arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()).arg(GlobalConfig->currentProfile->getConnectionStatusInterval()) );
	// 		// kill connection
	// 		disconnectClicked();
	// 	}
}

void KVpnc::readPppdtestProcessOutput()
{
	QString msg="";
	msg+= QString(TestPppdProcess->readStdout() );
	msg+= QString(TestPppdProcess->readStderr() );

	if (msg == "")
		return;

	// try new style
	if (testOldPppdStyle==false)
	{
		if (msg.contains("unrecognized option 'require-mppe'"))
		{
			oldPppdStyle=true;
			pppdHasMppeSupport=false;
		}
		else
		{
			if (msg.contains("The remote system is required to authenticate itself"))
			{
				// old style found
				oldPppdStyle=false;
				pppdHasMppeSupport=true;
			}
		}
	}

	if (testOldPppdStyle==true)
	{
		// try old style
		if (msg.contains("unrecognized option 'mppe'"))
		{
			// no mppe support :(
			oldPppdStyle=false;
			pppdHasMppeSupport=false;
		}
		else
		{
			if (msg.contains("The remote system is required to authenticate itself"))
			{
				// old style found
				oldPppdStyle=true;
				pppdHasMppeSupport=true;
			}
		}
	}
}

void KVpnc::terminateConnection ( QProcess *proc )
{
	if ( proc->isRunning() )
	{
		proc->tryTerminate();
		QTimer::singleShot( 5000, proc, SLOT( kill() ) );
		sleep(5);
		proc->kill();

	}
	timer.stop();
	durationTimer.stop();
	GlobalConfig->status = GlobalConfig->disconnected;
	connectCounter = 0;
	setGuiStatus ( disconnected );

}

void KVpnc::connectionEnded()
{
	durationTimer.stop();
	GlobalConfig->status = GlobalConfig->disconnected;

	GlobalConfig->appendLogEntry ( i18n( "Successful disconnected." ) ,GlobalConfig->info);

	// clean up scripts
	if ( !GlobalConfig->holdGeneratedScripts )
	{

		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
		{
			QFile file( tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".conf" );
			file.remove();
			file.setName( tmpPath + "/setkey." + GlobalConfig->currentProfile->getName() + ".sh" );
			file.remove();
			file.setName( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf" );
			file.remove();
			file.setName( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_racoon.sh" );
			file.remove();
			file.setName( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_racoon.sh" );
			file.remove();
			file.setName( tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh" );
			file.remove();

			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
			{
				file.setName( tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key" );
				file.remove();
			}
			file.setName( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" );
			file.remove();
		} // racoon

		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
		{
			QFile file( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh" );
			file.remove();
			file.setName( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh" );
			file.remove();

		} // freeswan

	}

	QString durationString ( i18n( "%1:%2:%3" ).arg( QString().sprintf( "%02u", hour ) ).arg( QString().sprintf( "%02u", min ) , QString().sprintf( "%02u", sec ) ) );
	GlobalConfig->appendLogEntry ( i18n( "Connection duration was %1 hours, %2 minutes, %3 seconds" ).arg( QString().sprintf( "%02u", hour ), QString().sprintf( "%02u", min ) , QString().sprintf( "%02u", sec ) ), GlobalConfig->info );
	connectCounter = 0;
	TmpPassword="";
	TmpGroupPassword="";
}

void KVpnc::slotConnectTimedOut()
{
	this->connectCounter++;

	if ( connectCounter > GlobalConfig->connectSleepRetry && timer.isActive())
	{
		timer.stop();
		// it dont get it connected so we kill it :)
		GlobalConfig->appendLogEntry ( i18n( "Timeout! Kill connect process!" ),GlobalConfig->info );
		ConnectProcess->kill();
		GlobalConfig->status = GlobalConfig->disconnected;
		mw->buttonConnect->setEnabled( true );
		mw->buttonDisconnect->setEnabled( false );
		this->connectAction->setEnabled( true );
		this->disconnectAction->setEnabled( false );
		//parent->statusBar() ->insertItem( i18n( "Connected" ), 2, 0, true );
		KVpncDock->setStatus( disconnected );
		GlobalConfig->appendLogEntry ( i18n( "Connection failed (timeout)." ),GlobalConfig->info );
		disconnectClicked();
		slotStatusMsg( i18n( "Connection timed out, \"%1\" killed." ).arg("vpnc"), ID_FLASH_MSG );
		slotStatusMsg( i18n( "Disconnected" ), ID_CONNECTION_MSG );
		QToolTip::remove
			( KVpncDock );
		QToolTip::add
			( KVpncDock, i18n( "Disconnected" ) );
		connectCounter = 0;

		setGuiStatus(disconnected);
	}
	else if (GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
	{
		GlobalConfig->appendLogEntry ( i18n( "Waiting %1 seconds for connect..." ).arg( GlobalConfig->connectSleepDelay ),GlobalConfig->info );
		slotStatusMsg( i18n( "Waiting for connect..." ), ID_FLASH_MSG );
	}
}

void KVpnc::newSessionClicked()
{
	// call new profile dialog...
	NewProfileDialog newdlg( parent, this, i18n("New Profile"),GlobalConfig);
	newdlg.exec();
	if ( newdlg.newProfileCreated )
	{

		profileAddedOrDeleted();
		mw->SessionCombo->setCurrentText(newdlg.getName());

		mw->SessionCombo->setEnabled(TRUE);
		deleteSessionAction->setEnabled ( TRUE );
		saveSessionAction->setEnabled ( TRUE );
		importSessionAction->setEnabled ( TRUE );
		connectAction->setEnabled ( TRUE );
		mw->buttonConnect->setEnabled ( TRUE );

		sessionToggled(newdlg.getName());

		slotStatusMsg ( i18n( "Profile \"%1\" added." ).arg( mw->SessionCombo->currentText() ), ID_FLASH_MSG );
		GlobalConfig->appendLogEntry ( i18n( "Profile \"%1\" added." ).arg( mw->SessionCombo->currentText() ) ,GlobalConfig->info);
		GlobalConfig->saveOptions();
		saveGuiOptions();

		QuickConnectMenu->clear();
		for (uint i=0; i < GlobalConfig->AccountList->count();i++)
		{
			QuickConnectMenu->insertItem( GlobalConfig->AccountList->at(i)->getName());
		}

	}
	else
	{
		slotStatusMsg ( i18n( "Creating new profile canceled." ), ID_FLASH_MSG );
		GlobalConfig->appendLogEntry ( i18n( "Creating new profile canceled." ),GlobalConfig->info );
	}
}

void KVpnc::saveSessionClicked()
{
	if ( !GlobalConfig->AccountList->isEmpty() )
	{
		GlobalConfig->saveOptions();
	}
	saveGuiOptions();
}

void KVpnc::deleteSessionClicked()
{
	if (GlobalConfig->currentProfile == 0)
		return;

	QString Name = GlobalConfig->currentProfile->getName();
	if ( !Name.isEmpty() )
	{
		int result = KMessageBox::questionYesNo ( this, i18n( "Really delete \"%1\"?" ).arg( GlobalConfig->currentProfile->getName() ), i18n( "Delete?" ), KStdGuiItem::del(), KStdGuiItem::cancel());
		if ( result == 3 ) // yes
		{
			VpnAccountData * it;
			QuickConnectMenu->clear();
			mw->SessionCombo->clear();
			GlobalConfig->removeEntry(GlobalConfig->currentProfile->getName());

			if (GlobalConfig->AccountList->isEmpty())
			{
				GlobalConfig->currentProfile=0L;
				mw->SessionCombo->setEnabled ( FALSE );
				connectAction->setEnabled( FALSE );
				mw->buttonConnect->setEnabled ( FALSE );
				deleteSessionAction->setEnabled ( FALSE );
				GlobalConfig->lastProfile="";
			}
			else
			{
				for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
				{
					kdDebug() << "item: " << it->getName() << endl;
					QuickConnectMenu->insertItem(it->getName());
					mw->SessionCombo->insertItem(it->getName());
				}
				GlobalConfig->currentProfile = GlobalConfig->AccountList->first();
				mw->SessionCombo->setEnabled( TRUE );
				mw->buttonConnect->setEnabled( TRUE );
				this->sessionToggled( GlobalConfig->currentProfile->getName() );
			}

			slotStatusMsg ( i18n( "Profile \"%1\" deleted." ).arg( Name ), ID_FLASH_MSG );
			GlobalConfig->appendLogEntry ( i18n( "Profile \"%1\" deleted." ).arg( Name ) ,GlobalConfig->info);
			GlobalConfig->saveOptions();
			saveGuiOptions();

		}
	}

}

void KVpnc::sessionToggled( const QString& Name )
{
	//  mw->DebugOutput->append( "sessionToggled" );
	if ( Name.isEmpty() )
	{
		this->deleteSessionAction->setEnabled ( FALSE );
		//   this->advancedSessionAction->setEnabled ( FALSE );
		this->saveSessionAction->setEnabled ( FALSE );
	}
	else
	{
		this->deleteSessionAction->setEnabled ( TRUE );
		//   this->advancedSessionAction->setEnabled ( TRUE );
		this->saveSessionAction->setEnabled ( TRUE );
		VpnAccountData * it;
		GlobalConfig->currentProfile = GlobalConfig->AccountList->first();
		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			QString Name = mw->SessionCombo->currentText();
			if ( !Name.isEmpty() )
			{
				if ( it->getName() == Name )
				{
					// profile found
					GlobalConfig->currentProfile = it;

					QString type=""; // visible name
					QString bin="";  // executable name
					if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
					{
						type = "vpnc";
						bin = "vpnc";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
					{
						type = "freeswan";
						bin="ipsec";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
					{
						type = "racoon";
						bin="racoon";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
					{
						type = "pptp";
						bin="pppd pptp";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
					{
						type = "openvpn";
						bin="openvpn";
					}
					else
					{
						type = "other";
						bin="";
					}

					if ( GlobalConfig->KvpncDebugLevel > 0 )
					{
						GlobalConfig->appendLogEntry( i18n( "New type: %1." ).arg( type ), GlobalConfig->debug );
					}

					ToolInfo *it;
					//std::cout << "Tool (bin): " << bin << std::endl;

					if (!GlobalConfig->ToolList->isEmpty())
					{
						if (type!="pptp")
						{
							it = Utils(GlobalConfig).getToolInfo(GlobalConfig, bin);
							if (it->PathToExec.section('/',-1) == bin )
							{
								// program is installed
								this->connectAction->setEnabled ( TRUE );
								mw->buttonConnect->setEnabled ( TRUE );

								if (GlobalConfig->KvpncDebugLevel > 0)
									GlobalConfig->appendLogEntry(i18n("The required deamon (%1) is available, connect will be enabled.").arg(bin),KVpncConfig::info);
							}
							else
							{
								this->connectAction->setEnabled ( FALSE );
								mw->buttonConnect->setEnabled ( FALSE );
								if (GlobalConfig->KvpncDebugLevel > 0)
									GlobalConfig->appendLogEntry(i18n("The required deamon (%1) isn't available, connect will be disabled.").arg(bin),KVpncConfig::error);
							}
						}
						else
						{
							bool pppd_and_pptp_available=false;
							it = Utils(GlobalConfig).getToolInfo(GlobalConfig, "pppd");
							if (it->PathToExec.section('/',-1) == "pppd" )
							{
								it = Utils(GlobalConfig).getToolInfo(GlobalConfig, "pptp");
								if (it->PathToExec.section('/',-1) == "pptp" )
									pppd_and_pptp_available=true;
							}
							if ( pppd_and_pptp_available )
							{
								// programs are installed
								if (GlobalConfig->KvpncDebugLevel > 0)
									GlobalConfig->appendLogEntry(i18n("The required deamons (%2 and %2) are available, connect will be enabled.").arg("pppd").arg("pptp"),KVpncConfig::info);

								this->connectAction->setEnabled ( TRUE );
								mw->buttonConnect->setEnabled ( TRUE );

							}
							else
							{
								GlobalConfig->appendLogEntry(i18n("The required deamons (%1 and %2) are not available, connect will be disabled.").arg("pppd").arg("pptp"),KVpncConfig::error);
							}
						}
					}
				}
			}
		}
	}
}

void KVpnc::slotDurationEvent()
{
	sec += 1;
	if ( sec > 59 )
	{
		sec = 0;
		min += 1;
	}
	if ( min > 59 )
	{
		sec=0;
		min = 0;
		hour += 1;
	}

	QString durationString ( i18n( "%1:%2:%3" ).arg( QString().sprintf( "%02u", hour ), QString().sprintf( "%02u", min ), QString().sprintf( "%02u", sec ) ) );
	QString ToolTipMsg="";
	QString StatusMsg;
	QString TypeString=i18n("other");
	QString IP = TunnelInterfaceIP;
	if (TunnelInterfaceIP.isEmpty())
		IP="none";


	if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco)
	{
		TypeString="Cisco";
		StatusMsg=i18n( "Connected: %2@%1, %3" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg(TypeString).arg ( durationString );
	}
	else 	if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp)
	{
		TypeString="PPTP";
		StatusMsg=i18n( "Connected: %2@%1 (%3), %4" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg(TypeString).arg ( durationString );
	}
	else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan ||
	         GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon ||
	         GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn
	        )
	{
		if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan)
			TypeString="*S/WAN";
		else
			if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon)
				TypeString="racoon";
		if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn)
			TypeString="OpenVPN";
		StatusMsg=i18n( "Connected: %1 (%2) %3" ).arg( GlobalConfig->currentProfile->getGateway() ).arg(TypeString).arg ( durationString );
	}


	ToolTipMsg+= i18n( "server: %1\n").arg( GlobalConfig->currentProfile->getGateway());
	ToolTipMsg+= i18n( "type: %1\n").arg( TypeString);

	if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco)
		ToolTipMsg+= i18n( "IPSec ID: %1\n").arg( GlobalConfig->currentProfile->getID() );

	if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp || (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()))
		if (!GlobalConfig->currentProfile->getUserName().isEmpty())
			ToolTipMsg+= i18n( "user: %1\n").arg( GlobalConfig->currentProfile->getUserName() );
		else
			ToolTipMsg+= i18n( "user: %1\n").arg( TmpUsername );

	if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		ToolTipMsg+= i18n( "tunnel IP: %1\n").arg( IP );

	QToolTip::add
		( KVpncDock, ToolTipMsg );
	slotStatusMsg( StatusMsg, ID_CONNECTION_MSG );
	/*
	runningCheckCounter += 1;
	if ( runningCheckCounter == runningCheckTimeout ) {
	if ( !ConnectProcess->isRunning() ) {
	KMessageBox::error( this, i18n( "Connection lost in las^t %1 seconds!" ).arg( QString().setNum( runningCheckTimeout ) ) );
	GlobalConfig->appendLogEntry ( i18n( "Connection to %1 lost at %2" ).arg( mw->gatewayLineEdit->text() ).arg( QDateTime::currentDateTime().toString( Qt::TextDate ) ),GlobalConfig->info );
	terminateConnection ( ConnectProcess );
	} else {
	runningCheckCounter = 0;
	}
	}
	*/
}

void KVpnc::setGuiStatus( int status )
{
	if ( status == GlobalConfig->connected )
	{
		setIcon( connectedIcon );

		QString durationString ( i18n( "%1:%2:%3" ).arg( QString().sprintf( "%02u", hour ) ).arg( QString().sprintf( "%02u", min ) ).arg( QString().sprintf( "%02u", sec ) ) );
		QString TypeString="";
		QString ConnectMsg="";
		QString LogMsg="";
		QString ToolTipMsg="";

		mw->SessionCombo->setEnabled( false );
		importCertAction->setEnabled( false );
		newSessionAction->setEnabled( false );
		deleteSessionAction->setEnabled( false );
		importSessionAction->setEnabled( false );

		QToolTip::remove
			( KVpncDock );

		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
		{
			TypeString="Cisco";
			ToolTipMsg= i18n( "\nstatus: connected\nserver: %1\nuser: %2\nIPSec ID: %3\nduration: %4\nprofile: %5 (%6)" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg( GlobalConfig->currentProfile->getID() ).arg ( durationString ).arg(GlobalConfig->currentProfile->getName()).arg(TypeString);

			ConnectMsg = i18n( "Connected: %2@%1, %3" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg ( durationString );

			LogMsg = i18n( "Successful connected to server: \"%1\", user: \"%2\", IPSec ID: \"%3\") at %4" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg( GlobalConfig->currentProfile->getID() ).arg( QDateTime::currentDateTime().toString( Qt::TextDate ));
		}

		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
		{
			TypeString="PPTP";
			ToolTipMsg= i18n( "status: connected\nserver: %1\nuser: %2\nduration: %3\nprofile %4 (%6)" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg ( durationString ).arg(GlobalConfig->currentProfile->getName()).arg(TypeString);

			ConnectMsg = i18n( "Connected: %2@%1, %3" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg ( durationString );

			LogMsg = i18n( "Successful connected to server \"%1\"\nuser: \"%2\") at %3" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( GlobalConfig->currentProfile->getUserName() ).arg( QDateTime::currentDateTime().toString( Qt::TextDate ));
		}

		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
		{
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
				TypeString = "racoon";
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
				TypeString = "freeswan";

			ConnectMsg = i18n( "Policy successful activated and daemon (%1) running." ).arg( TypeString );

			LogMsg = i18n( "Policy successful activated and daemon (%1) running for server \"%2\" (%3) at date %4, profile \"%5\" (%6)" ).arg( TypeString ).arg( GlobalConfig->currentProfile->getGateway() ).arg(TmpGatewayIP).arg( QDateTime::currentDateTime().toString( Qt::TextDate ) ).arg(GlobalConfig->currentProfile->getName()).arg( TypeString );

		}

		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		{
			TypeString = "OpenVPN";
			ToolTipMsg =  i18n( "status: connected \nserver: %1\nduration: %2" ).arg( GlobalConfig->currentProfile->getGateway() ).arg ( durationString );

			ConnectMsg = i18n( "Connected: %1, %2, profile \"%3\"" ).arg( GlobalConfig->currentProfile->getGateway() ).arg ( durationString ).arg(GlobalConfig->currentProfile->getName());

			LogMsg = i18n( "Successful connected to server \"%1\" at %2, profile \"%3\" (%4)" ).arg( GlobalConfig->currentProfile->getGateway() ).arg( QDateTime::currentDateTime().toString( Qt::TextDate )).arg(GlobalConfig->currentProfile->getName()).arg(TypeString);
		}
		KVpncDock->setStatus( connected );
		statusColorLabel->setPixmap(*connectedStatusPixmap);
		mw->buttonConnect->setEnabled( false );
		mw->buttonDisconnect->setEnabled( true );
		this->connectAction->setEnabled( false );
		this->disconnectAction->setEnabled( true );
		mw->SessionCombo->setEnabled( false );

		ToolTipMsg = ConnectMsg;
		QToolTip::add
			( KVpncDock, ToolTipMsg );

		slotStatusMsg ( i18n( "Successful connected." ), ID_FLASH_MSG );
		slotStatusMsg ( ConnectMsg , ID_CONNECTION_MSG );
		GlobalConfig->appendLogEntry ( LogMsg ,GlobalConfig->info );

		KNotifyClient::event( topLevelWidget()->winId(), "connection established",ToolTipMsg );

		//sleep(2);
		if ( GlobalConfig->minimizeAfterConnect )
			hide();


		QuickConnectMenu = new QPopupMenu(KVpncDock->menu());


		//setItemEnabled ( int id, bool enable )

	}
	else if ( status == GlobalConfig->connecting )
	{
		//setIcon( connectingIcon );
		mw->buttonConnect->setEnabled( false );
		mw->buttonDisconnect->setEnabled( false );
		mw->SessionCombo->setEnabled( false );
		importCertAction->setEnabled( false );
		newSessionAction->setEnabled( false );
		deleteSessionAction->setEnabled( false );
		importSessionAction->setEnabled( false );
		KVpncDock->setStatus( connecting );
		mw->SessionCombo->setEnabled( false );
		QToolTip::remove
			( KVpncDock );
		QToolTip::add
			( KVpncDock, i18n( "Connecting..." ) );

		statusColorLabel->setPixmap(*connectingStatusPixmap);

		slotStatusMsg( i18n( "Connecting..." ), ID_CONNECTION_MSG );
		slotStatusMsg ( i18n( "Connecting..." ), ID_FLASH_MSG );

		connectClicked();

	}
	else if ( status == GlobalConfig->disconnected )
	{
		setIcon( disconnectedIcon );
		mw->buttonConnect->setEnabled( true );
		mw->buttonDisconnect->setEnabled( false );
		disconnectAction->setEnabled( false );
		connectAction->setEnabled( true );
		mw->SessionCombo->setEnabled( false );
		importCertAction->setEnabled( true );
		newSessionAction->setEnabled( true );
		deleteSessionAction->setEnabled( true );
		importSessionAction->setEnabled( true );
		KVpncDock->setStatus( disconnected );
		mw->SessionCombo->setEnabled( true );
		QToolTip::remove
			( KVpncDock );
		QToolTip::add
			( KVpncDock, i18n( "Disconnected" ) );

		statusColorLabel->setPixmap(*disconnectedStatusPixmap);

		slotStatusMsg( i18n( "Disconnected" ), ID_CONNECTION_MSG );
		slotStatusMsg ( i18n( "Disconnected." ), ID_FLASH_MSG );
		KNotifyClient::event( topLevelWidget()->winId(), "connection finished",i18n("Connection \"%1\" finished").arg(GlobalConfig->currentProfile->getName()) );

	}

}

void KVpnc::advancedSettingsClicked()
{
	VpnAccountData * it = 0L;
	VpnAccountData *currentAccount = 0L;


	if ( mw->SessionCombo->isEnabled() )
	{

		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			if ( it->getName() == mw->SessionCombo->currentText() )
			{
				currentAccount = it;
				break;
			} // profile found
		} // for

	}

	if (currentAccount != 0)
	{
		AdvancedSettingsDialog d1(this, i18n("Advanced Settings"), currentAccount, currentAccount->getConnectionType(),GlobalConfig);
		d1.main->AdvancedSettingsCheckbox->setChecked ( false );
		d1.main->UseGlobalIpsecSecretCheckbox->setChecked ( false );
		d1.main->SingleDesCheckbox->setChecked( false );
		d1.main->IkeGroupCheckbox->setChecked ( false );
		d1.main->LocalPortCheckbox->setEnabled ( false );
		d1.main->PerfectForwardSecurityCheckbox->setChecked( false );
		d1.main->NtDomainNameCheckbox->setEnabled ( false );
		d1.main->ApplicationVersionCheckbox->setEnabled ( false );
		d1.main->UseGlobalIpsecSecretCheckbox->setEnabled ( false );

		d1.main->LocalPortSpinbox->setValue( currentAccount->getLocalPort() );
		d1.main->IkeGroupCombobox->setCurrentText( currentAccount->getIkeGroup() );
		d1.main->PerfectForwardSecrecyCombobox->setCurrentText( currentAccount->getPerfectForwardSecrety() );
		d1.main->NtDomainNameLineedit->setText( currentAccount->getNtDomainName() );
		d1.main->ApplicationVersionLineedit->setText( currentAccount->getApplicationVersion() );

		if ( currentAccount->getUseAdvancedSettings() )
		{
			d1.main->LocalPortCheckbox->setEnabled ( true );
			d1.main->IkeGroupCheckbox->setEnabled ( true );
			d1.main->PerfectForwardSecurityCheckbox->setEnabled ( true );
			d1.main->SingleDesCheckbox->setEnabled ( true );
			d1.main->NtDomainNameCheckbox->setEnabled ( true );
			d1.main->ApplicationVersionCheckbox->setEnabled ( true );
			d1.main->UseGlobalIpsecSecretCheckbox->setEnabled ( true );
			d1.main->AdvancedSettingsCheckbox->setChecked ( true );

			if ( currentAccount->getUseSingleDes() )
			{
				d1.main->SingleDesCheckbox->setChecked( true );
			}

			if ( currentAccount->getUseIkeGroup() )
			{
				d1.main->IkeGroupCheckbox->setChecked ( true );
			}

			if ( currentAccount->getUseGlobalIpsecSecret() )
			{
				d1.main->UseGlobalIpsecSecretCheckbox->setChecked ( true );
			}

			if ( currentAccount->getUsePerfectForwardSecrety() )
			{
				d1.main->PerfectForwardSecrecyCombobox->setEnabled ( true );
				d1.main->PerfectForwardSecurityCheckbox->setChecked( true );
			}

			if ( currentAccount->getUseNtDomainName() )
			{
				d1.main->NtDomainNameLineedit->setEnabled ( true );
				d1.main->NtDomainNameCheckbox->setChecked( true );
			}

			if ( currentAccount->getUseApplicationVersion() )
			{
				d1.main->ApplicationVersionLineedit->setEnabled ( true );
				d1.main->ApplicationVersionCheckbox->setChecked( true );
			}

			if ( currentAccount->getUseLocalPort() )
			{
				d1.main->LocalPortSpinbox->setEnabled ( true );
				d1.main->LocalPortCheckbox->setChecked( true );
			}

			if ( currentAccount->getUseIkeGroup() )
			{
				d1.main->IkeGroupCombobox->setEnabled ( true );
			}

		} // advanced settings



		d1.exec();

		if ( !mw->SessionCombo->currentText()
		        .isEmpty() )
		{
			if ( d1.main->AdvancedSettingsCheckbox->isChecked() )
			{
				currentAccount->setUseAdvancedSettings( true );
			}
			else
			{
				currentAccount->setUseAdvancedSettings( false );
			}
			if ( d1.main->NtDomainNameCheckbox->isChecked() )
			{
				currentAccount->setNtDomainName( d1.main->NtDomainNameLineedit->text() );
				currentAccount->setUseNtDomainName( true );
			}
			else
			{
				currentAccount->setUseNtDomainName( false );
			}

			if ( d1.main->ApplicationVersionCheckbox->isChecked() )
			{
				currentAccount->setApplicationVersion( d1.main->ApplicationVersionLineedit->text() );
				currentAccount->setUseApplicationVersion( true );
			}
			else
			{
				currentAccount->setUseApplicationVersion( false );
			}

			if ( d1.main->IkeGroupCheckbox->isChecked() )
			{
				currentAccount->setIkeGroup( d1.main->IkeGroupCombobox->currentText() );
				currentAccount->setUseIkeGroup( true );
			}
			else
			{
				currentAccount->setUseIkeGroup( false );
			}

			if ( d1.main->PerfectForwardSecurityCheckbox->isChecked() )
			{
				currentAccount->setPerfectForwardSecrety( d1.main->PerfectForwardSecrecyCombobox->currentText() );
				currentAccount->setUsePerfectForwardSecrety( true );
			}
			else
			{
				currentAccount->setUsePerfectForwardSecrety( false );
			}


			if ( d1.main->SingleDesCheckbox->isChecked() )
			{
				currentAccount->setUseSingleDes( true );
			}
			else
			{
				currentAccount->setUseSingleDes( false );
			}

			if ( d1.main->UseGlobalIpsecSecretCheckbox->isChecked() )
			{
				currentAccount->setUseGlobalIpsecSecret( true );
			}
			else
			{
				currentAccount->setUseGlobalIpsecSecret( false );
			}


			if ( d1.main->LocalPortCheckbox->isChecked() )
			{
				currentAccount->setLocalPort( d1.main->LocalPortSpinbox->value() );
				currentAccount->setUseLocalPort( true );
			}
			else
			{
				currentAccount->setUseLocalPort( false );
			}

		}
		else
		{
			currentAccount->setUseAdvancedSettings( false );
		}
		saveSessionClicked();

		mw->SessionCombo->clear();
		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			mw->SessionCombo->insertItem( it->getName() );
		} // for
		mw->SessionCombo->setCurrentText(GlobalConfig->lastProfile);

	}
}

void KVpnc::importProfileClicked()
{

	ImportProfileDialog dlg(GlobalConfig, this,i18n("Import profile"));
	dlg.exec();

	bool importOK = dlg.importOk;
	if ( importOK )
	{
		VpnAccountData * account = dlg.acc;

		VpnAccountData * it;
		bool nameOk=false;
		while (nameOk==false)
		{
			for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
			{
				if ( it->getName() == account->getName() )
				{
					//account->setName( QString( account->getName() + "_2" ) );
					// 				KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\"." ).arg( account->getName() ), i18n( "Name exist, renamed" ) );
					KMessageBox::error ( this, i18n( "Profile name exists!"), i18n( "Name Exists" ) );
					it->setName(KInputDialog::getText   (   i18n("New Name"),i18n("New name for profile:")));
					nameOk=true;
					break;
				}
				nameOk=true;
			}
			nameOk=true;
		}

		GlobalConfig->AccountList->append( account );
		mw->SessionCombo->clear();
		QuickConnectMenu->clear();

		for (uint i=0; i < GlobalConfig->AccountList->count();i++)
		{
			QuickConnectMenu->insertItem( GlobalConfig->AccountList->at(i)->getName());
			mw->SessionCombo->insertItem( GlobalConfig->AccountList->at(i)->getName());
		}
		mw->SessionCombo->setCurrentText( account->getName() );

		if ( !mw->SessionCombo->isEnabled() )
			mw->SessionCombo->setEnabled( TRUE );

		this->connectAction->setEnabled( true );
		sessionToggled( account->getName() );

		KMessageBox::information( 0, i18n( "Import of \"%1\" was successful." ).arg( account->getName() ) );
		GlobalConfig->appendLogEntry ( i18n( "Import of \"%1\" (%2) was successful." ).arg( account->getName() ).arg("PCF"), GlobalConfig->info );
		slotStatusMsg ( i18n( "Import of \"%1\" (%2) was successful." ).arg( account->getName() ).arg("PCF"), ID_FLASH_MSG );

		GlobalConfig->saveOptions();
		//		std::cout << "save done" << std::endl;

		QString bin="vpnc";
		ToolInfo *tool;
		//std::cout << "Tool (bin): " << bin << std::endl;
		if (!GlobalConfig->ToolList->isEmpty())
		{
			for ( tool = GlobalConfig->ToolList->first(); tool; tool = GlobalConfig->ToolList->next() )
			{
				if (bin == tool->Name)
				{
					if (tool->PathToExec.section('/',-1) != bin )
					{
						// program is NOT installed
						KMessageBox::information ( this, i18n( "The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc.").arg(bin), i18n( "Tool Missing" ) );
					}
					break;
				}
			}
		}

		showProfileManagerClicked();
		std::cout << "show profilemanager" << std::endl;
	}

}

void KVpnc::importOpenvpnProfileClicked()
{

	ImportOpenvpnProfileDialog dlg(GlobalConfig, this,i18n("Import OpenVPN profile"));
	dlg.exec();
	bool importOK = dlg.importOk;
	if ( importOK )
	{
		VpnAccountData * account = dlg.acc;

		VpnAccountData * it;
		bool nameOk=false;
		while (nameOk==false)
		{
			for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
			{
				if ( it->getName() == account->getName() )
				{
					//account->setName( QString( account->getName() + "_2" ) );
					// 				KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\"." ).arg( account->getName() ), i18n( "Name exist, renamed" ) );
					KMessageBox::error ( this, i18n( "Profile name exists!"), i18n( "Name Exists" ) );
					account->setName(KInputDialog::getText   (   i18n("New Name"),i18n("New name for profile:")));
					if (!account->getName().isEmpty())
					{
						nameOk=true;
						break;
					}
				}
				nameOk=true;
			}
			nameOk=true;
		}

		GlobalConfig->AccountList->append( account );
		mw->SessionCombo->clear();
		QuickConnectMenu->clear();

		for (uint i=0; i < GlobalConfig->AccountList->count();i++)
		{
			QuickConnectMenu->insertItem( GlobalConfig->AccountList->at(i)->getName());
			mw->SessionCombo->insertItem( GlobalConfig->AccountList->at(i)->getName());
		}
		mw->SessionCombo->setCurrentText( account->getName() );

		if ( !mw->SessionCombo->isEnabled() )
			mw->SessionCombo->setEnabled( TRUE );

		this->connectAction->setEnabled( true );
		sessionToggled( account->getName() );

		KMessageBox::information( 0, i18n( "Import of \"%1\" was successful." ).arg( account->getName() ) );
		GlobalConfig->appendLogEntry ( i18n( "Import of \"%1\" (%2) was successful." ).arg( account->getName() ).arg("OpenVPN"), GlobalConfig->info );
		slotStatusMsg ( i18n( "Import of \"%1\" (%2) was successful." ).arg( account->getName() ).arg("OpenVPN"), ID_FLASH_MSG );

		GlobalConfig->saveOptions();
		//		std::cout << "save done" << std::endl;

		QString bin="openvpn";
		ToolInfo *tool;
		//std::cout << "Tool (bin): " << bin << std::endl;
		if (!GlobalConfig->ToolList->isEmpty())
		{
			for ( tool = GlobalConfig->ToolList->first(); tool; tool = GlobalConfig->ToolList->next() )
			{
				if (bin == tool->Name)
				{
					if (tool->PathToExec.section('/',-1) != bin )
					{
						// program is NOT installed
						KMessageBox::information ( this, i18n( "The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc.").arg(bin), i18n( "Tool Missing" ) );
					}
					break;
				}
			}
		}

		showProfileManagerClicked();
		// 		std::cout << "show profilemanager" << std::endl;
	}

}

void KVpnc::slotCancelClicked()
{
	cancelClicked = true;
}

void KVpnc::doRouteRacoon()
{

	if ( ConnectProcess->normalExit () )
	{
		disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doRouteRacoon() ) );
		/*
		route add -net 192.168.1.0/24 eth0
		*/
		putenv( ( char* ) ( "LC_ALL=C" ) );
		ConnectProcess->clearArguments();
		ConnectProcess->addArgument( "/sbin/route" );
		ConnectProcess->addArgument( "add" );
		ConnectProcess->addArgument( "-net" );
		QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
		QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
		QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;
		ConnectProcess->addArgument( RemoteNet );
		QString dev;

		dev = GlobalConfig->currentProfile->getNetworkDevice();


		if ( dev == "default" || dev.isEmpty() )
		{
			dev = tmpInterface;
			QString defaultinterface=dev;
			if (GlobalConfig->KvpncDebugLevel>0)
				GlobalConfig->appendLogEntry( i18n("Default interface").arg(defaultinterface), GlobalConfig->debug );
		}

		if (!GlobalConfig->currentProfile->getUseVirtualIP())
		{
			ConnectProcess->addArgument( dev );
			tmpInterface = dev;
		}
		else
		{
			ConnectProcess->addArgument( QString(dev+":100"));
			tmpInterface = QString(dev+":100");
		}

		if ( GlobalConfig->currentProfile->getAuthType() != VpnAccountData::psk )
			connect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doIptablesRacoon() ) );
		else
			connect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doChmodPskFile() ) );

		if ( !ConnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("route: \"route add -net " + RemoteNet + " " + tmpInterface + "\"") );
			GlobalConfig->appendLogEntry( i18n( "\"%1\" start failed!" ).arg("route: \"route add -net " + RemoteNet + " " + tmpInterface + "\"") ,GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->RacoonDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "route: \"route add -net " + RemoteNet + " " + tmpInterface + "\"", GlobalConfig->debug );
		}
	}
}

void KVpnc::doChmodPskFile()
{
	if ( ConnectProcess )
		disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doChmodPskFile() ) );

	tmpPath = locateLocal ( "data", "kvpnc/" ); // should be
	putenv( ( char* ) ( "LC_ALL=C" ) );
	ConnectProcess->clearArguments();
	ConnectProcess->addArgument( "chmod" );
	ConnectProcess->addArgument( "go-rwx" );
	ConnectProcess->addArgument( tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key" );

	connect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doIptablesRacoon() ) );

	if ( !ConnectProcess->start() )
	{
		KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "chmod go-rwx "+tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key" ) );
		GlobalConfig->appendLogEntry( i18n( "\"%1\" start failed!" ).arg( "chmod go-rwx "+tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key" ),GlobalConfig->error);
		disconnectClicked();
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg( "chmod go-rwx "+tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key" ), GlobalConfig->debug );
	}

}

void KVpnc::doIptablesRacoon()
{
	if ( ConnectProcess->normalExit () )
	{
		if ( ConnectProcess )
			disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doIptablesRacoon() ) );
		/*
		iptables -I INPUT -p 50 -i $IFACE -s $VPNGW_IP -j ACCEPT
		*/
		putenv( ( char* ) ( "LC_ALL=C" ) );
		ConnectProcess->clearArguments();
		ConnectProcess->addArgument( "/bin/sh" );
		ConnectProcess->addArgument( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_racoon.sh" );

		connect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doRacoon() ) );

		if ( !ConnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".add_ipsec_racoon.sh" ) );
			GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".add_ipsec_racoon.sh" ) ,GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->RacoonDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "\"%1\" started." ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".add_ipsec_racoon.sh" ) , GlobalConfig->debug);
		}
	}
}

void KVpnc::doTailRacoonLog()
{

	putenv( ( char* ) ( "LC_ALL=C" ) );
	TailProcess = new QProcess( this );
	TailProcess->addArgument( "tail" );
	TailProcess->addArgument( "-n" );
	TailProcess->addArgument( "100" );
	TailProcess->addArgument( "-f" );
	TailProcess->addArgument( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" );

	connect( TailProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_tail_racoon() ) );
	connect( TailProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_tail_racoon() ) );

	if ( !TailProcess->start() )
	{
		KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "tail -f "+tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" ) );
		GlobalConfig->appendLogEntry( i18n( "\"%1\" start failed!" ).arg( "tail -f "+tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" )  ,GlobalConfig->error);
		disconnectClicked();
	}
	else
	{
		//         status=connected;
		//         setGuiStatus(connected);

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "\"%1\" started." ).arg( "tail -f "+tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" ), GlobalConfig->debug );

		//     /* first: kick up the tunnel */
		//     putenv( ( char* ) ( "LC_ALL=C" ) );
		//     PingProcess = new QProcess( this );
		// QString PathToPing="";
		// for (Tool=GlobalConfig->ToolList->first();Tool;Tool=GlobalConfig->ToolList->next())
		// 			{
		// 				if (Tool->Name == "ping")
		// 				{
		// 					PathToPing=Tool->PathToExec;
		// 					break;
		// 				}
		// 	}

		//     PingProcess->addArgument( PathToPing );
		//     //PingProcess->addArgument( "-b" );
		//     PingProcess->addArgument( "-c1" );
		//     PingProcess->addArgument( GlobalConfig->currentProfile->getRemoteNet() );
		//     if ( !PingProcess->start() )
		//         KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "ping -c1 "+GlobalConfig->currentProfile->getRemoteNet() ) );
		//     else
		//     {
		//         if ( GlobalConfig->KvpncDebugLevel > 0 )
		//             GlobalConfig->appendLogEntry( i18n( "\"%1\" started." ).arg( "ping for kick up the tunnel (%1)..." ).arg("racoon"), GlobalConfig->debug );
		//     }
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( "[racoon] "+i18n( "Connection established." ), GlobalConfig->debug );

		//connectionTime.restart();
		//uint duration = connectionTime.elapsed();

		sec = hour = min = 0;

		GlobalConfig->status = GlobalConfig->connected;

		connectionTime.start();
		connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		durationTimer.start( 1000, FALSE );
		setGuiStatus(connected);


		if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
			executeCommandAfterConnect();

		if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes()  && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
			addAdditionalNetworkRoutes();

		if ( GlobalConfig->currentProfile->getUseConnectionStatusCheck())
		{
			startConnectionStatusCheck();
		}
	}
}

void KVpnc::doRacoon()
{
	if ( ConnectProcess->normalExit () )
	{
		if ( ConnectProcess )
			disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doRacoon() ) );
		/*
		/usr/sbin/racoon -f <configfile> -l <logfile>
		*/
		QFile f( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log");
		if (f.exists())
			f.remove();
		QTextStream s (&f);
		if ( f.open( IO_WriteOnly ) )
		{
			s << "\n";
		}
		f.close();
		s.unsetDevice();
		putenv( ( char* ) ( "LC_ALL=C" ) );
		RacoonProcess = new QProcess ( this );
		RacoonProcess->addArgument( GlobalConfig->pathToRacoon );
		RacoonProcess->addArgument( "-F" ); // foreground we want :)
		RacoonProcess->addArgument( "-f" );
		RacoonProcess->addArgument( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf" );
		RacoonProcess->addArgument( "-l" ); // logfile (we get content with tail process)
		RacoonProcess->addArgument( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" );
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "racoon: " +GlobalConfig->pathToRacoon+ " -f "+tmpPath+"/racoon"+ GlobalConfig->currentProfile->getName() + ".conf", GlobalConfig->debug );


		connect( RacoonProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoon() ) );
		connect( RacoonProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoon() ) );


		if ( !RacoonProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("racoon") );
			GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("racoon") ,GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			doTailRacoonLog();
			racoonStarted();
			if ( GlobalConfig->RacoonDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "debug: racoon: " + GlobalConfig->pathToRacoon + " -f " + tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf", GlobalConfig->debug );

			//			sec = hour = min = 0;

			//    GlobalConfig->status = GlobalConfig->disconnected;
			// 			timer.stop();
			//			connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
			//			durationTimer.start( 1000, FALSE );
		}
	}

}

void KVpnc::removeRouteRacoon()
{

	if ( DisconnectProcess->normalExit () )
	{
		if ( DisconnectProcess )
			disconnect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeRouteRacoon() ) );
		/*
		route del -net 192.168.1.0/24 eth0
		*/
		putenv( ( char* ) ( "LC_ALL=C" ) );
		DisconnectProcess->clearArguments();
		DisconnectProcess->addArgument( "/sbin/route" );
		DisconnectProcess->addArgument( "del" );
		DisconnectProcess->addArgument( "-net" );
		QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
		QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
		QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;
		DisconnectProcess->addArgument( RemoteNet );
		QString dev;
		//   NetworkInterface iface(parent);
		//   if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" ) {
		//
		//    QString defaultinterface=iface.getDefaultInterface();
		//    dev = defaultinterface;
		//    DisconnectProcess->addArgument( dev );
		//   } else

		if (!GlobalConfig->currentProfile->getUseVirtualIP())
		{
			dev = GlobalConfig->currentProfile->getNetworkDevice();

			if ( dev == "default" || dev.isEmpty() )
				dev = tmpInterface;

		}
		else
			dev = QString(GlobalConfig->currentProfile->getNetworkDevice()+":100");

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n( "Default interface: %1" ).arg( dev ), GlobalConfig->debug);

		if ( GlobalConfig->KvpncDebugLevel	 > 0 )
			GlobalConfig->appendLogEntry ( i18n( "Network device: %1" ).arg( dev ), GlobalConfig->debug );
		DisconnectProcess->addArgument( dev );
		tmpInterface = dev;
		connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesRacoon() ) );

		if ( !DisconnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("route del") );
			GlobalConfig->appendLogEntry( i18n( "\"%1\" start failed!" ).arg("route del")  ,GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "route: route del -net "  + RemoteNet + " " + tmpInterface, GlobalConfig->debug);
		}
	}
}

void KVpnc::removeIptablesRacoon()
{
	if ( DisconnectProcess->normalExit () )
	{
		if ( DisconnectProcess )
			disconnect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesRacoon() ) );

		putenv( ( char* ) ( "LC_ALL=C" ) );
		DisconnectProcess->clearArguments();
		DisconnectProcess->addArgument( "/bin/sh" );
		DisconnectProcess->addArgument( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_racoon.sh" );
		if ( !DisconnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".remove_ipsec_racoon.sh" ) );
			GlobalConfig->appendLogEntry(  i18n( "\"%1\" start failed!" ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".remove_ipsec_racoon.sh" ),GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".remove_ipsec_racoon.sh"  ), GlobalConfig->debug );
		}
	}
}

void KVpnc::removeSetkey()
{
	if ( DisconnectProcess )
		disconnect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeSetkey() ) );

	putenv( ( char* ) ( "LC_ALL=C" ) );
	DisconnectProcess = new QProcess ( this );
	DisconnectProcess->addArgument( "/bin/sh" );
	DisconnectProcess->addArgument( tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh" );

	connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoon() ) );
	connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoon() ) );
	connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeRouteRacoon() ) );

	if ( !DisconnectProcess->start() )
	{
		KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("setkey (remove)") );
		GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("setkey (remove)") ,GlobalConfig->error);
		disconnectClicked();
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "\"%1\" started." ).arg("setkey (remove)"), GlobalConfig->debug );
	}

	connectionEnded();
}

void KVpnc::doRouteFreeswan()
{

	if ( ConnectProcess->normalExit () )
	{
		disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doRouteFreeswan() ) );
		/*
		route add -net 192.168.1.0/24 ipsec0
		*/
		putenv( ( char* ) ( "LC_ALL=C" ) );
		ConnectProcess->clearArguments();
		ConnectProcess->addArgument( "/sbin/route" );
		ConnectProcess->addArgument( "add" );
		ConnectProcess->addArgument( "-net" );
		QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
		QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
		QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;
		ConnectProcess->addArgument( RemoteNet );
		ConnectProcess->addArgument( "ipsec0" );
		QString dev;

		dev = GlobalConfig->currentProfile->getNetworkDevice();

		NetworkInterface iface(GlobalConfig,parent);
		QString defaultinterface = "Defaultinterface: " + iface.getDefaultInterface();

		if ( dev.isEmpty() )
		{
			if ( defaultinterface.isEmpty() )
				dev = "lo";
			dev = defaultinterface;
		}

		if (GlobalConfig->currentProfile->getUseVirtualIP())
			dev= QString(dev+":100");

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Default interface: %1" ).arg( defaultinterface ), GlobalConfig->debug );

		ConnectProcess->addArgument( dev );
		tmpInterface = dev;
		connect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doIptablesFreeswan() ) );

		if ( !ConnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("route (freeswan)") );
			GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("route (freeswan)") ,GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n( "route (freeswan): route add -net " ) + RemoteNet + " " + tmpInterface, GlobalConfig->debug );
		}
	}
}

void KVpnc::doIptablesFreeswan()
{
	if ( ConnectProcess->normalExit () )
	{
		disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doIptablesFreeswan() ) );
		/*
		iptables -I INPUT -p 50 -i $IFACE -s $VPNGW_IP -j ACCEPT
		*/
		putenv( ( char* ) ( "LC_ALL=C" ) );
		ConnectProcess->clearArguments();
		ConnectProcess->addArgument( "/bin/sh" );
		ConnectProcess->addArgument( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh" );

		if ( !ConnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("iptables."+GlobalConfig->currentProfile->getName()+".add_ipsec_freeswan.sh" ) );
			GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("iptables."+GlobalConfig->currentProfile->getName()+".add_ipsec_freeswan.sh" ) ,GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("iptables.%1.add_ipsec_freeswan.sh"), GlobalConfig->debug );

			if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
				executeCommandAfterConnect();
		}
	}
}

void KVpnc::removeRouteFreeswan()
{

	if ( DisconnectProcess->normalExit () )
	{
		disconnect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeRouteFreeswan() ) );
		/*
		route del -net 192.168.1.0/24 eth0
		*/
		putenv( ( char* ) ( "LC_ALL=C" ) );
		DisconnectProcess->clearArguments();
		DisconnectProcess->addArgument( "/sbin/route" );
		DisconnectProcess->addArgument( "del" );
		DisconnectProcess->addArgument( "-net" );
		QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
		QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
		QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;
		DisconnectProcess->addArgument( RemoteNet );
		DisconnectProcess->addArgument( "ipsec0" );
		QString dev;
		NetworkInterface iface(GlobalConfig,parent);
		//   if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" ) {
		//
		//    QString defaultinterface=iface.getDefaultInterface();
		//    dev = defaultinterface;
		//    DisconnectProcess->addArgument( dev );
		//   } else
		dev = GlobalConfig->currentProfile->getNetworkDevice();

		if (GlobalConfig->KvpncDebugLevel > 0)
		{
			QString defaultinterface=iface.getDefaultInterface();
			GlobalConfig->appendLogEntry( i18n("Default interface: %1").arg(defaultinterface), GlobalConfig->debug );
			GlobalConfig->appendLogEntry ( i18n("Device: %1").arg(dev ), GlobalConfig->debug);
		}
		DisconnectProcess->addArgument( dev );
		tmpInterface = dev;
		connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesFreeswan() ) );

		if ( !DisconnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("route (freeswan) del") );
			GlobalConfig->appendLogEntry(  i18n( "\"%1\" start failed!" ).arg("route (freeswan) del") ,GlobalConfig->error);
			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "route(freeswan): route del -net " + RemoteNet + " " + tmpInterface, GlobalConfig->debug );
		}
	}
}

void KVpnc::removeIptablesFreeswan()
{
	if ( DisconnectProcess->normalExit () )
	{
		disconnect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesFreeswan() ) );

		putenv( ( char* ) ( "LC_ALL=C" ) );
		DisconnectProcess->clearArguments();
		DisconnectProcess->addArgument( "/bin/sh" );
		DisconnectProcess->addArgument( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh" );
		if ( !DisconnectProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".remove_ipsec_freeswan.sh" ) );
			GlobalConfig->appendLogEntry(  i18n( "\"%1\" start failed!" ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".remove_ipsec_freeswan.sh" ),GlobalConfig->error);
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg( "iptables."+GlobalConfig->currentProfile->getName()+".remove_ipsec_freeswan.sh" ), GlobalConfig->debug );
		}
	}
	disconnectClicked();
}

void KVpnc::doPingTest()
{
	/*
	ping -c3 -I <interfaceIP> <gateway>
	*/
	QString LocalIP;
	QString Interface;
	NetworkInterface iface(GlobalConfig,parent);
	//LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
	if ( GlobalConfig->currentProfile->getNetworkDevice().isEmpty() )
		Interface = iface.getInterfaceIP( iface.getDefaultInterface() );
	else
		Interface = GlobalConfig->currentProfile->getNetworkDevice();
	QString PingHostIP = GlobalConfig->currentProfile->getPingHostIP();
	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry( i18n( "Host for ping: %1" ).arg( PingHostIP ), GlobalConfig->debug );

	/* first: kick up the tunnel */
	putenv( ( char* ) ( "LC_ALL=C" ) );
	PingProcess = new QProcess( this );

	QString PathToPing="";
	ToolInfo *Tool;
	for (Tool=GlobalConfig->ToolList->first();Tool;Tool=GlobalConfig->ToolList->next())
	{
		if (Tool->Name == "ping")
		{
			PathToPing=Tool->PathToExec;
			break;
		}
	}
	PingProcess->addArgument(PathToPing);
	PingProcess->addArgument( "-c1" );
	PingProcess->addArgument( PingHostIP );
	if ( !PingProcess->start() )
	{
		KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "ping "+GlobalConfig->currentProfile->getPingHostIP() ) );
		GlobalConfig->appendLogEntry( i18n( "\"%1\" start failed!" ).arg( "ping "+GlobalConfig->currentProfile->getPingHostIP() ),GlobalConfig->error);
	}
	else
	{
		//sleep( 3 );
		PingProcess->kill();
		/* second: real ping */
		PingProcess->clearArguments();
		PingProcess->addArgument( PathToPing );
		PingProcess->addArgument( "-c5" );
		PingProcess->addArgument( "-v" );
		//PingProcess->addArgument( "-I" );
		//PingProcess->addArgument( Interface );
		PingProcess->addArgument( PingHostIP );

		connect( PingProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_ping() ) );
		connect( PingProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_ping() ) );
		connect( PingProcess, SIGNAL( processExited() ), this, SLOT( pingTestExited() ) );

		pingtest = true;

		if ( !PingProcess->start() )
		{
			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "ping "+GlobalConfig->currentProfile->getPingHostIP() ) );
			GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "ping "+GlobalConfig->currentProfile->getPingHostIP() ) ,GlobalConfig->error);
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("ping"), GlobalConfig->debug );
			//sleep(5);
			PingProcess->kill();
			PingProcess->start();
		}
	}
}

void KVpnc::pingTestExited()
{
	disconnect( PingProcess, SIGNAL( processExited () ), this, SLOT( pingTestExited() ) );
	//  disconnect( PingProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_ping() ) );
	//  disconnect( PingProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_ping() ) );
	// pingtest = false;
}

void KVpnc::vpncStarted()
{
	disconnect ( ConnectProcess, SIGNAL( processExited () ), this, SLOT( vpncStarted() ) );

	/* doing some after tunnel is up */

	//   ConnectProcess->clearArguments();
	//   ConnectProcess->addArgument( "/bin/sh" );
	//   ConnectProcess->addArgument( VpncConnectScript );
	//
	//   connect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_vpnc() ) );
	//   connect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_vpnc() ) );
	//
	//   if ( !ConnectProcess->start() ) {
	//    KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "vpnc-connect" ) );
	//   } else {
	//    GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("vpnc-connect"),GlobalConfig->info );
	//
	//    //                                 connect( &timer, SIGNAL( timeout() ), this, SLOT( slotConnectTimedOut() ) );
	//    //                                 timer.start( tryConnectTimeout * 1000, FALSE );
	//    //
	//    //                                 mw->buttonConnect->setEnabled( false );
	//
	//   }


}

void KVpnc::racoonStarted()
{}

void KVpnc::freeswanStarted()
{
	disconnect ( FreeswanProcess, SIGNAL( processExited () ), this, SLOT( freeswanStarted() ) );


	if (GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry("[freeswan] "+i18n( "Starting connection \"%1\"..." ).arg( GlobalConfig->currentProfile->getName() ) ,GlobalConfig->debug);

	/* Kick up the connection */
	FreeswanProcess = new QProcess ( this );
	//
	FreeswanProcess->addArgument( GlobalConfig->pathToFreeswan );
	FreeswanProcess->addArgument( "auto" );
	if (GlobalConfig->enableFreeswanVerbose)
		FreeswanProcess->addArgument( "--verbose" );
	FreeswanProcess->addArgument( "--up" );
	FreeswanProcess->addArgument( GlobalConfig->currentProfile->getName() );


	connect( FreeswanProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_freeswan() ) );
	connect( FreeswanProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_freeswan() ) );
	// 			connect( FreeswanProcess, SIGNAL( processExited () ), this, SLOT( doRouteFreeswan() ) );

	if ( !FreeswanProcess->start() )
	{
		KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "freeswan (ipsec): connection" ) );
		GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "freeswan (ipsec): connection" ) ,GlobalConfig->error);
		disconnectClicked();
		setGuiStatus(disconnected);
	}
	else
	{
		connectionTime.start();
		connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		ConnectingProcess = VpnAccountData::freeswan;
		GlobalConfig->status = GlobalConfig->connecting;
		mw->buttonDisconnect->setEnabled( true );
		durationTimer.start( 1000, FALSE );
		setGuiStatus(connected);
		GlobalConfig->status = GlobalConfig->connected;

		if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
			executeCommandAfterConnect();

		if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
			addAdditionalNetworkRoutes();
	}
}

void KVpnc::pppdStarted()
{
	disconnect ( PptpProcess, SIGNAL( processExited () ), this, SLOT( pppdStarted() ) );

	// do replace default route (pppd 2.4.2 doesnt support it)
	//ip route replace default dev ppp0

	QString pppdev="";
	if (!PppdDevice.isEmpty())
		pppdev=PppdDevice;
	else
		pppdev="ppp0";

	if (GlobalConfig->currentProfile->getReplaceDefaultRoute())
	{
		tmpPath = locateLocal ( "data", "kvpnc/" );
		QString PppdReplaceDefaultRouteScript = tmpPath + "pppd_replace_defaultroute." + GlobalConfig->currentProfile->getName()+".sh";

		QFile file ( PppdReplaceDefaultRouteScript );
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
		{
			stream << "# generated by kvpnc. Do not edit it." << "\n";
			stream << "\n";
			stream << "ip route replace default dev "+pppdev+"\n";
			file.close();
		}

		ReplaceDefaultRouteProcess = new QProcess(this);
		ReplaceDefaultRouteProcess->addArgument("/bin/sh");
		ReplaceDefaultRouteProcess->addArgument(PppdReplaceDefaultRouteScript);
		if ( !ReplaceDefaultRouteProcess->start() )
		{
			KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( i18n("pppd replace route process") ) );
			// 			disconnectClicked();
			// 			setGuiStatus(disconnected);
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg(i18n("pppd replace route process")),GlobalConfig->info );
		}
	}
	PptpRouteProcess = new QProcess(this);
	PptpRouteProcess->addArgument(GlobalConfig->pathToRoute);
	PptpRouteProcess->addArgument("add");
	PptpRouteProcess->addArgument("-net");
	PptpRouteProcess->addArgument(GlobalConfig->currentProfile->getRemoteNetAddr()+"/"+GlobalConfig->currentProfile->getRemoteNetMask());
	PptpRouteProcess->addArgument(pppdev);

	if ( !PptpRouteProcess->start() )
	{
		KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( i18n("pppd route process") ) );
		// 			disconnectClicked();
		// 			setGuiStatus(disconnected);
	}
	else
	{
		GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg(i18n("pppd route process")),GlobalConfig->info );
	}
}

void KVpnc::openvpnStarted()
{
	disconnect ( OpenvpnProcess, SIGNAL( processExited () ), this, SLOT( openvpnStarted() ) );

}

QString KVpnc::getX509CertificateID( QString Cert, bool user )
{
	issuerID = "";
	userID = "";

	/*
	issuer
	openssl x509 -noout -issuer -in mykeys.pem

	user
	openssl x509 -noout -subject -in mykeys.pem
	*/
	putenv( ( char* ) ( "LC_ALL=C" ) );
	X509CertificateExtractProcess = new QProcess ( this );
	X509CertificateExtractProcess->addArgument( GlobalConfig->pathToOpenssl );
	X509CertificateExtractProcess->addArgument( "x509" );
	X509CertificateExtractProcess->addArgument( "-noout" );
	if ( user )
		X509CertificateExtractProcess->addArgument( "-subject" );
	else
		X509CertificateExtractProcess->addArgument( "-issuer" );

	X509CertificateExtractProcess->addArgument( "-in" );
	X509CertificateExtractProcess->addArgument( Cert );

	X509CertificateExtractUser = user;

	connect( X509CertificateExtractProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_getX509CertificateID() ) );
	connect( X509CertificateExtractProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_getX509CertificateID() ) );
	connect( X509CertificateExtractProcess, SIGNAL( processExited () ), this, SLOT( openSSLEnded() ) );

	if ( !X509CertificateExtractProcess->start() )
	{
		KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("openssl") );
		GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("openssl") ,GlobalConfig->error);
		return "";
	}
	else
	{
		//KMessageBox::information( this, i18n( "\"%1\" started." ).arg("openssl") );
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "\"%1\" started." ).arg("openssl (getCertificate)"), GlobalConfig->debug );
		X509CertificateExtractRunning = true;

		while ( X509CertificateExtractRunning )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry( i18n( "Waiting for process end (getCertificate)." ), GlobalConfig->debug );
			parent->QApplication::processEvents();
		}
		disconnect( X509CertificateExtractProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_getX509CertificateID() ) );
		disconnect( X509CertificateExtractProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_getX509CertificateID() ) );
		disconnect( X509CertificateExtractProcess, SIGNAL( processExited () ), this, SLOT( openSSLEnded() ) );
		delete X509CertificateExtractProcess;
		if ( user )
			return userID;
		else
			return issuerID;
	}

}

void KVpnc::readFromStdout_getX509CertificateID()
{
	QString ProcessMsg = "";
	if ( X509CertificateExtractProcess->canReadLineStdout() )
		ProcessMsg = X509CertificateExtractProcess->readLineStdout();
	if ( !ProcessMsg.isEmpty() )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "ID found: %1" ).arg( ProcessMsg.section( '=', 1 ) ), GlobalConfig->debug );
		if ( X509CertificateExtractUser )
		{
			userID = ProcessMsg.section( '=', 1 ); // subject = /C=DE... => /C=DE...
			if ( userID.left( 0 ) == " " )
				userID = userID.right( userID.length() - 1 );

		}
		else
		{
			issuerID = ProcessMsg.section( '=', 1 ); // issuer= /C=DE... => /C=DE...
			if ( issuerID.left( 0 ) == " " )
				issuerID = issuerID.right( issuerID.length() - 1 );
		}
	}
}

void KVpnc::readFromStderr_getX509CertificateID()
{
	QString ProcessMsg = QString( X509CertificateExtractProcess->readStderr() );
	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry( i18n( "getX509CertificateID() err: %1" ).arg( ProcessMsg ), GlobalConfig->debug );
}

void KVpnc::openSSLEnded()
{
	X509CertificateExtractRunning = false;
	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry( i18n( "OpenSSL finished.\n" ), GlobalConfig->debug );

}

void KVpnc::importCertClicked()
{
	ImportCertificateDialog dlg( this, i18n("Import Certificate...").ascii(), GlobalConfig);
	//int result =
	dlg.exec();
}

void KVpnc::showProfileManagerClicked()
{
	PreferencesDialog manager( this,parent, mw->DebugOutput, GlobalConfig, true);
	manager.setMinimumSize(800,600);

	VpnAccountData *oldProfile = GlobalConfig->currentProfile;

	manager.exec();

	if (manager.profileAddedOrDeleted)
	{
		if (GlobalConfig->AccountList->isEmpty())
		{
			GlobalConfig->currentProfile=0L;
			mw->SessionCombo->setEnabled ( FALSE );
		}
		else
		{
			if ( GlobalConfig->currentProfile != 0 )
				if (GlobalConfig->currentProfile->getName() != mw->SessionCombo->currentText())
					GlobalConfig->currentProfile=oldProfile; // restore from before calling pref dialog

		}

		profileAddedOrDeleted();
		if (!manager.NewProfileName.isEmpty())
		{
			mw->SessionCombo->setCurrentText(manager.NewProfileName);
			sessionToggled(manager.NewProfileName);
		}
	}
}

void KVpnc::executeCommandBeforeConnect()
{
	if ( GlobalConfig->currentProfile->getExecuteCmdBeforeConnect() &&  !GlobalConfig->currentProfile->getCommandBeforeConnect().isEmpty())
	{
		QString cmd = GlobalConfig->currentProfile->getCommandBeforeConnect();

		// write command after connect script
		QString CmdBeforeConnectScript = tmpPath + "cmd_before_connect_script." + GlobalConfig->currentProfile->getName();

		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry( "CmdBeforeConnectScript: " + CmdBeforeConnectScript + "\n", GlobalConfig->debug );
		QFile file ( CmdBeforeConnectScript );
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
			stream << cmd;
		file.close();

		CmdBeforeConnectProcess = new QProcess ( this );
		CmdBeforeConnectProcess->addArgument( "/bin/sh" );
		CmdBeforeConnectProcess->addArgument( CmdBeforeConnectScript );

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Executing command before connect:\n%1" ).arg( cmd ), GlobalConfig->debug );
		if ( !CmdBeforeConnectProcess->start() )
		{
			KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( CmdBeforeConnectScript ) );
			disconnectClicked();
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("CmdBeforeConnectScript"),GlobalConfig->info );
			while(CmdBeforeConnectProcess->isRunning())
				parent->QApplication::processEvents();
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" finished." ).arg("CmdBeforeConnectScript"),GlobalConfig->info );
		}

	}
}

void KVpnc::executeCommandAfterConnect()
{
	if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect() && !GlobalConfig->currentProfile->getCommandAfterConnect().isEmpty())
	{
		QString cmd = GlobalConfig->currentProfile->getCommandAfterConnect();

		// write command after connect script
		QString CmdAfterConnectScript = tmpPath + "cmd_after_connect_script." + GlobalConfig->currentProfile->getName();
		if(GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry( "CmdAfterConnectScript: " + CmdAfterConnectScript + "\n", GlobalConfig->debug );
		QFile file ( CmdAfterConnectScript );
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
			stream << cmd;
		file.close();

		CmdAfterConnectProcess = new QProcess ( this );
		CmdAfterConnectProcess->addArgument( "/bin/sh" );
		CmdAfterConnectProcess->addArgument( CmdAfterConnectScript );

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Executing command after connect:\n%1" ).arg( cmd ), GlobalConfig->debug );
		if ( !CmdAfterConnectProcess->start() )
		{
			KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( CmdAfterConnectScript ) );
			disconnectClicked();
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("CmdAfterConnectScript"),GlobalConfig->info );
			while(CmdAfterConnectProcess->isRunning())
				parent->QApplication::processEvents();
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" finished." ).arg("CmdAfterConnectScript"),GlobalConfig->info );
		}

	}
}

void KVpnc::executeCommandBeforeDisconnect()
{
	if (GlobalConfig->currentProfile->getExecuteCmdBeforeDisconnect() &&  !GlobalConfig->currentProfile->getCommandBeforeDisconnect().isEmpty())
	{
		QString cmd = GlobalConfig->currentProfile->getCommandBeforeDisconnect();

		// write command after connect script
		QString CmdBeforeDisconnectScript = tmpPath + "cmd_before_disconnect_script." + GlobalConfig->currentProfile->getName();
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry( "CmdBeforeDisconnectScript: " + CmdBeforeDisconnectScript + "\n", GlobalConfig->debug );
		QFile file ( CmdBeforeDisconnectScript );
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
			stream << cmd;
		file.close();

		CmdBeforeDisconnectProcess = new QProcess ( this );
		CmdBeforeDisconnectProcess->addArgument( "/bin/sh" );
		CmdBeforeDisconnectProcess->addArgument( CmdBeforeDisconnectScript );

		if ( !CmdBeforeDisconnectProcess->start() )
		{
			KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( CmdBeforeDisconnectScript ) );
			disconnectClicked();
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("CmdBeforeDisconnectScript") ,GlobalConfig->info);
			while(CmdBeforeDisconnectProcess->isRunning())
				parent->QApplication::processEvents();
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" finished." ).arg("CmdBeforeDisconnectScript"),GlobalConfig->info );
		}

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Executing command before disconnect:\n%1" ).arg( cmd ), GlobalConfig->debug );
	}
}

void KVpnc::executeCommandAfterDisconnect()
{
	if (GlobalConfig->currentProfile->getExecuteCmdAfterDisconnect() && !GlobalConfig->currentProfile->getCommandAfterDisconnect().isEmpty())
	{
		QString cmd = GlobalConfig->currentProfile->getCommandAfterDisconnect();

		// write command after connect script
		QString CmdAfterDisconnectScript = tmpPath + "cmd_after_disconnect_script." + GlobalConfig->currentProfile->getName();

		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry( "CmdAfterDisconnectScript: " + CmdAfterDisconnectScript + "\n", GlobalConfig->debug );
		QFile file ( CmdAfterDisconnectScript );
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
			stream << cmd;
		file.close();

		CmdAfterDisconnectProcess = new QProcess ( this );
		CmdAfterDisconnectProcess->addArgument( "/bin/sh" );
		CmdAfterDisconnectProcess->addArgument( CmdAfterDisconnectScript );

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Executing command after disconnect:\n%1" ).arg( cmd ), GlobalConfig->debug );
		if ( !CmdAfterConnectProcess->start() )
		{
			KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( CmdAfterDisconnectScript ) );
			disconnectClicked();
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("CmdAfterDisconnectScript"),GlobalConfig->info );
			while(CmdAfterDisconnectProcess->isRunning())
				parent->QApplication::processEvents();
			GlobalConfig->appendLogEntry ( i18n( "\"%1\" finished." ).arg("CmdAfterDisconnectScript"),GlobalConfig->info );
		}
	}
}

void KVpnc::doRoutePptp()
{
	/*
	route add -net 192.168.1.0/24 eth0
	*/
	putenv( ( char* ) ( "LC_ALL=C" ) );
	RouteProcess = new QProcess(this);
	RouteProcess->addArgument( "/sbin/route" );
	RouteProcess->addArgument( "add" );
	RouteProcess->addArgument( "-net" );
	QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
	QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
	QString RemoteNet = RemoteNetAddr+"/"+RemoteNetMask;
	RouteProcess->addArgument( RemoteNet );
	QString dev;

	if (!GlobalConfig->currentProfile->getNetworkDevice().isEmpty())
		dev = GlobalConfig->currentProfile->getNetworkDevice();
	else
		dev="ppp0";

	if (GlobalConfig->KvpncDebugLevel > 0)
	{
		NetworkInterface iface(GlobalConfig,parent);
		QString defaultinterface=iface.getDefaultInterface();
		GlobalConfig->appendLogEntry( i18n("Default interface %1").arg(defaultinterface), GlobalConfig->debug );
	}

	RouteProcess->addArgument( dev );
	tmpInterface = dev;

	connect( RouteProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_pptp() ) );
	connect( RouteProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_pptp() ) );

	if ( !RouteProcess->start() )
	{
		KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("route") );
		GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("route") ,GlobalConfig->error);
		disconnectClicked();
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "route: \"route add -net "  + RemoteNet + " " + tmpInterface + "\"", GlobalConfig->debug );
	}

}

void KVpnc::slotConnecting()
{
	setGuiStatus(connecting);
}

void KVpnc::profileAddedOrDeleted()
{

	if ( !GlobalConfig->lastProfile.isEmpty() )
	{
		// 		mw->SessionCombo->setCurrentItem( 1 );
		sessionToggled( GlobalConfig->lastProfile );
	}

	if ( !GlobalConfig->AccountList->isEmpty() )
	{
		this->deleteSessionAction->setEnabled ( TRUE );
		//    this->advancedSessionAction->setEnabled ( TRUE );
		this->saveSessionAction->setEnabled ( TRUE );
		this->importSessionAction->setEnabled ( TRUE );

		this->connectAction->setEnabled ( TRUE );
		mw->buttonConnect->setEnabled ( TRUE );

		mw->SessionCombo->clear();
		QuickConnectMenu->clear();
		VpnAccountData *it;
		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			QuickConnectMenu->insertItem(it->getName());
			mw->SessionCombo->insertItem(it->getName());
		}

	}
	else
	{
		this->deleteSessionAction->setEnabled ( FALSE );
		//    this->advancedSessionAction->setEnabled ( FALSE );
		this->saveSessionAction->setEnabled ( FALSE );
		this->importSessionAction->setEnabled ( TRUE );

		this->connectAction->setEnabled ( FALSE );
		mw->buttonConnect->setEnabled ( FALSE );
	}

}

bool KVpnc::setVirtualIP()
{
	/*
	if (GlobalConfig->currentProfile->getNetworkDevice().isEmpty() || GlobalConfig->currentProfile->getVirtualIP().isEmpty()){
	KMessageBox::error ( this, i18n( "Empty interface or empty virtual IP!" ), i18n( "Bad Value" ) );
	return false;
	}
	if (!Utils( GlobalConfig, parent ).isValidNetworkDevice(GlobalConfig->currentProfile->getNetworkDevice())){
	KMessageBox::error ( this, i18n( "Interface doesnt exits!" ), i18n( "No Interface" ) );
	return false;
	}

	setVirtualIPSuccess=true;
	SetVirtualIPProcess = new QProcess(this);
	SetVirtualIPProcess->addArgument("/sbin/ifconfig");
	SetVirtualIPProcess->addArgument(QString(NetworkDevice+":100"));
	SetVirtualIPProcess->addArgument(GlobalConfig->currentProfile->getVirtualIP());
	connect( SetVirtualIPProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_setVirtualIP() ) );
	connect( SetVirtualIPProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_setVirtualIP() ) );

	if ( !SetVirtualIPProcess->start() )
	{
	std::cerr << i18n("Unable to set virtual IP!") << std::endl;
	return false;
	}
	else {
	while (SetVirtualIPProcess->isRunning()) {}
	return setVirtualIPSuccess;
	}
	*/


	return false;
}

void KVpnc::toggleDebugConsole()
{
	if ( !GlobalConfig->showDebugConsole )
	{
		GlobalConfig->showDebugConsole = true;
		debugconsoleAction ->setChecked( true );
		mw->DebugOutput->show();
		//resize( minimumSizeHint() );
	}
	else
	{
		GlobalConfig->showDebugConsole=false;
		debugconsoleAction ->setChecked( false );
		mw->DebugOutput->hide();
		// 		setMinimumSize(0,0);
		// 		this->resize( minimumSizeHint() );
	}
}

void KVpnc::addAdditionalNetworkRoutes()
{
	if (GlobalConfig->currentProfile == 0)
		return;

	if  (!GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Setting additional network routes..." ), GlobalConfig->debug);
		QStringList AdditionalNetworkRoutes = GlobalConfig->currentProfile->getAdditionalNetworkRoutes();


		QString dev = GlobalConfig->currentProfile->getNetworkDevice();

		NetworkInterface iface(GlobalConfig,parent);
		QString defaultinterface = iface.getDefaultInterface();


		if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
		{
			if ( dev.isEmpty() )
			{
				if ( defaultinterface.isEmpty() )
					dev = "lo";
				else
					dev = defaultinterface;

			}
		}
		else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco ||
		         GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		{
			if ( dev.isEmpty() || dev=="default" )
			{
				//FIXME dynamiclly?
				dev="tun0";
			}
		}
		else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
		{
			if ( dev.isEmpty() || dev=="default" )
			{
				//FIXME dynamiclly?
				dev="ipsec0";
			}
		}
		else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
		{
			//if ( dev.isEmpty() || dev=="default" )
			{
				//FIXME dynamiclly?
				dev="ppp0";
			}
		}

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Default interface: %1" ).arg( dev ), GlobalConfig->debug );

		QString tmpPath = locateLocal ( "data", "kvpnc/" );
		QFile file( tmpPath + "addAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh" );
		QString Routes="";
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
		{
			for (QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end();++it)
			{
				QString net = (*it).section('#',0,0);

				QString Gateway=QString(*it).section('#',1,1);
				QString GatewayString ="";
				if (!Gateway.isEmpty() && Gateway!="-")
				{
					GatewayString+="gateway ";
					GatewayString+=Gateway;
					Routes+=net+" "+i18n("over")+Gateway+"\n";
				}
				else
				{
					Routes+=net+"\n";
				}

				if (net.find("/32") > 0 )
					stream << "/sbin/route add " << net << GatewayString << " " << dev << "\n";
				else
					stream << "/sbin/route add -net " << net << " " <<  GatewayString << " " << dev << "\n";

			}
			file.close();
			RouteProcess = new QProcess(this);
			RouteProcess->addArgument( "/bin/sh" );
			RouteProcess->addArgument( tmpPath + "addAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh" );
			tmpInterface = dev;

			connect( RouteProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_route() ) );
			connect( RouteProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_route() ) );

			if ( !RouteProcess->start() )
			{
				KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("route (addtitional network routes)") );
				GlobalConfig->appendLogEntry( i18n( "\"%1\" start failed!" ).arg("route (addtitional network routes)")  ,GlobalConfig->error);
				//disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n( "Adding the following additional network routes:\n" ) + Routes, GlobalConfig->debug );
				while (RouteProcess->isRunning())
					parent->processEvents();
				disconnect( RouteProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_route() ) );
				disconnect( RouteProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_route() ) );
			}
		}
	}
}

void KVpnc::removeAdditionalNetworkRoutes()
{
	if( !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
	{
		QStringList AdditionalNetworkRoutes = GlobalConfig->currentProfile->getAdditionalNetworkRoutes();
		QString dev = GlobalConfig->currentProfile->getNetworkDevice();

		NetworkInterface iface(GlobalConfig,parent);
		QString defaultinterface = iface.getDefaultInterface();

		if ( dev.isEmpty() )
		{
			if ( defaultinterface.isEmpty() )
				dev = "lo";
		}
		dev = defaultinterface;

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Default interface: %1" ).arg( defaultinterface ), GlobalConfig->debug );

		tmpPath = locateLocal ( "data", "kvpnc/" );
		QFile file( tmpPath + "delAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh" );
		QString Routes="";
		QTextStream stream( &file );
		if ( file.open( IO_WriteOnly ) )
		{
			for (QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end();++it)
			{
				QString net = (*it).section('#',0,0);
				QString Gateway=QString(*it).section('#',1,1);
				QString GatewayString ="";
				if (!Gateway.isEmpty() && Gateway!="-")
				{
					GatewayString+="gateway ";
					GatewayString+=Gateway;
					Routes+=net+" "+i18n("over")+Gateway+"\n";
				}
				else
				{
					Routes+=net+"\n";
				}

				if (net.find("/32") > 0 )
					stream << "/sbin/route del " << net << GatewayString << " " << dev << "\n";
				else
					stream << "/sbin/route del -net " << net << " " <<  GatewayString << " " << dev << "\n";

			}
			file.close();
			RouteProcess = new QProcess(this);
			RouteProcess->addArgument( "/bin/sh" );
			RouteProcess->addArgument( tmpPath + "delAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh" );
			tmpInterface = dev;

			if ( !RouteProcess->start() )
			{
				KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("route (addtitional network routes)") );
				GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg("route (addtitional network routes)") ,GlobalConfig->error);
				//disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n( "Removing the following additional network routes:\n" ) + Routes, GlobalConfig->debug );
				while (RouteProcess->isRunning())
					parent->processEvents();
			}

		}
	}
}

void KVpnc::showLogViewer()
{
	LogViewerDialog dlg(this,parent ,GlobalConfig, i18n("Log Viewer"));
	LogViewerAction->setChecked(true);
	dlg.exec();
	LogViewerAction->setChecked(false);
}

void KVpnc::doQuickConnect(int id)
{
	QString itemtext=QuickConnectMenu->text(id );
	if (GlobalConfig->status == GlobalConfig->connected)
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("Connect to \"%1\" requested but still to \"%2\" connected, current connection will be terminated.").arg(GlobalConfig->currentProfile->getName()).arg(itemtext),GlobalConfig->info);
		disconnectClicked();
	}
	//KMessageBox::information(0,"item",QString("item: "+itemtext));
	if (GlobalConfig->KvpncDebugLevel > 0)
		GlobalConfig->appendLogEntry(i18n("Connect to \"%1\" requested.").arg(itemtext),GlobalConfig->info);
	sessionToggled( itemtext );
	connectClicked();
}

void KVpnc::saveGuiOptions()
{
	GlobalConfig->config->setGroup( "General Options" );
	GlobalConfig->config->writeEntry( "Mainwindow width", width() );
	GlobalConfig->config->writeEntry( "Mainwindow height", height() );
	GlobalConfig->config->writeEntry( "Mainwindow position x", x() );
	GlobalConfig->config->writeEntry( "Mainwindow position y", y() );
	toolBar( "mainToolBar" ) ->saveSettings( GlobalConfig->config, "ToolBar Settings" );
	GlobalConfig->config->sync();
}

void KVpnc::startConnectionStatusCheck()
{
	KStandardDirs *dirs = KGlobal::dirs();
	QString PingCheckScript = QString(dirs->findResource("data", "kvpnc/ping_check.sh" ));
	//GlobalConfig->appendLogEntry( QString("PingCheckScript : " +PingCheckScript), GlobalConfig->debug);
	ConnectionStatusCheckProcess = new QProcess(this);
	ConnectionStatusCheckProcess->addArgument("/bin/sh");
	ConnectionStatusCheckProcess->addArgument(PingCheckScript);
	QString PathToPing=Utils(GlobalConfig).getToolInfo(GlobalConfig,"ping")->PathToExec;

	ConnectionStatusCheckProcess->addArgument(PathToPing);
	if ( GlobalConfig->currentProfile->getDoPingIP() )
	{
		ConnectionStatusCheckProcess->addArgument(GlobalConfig->currentProfile->getPingHostIP());
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Use userdefined IP address (%1) for connection status check." ).arg(GlobalConfig->currentProfile->getPingHostIP()), GlobalConfig->debug );
	}
	else
	{
		ConnectionStatusCheckProcess->addArgument(GlobalConfig->currentProfile->getGateway());
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry( i18n( "Use gateway address (%1) for connection status check." ).arg(GlobalConfig->currentProfile->getGateway()), GlobalConfig->debug );
	}
	ConnectionStatusCheckProcess->addArgument(QString().setNum(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()));
	ConnectionStatusCheckProcess->addArgument(QString().setNum(GlobalConfig->currentProfile->getConnectionStatusInterval()));
	ConnectionStatusCheckProcess->addArgument(QString().setNum(1)); // verbosity

	connect( ConnectionStatusCheckProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_connectionStatusCheck() ) );
	connect( ConnectionStatusCheckProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_connectionStatusCheck() ) );

	if ( !ConnectionStatusCheckProcess->start() )
	{
		//KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "ping_check.sh" ) );
		GlobalConfig->appendLogEntry(i18n( "\"%1\" start failed!" ).arg( "ping_check.sh" ) ,GlobalConfig->error);
	}
	else
	{
		GlobalConfig->appendLogEntry ( i18n( "\"%1\" started." ).arg("ping_check.sh"),GlobalConfig->info );
	}
}

void KVpnc::generateOpenvpnKey()
{
	GenerateOpenvpnKeyDialog dlg(GlobalConfig,this,i18n("Generate Key"));
	dlg.exec();
}

void KVpnc::preserveNetworkEnvironment()
{
	// TODO really needed? What must be also saved?

	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry(i18n("Preserving network environment"), KVpncConfig::debug);

	// resolv.conf
	QFile originalResolvConfFile("/etc/resolv.conf");
	QString originalResolvConfFileContent="";
	if (originalResolvConfFile.open(IO_ReadOnly))
	{
		originalResolvConfFileContent = QString(originalResolvConfFile.readAll());
		originalResolvConfFile.close();
	}

	QFile backupOriginalResolvConfFile("/etc/resolv.conf.before.kvpnc");
	QTextStream stream(&backupOriginalResolvConfFile);
	if ( backupOriginalResolvConfFile.open( IO_WriteOnly ) )
	{
		stream << originalResolvConfFileContent;
		backupOriginalResolvConfFile.close();
	}

	// defaultroute
	QString tmpPath = locateLocal ( "data", "kvpnc/" );

	QString GetRouteScript = tmpPath+ "get_route.sh";

	QString backupOriginalRoute = locateLocal ( "data", "kvpnc/" );
	backupOriginalRoute+="route_before_kvpnc";

	QFile file ( GetRouteScript );
	stream.setDevice( &file );
	if ( file.open( IO_WriteOnly ) )
	{
		stream << "# generated by kvpnc. Do not edit it." << "\n";
		stream << "\n";
		stream << GlobalConfig->pathToIp +" route show > "+ backupOriginalRoute+"\n";
		file.close();
	}


	QProcess *proc = new QProcess(this);
	proc->addArgument( "/bin/sh" );
	proc->addArgument(GetRouteScript);


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

	if ( !proc->start(env) )
	{
		GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("script for getting original route info")), KVpncConfig::error);
	}
	else
	{
		//std::cout << "getDefaultInterface() started." << std::endl;
		while ( proc->isRunning())
		{
			parent->processEvents();
		}
	}

}

void KVpnc::restoreNetworkEnvironment()
{
	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry(i18n("Restoring network environment"), KVpncConfig::debug);

	// resolv.conf
	QFile originalResolvConfFile("/etc/resolv.conf.before.kvpnc");
	QString originalResolvConfFileContent="";
	if (originalResolvConfFile.open(IO_ReadOnly))
	{
		originalResolvConfFileContent = QString(originalResolvConfFile.readAll())	                                        ;
		originalResolvConfFile.close();
	}
	QFile backupOriginalResolvConfFile("/etc/resolv.conf");
	QTextStream stream(&backupOriginalResolvConfFile);
	if ( backupOriginalResolvConfFile.open( IO_WriteOnly ) )
	{
		stream << originalResolvConfFileContent;
		backupOriginalResolvConfFile.close()
		;
		originalResolvConfFile.remove();

	}

	// default route
	// TODO
	QString backupOriginalRoute = locateLocal ( "data", "kvpnc/" );
	backupOriginalRoute+="route_before_kvpnc";
	QFile backupOriginalRouteFile(backupOriginalRoute);

	// FIXME make it in GlobalConfig

	if ( backupOriginalRouteFile.open(IO_ReadOnly) )
	{
		QTextStream stream( &backupOriginalRouteFile )
		;
		QString line;
		while ( !stream.atEnd() )
		{
			line = stream.readLine();
			if ( line.contains( "default via" ) ) // default via 192.168.0.5 dev eth0
			{
				QString tmpPath = locateLocal ( "data", "kvpnc/" );
				QString RestoreDefaultrouteKvpncExitScript = tmpPath+ "restore_defaultroute_kvpnc_exit.sh";

				QFile file ( RestoreDefaultrouteKvpncExitScript );
				QTextStream stream( &file );
				if ( file.open( IO_WriteOnly ) )
				{
					stream << "# generated by kvpnc. Do not edit it." << "\n";
					stream << GlobalConfig->pathToRoute+" del default 2>&1>/dev/null\n";
					stream <<  GlobalConfig->pathToIp+" route add "+line+"\n"; // ip route add default via 192.168.0.5 dev eth0
					file.close();
				}

				QProcess *proc = new QProcess(this);
				proc->addArgument( "/bin/sh" );
				proc->addArgument(RestoreDefaultrouteKvpncExitScript);


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

				if ( !proc->start(env) )
				{
					GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)!").arg(i18n("script for restoring defaultroute on kvpnc exit")), KVpncConfig::error);
				}
				else
				{
					while ( proc->isRunning())
					{
						parent->processEvents();
					}
				}
				break;
			}
		}
		backupOriginalRouteFile.close();
	}
}

void KVpnc::showNewProfileWizardClicked()
{
	NewProfileWizard wizard(GlobalConfig);
	if ( wizard.exec() &&  wizard.newProfileCreated )
	{

		bool importOK = true;
		if ( importOK )
		{
			VpnAccountData * account = wizard.profileData;
// 			if (account->getUseConnectionStatusCheck())
// 				KMessageBox::information ( this, "Use connection status check: true", "value" );
// 			else
// 				KMessageBox::information ( this, "Use connection status check: false", "value" );

			VpnAccountData * it;
			bool nameOk=false;
			while (nameOk==false)
			{
				for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
				{
					if ( it->getName() == account->getName() )
					{
						//account->setName( QString( account->getName() + "_2" ) );
						// 				KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\"." ).arg( account->getName() ), i18n( "Name exist, renamed" ) );
						KMessageBox::error ( this, i18n( "Profile name exists!"), i18n( "Name Exists" ) );
						it->setName(KInputDialog::getText   (   i18n("New Name"),i18n("New name for profile:")));
						account->setName(it->getName());
						nameOk=true;
						break;
					}
					nameOk=true;
				}
				nameOk=true;
			}

			GlobalConfig->AccountList->append( account );
			mw->SessionCombo->clear();
			QuickConnectMenu->clear();

			for (uint i=0; i < GlobalConfig->AccountList->count();i++)
			{
				QuickConnectMenu->insertItem( GlobalConfig->AccountList->at(i)->getName());
				mw->SessionCombo->insertItem( GlobalConfig->AccountList->at(i)->getName());
			}
			mw->SessionCombo->setCurrentText( account->getName() );
			setProfile( account->getName());

			if ( !mw->SessionCombo->isEnabled() )
				mw->SessionCombo->setEnabled( TRUE );

			this->connectAction->setEnabled( true );
			sessionToggled( account->getName() );

			GlobalConfig->saveOptions();
			//		std::cout << "save done" << std::endl;


			//     showProfileManagerClicked();
			//     std::cout << "show profilemanager" << std::endl;
		}

		mw->SessionCombo->setEnabled(TRUE);
		deleteSessionAction->setEnabled ( TRUE );
		saveSessionAction->setEnabled ( TRUE );
		importSessionAction->setEnabled ( TRUE );
		connectAction->setEnabled ( TRUE );
		mw->buttonConnect->setEnabled ( TRUE );

		slotStatusMsg ( i18n( "Profile \"%1\" added." ).arg( mw->SessionCombo->currentText() ), ID_FLASH_MSG );
		GlobalConfig->appendLogEntry ( i18n( "Profile \"%1\" added." ).arg( mw->SessionCombo->currentText() ) ,GlobalConfig->info);
		GlobalConfig->saveOptions();
		saveGuiOptions();

		QuickConnectMenu->clear();
		for (uint i=0; i < GlobalConfig->AccountList->count();i++)
		{
			QuickConnectMenu->insertItem( GlobalConfig->AccountList->at(i)->getName());
		}
		sessionToggled( mw->SessionCombo->currentText());

		if (wizard.connectaftercreating)
		{
			if (wizard.deamonavailable)
			{
				if (GlobalConfig->KvpncDebugLevel > 0)
					GlobalConfig->appendLogEntry ( i18n( "Connecting to profile \"%1\" after creating it." ).arg( mw->SessionCombo->currentText() ) ,GlobalConfig->debug);
				connectClicked();
			}
			else
			{
				if (GlobalConfig->KvpncDebugLevel > 0)
					GlobalConfig->appendLogEntry ( i18n( "Connecting to profile \"%1\" is requested but deamon is not available, skipping connecting." ).arg( mw->SessionCombo->currentText() ) ,GlobalConfig->debug);
			}
		}
	}
	else
	{
		slotStatusMsg ( i18n( "Creating new profile canceled." ), ID_FLASH_MSG );
		GlobalConfig->appendLogEntry ( i18n( "Creating new profile canceled." ),GlobalConfig->info );
	}
}

#include "kvpnc.moc"


// --- DCOP stuff ---
QString KVpnc::getVersion()
{
	return parent->aboutData()->version();
}

void KVpnc::doConnect()
{
	connectClicked();
}

void KVpnc::doDisconnect()
{
	disconnectClicked();
}

uint KVpnc::getConnectedTime()
{

	if (GlobalConfig->status == GlobalConfig->connected)
	{
		// return secs
		return hour*60*60+min*60+sec;
	}
	else
		return 0;
}

QString KVpnc::getStatus()
{
	if (GlobalConfig->status == GlobalConfig->connected)
		return "connected";
	else if (GlobalConfig->status == GlobalConfig->disconnected)
		return "disconnected";
	else if (GlobalConfig->status == GlobalConfig->connecting)
		return "connecting";
	else
		return "unknown";
}

QString KVpnc::getCurrentProfile()
{
	return GlobalConfig->currentProfile->getName();
}

void KVpnc::setProfile(QString profilename)
{
	VpnAccountData * it;
	for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
	{
		if ( it->getName() == profilename )
		{
			mw->SessionCombo->setCurrentText(profilename);
			break;
		}
	}
}

void KVpnc::createNewProfile()
{
	newSessionClicked();
}

void KVpnc::createNewProfileWithWizard()
{
	showNewProfileWizardClicked();
}

void KVpnc::deleteCurrentProfile()
{
	deleteSessionClicked();
}

void KVpnc::openPreferences()
{
	slotSettings();
}

void KVpnc::doImportCert()
{
	importCertClicked();
}

void KVpnc::doImportPcf()
{
	importProfileClicked();
}

void KVpnc::doImportOpenvpnConfig()
{
	importOpenvpnProfileClicked();
}

QStringList KVpnc::profiles()
{
	QStringList profiles;
	VpnAccountData * it;
	if (!GlobalConfig->AccountList->isEmpty())
	{
		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			//std::cout << it->getName() << "\n";
			profiles.append(it->getName());
		}
	}
	return profiles;
}

void KVpnc::doQuit()
{
	quitCalled();
}

QStringList KVpnc::toolinfo()
{
	QStringList toolinfo;
	ToolInfo *tool=0;
	for ( tool = GlobalConfig->ToolList->first(); tool; tool = GlobalConfig->ToolList->next() )
	{
		QString toolstring;
		std::cout << "tool: " << tool->Name.ascii() << std::endl;
		// 		std::cout << "Version: " << tool->Version << std::endl;
		// 		std::cout << "Path: " << tool->PathToExec << std::endl << std::endl;
		QString state="";
		QString usability="";
		QString comment="";

		//FIXME how it could be better?
		if (tool->Name == "vpnc")
		{
			if (!GlobalConfig->pathToVpnc.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToVpnc.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "ipsec")
		{
			if (!GlobalConfig->pathToFreeswan.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToFreeswan.section('/',0,-2));
				tool->collectToolInfo(); // crash if enabled (why the hell?)
			}
		}
		else	if (tool->Name == "racoon")
		{
			if (!GlobalConfig->pathToRacoon.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToRacoon.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "setkey")
		{
			if (!GlobalConfig->pathToSetkey.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToSetkey.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "openvpn")
		{
			if (!GlobalConfig->pathToOpenvpn.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToOpenvpn.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "openssl")
		{
			if (!GlobalConfig->pathToOpenssl.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToOpenssl.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "pppd")
		{
			if (!GlobalConfig->pathToPppd.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToPppd.section('/',0,-2));
				tool->collectToolInfo();
			}

		}
		else	if (tool->Name == "iptables")
		{
			if (!GlobalConfig->pathToIptables.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToIptables.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "kill")
		{
			if (!GlobalConfig->pathToKill.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToKill.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "killall")
		{
			if (!GlobalConfig->pathToKillall.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToKillall.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "ping")
		{
			if (!GlobalConfig->pathToPing.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToPing.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "ip")
		{
			if (!GlobalConfig->pathToIp.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToIp.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "ifconfig")
		{
			if (!GlobalConfig->pathToIfconfig.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToIfconfig.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else	if (tool->Name == "route")
		{
			if (!GlobalConfig->pathToRoute.isEmpty())
			{
				tool->addSearchPath(GlobalConfig->pathToRoute.section('/',0,-2));
				tool->collectToolInfo();
			}
		}
		else
		{
			//std::cout << "Invalid tool!" << std::endl;
		}

		if (!tool->PathToExec.isEmpty())
		{
			state=i18n("Found");
			if (tool->Name == "vpnc")
			{
				if ( tool->Version.find("3.3",0,-1) > -1)
				{
					usability=i18n("full");
				}
				else if ( tool->Version.find("3.2",0,-1) > -1)
				{
					usability=i18n("limited");
					comment=i18n("no split DNS support");
				}
				else if ( tool->Version.find("2.",0,-1) > -1)
				{
					usability=i18n("basic");
					comment=i18n("no NAT-T, IPSec over IP, no split DNS support");
				}
			}
			else if (tool->Name == "freeswan")
			{
				if ( tool->Version.find("2.",0,-1) > -1)
					usability=i18n("full");
				else if ( tool->Version.find("1.",0,-1) > -1)
					usability=i18n("limited");
			}
			else if (tool->Name == "racoon")
			{
				//if ( tool->Version.find("2.",0,-1) > -1)
				usability=i18n("full");
				//else if ( tool->Version.find("2.",0,-1) > -1)
				//	usability=i18n("limited");
			}
			else if (tool->Name == "openvpn")
			{
				if ( tool->Version.find("2.",0,-1) > -1)
					usability=i18n("full");
				else if ( tool->Version.find("1.",0,-1) > -1)
					//else
					usability=i18n("limited");
			}
			else if (tool->Name == "pppd")
			{
				//if ( tool->Version.find("2.",0,-1) > -1)
				usability=i18n("full");
				//else if ( tool->Version.find("2.",0,-1) > -1)
				//	usability=i18n("limited");
			}
			else if (tool->Name == "kill")
			{
				//if ( tool->Version.find("2.",0,-1) > -1)
				usability=i18n("full");
				//else if ( tool->Version.find("2.",0,-1) > -1)
				//	usability=i18n("limited");
			}
			else if (tool->Name == "ip")
			{
				//if ( tool->Version.find("2.",0,-1) > -1)
				usability=i18n("full");
				//else if ( tool->Version.find("2.",0,-1) > -1)
				//	usability=i18n("limited");
			}
			else if (tool->Name == "ifconfig")
			{
				//if ( tool->Version.find("2.",0,-1) > -1)
				usability=i18n("full");
				//else if ( tool->Version.find("2.",0,-1) > -1)
				//	usability=i18n("limited");
			}
			else if (tool->Name == "route")
			{
				//if ( tool->Version.find("2.",0,-1) > -1)
				usability=i18n("full");
				//else if ( tool->Version.find("2.",0,-1) > -1)
				//	usability=i18n("limited");
			}
			else
			{
				// other tools
				usability=i18n("full");
			}
		}
		else
		{
			state=i18n("Not found");
			usability=i18n("none");
		}

		std::cout << "Version: " << tool->Version.ascii() << std::endl;

		toolstring+=tool->Name;
		toolstring+=",";
		toolstring+=state;
		toolstring+=",";
		toolstring+=tool->Version;
		toolstring+=",";
		toolstring+=usability;
		toolstring+=",";
		toolstring+=comment;

		toolinfo.append(toolstring);

	}

	return toolinfo;
}

void KVpnc::doGenerateOpenvpnKey()
{
	generateOpenvpnKey();
}
