/*************************************************************************
*  Copyright (C) 2004 by Christoph Thielecke               *
*  crissi99@gmx.de                            *
*                                     *
*  Contains parts of code from klcc project               *
*  (Peter Simonsson <psn@linux.se>).                   *
*                                     *
*  Contains parts of code from kdirstat project          *
*  (Stefan Hundhammer <sh@suse.de>)                 *
*                                     *
*  This program is free software; you can redistribute it and/or modify *
*  it under the terms of the GNU General Public License as published by *
*  the Free Software Foundation; either version 2 of the License, or   *
*  (at your option) any later version.                  *
*                                     *
*  This program is distributed in the hope that it will be useful,    *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of    *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the     *
*  GNU General Public License for more details.             *
*                                     *
*  You should have received a copy of the GNU General Public License   *
*  along with this program; if not, write to the             *
*  Free Software Foundation, Inc.,                    *
*  59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.       *
***************************************************************************/
//BEGIN includes
#include <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 <qcursor.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 <kfiledialog.h>

#include "kvpnc.h"
#include "mainview.h"
#include "mainviewbase.h"
#include "helpdialog.h"
#include "importprofiledialog.h"
#include "importopenvpnprofiledialog.h"
#include "networkinterface.h"
#include "newprofiledialog.h"
#include "importcertificatedialog.h"
#include "vpnaccountdata.h"
#include "enterpassworddialog.h"
#include "enterxauthinteractivepasscodedialog.h"
#include <ktempfile.h>
#include <iostream>
#include "utils.h"
#include "toolsinfodialog.h"
#include "logviewerdialog.h"
#include "generateopenvpnkeydialog.h"
#include "newprofilewizard.h"
#include "manageciscocert.h"
#include "ciscocertificateenrollment.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, statusBar() );
	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 = "";
	VpncDevice = "";
	PppdDevice = "";
	OpenvpnDevice = "";

	connectCounter = 0;

	ConnectProcess = 0;
	DisconnectProcess = 0;
	RacoonProcess = 0;
	IpsecProcess = 0;
	PingProcess = 0;
	RacoonTailProcess = 0;
	X509CertificateExtractProcess = 0;
	PptpProcess = 0;
	OpenvpnProcess = 0;
	CmdAfterConnectProcess = 0;
	CmdAfterDisconnectProcess = 0;
	RouteProcess = 0;
	SetVirtualIPProcess = 0;
	ReplaceDefaultRouteProcess = 0;
	ConnectionStatusCheckProcess = 0;
	hour = min = sec = 0;
	env = new QStringList();
	*env << "LC_ALL=C" << "LANG=C" << "PATH=/bin:/usr/bin:/usr/sbin:/sbin";

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

	tmpPath = locateLocal ( "data", "kvpnc/" );
	QFile file ( tmpPath + "kvpnc_running" );

	if ( !file.exists() )
	{
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "KVpnc started normal." ), GlobalConfig->debug );
		QTextStream stream ( &file );
		if ( file.open ( IO_WriteOnly ) )
		{
			stream << "created at: " << QDate().currentDate().toString ( "yyyyMMdd" ) << QTime().currentTime().toString ( "hhmm" ) << "\n";
			file.close();
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n ( "Warning: could not write lock file in kde data dir, please check permissions." ), GlobalConfig->info );
		}
		GlobalConfig->loadOptions();
		preserveNetworkEnvironment();
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "KVpnc started after a crash, restoring network environment and config." ), GlobalConfig->debug );
		restoreNetworkEnvironment();
		GlobalConfig->restoreBackupConfig();
		GlobalConfig->loadOptions();
	}

	GlobalConfig->ToolList = Utils ( GlobalConfig ).getToolList();
	GlobalConfig->getToolsInfo();

	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 );
	GlobalConfig->LogOutput->setPaper ( QBrush ( QColor ( GlobalConfig->DebugBackgroundcolor ) ) );

	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 );

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

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

	connect ( KVpncDock, SIGNAL(closeEventKicker(QCloseEvent *)),this,SLOT(closeEvent(QCloseEvent *)));

	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 > 2 )
			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 > 2 )
			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 );
			GlobalConfig->currentProfile = 0;
		}
	}




	//Failsafe
	if ( KVpncDock->isHidden() && isHidden() )
	{
		this->show();
	}
	else
	{
		if ( GlobalConfig->hideMainWindow )
			hide();
		else
			show();
	}

	// 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 > 1 )
					GlobalConfig->appendLogEntry ( i18n ( "Automatic connection at startup to \"%1\" requested." ).arg ( GlobalConfig->AutoConnectProfile ), GlobalConfig->debug );

				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 ReportBugAction;
	delete DebugconsoleAction;
	delete ToolsInfoAction;
	delete LogViewerAction;
	delete GenerateOpenvpnKeyAction;
	delete ManageCiscoCertAction;
	delete CiscoCertEnrollmentAction;
}

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_F, this, SLOT ( importProfileClicked() ), actionCollection(), "importSession" );
	ImportOpenvpnProfileAction = new KAction ( i18n ( "Import &OpenVPN config file..." ), "openvpnimport", Key_O, this, SLOT ( importOpenvpnProfileClicked() ), actionCollection(), "importOpenvpnConfig" );
	ImportFreeswanProfileAction = new KAction ( i18n ( "Import &Freeswan/openSwan config file..." ), "openswan", Key_I, this, SLOT ( importIpsecProfileClicked() ), actionCollection(), "importFreeswanConfig" );
	ImportCertAction = new KAction ( i18n ( "Import &certificate..." ), "certimport", Key_C, this, SLOT ( importCertClicked() ), actionCollection(), "importCert" );
	ManageCiscoCertAction = new KAction ( i18n (  "Manage Cisco certificates..." ), "certimport", Key_C, this, SLOT ( manageCiscoCertClicked() ), actionCollection(), "manageCiscoCert" );
	CiscoCertEnrollmentAction = new KAction ( i18n (  "Enroll Cisco certificates..." ), "certimport", Key_T, this, SLOT ( enrollCiscoCertClicked() ), actionCollection(), "enrollCiscoCert" );
	ExportOpenvpnProfileAction = new KAction ( i18n ( "Export &OpenVPN profile to config file" ), "openvpnexport", Key_O, this, SLOT ( exportOpenvpnProfileClicked() ), actionCollection(), "exportOpenvpnConfig" );

	ImportKvpncSettingsAction = new KAction ( i18n ( "Import KVpnc settings..." ), "2downarrow", Key_I, this, SLOT ( importKvpncSettingsClicked() ), actionCollection(), "importKvpncSettings" );
	ExportKvpncSettingsAction = new KAction ( i18n ( "Export KVpnc settings to file" ), "2uparrow", Key_E, this, SLOT ( exportKvpncSettingsClicked() ), actionCollection(), "exportKvpncSettings" );

	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" );
	ReportBugAction = new KAction ( i18n ( "&Report a bug..." ), "bug", CTRL + Key_R, this, SLOT ( reportBugClicked() ), actionCollection(), "reportbug" );
	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" );
	SendFeedbackMailAction = new KAction ( i18n ( "Send &Feedback Mail..." ), 0, this, SLOT ( sendFeedbackMail() ), actionCollection(), "help_send_feedback_mail" );
	PrefAction = 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 (GlobalConfig, 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, showProfilesOnly );
	prefDlg.setMinimumSize ( 800, 600 );

	VpnAccountData *oldProfile = GlobalConfig->currentProfile;
	connect ( prefDlg.ProfileGeneralOptionsWidget->NewSessionPushButton , SIGNAL ( clicked () ), this, SLOT ( showNewProfileWizardClicked() ) );
	prefDlg.exec();

	GlobalConfig->LogOutput->setPaper ( QBrush ( QColor ( GlobalConfig->DebugBackgroundcolor ) ) );

	if ( prefDlg.profileAddedOrDeleted )
	{
		GlobalConfig->saveOptions();
		saveGuiOptions();
		sessionToggled ( GlobalConfig->currentProfile->getName() );
		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 (prefDlg.profileHasChanged )
	{
		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();
	saveSessionClicked();
	showProfilesOnly=false;
}

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 =  i18n("Cisco");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
			TypeString =  i18n("Cisco (propritary)");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
			TypeString =  i18n("PPTP");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			TypeString =  i18n("racoon");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			TypeString = IpsecType;
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
			TypeString =  i18n("OpenVPN");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
			TypeString =  i18n("L2TP (racoon)");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
			TypeString = IpsecType;
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
			TypeString = i18n("Vtun");
		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();
				tmpPath = locateLocal ( "data", "kvpnc/" );
				QFile file ( tmpPath + "kvpnc_running" );
				file.remove();
				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();
			tmpPath = locateLocal ( "data", "kvpnc/" );
			QFile file ( tmpPath + "kvpnc_running" );
			file.remove();
			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();
			tmpPath = locateLocal ( "data", "kvpnc/" );
			QFile file ( tmpPath + "kvpnc_running" );
			file.remove();
			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 )
{
	if ( GlobalConfig->KvpncDebugLevel > 1 )
		GlobalConfig->appendLogEntry ( i18n ( "CloseEvent recieved (reciever: %1)." ).arg("kvpnc"), GlobalConfig->debug );

	QString TypeString = "";
	if ( GlobalConfig->currentProfile != 0 )
	{
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
			TypeString =  i18n("Cisco");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
			TypeString =  i18n("Cisco (propritary)");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
			TypeString =  i18n("PPTP");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			TypeString =  i18n("racoon");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			TypeString = IpsecType;
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
			TypeString =  i18n("OpenVPN");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
			TypeString =  i18n("L2TP (racoon)");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
			TypeString = IpsecType;
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
			TypeString = i18n("Vtun");
		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();
								}
							}
							tmpPath = locateLocal ( "data", "kvpnc/" );
							QFile file ( tmpPath + "kvpnc_running" );
							file.remove();

							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();
			tmpPath = locateLocal ( "data", "kvpnc/" );
			QFile file ( tmpPath + "kvpnc_running" );
			file.remove();
			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();
	}
}

bool KVpnc::queryExit()
{
	kdDebug() << "KVpnc::queryExit()" << endl;
	if ( !kapp->sessionSaving() )
	{}
	else
		kdDebug ( "KVpnc::queryExit(): saving session" );
	return KMainWindow::queryExit();
}

bool KVpnc::queryClose()
{
	if ( kapp->sessionSaving() )
	{
		return true;
	}
	else
	{
		KMessageBox::information ( this, i18n ( "<qt><p>Closing the main window will keep KVpnc running in the system tray. Use 'Quit' from the 'File' menu to quit the application.</p><p><center><img source=\"systray_shot\"></center></p></qt>" ), i18n ( "Docking in System Tray" ), "hideOnCloseInfo" );
		hide();
		return false;
	}
}

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

	bool ok = true; // if ok we will run process
	bool useL2tpAfterFirstConnection = false;
	stopContinue = false;
	ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "ipsec" ) ;

	QString TypeString = i18n ( "unknown" );
	if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
		TypeString =  i18n("Cisco");
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
		TypeString =  i18n("Cisco (propritary)");
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
		TypeString =  i18n("PPTP");
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
	{
		if ( IpsecToolInfo->Version.contains ( "Openswan" ) )
			IpsecType = TypeString =  i18n("Openswan");
		else if ( IpsecToolInfo->Version.contains ( "strongSwan" ) )
			IpsecType = TypeString =  i18n("strongSwan");
		else
			IpsecType = TypeString =  i18n("FreeS/WAN");
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
		TypeString = "racoon";
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		TypeString = "OpenVPN";
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
	{
		TypeString = "L2TP (racoon)";
		useL2tpAfterFirstConnection = true;
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
	{
		if ( IpsecToolInfo->Version.contains ( "Openswan" ) )
			IpsecType = TypeString = "L2TP (Openswan)";
		else if ( IpsecToolInfo->Version.contains ( "strongSwan" ) )
			IpsecType = TypeString = "L2TP (strongSwan)";
		else
			IpsecType = TypeString = "L2TP (FreeS/WAN)";
		useL2tpAfterFirstConnection = true;
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
		TypeString = "Vtun";

	if ( GlobalConfig->KvpncDebugLevel > 1 )
		GlobalConfig->appendLogEntry ( i18n ( "Connect try requested, profile: %1, type: %2" ).arg ( GlobalConfig->currentProfile->getName() ).arg ( TypeString ), GlobalConfig->debug );

	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 ;
	}

	if (! backupResolvConf())
	{
		// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because %1 could not be backuped." ).arg ( "resolv.conf" ), GlobalConfig->error );
		return ;
	}

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

		//setGuiStatus(connecting);

		// looking for vpnc
		if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "vpnc" )->found == false )
		{
			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;
		}

		GlobalConfig->TmpGatewayIP = Utils ( GlobalConfig, parent ).resolveName ( GlobalConfig->currentProfile->getGateway() );
		if ( GlobalConfig->TmpGatewayIP == "0.0.0.0" || GlobalConfig->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
		{
			GlobalConfig->appendLogEntry ( i18n ( "Gateway hostname (%1) resolved to \"%2\"." ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->TmpGatewayIP ), GlobalConfig->info );
		}

		// 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->debug );
				GlobalConfig->appendLogEntry ( i18n ( "vpnc version (minor): \"%1\"" ).arg ( vpnc_version_minor ) , GlobalConfig->debug );
				GlobalConfig->appendLogEntry ( i18n ( "vpnc version (subminor): \"%1\"" ).arg ( vpnc_version_subminor ) , GlobalConfig->debug );
			}
		}


		if ( vpnc_version_minor < 3 )
		{
			KMessageBox::error ( this, i18n ( "%1 is too old. Minimum requirement is %2" ).arg ( "vpnc" ).arg ( "0.3.x" ) );
			GlobalConfig->appendLogEntry ( i18n ( "%1 is too old. Minimum requirement is %2" ).arg ( "vpnc" ).arg ( "0.3.x" ), GlobalConfig->error );
			ok = false;
		}

		if ( GlobalConfig->currentProfile->getID().isEmpty() )
		{
			KMessageBox::error ( this, i18n ( "%1 is empty. Please go to profile settings and enter %2" ).arg ( i18n("VPN ID") ).arg ( i18n("VPN ID") ) );
			GlobalConfig->appendLogEntry ( i18n ( "%1 is empty. Please go to profile settings and enter %2" ).arg ( i18n("VPN ID") ).arg ( i18n("VPN ID")), GlobalConfig->error );
			ok = false;
		}

		if ( ok )
		{
			bool askUsernamePass = false;
			VpncDevice = "tun0";

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

			else if ( GlobalConfig->currentProfile->getAllowEmptyGroupPassword() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
				askUsernamePass = true;

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

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


			bool requestUsername= false;
			requestUsername = GlobalConfig->currentProfile->getUserPassword().isEmpty();
			if ( AuthRetry )
			{
				askUsernamePass = true;
				requestUsername = true;
			}

			if ( askUsernamePass )
			{
				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();
				}

				if (GlobalConfig->currentProfile->getSaveUserPassword())
					dlg.main->SavePasswordCheckBox->setChecked ( true );
				else
					dlg.main->SavePasswordCheckBox->setChecked ( false );

				if (!GlobalConfig->currentProfile->getDontSaveUsername())
					dlg.main->SaveUsernameCheckBox->setChecked ( true );
				else
					dlg.main->SaveUsernameCheckBox->setChecked ( false );

				if (GlobalConfig->currentProfile->getSavePsk())
					dlg.main->SavePskCheckBox->setChecked ( true );
				else
					dlg.main->SavePskCheckBox->setChecked ( false );

				if ( dlg.exec() )
				{
					GlobalConfig->TmpGroupPassword = dlg.main->PSKLineEdit->text();
					GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
					GlobalConfig->TmpPassword = dlg.main->PasswordEdit->text();
					bool needSave=false;

					if ( GlobalConfig->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->SaveUsernameCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setDontSaveUsername(false);
						GlobalConfig->currentProfile->setUserName ( GlobalConfig->TmpUsername );
						needSave=true;
					}
					else
					{
						GlobalConfig->currentProfile->setDontSaveUsername(true);
					}


					if ( dlg.main->SavePskCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSavePsk ( true );
						GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
						needSave=true;
					}
					else
					{
						GlobalConfig->currentProfile->setSavePsk( false );
					}

					if ( dlg.main->SavePasswordCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSaveUserPassword ( true );
						GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
						needSave=true;
					}
					else
					{
						GlobalConfig->currentProfile->setSaveUserPassword( false );
					}
					if(needSave == true)
						saveSessionClicked();
				}
				else
				{
					ok = false;
					AuthRetry = false;
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because account data dialog aborted." ), GlobalConfig->debug );
					setGuiStatus ( disconnected );
					return;
				}
			}
			else
			{
				GlobalConfig->TmpPassword= GlobalConfig->currentProfile->getUserPassword();
				GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey();
				GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
			}
}


		// 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->debug );
				LocalIP = iface.getInterfaceIP ( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "IP address of default interface: \"%1\"." ).arg ( LocalIP ) , GlobalConfig->debug );
			}
			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";
			OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>

			QFile DefaultRouteBackupFile ( OldDefaultroute + ".sh" );
			QTextStream DefaultRouteBackupFileStream ( &DefaultRouteBackupFile );
			if ( DefaultRouteBackupFile.open ( IO_WriteOnly ) )
			{
				DefaultRouteBackupFileStream << "# generated by kvpnc. Do not edit it." << "\n";
				DefaultRouteBackupFileStream << "\n";
				DefaultRouteBackupFileStream << GlobalConfig->pathToIp + " route show | grep default > " + OldDefaultroute + "\n";
				DefaultRouteBackupFile.close();
				QProcess backupDefaultRouteProcess ( this );
				backupDefaultRouteProcess.addArgument ( GlobalConfig->InterpreterShell );
				backupDefaultRouteProcess.addArgument ( OldDefaultroute + ".sh" );
				if ( !backupDefaultRouteProcess.start() )
				{
					// 				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because default route backup process could not be started." ), GlobalConfig->error );
					return ;
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Default route backup process started." ), GlobalConfig->debug );
				}
			}
			else
			{
				// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because default route could not be backuped." ), GlobalConfig->error );
				return ;
			}

			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

			// 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 <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
				stream << "#* reason                       -- why this script was called, one of: pre-init connect disconnect\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 << "#set -x\n";
				stream << "\n";
				stream << "OS=\"`uname -s`\"\n";
				stream << "DEFAULT_ROUTE_FILE=/var/run/vpnc/defaultroute\n";
				stream << "RESOLV_CONF_BACKUP=" + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + "\n";
				stream << "\n";
				stream << "IPROUTE=" + GlobalConfig->pathToIp + "\n";
				stream << "\n";
				stream << "if [ \"$OS\" = \"Linux\" ]; then\n";
				stream << "	ifconfig_syntax_ptp=\"pointopoint\"\n";
				stream << "	route_syntax_gw=\"gw\"\n";
				stream << "	route_syntax_del=\"del\"\n";
				stream << "	route_syntax_netmask=\"netmask\"\n";
				stream << "else\n";
				stream << "	ifconfig_syntax_ptp=\"\"\n";
				stream << "	route_syntax_gw=\"\"\n";
				stream << "	route_syntax_del=\"delete\"\n";
				stream << "	route_syntax_netmask=\"-netmask\"\n";
				stream << "fi\n";
				stream << "\n";
				stream << "####\n";
				stream << "\n";
				stream << "kernel_is_2_6_or_above()\n";
				stream << "{\n";
				stream << "	case \"$(uname -r)\" in\n";
				stream << "		1.*|2.[012345]*) return 1 ;;\n";
				stream << "		*) return 0 ;;\n";
				stream << "	esac\n";
				stream << "}\n";
				stream << "\n";
				stream << "udev_is_active()\n";
				stream << "{\n";
				stream << "	test -e /dev/.udev.tdb || test -d /dev/.udevdb || return 1\n";
				stream << "	kernel_is_2_6_or_above || return 1\n";
				stream << "	return 0\n";
				stream << "}\n";
				stream << "\n";
				stream << "\n";
				stream << "do_pre_init() {\n";
				stream << "	if [ \"$OS\" = \"Linux\" ]; then\n";
				stream << "		if (exec 6<> /dev/net/tun) > /dev/null 2>&1 ; then\n";
				stream << "			:\n";
				stream << "		else # can't open /dev/net/tun\n";
				stream << "			test -e /proc/sys/kernel/modprobe && `cat /proc/sys/kernel/modprobe` tun 2>/dev/null\n";
				stream << "			# fix for broken devfs in kernel 2.6.x\n";
				stream << "			if [ \"`readlink /dev/net/tun`\" = misc/net/tun \\\n";
				stream << "				-a ! -e /dev/net/misc/net/tun -a -e /dev/misc/net/tun ] ; then\n";
				stream << "				ln -sf /dev/misc/net/tun /dev/net/tun\n";
				stream << "			fi\n";
				stream << "			# make sure tun device exists\n";
				stream << "			if [ ! -e /dev/net/tun ]; then\n";
				stream << "				mkdir -p /dev/net\n";
				stream << "				mknod -m 0640 /dev/net/tun c 10 200\n";
				stream << "			fi\n";
				stream << "\n";
				stream << "            # workaround for a possible latency caused by udev, sleep max. 10s\n";
				stream << "            if udev_is_active ; then\n";
				stream << "                for x in `seq 100` ; do\n";
				stream << "                    (exec 6<> /dev/net/tun) > /dev/null 2>&1 && break;\n";
				stream << "                    sleep 0.1\n";
				stream << "                done\n";
				stream << "            fi\n";
				stream << "		fi\n";
				stream << "	elif [ \"$OS\" = \"FreeBSD\" ]; then\n";
				stream << "		if [ ! -e /dev/tun ]; then\n";
				stream << "			kldload if_tun\n";
				stream << "		fi\n";
				stream << "	elif [ \"$OS\" = \"NetBSD\" ]; then\n";
				stream << "		:\n";
				stream << "	elif [ \"$OS\" = \"OpenBSD\" ]; then\n";
				stream << "		:\n";
				stream << "	elif [ \"$OS\" = \"SunOS\" ]; then\n";
				stream << "		:\n";
				stream << "	fi\n";
				stream << "}\n";
				stream << "\n";
				stream << "do_ifconfig() {\n";
				if ( GlobalConfig->currentProfile->getUseMtu() )
					stream << GlobalConfig->pathToIfconfig + " \"$TUNDEV\" inet \"$INTERNAL_IP4_ADDRESS\" $ifconfig_syntax_ptp \"$INTERNAL_IP4_ADDRESS\" netmask 255.255.255.255 mtu " + QString().setNum ( GlobalConfig->currentProfile->getMtu() ) + " up\n";
				else
					stream << GlobalConfig->pathToIfconfig + " \"$TUNDEV\" inet \"$INTERNAL_IP4_ADDRESS\" $ifconfig_syntax_ptp \"$INTERNAL_IP4_ADDRESS\" netmask 255.255.255.255 mtu 1390 up\n";
				stream << "}\n";
				stream << "\n";
				stream << "if [ -n \"$IPROUTE\" ]; then\n";
				stream << "	fix_ip_get_output () {\n";
//			stream << "		sed 's/cache//;s/metric \\?[0-9]\\+ [0-9]\\+//g'\n"; // (works on etch)
				stream << "		sed 's/cache//;s/metric[ 0-9]\\+//g;s/hoplimit[ 0-9]\\+//g'" << "\n"; // sed 's/cache//;s/metric[ 0-9]\+//g;s/hoplimit[ 0-9]\+//g' (works on fc6)
				stream << "	}\n";
				stream << "\n";
				stream << "	set_vpngateway_route() {\n";
				stream << "		$IPROUTE route add `" + GlobalConfig->pathToIp + " route get \"$VPNGATEWAY\" | fix_ip_get_output`\n";
				stream << "		$IPROUTE route flush cache\n";
				stream << "	}\n";
				stream << "	\n";
				stream << "	del_vpngateway_route() {\n";
				stream << "		$IPROUTE route del \"$VPNGATEWAY\"\n";
				stream << "		$IPROUTE route flush cache\n";
				stream << "	}\n";
				stream << "	\n";
				stream << "	set_default_route() {\n";
				if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
				{
					stream << "		$IPROUTE route | grep '^default' | fix_ip_get_output > \"$DEFAULT_ROUTE_FILE\"\n";
					stream << "		$IPROUTE route del default\n";
					stream << "		$IPROUTE route add default dev \"$TUNDEV\"\n";
					stream << "		$IPROUTE route flush cache\n";
				}
				else
				{
					stream << "		echo \"\"\n";
				}
				stream << "	}\n";
				stream << "	\n";
				stream << "	set_network_route() {\n";
				stream << "		NETWORK=\"$1\"\n";
				stream << "		NETMASK=\"$2\"\n";
				stream << "		NETMASKLEN=\"$3\"\n";
				stream << "		$IPROUTE route add \"$NETWORK/$NETMASKLEN\" dev \"$TUNDEV\"\n";
				stream << "		$IPROUTE route flush cache\n";
				stream << "	}\n";
				stream << "	\n";
				stream << "	reset_default_route() {\n";
				stream << "		$IPROUTE route del default > /dev/null 2>&1\n";
				stream << "		$IPROUTE route add `cat \"$DEFAULT_ROUTE_FILE\"`\n";
				stream << "		$IPROUTE route flush cache\n";
				stream << "	}\n";
				stream << "	\n";
				stream << "	del_network_route() {\n";
// 				if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
// 				{
// 					stream << "		# linux deletes routes automatically if the device is shut down\n";
// 					stream << "		return\n";
// 				}
				stream << "		#NETWORK=\"$1\"\n";
				stream << "		#NETMASK=\"$2\"\n";
				stream << "		#NETMASKLEN=\"$3\"\n";
				if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
					stream << "		#$IPROUTE route del \"$NETWORK/$NETMASKLEN\" dev \"$TUNDEV\" \n";
				else
					stream << "		#$IPROUTE route del \"$NETWORK/$NETMASKLEN\" dev \"" + tmpInterface + "\"\n";
				stream << "		#$IPROUTE route flush cache\n";
				stream << "		# linux deletes routes automatically if the device is shut down\n";
				stream << "		echo \"\"\n";
				stream << "	}\n";
				stream << "else\n";
				stream << "	get_default_gw() {\n";
				stream << "		# solaris again ...\n";
				stream << "		netstat -r -n | sed 's/default/0.0.0.0/' | grep '^0.0.0.0' | awk '{print $2}'\n";
				stream << "	}\n";
				stream << "	\n";
				stream << "	set_vpngateway_route() {\n";
				stream << "		" + GlobalConfig->pathToRoute + " add -host \"$VPNGATEWAY\" $route_syntax_gw \"`get_default_gw`\"\n";
				stream << "	}\n";
				stream << "\n";
				stream << "	del_vpngateway_route() {\n";
				stream << "		" + GlobalConfig->pathToRoute + " $route_syntax_del -host \"$VPNGATEWAY\"\n";
				stream << "	}\n";
				stream << "	\n";
				stream << "	set_default_route() {\n";
				if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
				{
					stream << "		DEFAULTGW=\"`get_default_gw`\"\n";
					stream << "		echo \"$DEFAULTGW\" > \"$DEFAULT_ROUTE_FILE\"\n";
					stream << "		route $route_syntax_del default \"$DEFAULTGW\"\n";
					stream << "		route add default $route_syntax_gw \"$INTERNAL_IP4_ADDRESS\"\n";
				}
				else
				{
					stream << "		echo \"\"\n";
				}
				stream << "	}\n";
				stream << "	\n";
				stream << "	set_network_route() {\n";
				stream << "		NETWORK=\"$1\"\n";
				stream << "		NETMASK=\"$2\"\n";
				stream << "		NETMASKLEN=\"$3\"\n";
				stream << "		route add -net \"$NETWORK\" $route_syntax_netmask \"$NETMASK\" $route_syntax_gw \"$INTERNAL_IP4_ADDRESS\"\n";
				stream << "	}\n";
				stream << "	\n";
				stream << "	reset_default_route() {\n";
				if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
				{
					stream << "		route $route_syntax_del default\n";
					stream << "		route add default $route_syntax_gw `cat \"$DEFAULT_ROUTE_FILE\"`\n";
				}
				else
				{
					stream << "		echo \"\"\n";
				}
				stream << "	}\n";
				stream << "	\n";
				stream << "	del_network_route() {\n";
				stream << "		if [ \"$OS\" = \"Linux\" ]; then\n";
				stream << "			# linux deletes routes automatically if the device is shut down\n";
				stream << "			return\n";
				stream << "		fi\n";
				stream << "		NETWORK=\"$1\"\n";
				stream << "		NETMASK=\"$2\"\n";
				stream << "		NETMASKLEN=\"$3\"\n";
				stream << "		route $route_syntax_del -net \"$NETWORK\" $route_syntax_netmask \"$NETMASK\" $route_syntax_gw \"$INTERNAL_IP4_ADDRESS\"\n";
				stream << "	}\n";
				stream << "fi\n";
				stream << "\n";
				stream << "write_resolvconf() {\n";
				stream << "\n";
				stream << "    case \"$DNS_UPDATE\" in\n";
				stream << "        *no|*NO|*No|*nO)\n";
				stream << "        return\n";
				stream << "        ;;\n";
				stream << "    esac\n";
				stream << "        \n";
				stream << "    if [ -x /sbin/resolvconf ] ; 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 << "        return\n";
				stream << "    fi\n";
				stream << "\n";
				stream << "	grep '^#@VPNC_GENERATED@' /etc/resolv.conf > /dev/null 2>&1 || cp -- /etc/resolv.conf \"$RESOLV_CONF_BACKUP\"\n";
				stream << "	NEW_RESOLVCONF=\"#@VPNC_GENERATED@ -- this file is generated by vpnc\n";
				stream << "# and will be overwritten by vpnc\n";
				stream << "# as long as the above mark is intact\"\n";
				stream << "	\n";
				stream << "	exec 6< /etc/resolv.conf\n";
				stream << "	while read LINE <&6 ; do\n";
				stream << "		case \"$LINE\" in\n";
				stream << "			nameserver*)\n";
				stream << "				if [ -n \"$INTERNAL_IP4_DNS\" ]; then\n";
				stream << "					read ONE_NAMESERVER INTERNAL_IP4_DNS <<-EOF\n";
				stream << "	$INTERNAL_IP4_DNS\n";
				stream << "EOF\n";
				stream << "					LINE=\"nameserver $ONE_NAMESERVER\"\n";
				stream << "				else\n";
				stream << "					LINE=""\n";
				stream << "				fi\n";
				stream << "				;;\n";
				stream << "			domain*|search*)\n";
				stream << "				if [ -n \"$CISCO_DEF_DOMAIN\" ]; then\n";
				stream << "					LINE=\"$LINE $CISCO_DEF_DOMAIN\"\n";
				stream << "					CISCO_DEF_DOMAIN=""\n";
				stream << "				fi\n";
				stream << "				;;\n";
				stream << "		esac\n";
				stream << "		NEW_RESOLVCONF=\"$NEW_RESOLVCONF\n";
				stream << "$LINE\"\n";
				stream << "	done\n";
				stream << "	exec 6<&-\n";
				stream << "	\n";
				stream << "	for i in $INTERNAL_IP4_DNS ; do\n";
				stream << "		NEW_RESOLVCONF=\"$NEW_RESOLVCONF\n";
				stream << "nameserver $i\"\n";
				stream << "	done\n";
				stream << "	if [ -n \"$CISCO_DEF_DOMAIN\" ]; then\n";
				stream << "		NEW_RESOLVCONF=\"$NEW_RESOLVCONF\n";
				stream << "search $CISCO_DEF_DOMAIN\"\n";
				stream << "	fi\n";
				stream << "	echo \"$NEW_RESOLVCONF\" > /etc/resolv.conf\n";
				stream << "}\n";
				stream << "\n";
				stream << "reset_resolvconf() {\n";
				stream << "\n";
				stream << "    case \"$DNS_UPDATE\" in\n";
				stream << "        *no|*NO|*No|*nO)\n";
				stream << "        return\n";
				stream << "        ;;\n";
				stream << "    esac\n";
				stream << "\n";
				stream << "    if [ -x /sbin/resolvconf ] ; then\n";
				stream << "        /sbin/resolvconf -d \"$TUNDEV\"\n";
				stream << "        return\n";
				stream << "    fi\n";
				stream << "	if [ ! -e \"$RESOLV_CONF_BACKUP\" ]; then\n";
				stream << "		return\n";
				stream << "	fi\n";
				stream << "	grep '^#@VPNC_GENERATED@' /etc/resolv.conf > /dev/null 2>&1 && cat \"$RESOLV_CONF_BACKUP\" > /etc/resolv.conf\n";
				stream << "	rm -f -- \"$RESOLV_CONF_BACKUP\"\n";
				stream << "}\n";
				stream << "\n";
				stream << "do_connect() {\n";
				stream << "    # Debian specific, insert your code there to avoid modification of\n";
				stream << "    # conffiles like this script\n";
				stream << "    if [ -r /etc/vpnc/vpnc-script-connect-action ] ; then\n";
				stream << "        . /etc/vpnc/vpnc-script-connect-action\n";
				stream << "    fi\n";
				stream << "	if [ -n \"$CISCO_BANNER\" ]; then\n";
				stream << "		echo \"Connect Banner:\"\n";
				stream << "		echo \"$CISCO_BANNER\" | while read LINE ; do echo \"|\" \"$LINE\" ; done\n";
				stream << "		echo\n";
				stream << "	fi\n";
				stream << "	\n";
				stream << "	do_ifconfig\n";
				stream << "	set_vpngateway_route\n";
				stream << "\n";
				stream << "        # -- Debian specific\n";
				stream << "        if test \"$TARGET_NETWORKS\" ; then\n";
				stream << "            for network in $TARGET_NETWORKS ; do\n";
				stream << "                " + GlobalConfig->pathToIp + " route del $network 2>/dev/null\n";
				stream << "                " + GlobalConfig->pathToIp + " route add $network dev $TUNDEV\n";
				stream << "            done\n";
				stream << "        else\n";
				stream << "\n";
				stream << "	if [ -n \"$CISCO_SPLIT_INC\" ]; then\n";
				stream << "		i=0\n";
				stream << "		while [ $i -lt $CISCO_SPLIT_INC ] ; 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 << "			set_network_route \"$NETWORK\" \"$NETMASK\" \"$NETMASKLEN\"\n";
				stream << "			i=`expr $i + 1`\n";
				stream << "		done\n";
				stream << "		for i in $INTERNAL_IP4_DNS ; do\n";
				stream << "			set_network_route \"$i\" \"255.255.255.255\" \"32\"\n";
				stream << "		done\n";
				stream << "	else\n";
				stream << "		set_default_route\n";
				stream << "	fi\n";
				stream << "\n";
				stream << "        fi\n";
				stream << "	\n";
				stream << "	if [ -n \"$INTERNAL_IP4_DNS\" ]; then\n";
				stream << "		write_resolvconf\n";
				stream << "	fi\n";
				stream << "}\n";
				stream << "\n";
				stream << "do_disconnect() {\n";
				stream << "	# Debian specific, insert your code there to avoid modification of\n";
				stream << "	# conffiles like this script\n";
				stream << "	if [ -r /etc/vpnc/vpnc-script-disconnect-action ] ; then\n";
				stream << "		. /etc/vpnc/vpnc-script-disconnect-action\n";
				stream << " 	fi\n";
				stream << "	if [ -n \"$CISCO_SPLIT_INC\" ]; then\n";
				stream << "		i=0\n";
				stream << "		while [ $i -lt $CISCO_SPLIT_INC ] ; 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 << "			del_network_route \"$NETWORK\" \"$NETMASK\" \"$NETMASKLEN\"\n";
				stream << "			i=`expr $i + 1`\n";
				stream << "		done\n";
				stream << "		for i in $INTERNAL_IP4_DNS ; do\n";
				stream << "			del_network_route \"$i\" \"255.255.255.255\" \"32\"\n";
				stream << "		done\n";
				stream << "	else\n";
				stream << "		if [ -s \"$DEFAULT_ROUTE_FILE\" ]; then\n";
				stream << "			reset_default_route\n";
				stream << "			rm -f -- \"$DEFAULT_ROUTE_FILE\"\n";
				stream << "		fi\n";
				stream << "	fi\n";
				stream << "	\n";
				stream << "	del_vpngateway_route\n";
				stream << "	\n";
				stream << "	if [ -n \"$INTERNAL_IP4_DNS\" ]; then\n";
				stream << "		reset_resolvconf\n";
				stream << "	fi\n";
				stream << "}\n";
				stream << "\n";
				stream << "####\n";
				stream << "\n";
				stream << "if [ -z \"$reason\" ]; then\n";
				stream << "	echo \"this script must be called from vpnc\" 1>&2\n";
				stream << "	exit 1\n";
				stream << "fi\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";
				stream << "exit 0\n";
			}

			file.close();

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

			if ( ChmodProcess->start(env) )
			{

				//sleep ( 1 );

				if ( !NetworkInterface ( GlobalConfig, parent, this ).interfaceExist ( "tun0" ) )              //FIXME make it dynamiclly (tun+)
				{
					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
						{
							if ( GlobalConfig->KvpncDebugLevel > 0 )
								GlobalConfig->appendLogEntry ( i18n ( "Tunnel device is missing, creating has been succeded." ), GlobalConfig->debug );
						}
					}
					// 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
						{
							if ( GlobalConfig->KvpncDebugLevel > 0 )
								GlobalConfig->appendLogEntry ( i18n ( "Loading of module \"%1\" was successful." ).arg ( "tun" ), GlobalConfig->debug );
						}
					}
				}


				QString vpncConfig = "";
				vpncConfig += "IPSec gateway " + GlobalConfig->TmpGatewayIP + "\n";
				vpncConfig += "IPSec ID " + GlobalConfig->currentProfile->getID() + "\n";
				QString GrpPassStr = "";
				if ( !GlobalConfig->currentProfile->getSavePsk() || AuthRetry )
					GrpPassStr = GlobalConfig->TmpGroupPassword;
				else
					GrpPassStr = GlobalConfig->currentProfile->getPreSharedKey();
				vpncConfig += "IPSec secret " + GrpPassStr + "\n";
				vpncConfig += "Xauth username " + GlobalConfig->currentProfile->getUserName() + "\n";

				if ( ( vpnc_version_minor == 3 && vpnc_version_minor >= 2 ) || ( vpnc_version_minor > 3 ) )
				{
					QString UserPassStr = "";
					if ( !GlobalConfig->currentProfile->getUserPassword() || GlobalConfig->currentProfile->getUserPassword() == "" || AuthRetry )
						UserPassStr = GlobalConfig->TmpPassword;
					else
						UserPassStr = GlobalConfig->currentProfile->getUserPassword();
					vpncConfig += "Xauth password " + UserPassStr + "\n";
				}

				if ( GlobalConfig->KvpncDebugLevel > 3 )
				{
					QStringList vpncConfigLineList = QStringList::split( '\n', vpncConfig);
					//GlobalConfig->appendLogEntry ( i18n ( "start\n" ), GlobalConfig->debug );
					for ( QStringList::Iterator it = vpncConfigLineList.begin(); it != vpncConfigLineList.end(); ++it )
					{
						QString configstring = *it;
						if (configstring.find("Xauth password",0) > -1)
							configstring = "Xauth password: ******";
						GlobalConfig->appendLogEntry ( i18n ( "vpnconfig: %1" ).arg ( configstring ), GlobalConfig->debug );
						//GlobalConfig->appendLogEntry ( i18n ( "end" ).arg ( vpncConfig ), GlobalConfig->debug );
					}
				}

				QString VpncConfigFile = tmpPath + "vpnc-config." + GlobalConfig->currentProfile->getName(); // vpnc-config.<name>
				if ( vpnc_version_major <= 0 && vpnc_version_minor <= 3 && vpnc_version_subminor <= 2 )
				{
					// write vpnc connect script
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( "VpncConfig: " + VpncConfigFile + "\n", GlobalConfig->debug );
					QFile configfile ( VpncConfigFile );
					QTextStream configstream ( &configfile );
					if ( configfile.open ( IO_WriteOnly ) )
					{
						configstream << vpncConfig << "\n";
						configfile.close();
					}
					else
					{
						KMessageBox::information ( this, i18n ( "Write of \"%1\" has been failed!" ).arg ( VpncConfigFile ));
						GlobalConfig->appendLogEntry ( i18n ( "Write of \"%1\" has been failed!" ).arg ( VpncConfigFile ), GlobalConfig->error );
						disconnectClicked();
						setGuiStatus ( disconnected );
						GlobalConfig->status = GlobalConfig->disconnected;
						return ;
					}
					
				}

				ConnectProcess = new QProcess ( this );
				ConnectProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
				connect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readOutputFrom_vpnc() ) );
				

				ConnectProcess->addArgument ( GlobalConfig->pathToVpnc );
				ConnectProcess->addArgument ( "--script" );
				ConnectProcess->addArgument ( VpncScript );

				if ( vpnc_version_major <= 0 && vpnc_version_minor <= 3 && vpnc_version_subminor <= 2 )
				{
// 					ConnectProcess->addArgument ( "--gateway" );
// 					ConnectProcess->addArgument ( GlobalConfig->TmpGatewayIP );
// 					ConnectProcess->addArgument ( "--id" );
// 					ConnectProcess->addArgument ( GlobalConfig->currentProfile->getID() );
					ConnectProcess->addArgument(VpncConfigFile);
				}

				if ( GlobalConfig->VpncDebugLevel > 0 )
				{

					ConnectProcess->addArgument ( "--debug" );
					ConnectProcess->addArgument ( QString().setNum ( GlobalConfig->VpncDebugLevel ) );
				}
				ConnectProcess->addArgument ( "--pid-file" );
				ConnectProcess->addArgument ( GlobalConfig->Vpnc_pid_file );

				if ( vpnc_version_minor == 3 && vpnc_version_subminor >= 3 || vpnc_version_minor >= 3 && vpnc_version_minor >= 3 && vpnc_version_subminor >= 3 )
					ConnectProcess->addArgument ( "--non-inter" );

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

				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					if ( vpnc_version_major >= 0 && vpnc_version_minor >= 4 )
					{
						// TODO add other nat modes
						ConnectProcess->addArgument ( "--natt-mode");
						ConnectProcess->addArgument ( GlobalConfig->currentProfile->getCiscoNatMode());
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "Using NAT-T mode \"%1\"." ).arg ( GlobalConfig->currentProfile->getCiscoNatMode() ), GlobalConfig->debug );
					}
					else
						ConnectProcess->addArgument ( "--udp" );
					
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Using UDP." ), GlobalConfig->debug );
				}
				else
				{
					if ( vpnc_version_major >= 0 && vpnc_version_minor >= 4 )
					{
						ConnectProcess->addArgument ( "--natt-mode" );
						ConnectProcess->addArgument ( "none" );
					}	
					else
						ConnectProcess->addArgument ( "--disable-natt" );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Dont using UDP." ), GlobalConfig->debug );
				}

				if ( GlobalConfig->currentProfile->getUseLocalPort() == true )
				{
					ConnectProcess->addArgument ( "--local-port" );
					ConnectProcess->addArgument ( QString().setNum ( GlobalConfig->currentProfile->getLocalPort() ) );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Using userdefined local port \"%1\"." ).arg ( QString().setNum ( GlobalConfig->currentProfile->getLocalPort() ) ), GlobalConfig->debug );
				}


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


				if ( GlobalConfig->currentProfile->getUseXauthInteractive() && ( ( vpnc_version_minor == 3 && vpnc_version_minor >= 2 ) || ( vpnc_version_minor > 3 ) ) )
				{
					ConnectProcess->addArgument ( "--xauth-inter" );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Enabling interactive extended authentication (for challange response auth)" ), GlobalConfig->debug );
				}

				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 );
				}


				// 					else
				// 					{
				// 						ConnectProcess->addArgument( "--local-port" );
				// 						ConnectProcess->addArgument( "0" ); // random port
				// 						GlobalConfig->appendLogEntry ( i18n( "Using random port." ), KVpncConfig::info);
				// 					}


				if ( GlobalConfig->currentProfile->getUsePerfectForwardSecrety() && !GlobalConfig->currentProfile->getPerfectForwardSecrety().isEmpty() )
				{
					ConnectProcess->addArgument ( "--pfs" );
					ConnectProcess->addArgument ( GlobalConfig->currentProfile->getPerfectForwardSecrety() );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Using userdefined PFS \"%1\"." ).arg ( GlobalConfig->currentProfile->getPerfectForwardSecrety() ), GlobalConfig->debug );
				}

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

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

				if ( vpnc_version_major >= 0 && vpnc_version_minor >= 4 )
				{
					ConnectProcess->addArgument ( "--ifmode");
					if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tap")
					{
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "Using tunnel device type: %1." ).arg("TAP"), GlobalConfig->debug );
						ConnectProcess->addArgument ( "tap");
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "Using tunnel device type: %1." ).arg("TUN"), GlobalConfig->debug );
						ConnectProcess->addArgument ( "tun");
					}
				}
				if (GlobalConfig->currentProfile->getDisableDataEncryption() == true)
				{
					if ( vpnc_version_major >= 0 && vpnc_version_minor >= 5 )
					{
						ConnectProcess->addArgument ( "--enable-no-encryption" );
					}	
				}
				if ( vpnc_version_major >= 0 && vpnc_version_minor > 2  )
				{
					if ( vpnc_version_minor > 3)
					{
					// we send config via stdin
					ConnectProcess->addArgument ( "-" );
					}
					else
					{
						if ( vpnc_version_subminor > 2)
						{
						// we send config via stdin
						ConnectProcess->addArgument ( "-" );
						}	
					}
				}


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

				
				setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);
				
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Setting DNS_UPDATE \"%1\"." ).arg ( getenv("DNS_UPDATE") ), GlobalConfig->debug );

				if ( GlobalConfig->KvpncDebugLevel > 1 )
				{
					QString args = "";
					QStringList list = ConnectProcess->arguments();
					QStringList::Iterator it = list.begin();
					while ( it != list.end() )
					{
						args += QString ( " " + *it ) ;
						++it;
					}
					GlobalConfig->appendLogEntry ( i18n ( "vpnc arguments: %1" ).arg ( args ), GlobalConfig->debug );
				}
				if ( !ConnectProcess->start(env) )
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "vpnc" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "vpnc" ), GlobalConfig->error );
					disconnectClicked();
					setGuiStatus ( disconnected );
				}
				else
				{
					slotStatusMsg ( i18n ( "Connecting..." ), ID_CONNECTION_MSG );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "vpnc" ), GlobalConfig->debug );
					ConnectingProcess = VpnAccountData::cisco;
					GlobalConfig->status = GlobalConfig->connecting;
					mw->buttonDisconnect->setEnabled ( true );
					this->DisconnectAction->setEnabled ( true );
					mw->buttonConnect->setEnabled ( false );
					this->ConnectAction->setEnabled ( false );

					connect ( ConnectProcess, SIGNAL ( processExited () ), this, SLOT ( vpncStarted() ) );
					connect ( ConnectProcess, SIGNAL ( wroteToStdin() ), this, SLOT ( wroteToStdin_vpncConfig() ) );
					
					if ( vpnc_version_major >= 0 && vpnc_version_minor > 2  )
					{
						if ( vpnc_version_minor > 3)
						{
						// we send config via stdin
						ConnectProcess->writeToStdin ( vpncConfig );
						}
						else
						{
							if ( vpnc_version_subminor > 2)
							{
							// we send config via stdin
							ConnectProcess->writeToStdin ( vpncConfig );
							}	
						}
					}

					disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
					connect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
					timer.start ( GlobalConfig->tryConnectTimeout * 1000, FALSE );
					}
				}
				else
				{
					VpncScript = tmpPath + "vpnc-script." + GlobalConfig->currentProfile->getName(); // vpnc-script.<name>
					GlobalConfig->appendLogEntry ( i18n ( "Making %1 (%2) excutable failed!" ).arg ( "VpncScript" ).arg ( VpncScript ), GlobalConfig->error );
					setGuiStatus ( disconnected );
					timer.stop();
					return ;
				}
			}
			else
			{
				setGuiStatus ( disconnected );
				return ;
			}
	} // vpnc

	/* ============ vpnclient (Cisco propritary) ================ */
	else if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
	{
		// looking for vpnclient
		if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "vpnclient" )->found == false )
		{
			KMessageBox::error ( this, i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "vpnclient" ).arg ( GlobalConfig->pathToCiscoVpnc ) );
			GlobalConfig->appendLogEntry ( i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "vpnclient" ).arg ( GlobalConfig->pathToCiscoVpnc ), GlobalConfig->error );
			ok = false;
			setGuiStatus ( disconnected );
			return ;
		}

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


		if ( checkCiscoVpncStatus() == false )
		{
			startCiscoVpnc();
			if ( checkCiscoVpncStatus() == false )
			{
				KMessageBox::error ( this, i18n ( "The Cisco ipsec interface could not setup!" ) );
				GlobalConfig->appendLogEntry ( i18n ( "The Cisco ipsec interface could not setup!" ), GlobalConfig->error );
				ok = false;
			}
			else
			{
				if (GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( i18n ( "The Cisco ipsec interface was down and could be started and is now up." ), GlobalConfig->debug );
			}
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( i18n ( "The Cisco ipsec interface is up." ), GlobalConfig->debug );
		}


		GlobalConfig->TmpGatewayIP = Utils ( GlobalConfig, parent ).resolveName ( GlobalConfig->currentProfile->getGateway() );
		if ( GlobalConfig->TmpGatewayIP == "0.0.0.0" || GlobalConfig->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
		{
			GlobalConfig->appendLogEntry ( i18n ( "Gateway hostname (%1) resolved to \"%2\"." ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->TmpGatewayIP ), GlobalConfig->info );
		}

		// here we go
		if ( ok )
		{
			bool askUsernamePass = false;
			bool askGroupPass=false;
			CiscoVpncDevice = "cipsec0";

			if ( GlobalConfig->currentProfile->getSaveUserPassword() )
			{
				if ( AuthRetry )
					askUsernamePass = true;
				else
					askUsernamePass = false;
			}
			else if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && !GlobalConfig->currentProfile->getSavePsk() )
				askUsernamePass = true;
			else if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && GlobalConfig->currentProfile->getAllowEmptyGroupPassword() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
				askUsernamePass = true;

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

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

			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
				askGroupPass=true;

			if ( AuthRetry )
				askUsernamePass = true;

			if ( askUsernamePass )
			{
				bool requestUsername = GlobalConfig->currentProfile->getUserPassword().isEmpty();
				EnterUsernamePasswordDialog dlg ( this, i18n ( "Enter Account Data" ), askGroupPass, 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();
				}

				if (GlobalConfig->currentProfile->getSaveUserPassword())
					dlg.main->SavePasswordCheckBox->setChecked ( true );
				else
					dlg.main->SavePasswordCheckBox->setChecked ( false );

				if (!GlobalConfig->currentProfile->getDontSaveUsername())
					dlg.main->SaveUsernameCheckBox->setChecked ( true );
				else
					dlg.main->SaveUsernameCheckBox->setChecked ( false );

				if (GlobalConfig->currentProfile->getSavePsk())
					dlg.main->SavePskCheckBox->setChecked ( true );
				else
					dlg.main->SavePskCheckBox->setChecked ( false );


				if ( dlg.exec() )
				{
					GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
					GlobalConfig->TmpGroupPassword = dlg.main->PSKLineEdit->text();
					GlobalConfig->TmpPassword = dlg.main->PasswordEdit->text();
					bool needSave=false;

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

					if ( requestUsername && GlobalConfig->TmpUsername.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->SaveUsernameCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setDontSaveUsername(false);
						GlobalConfig->currentProfile->setUserName ( dlg.main->UsernameEdit->text() );
						needSave=true;
					}
					else
					{
						GlobalConfig->currentProfile->setDontSaveUsername(true);
					}


					if ( dlg.main->SavePskCheckBox->isChecked() && askGroupPass )
					{
						GlobalConfig->currentProfile->setSavePsk ( true );
						GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
						needSave=true;
					}
					else
					{
						GlobalConfig->currentProfile->setSavePsk( false );
					}

					if ( dlg.main->SavePasswordCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSaveUserPassword ( true );
						GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
						needSave=true;
					}
					else
					{
						GlobalConfig->currentProfile->setSaveUserPassword( false );
					}
					if(needSave == true)
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Need to save because user had request it." ), GlobalConfig->debug );

						saveSessionClicked();
					}
				}
				else
				{
					ok = false;
					AuthRetry = false;
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because account data dialog aborted." ), GlobalConfig->debug );
					setGuiStatus ( disconnected );
					return;
				}
			}


			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->debug );
				LocalIP = iface.getInterfaceIP ( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "IP address of default interface: \"%1\"." ).arg ( LocalIP ) , GlobalConfig->debug );
			}
			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";
			OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>

			QFile DefaultRouteBackupFile ( OldDefaultroute + ".sh" );
			QTextStream DefaultRouteBackupFileStream ( &DefaultRouteBackupFile );
			if ( DefaultRouteBackupFile.open ( IO_WriteOnly ) )
			{
				DefaultRouteBackupFileStream << "# generated by kvpnc. Do not edit it." << "\n";
				DefaultRouteBackupFileStream << "\n";
				DefaultRouteBackupFileStream << GlobalConfig->pathToIp + " route show | grep default > " + OldDefaultroute + "\n";
				DefaultRouteBackupFile.close();
				QProcess backupDefaultRouteProcess ( this );
				backupDefaultRouteProcess.addArgument ( GlobalConfig->InterpreterShell );
				backupDefaultRouteProcess.addArgument ( OldDefaultroute + ".sh" );
				if ( !backupDefaultRouteProcess.start() )
				{
					// 				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because default route backup process could not be started." ), GlobalConfig->error );
					return ;
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Default route backup process started." ), GlobalConfig->debug );
				}
			}
			else
			{
				// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because default route could not be backuped." ), GlobalConfig->error );
				return ;
			}

			QString ResolvConfBackupProfile = tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName();

			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "Backup file of %1: %1" ).arg ( "resolv.conf" ).arg ( ResolvConfBackupProfile ), GlobalConfig->debug );

			QString UserPassStr = "";
			if ( !GlobalConfig->currentProfile->getUserPassword() || GlobalConfig->currentProfile->getUserPassword() == "" || AuthRetry )
				UserPassStr = GlobalConfig->TmpPassword;
			else
				UserPassStr = GlobalConfig->currentProfile->getUserPassword();
			
			CiscoVpncProcess = new QProcess ( this );
			CiscoVpncProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
			connect ( CiscoVpncProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readOutputFrom_ciscovpnc() ) );

			// write vpnc connect script
			QString CiscoVpncConfig = QString("/etc/opt/cisco-vpnclient/Profiles/")+QString("kvpnc_")+QString(GlobalConfig->currentProfile->getName()+".pcf"); // vpnc-script.<name>
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "CiscoVpncConfig: " + CiscoVpncConfig + "\n", GlobalConfig->debug );
			QFile file ( CiscoVpncConfig );
			QTextStream stream ( &file );
			if ( file.open ( IO_WriteOnly ) )
			{
// 				stream << "# generated by kvpnc. Do not edit it." << "\n";
 				stream << "[main]" << "\n";
				stream << "Description=KVpnc profile " << GlobalConfig->currentProfile->getName() << "\n";
 				stream << "Host=" << GlobalConfig->currentProfile->getGateway() << "\n";

				// 1 = Pre-shared keys (default)
				// 3 = Digital Certificate using an RSA signature.
				// 5 = Mutual authentication
				if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk)
 					stream << "AuthType=1" << "\n";
				if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert)
					stream << "AuthType=3" << "\n";

				if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk)
				{
 					stream << "GroupName=" << GlobalConfig->currentProfile->getID() << "\n";
 					stream << "GroupPwd=" << GlobalConfig->currentProfile->getPreSharedKey() << "\n";
				}
 				stream << "EnableISPConnect=0" << "\n";
 				stream << "ISPConnectType=0" << "\n";
 				stream << "ISPConnect=" << "\n";
 				stream << "ISPCommand=" << "\n";
				if (GlobalConfig->currentProfile->getUserName().isEmpty() || AuthRetry)
					stream << "Username=" << GlobalConfig->TmpUsername << "\n";
				else
 					stream << "Username=" << GlobalConfig->currentProfile->getUserName() << "\n";
				if (GlobalConfig->currentProfile->getSaveUserPassword())
 					stream << "SaveUserPassword=0" << "\n";
				else
					stream << "SaveUserPassword=1" << "\n";
//  				stream << "UserPassword=" << "\n";
				if (GlobalConfig->currentProfile->getUseNtDomainName())
 					stream << "NTDomain=" << GlobalConfig->currentProfile->getNtDomainName() << "\n";
				else
					stream << "NTDomain=" << "\n";
 				stream << "EnableBackup=0" << "\n";
 				stream << "BackupServer=" << "\n";
 				stream << "EnableMSLogon=0" << "\n";
 				stream << "MSLogonType=0" << "\n";

				// FIXME for now nat is always enabled
// 				if (GlobalConfig->currentProfile->getUseUdp())
					stream << "EnableNat=1" << "\n";
// 	 			else
// 					stream << "EnableNat=0" << "\n";

				if (GlobalConfig->currentProfile->getUseUdp())
 					stream << "TunnelingMode=0" << "\n";
				else
				{
					stream << "TunnelingMode=1" << "\n";
 					stream << "TcpTunnelingPort=10000" << "\n";
				}
				
				if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert)
				{
					stream << "CertStore=1" << "\n";
					stream << "CertName=" << GlobalConfig->currentProfile->getX509Certificate() << "\n";
					stream << "CertPath=" << "\n";
// 					stream << "CertSubjectName=" << "\n";
// 					stream << "CertSerialHash=00000000000000000000000000000000" << "\n";
					stream << "SendCertChain=0" << "\n";
				}
 				
 				stream << "PeerTimeout=90" << "\n";
 				stream << "EnableLocalLAN=0" << "\n"; //allways off

				file.close();

				CiscoVpncProcess->addArgument ( GlobalConfig->pathToCiscoVpnc );

				CiscoVpncProcess->addArgument ( "connect" );
				CiscoVpncProcess->addArgument ( "kvpnc_"+GlobalConfig->currentProfile->getName() );
				CiscoVpncProcess->addArgument ( "user" );
				CiscoVpncProcess->addArgument ( GlobalConfig->currentProfile->getUserName() );
// 				CiscoVpncProcess->addArgument ( "--script" );
// 				CiscoVpncProcess->addArgument ( VpncScript );
// 				if ( GlobalConfig->VpncDebugLevel > 0 )
// 				{
// 
// 					CiscoVpncProcess->addArgument ( "--debug" );
// 					CiscoVpncProcess->addArgument ( QString().setNum ( GlobalConfig->VpncDebugLevel ) );
// 				}
// 				CiscoVpncProcess->addArgument ( "--pid-file" );
// 				CiscoVpncProcess->addArgument ( GlobalConfig->Vpnc_pid_file );
// 
// 				if ( vpnc_version_minor == 3 && vpnc_version_subminor >= 3 || vpnc_version_minor >= 3 && vpnc_version_minor >= 3 && vpnc_version_subminor >= 3 )
// 					CiscoVpncProcess->addArgument ( "--non-inter" );
// 
// 				if ( GlobalConfig->currentProfile->getUseNtDomainName() )
// 				{
// 					CiscoVpncProcess->addArgument ( "--domain" );
// 					CiscoVpncProcess->addArgument ( GlobalConfig->currentProfile->getNtDomainName() );
// 					if ( GlobalConfig->KvpncDebugLevel > 0 )
// 						GlobalConfig->appendLogEntry ( i18n ( "Using (NT) domain name \"%1\"." ).arg ( GlobalConfig->currentProfile->getNtDomainName() ), GlobalConfig->debug );
// 				}
// 
// 				if ( GlobalConfig->currentProfile->getUseUdp() )
// 				{
// 					if ( vpnc_version_major >= 0 && vpnc_version_minor >= 4 )
// 					{
// 						// TODO add other nat modes
// 						CiscoVpncProcess->addArgument ( "--natt-mode");
// 						CiscoVpncProcess->addArgument ( "cisco-udp");
// 					}
// 					else
// 						CiscoVpncProcess->addArgument ( "--udp" );
// 					
// 					if ( GlobalConfig->KvpncDebugLevel > 0 )
// 						GlobalConfig->appendLogEntry ( i18n ( "Using UDP." ), GlobalConfig->debug );
// 				}
// 				else
// 				{
// 					CiscoVpncProcess->addArgument ( "--disable-natt" );
// 					if ( GlobalConfig->KvpncDebugLevel > 0 )
// 						GlobalConfig->appendLogEntry ( i18n ( "Dont using UDP." ), GlobalConfig->debug );
// 				}
// 
// 				if ( GlobalConfig->currentProfile->getUseLocalPort() == true )
// 				{
// 					CiscoVpncProcess->addArgument ( "--local-port" );
// 					CiscoVpncProcess->addArgument ( QString().setNum ( GlobalConfig->currentProfile->getLocalPort() ) );
// 					if ( GlobalConfig->KvpncDebugLevel > 0 )
// 						GlobalConfig->appendLogEntry ( i18n ( "Using userdefined local port \"%1\"." ).arg ( QString().setNum ( GlobalConfig->currentProfile->getLocalPort() ) ), GlobalConfig->debug );
// 				}
// 
// 
// 				if ( GlobalConfig->currentProfile->getUseUdpPort() )
// 				{
// 					CiscoVpncProcess->addArgument ( "--udp-port" );
// 					CiscoVpncProcess->addArgument ( QString().setNum ( GlobalConfig->currentProfile->getUdpPort() ) );
// 					if ( GlobalConfig->KvpncDebugLevel > 0 )
// 						GlobalConfig->appendLogEntry ( i18n ( "Using userdefined UDP port \"%1.\"" ).arg ( GlobalConfig->currentProfile->getUdpPort() ), GlobalConfig->debug );
// 				}
// 
// 
// 				if ( GlobalConfig->currentProfile->getUseXauthInteractive() && ( ( vpnc_version_minor == 3 && vpnc_version_minor >= 2 ) || ( vpnc_version_minor > 3 ) ) )
// 				{
// 					CiscoVpncProcess->addArgument ( "--xauth-inter" );
// 					if ( GlobalConfig->KvpncDebugLevel > 0 )
// 						GlobalConfig->appendLogEntry ( i18n ( "Enabling interactive extended authentication (for challange response auth)" ), GlobalConfig->debug );
// 				}
// 
// 				if ( GlobalConfig->currentProfile->getUseAdvancedSettings() == true )
// 				{
// 					GlobalConfig->appendLogEntry ( i18n ( "Using advanced settings." ) , GlobalConfig->debug );
// 
// 					if ( GlobalConfig->currentProfile->getUseApplicationVersion() )
// 					{
// 						CiscoVpncProcess->addArgument ( "--application-version" );
// 						CiscoVpncProcess->addArgument ( GlobalConfig->currentProfile->getApplicationVersion() );
// 						GlobalConfig->appendLogEntry ( i18n ( "Using userdefined application version \"%1\"." ).arg ( GlobalConfig->currentProfile->getApplicationVersion() ) , GlobalConfig->debug );
// 					}
// 
// 
// 					// 					else
// 					// 					{
// 					// 						CiscoVpncProcess->addArgument( "--local-port" );
// 					// 						CiscoVpncProcess->addArgument( "0" ); // random port
// 					// 						GlobalConfig->appendLogEntry ( i18n( "Using random port." ), KVpncConfig::info);
// 					// 					}
// 
// 
// 					if ( GlobalConfig->currentProfile->getUsePerfectForwardSecrety() )
// 					{
// 						CiscoVpncProcess->addArgument ( "--pfs" );
// 						CiscoVpncProcess->addArgument ( GlobalConfig->currentProfile->getPerfectForwardSecrety() );
// 						if ( GlobalConfig->KvpncDebugLevel > 0 )
// 							GlobalConfig->appendLogEntry ( i18n ( "Using userdefined PFS \"%1\"." ).arg ( GlobalConfig->currentProfile->getPerfectForwardSecrety() ), GlobalConfig->debug );
// 					}
// 
// 					if ( GlobalConfig->currentProfile->getUseIkeGroup() )
// 					{
// 						CiscoVpncProcess->addArgument ( "--dh" );
// 						CiscoVpncProcess->addArgument ( GlobalConfig->currentProfile->getIkeGroup() );
// 						if ( GlobalConfig->KvpncDebugLevel > 0 )
// 							GlobalConfig->appendLogEntry ( i18n ( "Using userdefined IKE group \"%1\"." ).arg ( GlobalConfig->currentProfile->getIkeGroup() ), GlobalConfig->debug );
// 					}
// 
// 					if ( GlobalConfig->currentProfile->getUseSingleDes() )
// 					{
// 						CiscoVpncProcess->addArgument ( "--enable-1des" );
// 						if ( GlobalConfig->KvpncDebugLevel > 0 )
// 							GlobalConfig->appendLogEntry ( i18n ( "Using single DES." ), GlobalConfig->debug );
// 					}
// 				}
// 
// 				if ( vpnc_version_major >= 0 && vpnc_version_minor >= 4 )
// 				{
// 					CiscoVpncProcess->addArgument ( "--ifmode");
// 					if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tap")
// 					{
// 						if ( GlobalConfig->KvpncDebugLevel > 1 )
// 							GlobalConfig->appendLogEntry ( i18n ( "Using tunnel device type: %1." ).arg("TAP"), GlobalConfig->debug );
// 						CiscoVpncProcess->addArgument ( "tap");
// 					}
// 					else
// 					{
// 						if ( GlobalConfig->KvpncDebugLevel > 1 )
// 							GlobalConfig->appendLogEntry ( i18n ( "Using tunnel device type: %1." ).arg("TUN"), GlobalConfig->debug );
// 						CiscoVpncProcess->addArgument ( "tun");
// 					}

				if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk)
				{
				GlobalConfig->appendLogEntry ( i18n ( "Trying to connect to server \"%1\" (%2) with user \"%3\" and IPSec ID \"%4\"...\n" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->TmpGatewayIP ).arg ( GlobalConfig->currentProfile->getUserName() ).arg ( GlobalConfig->currentProfile->getID() ), GlobalConfig->info );
				}
				if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert)
				{
				GlobalConfig->appendLogEntry ( i18n ( "Trying to connect to server \"%1\" (%2) with user \"%3\"...\n" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->TmpGatewayIP ).arg ( GlobalConfig->currentProfile->getUserName() ), GlobalConfig->info );
				}

				setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);
				
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Setting DNS_UPDATE \"%1\"." ).arg ( getenv("DNS_UPDATE") ), GlobalConfig->debug );


				if ( !CiscoVpncProcess->start(env) )
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "vpnclient" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "vpnclient" ), GlobalConfig->error );
					disconnectClicked();
					setGuiStatus ( disconnected );
				}
				else
				{
					slotStatusMsg ( i18n ( "Connecting..." ), ID_CONNECTION_MSG );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "vpnclient" ), GlobalConfig->debug );
					ConnectingProcess = VpnAccountData::cisco;
					GlobalConfig->status = GlobalConfig->connecting;
					mw->buttonDisconnect->setEnabled ( true );
					this->DisconnectAction->setEnabled ( true );
					mw->buttonConnect->setEnabled ( false );
					this->ConnectAction->setEnabled ( false );

// 				connect ( ConnectProcess, SIGNAL ( processExited () ), this, SLOT ( vpncStarted() ) );
// 				connect ( ConnectProcess, SIGNAL ( wroteToStdin() ), this, SLOT ( wroteToStdin_vpncConfig() ) );
				
				}
				disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
				connect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
				timer.start ( GlobalConfig->tryConnectTimeout * 1000, FALSE );
			}
			else
			{
				// file could not written
				GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because profile file could not be written." ), GlobalConfig->error );
				setGuiStatus ( disconnected );
				return ;
			}
		}
		else
		{
			// ok is false
			setGuiStatus ( disconnected );
			return ;
		}
	}

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

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "racoon" ), GlobalConfig->debug );

		//setGuiStatus(connecting);
		// looking for racoon
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "racoon" )->found == false )
			{
				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 ;
			}

		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
		{
			if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "l2tpd" )->found == false && Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "xl2tpd" )->found == false )
			{
				KMessageBox::error ( this, i18n ( "Unable to find \"%1\" or \"%2\"!" ).arg ( "l2tpd" ).arg ( "xl2tpd" ) );
				GlobalConfig->appendLogEntry ( i18n ( "Unable to find \"%1\" or \"%2\"!" ).arg ( "l2tpd" ).arg ( "xl2tpd" ), 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 ;
		}

		GlobalConfig->TmpGatewayIP = Utils ( GlobalConfig, parent ).resolveName ( GlobalConfig->currentProfile->getGateway() );
		if ( GlobalConfig->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
		{
			GlobalConfig->appendLogEntry ( i18n ( "Gateway hostname (%1) resolved to \"%2\"." ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->TmpGatewayIP ), 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->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;
		}


		bool askUsernamePass = false;
		bool askPsk = false;

		if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && ( GlobalConfig->currentProfile->getSavePsk() == false || GlobalConfig->currentProfile->getPreSharedKey().isEmpty() ) )
		{
			askUsernamePass = false;
			askPsk = true;
		}

		if ( AuthRetry )
			askUsernamePass = true;

		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon && ( !GlobalConfig->currentProfile->getSaveUserPassword() && GlobalConfig->currentProfile->getUserName().isEmpty() || GlobalConfig->currentProfile->getUserPassword().isEmpty() ) )
			askUsernamePass = true;

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

				if ( !GlobalConfig->currentProfile->getUserName().isEmpty() )
					dlg.main->UsernameEdit->setText ( GlobalConfig->currentProfile->getUserName() );
				dlg.main->LabelGroupPassword->setText ( i18n ( "PSK:" ) );

				if ( !GlobalConfig->currentProfile->getUserPassword().isEmpty() )
					dlg.main->PasswordEdit->setText ( GlobalConfig->currentProfile->getUserPassword() );
				else
					dlg.main->PasswordEdit->setFocus();
			}
			if ( askPsk )
			{
				if ( !GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
					dlg.main->PSKLineEdit->setText ( GlobalConfig->currentProfile->getPreSharedKey() );
				else
					if ( !GlobalConfig->currentProfile->getUserPassword().isEmpty() )
						dlg.main->PSKLineEdit->setFocus();
				if ( !askUsernamePass )
				{
					dlg.main->PasswordEdit->hide();
					dlg.main->UsernameEdit->hide();
					dlg.main->LabelPassword->hide();
					dlg.main->LabelUsername->hide();
				}
			}
			else
			{
				dlg.main->LabelGroupPassword->hide();
				dlg.main->PSKLineEdit->hide();
			}

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

			if ( dlg.exec() )
			{
				GlobalConfig->TmpGroupPassword = dlg.main->PSKLineEdit->text();
				GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
				GlobalConfig->TmpPassword = dlg.main->PasswordEdit->text();
				
				if ( askPsk || AuthRetry )
				{

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

					if ( dlg.main->SaveUsernameCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setDontSaveUsername(false);
						GlobalConfig->currentProfile->setUserName ( dlg.main->UsernameEdit->text() );
					}
					else
					{
						GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
						GlobalConfig->currentProfile->setDontSaveUsername(true);
					}


					if ( dlg.main->SavePskCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSavePsk ( true );
						GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSavePsk( false );
					}

					if ( dlg.main->SavePasswordCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSaveUserPassword ( true );
						GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSaveUserPassword( false );
					}
					saveSessionClicked();
				if ( ok )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Some account data which is needed got from password enter dialog." ), GlobalConfig->debug );
					// 					saveSessionClicked();
				}
			}
			else
			{
				ok = false;
				AuthRetry = false;
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because account data dialog aborted." ), GlobalConfig->debug );
			}
		}
		if ( GlobalConfig->currentProfile->getPskIsInFile() )
		{
			QFile f ( GlobalConfig->currentProfile->getPreSharedKeyFile() );
			if ( f.open ( IO_ReadOnly ) )
			{
				QTextStream stream ( &f );
				QString line = "";
				while ( !stream.atEnd() )
				{
					line = stream.readLine(); // line of text excluding '\n'
					if ( !line.find ( '#', 0 ) < 0 )
					{
						GlobalConfig->TmpGroupPassword = line;
						break;
					}
				}
				f.close();
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n ( "PSK could not read from file because PSK key file %1 could not be read." ).arg ( GlobalConfig->currentProfile->getPreSharedKeyFile() ), GlobalConfig->error );
				ok = false;
			}
			if ( GlobalConfig->TmpGroupPassword.isEmpty() )
			{
				GlobalConfig->appendLogEntry ( i18n ( "PSK could not read from file because PSK key file %1 contains no key." ).arg ( GlobalConfig->currentProfile->getPreSharedKeyFile() ), 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->debug );
				LocalIP = iface.getInterfaceIP ( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "IP address of default interface: \"%1\"." ).arg ( LocalIP ) , GlobalConfig->debug );
			}
			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 ) )
			{

				QString PolicyRemote = "";
				QString PolicyLocal = "";

				QString Remote = GlobalConfig->currentProfile->getGateway();

				//FIXME make it dynamiclly
				QString LocalPort = "4500";
				QString RemotePort = "4500";

				// FIXME replace useUdp with useNatT
				if ( !GlobalConfig->currentProfile->getUseUdp() )
				{
					// Use this for a non NAT-T setup
					PolicyLocal = LocalIP;
					PolicyRemote = GlobalConfig->TmpGatewayIP;
				}
				else
				{
					PolicyLocal = LocalIP + "[" + LocalPort + "]";
					PolicyRemote = GlobalConfig->TmpGatewayIP + "[" + RemotePort + "]";
				}

				stream << "flush;" << "\n";
				stream << "spdflush;" << "\n";

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
					stream << "spdadd " << Remote << "[1701] " << LocalIP << "[any] udp -P in ipsec esp/transport//require;" << "\n";
					stream << "spdadd " << LocalIP << "[any] " << Remote << "[1701] udp -P out ipsec esp/transport//require;" << "\n";
					// 					stream << "spdadd " << Remote << "[1701] " << LocalIP << "[any] udp -P in ipsec esp/tunnel/" + Remote + "-" + LocalIP + "/require;" << "\n";
					// 					stream << "spdadd " << LocalIP << "[any] " << Remote << "[1701] udp -P out ipsec esp/tunnel/" + LocalIP + "-" + Remote + "/require;" << "\n";
				}
				else
				{
					// 										stream << "spdadd " + LocalIP + " " + RemoteNet + " any -P out ipsec esp/tunnel/" + PolicyLocal + "-" + PolicyRemote + "/require;" << "\n";
					// 										stream << "spdadd " + RemoteNet + " " + LocalIP + " any -P in ipsec esp/tunnel/" + PolicyRemote + "-" + PolicyLocal + "/require;" << "\n";
					stream << "spdadd " + LocalIP + " " + RemoteNet + " any -P out ipsec esp/tunnel/" + LocalIP + "-" + Remote + "/require;" << "\n";
					stream << "spdadd " + RemoteNet + " " + LocalIP + " any -P in ipsec esp/tunnel/" + Remote + "-" + LocalIP + "/require;" << "\n";
				}


				if ( !GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
					// additional network routes
					if ( !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty() )
					{
						QStringList AdditionalNetworkRoutes = GlobalConfig->currentProfile->getAdditionalNetworkRoutes();

						for ( QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end();++it )
						{
							QString net = ( *it ).section ( '#', 0, 0 );
							// 							stream << "spdadd " + LocalIP + " " + net + " any -P out ipsec esp/tunnel/" + PolicyLocal + "-" + PolicyRemote + "/require;" << "\n";
							// 							stream << "spdadd " + net + " " + LocalIP + " any -P in ipsec esp/tunnel/" + PolicyRemote + "-" + PolicyLocal + "/require;" << "\n";
							stream << "spdadd " + LocalIP + " " + net + " any -P out ipsec esp/tunnel/" + LocalIP + "-" + Remote + "/require;" << "\n";
							stream << "spdadd " + net + " " + LocalIP + " any -P in ipsec esp/tunnel/" + Remote + "-" + 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"; // FIXME: validate racoon version

				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 << "listen" << "\n";
				stream << "{" << "\n";
				stream << "  isakmp " << LocalIP << "[500];" << "\n";

				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					stream << "  isakmp_natt " << LocalIP << "[4500];" << "\n";
				}
				stream << "}" << "\n";

				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					stream << "" << "\n";
					stream << "timer" << "\n";
					stream << "{" << "\n";

					//FIXME make it dynamiclly
					stream << "  natt_keepalive 10 sec;" << "\n";
					stream << "}" << "\n";
				}
				stream << "" << "\n";
				stream << "remote " << GlobalConfig->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 << "  ca_type x509 \"" << GlobalConfig->currentProfile->getCaCertificate() << "\";" << "\n";
					stream << "  verify_cert on;" << "\n"; // FIXME: make it dynamiclly
					if ( GlobalConfig->currentProfile->getUseSpecialRemoteID() )
					{
						stream << "  peers_identifier asn1dn " << GlobalConfig->currentProfile->getSpecialRemoteID() << ";" << "\n";
					}
					else
					{
						if ( GlobalConfig->currentProfile->getUseMailAddressAsIdentifier()  )
						{
							QString MailAddressOfUserCert = Utils ( GlobalConfig ).getEmailAddressOfCert ( GlobalConfig->currentProfile->getX509Certificate() );

							if ( GlobalConfig->KvpncDebugLevel > 0 )
								GlobalConfig->appendLogEntry ( i18n ( "Using mail address as VPN id: %1." ).arg ( MailAddressOfUserCert ), GlobalConfig->debug );

							// 							stream << "  peers_identifier asn1dn;" << "\n";
							//FIXME check if MailAddressOfUserCert is empty
							stream << "  my_identifier user_fqdn \"" << MailAddressOfUserCert << "\";" << "\n";
						}
						else
						{
							QString LocalIDType = GlobalConfig->currentProfile->getLocalIDType();
							
							if( LocalIDType == "asn1dn")
								stream << "  my_identifier asn1dn;" << "\n";
							if( LocalIDType == "address")
								stream << "  my_identifier address \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
							if( LocalIDType == "fqdn")
								stream << "  my_identifier fqdn \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
							if( LocalIDType == "keyid")
								stream << "  my_identifier keyid \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
							if( LocalIDType == "user_fqdn")
								stream << "  my_identifier user_fqdn \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";

							//TODO implement peers_identifier: same as my_identifier
							stream << "  peers_identifier asn1dn;" << "\n";
							
						}
					}
				}
				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					stream << "  nat_traversal on;" << "\n";
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Using NAT-T." ), GlobalConfig->debug );
				}
				if ( GlobalConfig->currentProfile->getUseModeConfig() )
				{
					stream << "  mode_cfg on;" << "\n";
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Using Mode Config." ), GlobalConfig->debug );
				}

				// 				stream << "  passive on;" << "\n";

				stream << "  proposal {" << "\n";

				stream << "    # for phase 1" << "\n";
				stream << "    encryption_algorithm " << GlobalConfig->currentProfile->getEncryptionAlgorithm() << ";" << "\n";

				if (! GlobalConfig->currentProfile->getHashAlgo().isEmpty())
					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";

				stream << "    dh_group " + GlobalConfig->currentProfile->getIkeGroup() + ";" << "\n";

				stream << "  }" << "\n";
				if ( GlobalConfig->currentProfile->getUseUdp() )
					stream << "proposal_check obey;" << "\n";

				stream << "}" << "\n";
				stream << "" << "\n";

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

				// 				stream << "sainfo address " << LocalIP << " any address " << GlobalConfig->currentProfile->getRemoteNetAddr() << "/" << GlobalConfig->currentProfile->getRemoteNetMask() << " any {" << "\n";

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
					stream << "sainfo anonymous {" << "\n";
				else
					stream << "sainfo address " << LocalIP << "/32 any address " << RemoteNet << " 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";

						if (!pfs_group.isEmpty())
							stream << "    pfs_group " << pfs_group << ";\n";
					}
					else
					{
						stream << "  pfs_group modp768;" << "\n";
					}
				}

				stream << "  encryption_algorithm " << GlobalConfig->currentProfile->getEncryptionAlgorithm() << ";" << "\n";
				stream << "  authentication_algorithm " << GlobalConfig->currentProfile->getAuthenticationAlgorithm() << ";" << "\n";
				stream << "  compression_algorithm deflate;" << "\n";
				stream << "}" << "\n";

				// 				stream << "listen {" << "\n";
				//
				// 				//FIXME make own port useable
				// 				stream << "  isakmp " << LocalIP << ";" << "\n";
				// 				if ( GlobalConfig->currentProfile->getUseUdp() )
				// 				{
				// 					if ( GlobalConfig->currentProfile->getUseUdpPort() )
				// 					{
				// 						stream << "  # isakmp port for nat-t" << "\n";
				// 						stream << "  isakmp_natt " << LocalIP << "["<< GlobalConfig->currentProfile->getUdpPort() << "];" << "\n";
				// 					}
				// 					else
				// 					{
				// 						stream << "  isakmp_natt " << LocalIP << ";" << "\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 <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + ProfileName << "\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_racoon.sh" );
			stream.setDevice ( &file );
			if ( file.open ( IO_WriteOnly )
			   )
			{
				stream << "#!"<< GlobalConfig->InterpreterShell << "\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->TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 50 -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  ESP" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p 51 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 51 -d " << GlobalConfig->TmpGatewayIP << " -j  ACCEPT" << "\n";
				stream << "" << "\n";
				stream << "#  IKE" << "\n";
				stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I OUTPUT -p udp --dport 500 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";

				stream << "" << "\n";
				stream << GlobalConfig->pathToIptables << " -I FORWARD -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				stream << GlobalConfig->pathToIptables << " -I FORWARD -p udp --dport 500 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";

				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					stream << "" << "\n";
					stream << "#  NAT-T" << "\n";
					stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
					stream << GlobalConfig->pathToIptables << " -I OUTPUT -p udp --sport 4500 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				}
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
					stream << "" << "\n";
					stream << "#  L2TP" << "\n";
					stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
					stream << GlobalConfig->pathToIptables << " -I OUTPUT -p udp --sport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				}
				file.close();
			}
			stream.unsetDevice();

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

				stream1 << "" << "\n";
				stream1 << GlobalConfig->pathToIptables << " -D FORWARD -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				stream1 << GlobalConfig->pathToIptables << " -D FORWARD -p udp --dport 500 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";

				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					stream1 << "" << "\n";
					stream1 << "#  NAT-T" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p udp --sport 4500 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				}
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
					stream1 << "" << "\n";
					stream1 << "#  L2TP" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p udp --sport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
				}
				file1.close();
			}

			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";

				}
				if ( GlobalConfig->currentProfile->getPskIsInFile() )
				{
					stream << GlobalConfig->TmpGatewayIP + "\t" + GlobalConfig->TmpGroupPassword << "\n";
				}
				else
				{
					if ( GlobalConfig->currentProfile->getSavePsk() )
						stream << GlobalConfig->TmpGatewayIP + "\t" + GlobalConfig->currentProfile->getPreSharedKey() << "\n";
					else
						stream << GlobalConfig->TmpGatewayIP + "\t" + GlobalConfig->TmpGroupPassword << "\n";
				}
				file.close();
				stream.unsetDevice();
			}

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

			setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);
			
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Setting DNS_UPDATE \"%1\"." ).arg ( getenv("DNS_UPDATE") ), GlobalConfig->debug );

			if ( useL2tpAfterFirstConnection )
				prepareL2tpd();


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

			connect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_racoon_helper() ) );
			connect ( ConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_racoon_helper() ) );
			connect ( ConnectProcess, SIGNAL ( processExited () ), this, SLOT ( doRacoon() ) );

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

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

		//setGuiStatus(connecting);

		// looking for ipsec

		if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "ipsec" )->found == false )
		{
			KMessageBox::error ( this, i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "ipsec (" + IpsecType + ")" ).arg ( GlobalConfig->pathToFreeswan ) );
			GlobalConfig->appendLogEntry ( i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "ipsec (" + IpsecType + ")" ).arg ( GlobalConfig->pathToFreeswan ), GlobalConfig->error );
			ok = false;
			setGuiStatus ( disconnected );
			return ;
		}
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
		{
			if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "l2tpd" )->found == false && Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "xl2tpd" )->found == false )
			{
				KMessageBox::error ( this, i18n ( "Unable to find \"%1\" or \"%2\"!" ).arg ( "l2tpd" ).arg ( "xl2tpd" ) );
				GlobalConfig->appendLogEntry ( i18n ( "Unable to find \"%1\" or \"%2\"!" ).arg ( "l2tpd" ).arg ( "xl2tpd" ), GlobalConfig->error );
				ok = false;
				setGuiStatus ( disconnected );
				return ;
			}
		}


		GlobalConfig->TmpGatewayIP = Utils ( GlobalConfig, parent ).resolveName ( GlobalConfig->currentProfile->getGateway() );
		if ( GlobalConfig->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
		{
			GlobalConfig->appendLogEntry ( i18n ( "Gateway hostname (%1) resolved to \"%2\"." ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->TmpGatewayIP ), GlobalConfig->info );
		}

		if ( GlobalConfig->currentProfile->authtype == VpnAccountData::cert )
		{
			if ( !GlobalConfig->currentProfile->getUseSmartcard() )
			{
				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;
				}
			}

			QFile CertTmpFile;
			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;
			}
		}

		// 		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;
		// 		}


		bool askUsernamePass = false;
		bool askPsk = false;

		if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && ( GlobalConfig->currentProfile->getSavePsk() == false || GlobalConfig->currentProfile->getPreSharedKey().isEmpty() ) )
		{
			askUsernamePass = false;
			askPsk = true;
		}

		if ( AuthRetry )
			askUsernamePass = true;

		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan && ( !GlobalConfig->currentProfile->getSaveUserPassword() && GlobalConfig->currentProfile->getUserName().isEmpty() || GlobalConfig->currentProfile->getUserPassword().isEmpty() ) )
			askUsernamePass = true;

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

				if ( !GlobalConfig->currentProfile->getUserName().isEmpty() )
					dlg.main->UsernameEdit->setText ( GlobalConfig->currentProfile->getUserName() );
				dlg.main->LabelGroupPassword->setText ( i18n ( "PSK:" ) );

				if ( !GlobalConfig->currentProfile->getUserPassword().isEmpty() )
					dlg.main->PasswordEdit->setText ( GlobalConfig->currentProfile->getUserPassword() );
				else
					dlg.main->PasswordEdit->setFocus();
			}
			if ( askPsk )
			{
				if ( !GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
					dlg.main->PSKLineEdit->setText ( GlobalConfig->currentProfile->getPreSharedKey() );
				else
					if ( !GlobalConfig->currentProfile->getUserPassword().isEmpty() )
						dlg.main->PSKLineEdit->setFocus();
				if ( !askUsernamePass )
				{
					dlg.main->PasswordEdit->hide();
					dlg.main->UsernameEdit->hide();
					dlg.main->LabelPassword->hide();
					dlg.main->LabelUsername->hide();
				}
			}
			else
			{
				dlg.main->LabelGroupPassword->hide();
				dlg.main->PSKLineEdit->hide();
			}

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

			if ( dlg.exec() )
			{
				GlobalConfig->TmpGroupPassword = dlg.main->PSKLineEdit->text();
				GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
				GlobalConfig->TmpPassword = dlg.main->PasswordEdit->text();
				if ( askPsk || AuthRetry )
				{
					if ( GlobalConfig->currentProfile->getPreSharedKey().isEmpty() || GlobalConfig->TmpGroupPassword.isEmpty() )
					{
						GlobalConfig->appendLogEntry ( i18n ( "PSK is empty!" ), GlobalConfig->error );
						ok = false;
					}
				}

					if ( dlg.main->SaveUsernameCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setDontSaveUsername(false);
						GlobalConfig->currentProfile->setUserName ( dlg.main->UsernameEdit->text() );
					}
					else
					{
						GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
						GlobalConfig->currentProfile->setDontSaveUsername(true);
					}


					if ( dlg.main->SavePskCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSavePsk ( true );
						GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSavePsk( false );
					}

					if ( dlg.main->SavePasswordCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSaveUserPassword ( true );
						GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSaveUserPassword( false );
					}
					saveSessionClicked();

				// 				if ( /*GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert && */GlobalConfig->currentProfile->getUseMailAddressAsIdentifier() && Utils( GlobalConfig ).getEmailAddressOfCert( GlobalConfig->currentProfile->getX509Certificate()).isEmpty())
				// 				{
				// 					GlobalConfig->appendLogEntry( i18n( "Mail address could not read from certificate!" ), GlobalConfig->error );
				// 					ok = false;
				// 				}

				if ( ok )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Some account data which is needed got from password enter dialog." ), GlobalConfig->debug );
					// 					saveSessionClicked();
				}
			}
			else
			{
				ok = false;
				AuthRetry = false;
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because account data dialog aborted." ), GlobalConfig->debug );
			}
		}
		if ( GlobalConfig->currentProfile->getPskIsInFile() )
		{
			QFile f ( GlobalConfig->currentProfile->getPreSharedKeyFile() );
			if ( f.open ( IO_ReadOnly ) )
			{
				QTextStream stream ( &f );
				QString line = "";
				while ( !stream.atEnd() )
				{
					line = stream.readLine(); // line of text excluding '\n'
					if ( !line.find ( '#', 0 ) < 0 )
					{
						GlobalConfig->TmpGroupPassword = line;
						break;
					}
				}
				f.close();
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n ( "PSK could not read from file because PSK key file %1 could not be read." ).arg ( GlobalConfig->currentProfile->getPreSharedKeyFile() ), GlobalConfig->error );
				ok = false;
			}
			if ( GlobalConfig->TmpGroupPassword.isEmpty() )
			{
				GlobalConfig->appendLogEntry ( i18n ( "PSK could not read from file because PSK key file %1 contains no key." ).arg ( GlobalConfig->currentProfile->getPreSharedKeyFile() ), GlobalConfig->error );
				ok = false;
			}
		}

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

		if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert && GlobalConfig->currentProfile->getUseSmartcard() )
		{
			GlobalConfig->TmpPassword = "";
			QCString password;
			QString pass = "";
			Pkcs11PIN = "";

			GlobalConfig->TmpPrivateKeyPass = "";
			EnterXauthInteractivePasscodeDialog dlg ( 0, i18n ( "Enter smartcard PIN" ) );
			dlg.main->DescriptionLabel->setText ( i18n ( "Enter PIN for unlocking smartcard \"%1\":" ).arg ( GlobalConfig->currentProfile->getPkcs11Slot() ) );
			dlg.main->LabelPassword->setText ( i18n ( "PIN:" ) );
			dlg.main->SavePasswordCheckBox->hide();
			dlg.main->adjustSize();
			dlg.adjustSize();
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "PIN for unlocking smartcard requested...\n" ), GlobalConfig->debug );
			if ( dlg.exec() )
			{

				pass = dlg.main->PasswordEdit->text();
				if ( !pass.isEmpty() )
				{

					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( "[ipsec]: " + i18n ( "PIN got from user" ), GlobalConfig->debug );


					GlobalConfig->TmpPrivateKeyPass = QString ( pass );
					Pkcs11PIN = GlobalConfig->TmpPrivateKeyPass;
				}
				else
				{
					GlobalConfig->appendLogEntry ( "[ipsec]: PIN empty, stop.", GlobalConfig->error );
					ok = false;
				}
			}
			else
			{
				GlobalConfig->appendLogEntry ( "[ipsec]: password dialog canceled and password empty, stop.", GlobalConfig->info );
				ok = false;
			}
		}

		//   // here we go
		if ( ok )
		{

			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert && !GlobalConfig->currentProfile->getUseSmartcard() )
				leftid = getX509CertificateID ( GlobalConfig->currentProfile->getX509Certificate(), true ); // local
			else
				leftid = "";
			if ( GlobalConfig->currentProfile->getUseSpecialRemoteID() )
				rightid = GlobalConfig->currentProfile->getSpecialRemoteID();
			else
			{
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
					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;
			// 				}
		

		GlobalConfig->TmpGatewayIP = Utils ( GlobalConfig, parent ).resolveName ( GlobalConfig->currentProfile->getGateway() );
		if ( GlobalConfig->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
		{
			GlobalConfig->appendLogEntry ( i18n ( "Gateway hostname (%1) resolved to \"%2\"." ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->TmpGatewayIP ), GlobalConfig->info );
		}

		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->debug );
			LocalIP = iface.getInterfaceIP ( iface.getDefaultInterface() );
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "IP address of default interface: \"%1\"." ).arg ( LocalIP ) , GlobalConfig->debug );
		}
		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 ( IpsecType ), 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();


		//FIXME replace this by adding connection via management interface and start the connection
		QProcess IpsecStopProcess ( this );
		IpsecStopProcess.addArgument ( "/etc/init.d/ipsec" );
		IpsecStopProcess.addArgument ( "stop" );
		if ( IpsecStopProcess.start() )
		{
			while ( IpsecStopProcess.isRunning() )
				usleep ( 500 );
		}

		// 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";
				if ( !GlobalConfig->currentProfile->getUseSmartcard() )
					stream << ": RSA " + GlobalConfig->currentProfile->getPrivateKey() + " \"" + GlobalConfig->currentProfile->getPrivateKeyPass() + "\"\n";
				else
				{
					stream << ": PIN %smartcard \"" << Pkcs11PIN << "\"" << "\n";
					// 						stream << ": PIN %smartcard \"123456\"" << "\n";
					// 						stream << ": PIN %smartcard %prompt" << "\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 << "# right: remote" << "\n";
				stream << "# left: local" << "\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 << "    interfaces=\"ipsec0=" << tmpInterface << "\"" << "\n";

				if ( GlobalConfig->currentProfile->getUseSmartcard() /*&& IpsecType.contains( "strongSwan" )*/ )
					stream << "    pkcs11module=" + GlobalConfig->currentProfile->getPkcs11Providers() + "\n";


				//FIXME make it dynamiclly
				stream << "    klipsdebug=none" << "\n";
				stream << "    plutodebug=none" << "\n";

				if ( ! IpsecType.contains ( "free" ) )
					stream << "    plutostderrlog=" << tmpPath + "ipsec." + GlobalConfig->currentProfile->getName() + ".log" << "\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";
				}
				else if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
				{
					stream << "    authby=secret" << "\n";
				}
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
					stream << "    type=transport" << "\n"; // we have to use transport mode
				else
					stream << "    type=tunnel" << "\n"; //TODO make it dynamiclly
				stream << "    keyingtries=1" << "\n";
				stream << "    #keylife=1200s" << "\n";
				stream << "    #ikelifetime=1200s" << "\n";
				stream << "\n";

				// our connection
				stream << "conn " << GlobalConfig->currentProfile->getName() << "\n";
				if ( GlobalConfig->currentProfile->getExchangeMode() == "aggressive" )
				{
					stream << "    aggrmode=yes" << "\n";
				}

				if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
					// udp/l2tp
					stream << "    rightprotoport=17/1701" << "\n";
					stream << "    leftprotoport=17/1701" << "\n";
				}

				stream << "    keyexchange=ike" << "\n";
				stream << "    " << GlobalConfig->currentProfile->getIpsecIke() << "\n";
				stream << "    " << GlobalConfig->currentProfile->getIpsecEsp()  << "\n";

				if ( GlobalConfig->currentProfile->getUseMtu() )
					stream << "    overridemtu=" << GlobalConfig->currentProfile->getMtu() << "\n";

				if ( GlobalConfig->currentProfile->getUsePerfectForwardSecrety() )
					stream << "    pf=yes" << "\n";
				else
					stream << "    pfs=no" << "\n";

				stream << "    auto=start" << "\n";
				stream << "    left=" + LocalIP << "\n"; // local ip
				// 				stream << " leftnexthop = "+LocalNet << "\n";
				// 				stream << " leftsubnet = " << "\n"; // local network

				if ( !GlobalConfig->currentProfile->getLeftNextHop().isEmpty() )
					stream << "    leftnexthop=" + GlobalConfig->currentProfile->getLeftNextHop() << "\n";
				//    stream << " rightnexthop = " << "192.168.1.1"  << "\n";
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
				{
					if ( !GlobalConfig->currentProfile->getUseSmartcard() )
						stream << "    leftcert=\"" + GlobalConfig->currentProfile->getX509Certificate() << "\""<< "\n";
					else
					{
						// we have to split slot id and name ("0 : foobar") => 0
						QString Pkcs11Slot = GlobalConfig->currentProfile->getPkcs11Slot().section ( ':', 0, 0 ).stripWhiteSpace();
						stream << "    leftcert=%smartcard" << Pkcs11Slot << ":" << GlobalConfig->currentProfile->getPkcs11Id() << "\n";
					}

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

					if ( GlobalConfig->currentProfile->getUseSpecialRemoteID() )
						stream << "    rightid=\"" + GlobalConfig->currentProfile->getSpecialRemoteID() << "\""<< "\n";
					//stream << "    rightid=\"/C=DE/ST=Sachsen-Anhalt/O=Powersoft/OU=IT/CN=212.100.100.212\"" << "\n";

				}
				//stream << "    right=" + GlobalConfig->currentProfile->getGateway() << "\n";
				stream << "    right=" + GlobalConfig->TmpGatewayIP << "\n";

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



			}
			if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
				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." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh" );
			stream.setDevice ( &file );
			if ( file.open ( IO_WriteOnly ) )
			{
				stream <<  "#!"<< GlobalConfig->InterpreterShell << "\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";
				if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
					stream << "#  L2TP" << "\n";
					stream << GlobalConfig->pathToIptables << " -I OUTPUT -p udp --sport 1701 -o " << tmpInterface2 << " -s " << LocalIP << " -j ACCEPT" << "\n";
					stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				}

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

			QFile file1 ( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh" );
			QTextStream stream1 ( &file1 );
			if ( file1.open ( IO_WriteOnly ) )
			{
				stream1 <<  "#!"<< GlobalConfig->InterpreterShell << "\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";
				if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
					stream1 << "#  L2TP" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p udp --sport 1701 -o " << tmpInterface2 << " -s " << LocalIP << " -j ACCEPT" << "\n";
					stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
				}
			}
			file1.close();

			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();
			}

			setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);
			
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Setting DNS_UPDATE \"%1\"." ).arg ( getenv("DNS_UPDATE") ), GlobalConfig->debug );

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


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

			if ( useL2tpAfterFirstConnection )
				prepareL2tpd();

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

			connect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStderr_ipsec() ) );
			connect ( ConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsec() ) );
			if ( ! IpsecType.contains ( "free" ) )
				connect ( ConnectProcess, SIGNAL ( processExited () ), this, SLOT ( doTailIpsecLog() ) );

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

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
					ConnectingProcess = VpnAccountData::freeswan;
				else
					ConnectingProcess = VpnAccountData::l2tpd_freeswan;
				GlobalConfig->status = GlobalConfig->connecting;
				mw->buttonDisconnect->setEnabled ( true );
				this->DisconnectAction->setEnabled ( true );
				mw->buttonConnect->setEnabled ( false );
				this->ConnectAction->setEnabled ( false );
				stopContinue = false;
				// 				ipsecStarted();
			}
		}
		}
		else
		{
			setGuiStatus ( disconnected );
		}
	} // freeswan

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

		// looking for pppd
		if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "pppd" )->found == false )
		{
			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->KvpncDebugLevel > 0 )
			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: new 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 (%1)" ).arg ( i18n ( "new style" ) ) ), 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 (%1)" ).arg ( i18n ( "old style" ) ) ), 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;
			}
		}

		//unrecognized option 'replacedefaultroute'
		// test defaultroute support of pppd

		// first: new style
		testPppdReplacedefaultroute = false;
		TestPppdProcess = new QProcess ( this );
		TestPppdProcess->addArgument ( GlobalConfig->pathToPppd );
		TestPppdProcess->addArgument ( "replacedefaultroute" );


		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 support of replacedefaultroute 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 ( pppdHasReplacedefaultrouteSupport )
			{
				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( i18n ( "Test support of replacedefaultroute pppd: %1" ).arg ( i18n ( "succeded" ) ) , KVpncConfig::debug );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( i18n ( "Test support of replacedefaultroute pppd: %1" ).arg ( i18n ( "failed" ) ) , KVpncConfig::debug );
			}
		}

		//unrecognized option 'require-mppe-128'
		// test require-mppe-128 support of pppd

		testPppdRequireMppe128 = false;
		TestPppdProcess = new QProcess ( this );
		TestPppdProcess->addArgument ( GlobalConfig->pathToPppd );
		TestPppdProcess->addArgument ( "require-mppe-128" );


		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 support of replacedefaultroute 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 ( pppdHasRequireMppe128Support )
			{
				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( i18n ( "Test support of require MPPE 128 pppd: %1" ).arg ( i18n ( "succeded" ) ) , KVpncConfig::debug );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( i18n ( "Test support of require MPPE 128 pppd: %1" ).arg ( i18n ( "failed" ) ) , KVpncConfig::debug );
			}
		}


		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();

			if ( dlg.exec() )
			{
				GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
				GlobalConfig->TmpPassword = dlg.main->PasswordEdit->text();
				bool needSave=false;

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

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

				if ( dlg.main->SaveUsernameCheckBox->isChecked() )
				{
					GlobalConfig->currentProfile->setDontSaveUsername(false);
					GlobalConfig->currentProfile->setUserName ( dlg.main->UsernameEdit->text() );
					needSave=true;
				}
				else
				{
					GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
					GlobalConfig->currentProfile->setDontSaveUsername(true);
				}

				if ( dlg.main->SavePasswordCheckBox->isChecked() )
				{
					GlobalConfig->currentProfile->setSaveUserPassword ( true );
					GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
					needSave=true;
				}
				else
				{
					GlobalConfig->currentProfile->setSaveUserPassword( false );
				}
				if(needSave == true)
					saveSessionClicked();


				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 )
		{

			PppdDevice = "ppp0";
			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->debug );
				LocalIP = iface.getInterfaceIP ( iface.getDefaultInterface() );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "IP address of default interface: \"%1\"." ).arg ( LocalIP ) , GlobalConfig->debug );
			}
			else
			{
				// 				QString device = GlobalConfig->currentProfile->getNetworkDevice()
				// 				QString device = PppdDevice;
				// 				tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
				// 				LocalIP = iface.getInterfaceIP( device );
			}
			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 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";
				QString pptpdebug="";
				if (GlobalConfig->enableDebugPptpd == true)
				{
					pptpdebug=" --debug ";
				if (GlobalConfig->KvpncDebugLevel > 2)
					GlobalConfig->appendLogEntry ( i18n ( "Enabling debug for pptpd." ), GlobalConfig->debug );
				}
				stream << "pty \"" << GlobalConfig->pathToPptp << " " << pptpdebug << "--loglevel " << QString().setNum ( GlobalConfig->PptpLogLevel )  << " " << 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
				{
					if ( GlobalConfig->currentProfile->getUseGetDnsFromPeer() )
					{
						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";
					}
					else
					{
						if (pppdHasRequireMppe128Support)
						{
							stream << "# require the use of MPPE, with 128-bit encryption\n";
							stream << "require-mppe-128\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";
				}

				stream << "# we do not require the peer to authenticate itself\n";
				stream << "noauth\n";
				stream << "\n";

				if ( GlobalConfig->enableDebugPppd )
				{
					stream << "# enable debug\n";
					stream << "debug\n";
					stream << "kdebug 1\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";
					stream << "\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() && pppdHasReplacedefaultrouteSupport )
						{
							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->getUseMru() )
				{
					stream << "# userdefined MRU\n";
					stream << "mru " + QString().setNum ( GlobalConfig->currentProfile->getMru() ) + "\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";
				}

				if ( GlobalConfig->currentProfile->getDisableCcp() )
				{
					stream << "# Disable CCP (Compression Control Protocol) negotiation\n";
					stream << "noccp\n";
					stream << "\n";
				}

				if ( GlobalConfig->currentProfile->getUseVirtualIP() )
				{
					stream << "# use virtual IP addresses\n";
					stream << "# <client ip>:<server ip>\n";
					stream << GlobalConfig->currentProfile->getLocalVirtualIP() << ":" << GlobalConfig->currentProfile->getRemoteVirtualIP() << "\n";
				}


				file.close();
/*
				if (GlobalConfig->currentProfile->getAuthMethod() != "chap" && GlobalConfig->currentProfile->getAuthMethod() != "chap")
					GlobalConfig->currentProfile->setAuthMethod("chap");*/
				if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
				{

// 					GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed!" ).arg ( "pppd secrets file" ), GlobalConfig->error );
						if (GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "Authentication method: %1" ).arg ( GlobalConfig->currentProfile->getAuthMethod() ), GlobalConfig->debug );


					stream << "# use chap" << "\n";
					stream << "refuse-chap" << "\n";
					stream << "refuse-pap" << "\n";
					stream << "refuse-eap" << "\n";
					stream << "\n";

					// write pppd /etc/ppp/chap-secrets
					QString ChapSecrets = "/etc/ppp/chap-secrets"; // /etc/ppp/chap-secrets
	
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/chap-secrets" ), 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() )
							GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();
	
						QString UsernameStr;
						if ( !GlobalConfig->currentProfile->getDontSaveUsername() )
							UsernameStr = GlobalConfig->currentProfile->getUserName();
						else
							UsernameStr = GlobalConfig->TmpUsername;
	
						GlobalConfig->appendLogEntry ( i18n ( "Username: %1" ).arg ( UsernameStr ), GlobalConfig->debug );
	
						if ( GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty() )
						{
							// 						stream << GlobalConfig->currentProfile->getName() + " " << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr + " " << GlobalConfig->TmpPassword << " *\n";
							stream << "\"" << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << "\" " + GlobalConfig->currentProfile->getName() + " \"" << GlobalConfig->TmpPassword << "\" *\n";
						}
						else
						{
							// 						stream << GlobalConfig->currentProfile->getName() + " " << UsernameStr + " " << GlobalConfig->TmpPassword << " *\n";
							stream << "\"" << UsernameStr + "\" " << GlobalConfig->currentProfile->getName() + " \"" << GlobalConfig->TmpPassword << "\" *\n";
						}
						stream << "# --- generated by kvpnc. Do not edit it." << "\n";
						file.close();
	
	
						Utils ( GlobalConfig, this ).doChmod ( "/etc/ppp/chap-secrets", "go-rwx" );
					}
				}
				if (GlobalConfig->currentProfile->getAuthMethod() == "pap")
				{

// 					GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed!" ).arg ( "pppd secrets file" ), GlobalConfig->error );
						if (GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "Authentication method: %1" ).arg ( GlobalConfig->currentProfile->getAuthMethod() ), GlobalConfig->debug );

					stream << "# use pap" << "\n";
					stream << "require-pap" << "\n";
					stream << "refuse-chap" << "\n";
					stream << "\n";

					// write pppd /etc/ppp/pap-secrets
					QString papSecrets = "/etc/ppp/pap-secrets"; // /etc/ppp/pap-secrets
	
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/pap-secrets" ), GlobalConfig->debug );
					file.setName ( papSecrets );
					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() )
							GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();
	
						QString UsernameStr;
						if ( !GlobalConfig->currentProfile->getDontSaveUsername() )
							UsernameStr = GlobalConfig->currentProfile->getUserName();
						else
							UsernameStr = GlobalConfig->TmpUsername;
	
						GlobalConfig->appendLogEntry ( i18n ( "Username: %1" ).arg ( UsernameStr ), GlobalConfig->debug );
	
						if ( GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty() )
						{
							// 						stream << GlobalConfig->currentProfile->getName() + " " << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr + " " << GlobalConfig->TmpPassword << " *\n";
							stream << "\"" << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << "\" " + GlobalConfig->currentProfile->getName() + " " << GlobalConfig->TmpPassword << " *\n";
						}
						else
						{
							// 						stream << GlobalConfig->currentProfile->getName() + " " << UsernameStr + " " << GlobalConfig->TmpPassword << " *\n";
							stream << UsernameStr + " " << GlobalConfig->currentProfile->getName() + " " << GlobalConfig->TmpPassword << " *\n";
						}
						stream << "# --- generated by kvpnc. Do not edit it." << "\n";
						file.close();
	
	
						Utils ( GlobalConfig, this ).doChmod ( "/etc/ppp/pap-secrets", "go-rwx" );
					}
				}




				// 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 );
								if ( !Utils ( GlobalConfig, parent ).loadKernelModule ( "ppp_mppe", parent ) )
								{
									if ( GlobalConfig->KvpncDebugLevel > 0 )
										GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" failed, adding \"ppp_mppe_mppc\" to %2." ).arg ( "ppp_mppe" ).arg ( "/etc/modprobe.conf" ), GlobalConfig->debug );
									stream << "\n" << "# added by kvpnc, do not edit it.\n" << "alias ppp-compress-18 ppp_mppe_mppc\n";
								}
								else
								{
									if ( GlobalConfig->KvpncDebugLevel > 0 )
										GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" succeded, adding \"ppp_mppe\" to %2." ).arg ( "ppp_mppe" ).arg ( "/etc/modprobe.conf" ), GlobalConfig->debug );
									stream << "\n" << "# added by kvpnc, do not edit it.\n" << "alias ppp-compress-18 ppp_mppe\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 );
							}
						}
					}
				}

				bool load_module_ok=true;
				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();
						load_module_ok=false;
					}
					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 );
							load_module_ok=true;
					}
				}

				if (load_module_ok)
				{

					//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( GlobalConfig->InterpreterShell );
					//      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 );

					setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);
					
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Setting DNS_UPDATE \"%1\"." ).arg ( getenv("DNS_UPDATE") ), GlobalConfig->debug );

					if ( !PptpProcess->start(env) )
					{
						KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "pppd" ) );
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "pppd" ), GlobalConfig->error );
						disconnectClicked();
						setGuiStatus ( disconnected );
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "pppd" ), GlobalConfig->debug );
						ConnectingProcess = VpnAccountData::pptp;
						GlobalConfig->status = GlobalConfig->connecting;
						mw->buttonDisconnect->setEnabled ( true );
						this->DisconnectAction->setEnabled ( true );
						mw->buttonConnect->setEnabled ( false );
						this->ConnectAction->setEnabled ( false );
// 						connect ( PptpProcess, SIGNAL( processExited () ), this, SLOT( pppdStarted() ) );

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

// 						connect ( PptpProcess, SIGNAL ( processExited() ), this, SLOT ( pptpProcessExited() ) );

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

	} // pptp

	/* ============ openvpn ================ */
	else if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
	{
		//setGuiStatus(connecting);
		tmpPath = locateLocal ( "data", "kvpnc/" );
		QString OpenvpnSecrectPath = tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".secret";

		// looking for openvpn
		if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "openvpn" )->found == false )
		{
			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->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "openvpn: %1" ) .arg ( GlobalConfig->pathToOpenvpn ) , GlobalConfig->debug );

		{

			if ( GlobalConfig->currentProfile->authtype == VpnAccountData::cert )
			{

				if ( GlobalConfig->currentProfile->getUseSmartcard() )
				{
					/* use cert on smartcard */
					// 					Utils(GlobalConfig).getSmartcardInfo();
					// 					if ( GlobalConfig->pathToPkcs11Tool.isEmpty() || KStandardDirs::findExe( GlobalConfig->pathToPkcs11Tool.section( '/', -1, -1 ), GlobalConfig->pathTopathToPkcs11Tool.section( '/', 0, -2 ) ).isEmpty() )
					// 					{
					// 						KMessageBox::error( this, i18n( "Unable to find \"%1\" at \"%2\"!" ).arg( "pkcs11-tool" ).arg( GlobalConfig->pathToPkcs11Tool) );
					// 						GlobalConfig->appendLogEntry( i18n( "Unable to find \"%1\" at \"%2\"!" ).arg( "pkcs11-tool" ).arg( GlobalConfig->pathToPkcs11Tool ), GlobalConfig->error );
					// 						ok = false;
					// 						setGuiStatus( disconnected );
					// 						return ;
					// 					}

					if ( GlobalConfig->currentProfile->getPkcs11Slot().isEmpty() )
					{
						KMessageBox::error ( this, i18n ( "Pkcs11 slot cant be empty!" ) );
						GlobalConfig->appendLogEntry ( i18n ( "Pkcs11 slot cant be empty!" ), GlobalConfig->error );
						ok = false;
						setGuiStatus ( disconnected );
						return ;
					}
					if ( GlobalConfig->currentProfile->getPkcs11Id().isEmpty() )
					{
						KMessageBox::error ( this, i18n ( "Pkcs11 id cant be empty!" ) );
						GlobalConfig->appendLogEntry ( i18n ( "Pkcs11 id cant be empty!" ), GlobalConfig->error );
						ok = false;
						setGuiStatus ( disconnected );
						return ;
					}
					if ( GlobalConfig->currentProfile->getUsePkcs11Providers() && GlobalConfig->currentProfile->getPkcs11Providers().isEmpty() )
					{
						KMessageBox::error ( this, i18n ( "Pkcs11 providers cant be empty!" ) );
						GlobalConfig->appendLogEntry ( i18n ( "Pkcs11 providers cant be empty!" ), GlobalConfig->error );
						ok = false;
						setGuiStatus ( disconnected );
						return ;
					}
				}
				else
				{
					/* use cert on filesystem */
					QFile CertTmpFile;
					if ( ! GlobalConfig->currentProfile->getUseOnlyCaCertAndUserAuth() )
					{
						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 ;
						}
						else
						{
							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 ;
							}
						}
					} // only if real certificate

					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 ;
					}
				}
			}

			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 );

				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
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "Tunnel device is missing, creating has been succeded." ), GlobalConfig->debug );
					}
				}
				else
				{
					// load the module 'tun'
					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
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "Loading of module \"%1\" was successful." ).arg ( "tun" ), GlobalConfig->debug );
					}
				}
			}

			// 			GlobalConfig->TmpGatewayIP = Utils( GlobalConfig, parent ).resolveName(GlobalConfig->currentProfile->getGateway());
			// 			if (GlobalConfig->TmpGatewayIP=="0.0.0.0" || GlobalConfig->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
			// 			{
			// 					GlobalConfig->appendLogEntry( i18n( "Gateway hostname (%1) resolved to \"%2\"." ).arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->TmpGatewayIP), GlobalConfig->info );
			// 			}

			bool askUsernamePass = false;
			bool requestUsername = GlobalConfig->currentProfile->getUserName().isEmpty();
			bool requestGrouppassword = false;

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

			if ( askUsernamePass )
			{

				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();

					if ( dlg.exec() )
					{
						GlobalConfig->TmpGroupPassword = dlg.main->PSKLineEdit->text();

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

					if ( dlg.main->SavePskCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSavePsk ( true );
						GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSavePsk( false );
					}
					saveSessionClicked();

					}
					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();

					if ( dlg.exec() )
					{
						GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
						GlobalConfig->TmpPassword = dlg.main->PasswordEdit->text();


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

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

					if ( dlg.main->SaveUsernameCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setDontSaveUsername(false);
						GlobalConfig->currentProfile->setUserName ( dlg.main->UsernameEdit->text() );
					}
					else
					{
						GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
						GlobalConfig->currentProfile->setDontSaveUsername(true);
					}


					if ( dlg.main->SavePskCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSavePsk ( true );
						GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSavePsk( false );
					}

					if ( dlg.main->SavePasswordCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSaveUserPassword ( true );
						GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSaveUserPassword( false );
					}
					saveSessionClicked();

					}
					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;

				// 				QFile OpenvpnSecrectFile (OpenvpnSecrectPath);
				// 				QTextStream openvpn_secret_stream( &OpenvpnSecrectFile);
				// 				if ( OpenvpnSecrectFile.open( IO_WriteOnly ) )
				// 				{
				// 					if (GlobalConfig->TmpUsername.isEmpty())
				// 						openvpn_secret_stream << GlobalConfig->currentProfile->getUserName() << "\n";
				// 					else
				// 						openvpn_secret_stream << GlobalConfig->TmpUsername << "\n";
				// 					if (GlobalConfig->TmpPassword.isEmpty())
				// 						openvpn_secret_stream << GlobalConfig->currentProfile->getUserPassword() << "\n";
				// 					else
				// 						openvpn_secret_stream << GlobalConfig->TmpPassword<< "\n";
				// 				}

			}

			// here we go
			if ( ok )
			{
				if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
					OpenvpnDevice = "tun0";
				else
					OpenvpnDevice = "tap0";

				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->debug );
					LocalIP = iface.getInterfaceIP ( iface.getDefaultInterface() );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "IP address of default interface: \"%1\"." ).arg ( LocalIP ) , GlobalConfig->debug );
				}
				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->debug );
					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->debug );
					LocalIP = "127.0.0.1"; // no IP for default interface found :(
				}

				//if (GlobalConfig->KvpncDebugLevel > 0)
				//		{
				// 				GlobalConfig->appendLogEntry( "debug: local virtual ip: "+GlobalConfig->currentProfile->getLocalVirtualIP(),GlobalConfig->debug );
				// 				GlobalConfig->appendLogEntry( "debug: remote virtual ip: "+GlobalConfig->currentProfile->getRemoteVirtualIP(),GlobalConfig->debug );
				// }
				// 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";

					QString certPath = "/etc/openvpn";
					if ( !GlobalConfig->currentProfile->getCertPath().isEmpty() )
						certPath = GlobalConfig->currentProfile->getCertPath();

					openvpn_stream << "# change to prefix" << "\n";
					openvpn_stream << "cd " << certPath << "\n\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";

					if ( GlobalConfig->currentProfile->getDisableLzoCompression() == false )
					{
						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";

					openvpn_stream << "" << "\n";
					if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::AuthenticationType ( VpnAccountData::cert ) )
					{
						openvpn_stream << "" << "\n";
						openvpn_stream << "# ca" << "\n";
						openvpn_stream << "ca " << GlobalConfig->currentProfile->getCaCertificate() << "\n\n";
						if ( GlobalConfig->currentProfile->getUseSmartcard() )
						{
							/* use cert on smartcard */
							openvpn_stream << "# use smartcard" << "\n";
							openvpn_stream << "pkcs11-providers \"" << GlobalConfig->currentProfile->getPkcs11Providers() << "\"\n";
							openvpn_stream << "pkcs11-slot-type \"" << GlobalConfig->currentProfile->getPkcs11SlotType() << "\"\n";

							// we have to split slot id and name ("0 : foobar") => 0
							QString Pkcs11Slot = GlobalConfig->currentProfile->getPkcs11Slot().section ( ':', 0, 0 ).stripWhiteSpace();
							openvpn_stream << "pkcs11-slot \"" << Pkcs11Slot << "\"\n";

							openvpn_stream << "pkcs11-id-type \"" << GlobalConfig->currentProfile->getPkcs11IdType() << "\"\n";
							openvpn_stream << "pkcs11-id \"" << GlobalConfig->currentProfile->getPkcs11Id() << "\"\n";
							openvpn_stream << "pkcs11-sign-mode \"" << GlobalConfig->currentProfile->getPkcs11SignMode() << "\"\n";
							openvpn_stream << "\n";
						}
						else
						{
							/* use cert on filesystem */
							QFile CertTmpFile;
							if ( !GlobalConfig->currentProfile->getUseOnlyCaCertAndUserAuth() )
							{
								CertTmpFile.setName ( GlobalConfig->currentProfile->getX509Certificate() );
								if ( CertTmpFile.exists() )
								{
									openvpn_stream << "# client cert" << "\n";
									openvpn_stream << "cert " << GlobalConfig->currentProfile->getX509Certificate() << "\n\n";
									openvpn_stream << "" << "\n";

									QFile PrivateKeyTmpFile ( GlobalConfig->currentProfile->getPrivateKey() );
									// 									if ( PrivateKeyTmpFile.exists() )
									{
										openvpn_stream << "# client private key" << "\n";
										openvpn_stream << "key \"" << GlobalConfig->currentProfile->getPrivateKey() << "\"\n\n";

									}
								}
							} // if real cert
						}

						openvpn_stream << "# client side" << "\n";
						openvpn_stream << "tls-client" << "\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() )
						{
							QString direction="";
							if (GlobalConfig->currentProfile->getAuthenticationDirection() != "none")
								direction= GlobalConfig->currentProfile->getAuthenticationDirection();
							openvpn_stream << "secret " << GlobalConfig->currentProfile->getPreSharedKeyFile() << " " << direction << "\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();
							QString direction="";
							if (GlobalConfig->currentProfile->getAuthenticationDirection() != "none")
								direction= GlobalConfig->currentProfile->getAuthenticationDirection();
							openvpn_stream << "secret " << tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".secret " << direction << "\n\n";
						}
					}

					if ( GlobalConfig->currentProfile->getUseUdp() )
					{
						openvpn_stream << "\n";
						openvpn_stream << "# use udp" << "\n";
						openvpn_stream << "proto udp" << "\n\n";

						if ( GlobalConfig->currentProfile->getUseMssfix() )
						{
							openvpn_stream << "\n";
							openvpn_stream << "# userdefinied packet size" << "\n";
							openvpn_stream << "mssfix " << GlobalConfig->currentProfile->getMssfix() << "\n\n";
						}

						if ( GlobalConfig->currentProfile->getUseMtu() )
						{
							openvpn_stream << "# tunnel mtu size" << "\n";
							openvpn_stream << "tun-mtu " << GlobalConfig->currentProfile->getMtu();
						}


						if ( GlobalConfig->currentProfile->getUseFragment() )
						{
							openvpn_stream << "\n";
							openvpn_stream << "# userdefinied packet size for fragmentation" << "\n";
							openvpn_stream << "fragment " << GlobalConfig->currentProfile->getFragment() << "\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();
					// 					openvpn_stream << "remote " << GlobalConfig->TmpGatewayIP;;
					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 << "# disable ping restart\n";
					openvpn_stream << "ping-restart 0\n";
					openvpn_stream << "\n";



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

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

					//  					openvpn_stream << "# keepalive\n";
					// //  					openvpn_stream << "keepalive 10000\n";

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

					if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
					{
						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";
						QString direction="";
						if (GlobalConfig->currentProfile->getAuthenticationDirection() != "none")
							direction= GlobalConfig->currentProfile->getAuthenticationDirection();
						openvpn_stream << "tls-auth " << GlobalConfig->currentProfile->getTlsAuthFile() << " "  << direction << "\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";
						QString HttpProxyAuthType = "";

						if ( GlobalConfig->currentProfile->getUseHttpProxyAuth() )
							HttpProxyAuthType = GlobalConfig->currentProfile->getHttpProxyAuthType();
						else
							HttpProxyAuthType = "none";

						openvpn_stream << "http-proxy " << GlobalConfig->currentProfile->getHttpProxy() << " " << GlobalConfig->currentProfile->getHttpProxyPort() << " " << "auto" << " " << HttpProxyAuthType << "\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_stream << "up-restart" << "\n";
					openvpn_stream << "\n";

					openvpn_stream << "# Use management interface\n";
					openvpn_stream << "management 127.0.0.1 " << GlobalConfig->OpenvpnManagementPort << "\n";
					openvpn_stream << "management-query-passwords" << "\n";
					if ( GlobalConfig->currentProfile->getUseSmartcard() || GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
					{

						// 						GlobalConfig->appendLogEntry( "use auth with pass: ", GlobalConfig->debug );
						// 						openvpn_stream << "management-hold\n";
// 						openvpn_stream << "management-query-passwords\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";
							// 							openvpn_stream << "auth-user-pass " << OpenvpnSecrectPath << "\n\n";

							if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::AuthenticationType ( VpnAccountData::psk ) )
								openvpn_stream << "pull" << "\n\n";
						}

					}
					openvpn_stream << "auth " << GlobalConfig->currentProfile->getAuthenticationAlgorithm() << "\n";

					if ( GlobalConfig->currentProfile->getAllowIpAddressChangeOfPeer() )
						openvpn_stream << "float" << "\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 <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
					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 << "if [ -f /sbin/resolvconf ]; then\n";
					// 					    if [ -x /sbin/resolvconf ] ; then
					//         (
					//         if [ "$CISCO_DEF_DOMAIN" ] ; then
					//             echo domain "$CISCO_DEF_DOMAIN"
					//             echo search "$CISCO_DEF_DOMAIN"
					//         fi
					//         for ip in "$INTERNAL_IP4_DNS" ; do
					//             echo nameserver $ip
					//         done
					//         ) | /sbin/resolvconf -a $TUNDEV
					//         return
					//     fi
					// 					upstream << "else\n";
					upstream << "cat /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 << "# init variables" << "\n";
					upstream << "" << "\n";
					upstream << "i=1" << "\n";
					upstream << "j=1" << "\n";
					upstream << "unset fopt" << "\n";
					upstream << "unset dns" << "\n";
					upstream << "unset opt" << "\n";
					upstream << "" << "\n";
					upstream << "# Convert ENVs to an array" << "\n";
					upstream << "" << "\n";
					upstream << "while fopt=\"foreign_option_$i\"; [ -n \"${!fopt}\" ]; do" << "\n";
					upstream << "{" << "\n";
					upstream << "	opt[i-1]=${!fopt}" << "\n";
					upstream << "	case ${opt[i-1]} in" << "\n";
					upstream << "		*DOMAIN* ) domain=`echo ${opt[i-1]} | \\" << "\n";
					upstream << "				sed -e 's/dhcp-option DOMAIN //g'` ;;" << "\n";
					upstream << "		*DNS*    ) dns[j-1]=`echo ${opt[i-1]} | \\" << "\n";
					upstream << "				sed -e 's/dhcp-option DNS //g'`" << "\n";
					upstream << "			       let j++ ;;" << "\n";
					upstream << "	esac" << "\n";
					upstream << "	let i++" << "\n";
					upstream << "}" << "\n";
					upstream << "done" << "\n";
					upstream << "" << "\n";
					upstream << "# Now, do the work" << "\n";
					upstream << "" << "\n";
					upstream << "if [ -n \"${dns[*]}\" ]; then" << "\n";
					upstream << "	for i in \"${dns[@]}\"; do" << "\n";
					upstream << "		sed -i -e \"1,1 i nameserver ${i}\" /etc/resolv.conf || die" << "\n";
					upstream << "	done" << "\n";
					upstream << "fi" << "\n";
					upstream << "" << "\n";
					upstream << "if [ -n \"${domain}\" ]; then" << "\n";
					upstream << "	sed -i -e \"$j,1 i search ${domain}\" /etc/resolv.conf || die" << "\n";
					upstream << "fi" << "\n";
// 					upstream << "if [ -f " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " ]; then" << "\n";
// 					upstream << "	cat  " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " | grep nameserver >> /etc/resolv.conf" << "\n";
// 					upstream << "	cat  " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " | grep domain >> /etc/resolv.conf" << "\n";
// 					upstream << "fi" << "\n";
					upstream << "" << "\n";

					upstream << "chmod u-w  /etc/resolv.conf\n";

					upstream << "exit 0\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";
					downstream << "chmod u+w  /etc/resolv.conf\n";
					/* uses parts of http://www.smop.co.uk/node/69 */
					downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf" << "\n";
					downstream << "exit 0";
				}
				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 ( "--writepid" );
				OpenvpnProcess->addArgument ( tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".pid" );
				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 ...\n" ).arg( GlobalConfig->currentProfile->getGateway()) ,GlobalConfig->info);
				slotStatusMsg ( i18n ( "Connecting..." ), ID_CONNECTION_MSG );

				setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);
				
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Setting DNS_UPDATE \"%1\"." ).arg ( getenv("DNS_UPDATE") ), GlobalConfig->debug );

				if ( !OpenvpnProcess->start(env) )
				{
					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 );
					mw->buttonConnect->setEnabled ( false );
					this->ConnectAction->setEnabled ( false );


					bool OpenvpnVersionOk = false;
					int major = Utils ( GlobalConfig, this ).getToolInfo ( GlobalConfig, "openvpn" ) ->Version.section ( '.', 0, 0 ).toInt();
					int minor = Utils ( GlobalConfig, this ).getToolInfo ( GlobalConfig, "openvpn" ) ->Version.section ( '.', 1, 1 ).toInt();
					int subminor = Utils ( GlobalConfig, this ).getToolInfo ( GlobalConfig, "openvpn" ) ->Version.section ( '.', 2, 2 ).toInt();

					if ( major >= 2 /* && minor >= 1 */ )
						OpenvpnVersionOk = true;

					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Openvpn Version: %1.%2.%3" ).arg ( QString().setNum ( major ) ).arg ( QString().setNum ( minor ) ).arg ( QString().setNum ( subminor ) ), GlobalConfig->debug );


					// 					if (OpenvpnVersionOk && ( GlobalConfig->currentProfile->getUseSmartcard() || GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )  )
					// 					{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Starting Openvpn management handler..." ), GlobalConfig->debug );
					managementhandler = new OpenvpnManagementHandler ( this, GlobalConfig );
					connect ( managementhandler, SIGNAL ( terminate_openvpn() ), this, SLOT ( disconnectClicked() ) );
					usleep ( 500 );
					GlobalConfig->appPointer->processEvents();
					usleep ( 500 );
					GlobalConfig->appPointer->processEvents();
					managementhandler->doConnect();

					// 					int maxfailManagementHandlerConnectCheckCount=10; // 10 sec should be enough for connecting to 127.0.0.1
					// 					int failManagementHandlerConnectCheckCount=0;
					// 					while (!managementhandler->isConnectedToManagementPort() && failManagementHandlerConnectCheckCount < maxfailManagementHandlerConnectCheckCount)
					// 					{
					// 						sleep(1);
					// 						GlobalConfig->appPointer->processEvents();
					// 						failManagementHandlerConnectCheckCount++;
					// 						if (managementhandler->isConnectedToManagementPort())
					// 						{
					// 							if (! GlobalConfig->KvpncDebugLevel > 1 )
					// 								GlobalConfig->appendLogEntry( i18n( "Connect to %1 management handler was sucessful" ).arg( "openvpn" ) , GlobalConfig->debug );
					// 							break;
					// 						}
					// 						if (! GlobalConfig->KvpncDebugLevel > 1 )
					// 							GlobalConfig->appendLogEntry( i18n( "Trying to connect to %1 management handler..." ).arg( "openvpn" ) , GlobalConfig->debug );
					// 					}
					// 					// 							managementhandler->sendToServer("help");
					// 					// 					}
					// 					if (failManagementHandlerConnectCheckCount  >= maxfailManagementHandlerConnectCheckCount)
					// 					{
					// // 					KMessageBox::sorry( this, i18n( "Could not connect to %1 management handler!" ).arg( "openvpn" ) );
					// 						GlobalConfig->appendLogEntry( i18n( "Could not connect to %1 management handler!" ).arg( "openvpn" ) , GlobalConfig->error );
					// 						if (OpenvpnProcess != 0)
					// 							OpenvpnProcess->kill();
					// 						setGuiStatus(disconnected);
					// 						return;
					// 					}

					//					sleep(5);

					if ( ! GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "openvpn" ), GlobalConfig->debug );

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

	/* ============ vtun ================ */
	else if ( GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
	{
		//setGuiStatus(connecting);
		tmpPath = locateLocal ( "data", "kvpnc/" );

		// looking for vtund
		if ( Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "vtund" )->found == false )
		{
			KMessageBox::error ( this, i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "vtund" ).arg ( GlobalConfig->pathToVtund) );
			GlobalConfig->appendLogEntry ( i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "vtund" ).arg ( GlobalConfig->pathToVtund ), GlobalConfig->error );
			ok = false;
			setGuiStatus ( disconnected );
			return ;
		}

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

		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 );

			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
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Tunnel device is missing, creating has been succeded." ), GlobalConfig->debug );
				}
			}
			else
			{
				// load the module 'tun'
				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
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Loading of module \"%1\" was successful." ).arg ( "tun" ), GlobalConfig->debug );
				}
			}
		}

	// 			GlobalConfig->TmpGatewayIP = Utils( GlobalConfig, parent ).resolveName(GlobalConfig->currentProfile->getGateway());
	// 			if (GlobalConfig->TmpGatewayIP=="0.0.0.0" || GlobalConfig->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
	// 			{
	// 					GlobalConfig->appendLogEntry( i18n( "Gateway hostname (%1) resolved to \"%2\"." ).arg(GlobalConfig->currentProfile->getGateway()).arg(GlobalConfig->TmpGatewayIP), GlobalConfig->info );
	// 			}

		bool askUsernamePass = false;
		bool requestUsername = false;
		bool requestGrouppassword = false;

	// 	if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
		{
			if ( GlobalConfig->currentProfile->getUserPassword().isEmpty() )
				askUsernamePass = true;
			else
				GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();

			if ( AuthRetry )
			{
				askUsernamePass = true;
				requestUsername = false;
			}
		}

		if (askUsernamePass || requestUsername)
		{
			EnterUsernamePasswordDialog dlg ( this, i18n ( "Enter Account Data" ), requestGrouppassword, requestUsername );

		
			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();

			if ( dlg.exec() )
			{
				GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
				GlobalConfig->TmpPassword = dlg.main->PasswordEdit->text();


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

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

			if ( dlg.main->SaveUsernameCheckBox->isChecked() )
			{
				GlobalConfig->currentProfile->setDontSaveUsername(false);
				GlobalConfig->currentProfile->setUserName ( dlg.main->UsernameEdit->text() );
			}
			else
			{
				GlobalConfig->TmpUsername = dlg.main->UsernameEdit->text();
				GlobalConfig->currentProfile->setDontSaveUsername(true);
			}


			if ( dlg.main->SavePskCheckBox->isChecked() )
			{
				GlobalConfig->currentProfile->setSavePsk ( true );
				GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
			}
			else
			{
				GlobalConfig->currentProfile->setSavePsk( false );
			}

			if ( dlg.main->SavePasswordCheckBox->isChecked() )
			{
				GlobalConfig->currentProfile->setSaveUserPassword ( true );
				GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
			}
			else
			{
				GlobalConfig->currentProfile->setSaveUserPassword( false );
			}
			saveSessionClicked();

			}
			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();

				// write vtun.<profile>.conf
				QFile vtun_file ( tmpPath + "vtun." + GlobalConfig->currentProfile->getName() + ".conf" );
				QTextStream vtun_stream ( &vtun_file );
				if ( vtun_file.open ( IO_WriteOnly ) )
				{
					vtun_stream << "# generated by kvpnc. Do not edit it." << "\n";
					vtun_stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					vtun_stream << "options {" << "\n";

					if (GlobalConfig->currentProfile->getUseLocalPort() )
						vtun_stream << "        port " << GlobalConfig->currentProfile->getLocalPort() << ";" << "\n";
					else
						vtun_stream << "        port 5000;" << "\n";
					vtun_stream << "\n";
					vtun_stream << "        # path to programs" << "\n";
					vtun_stream << "        ifconfig " << GlobalConfig->pathToIfconfig << ";" << "\n";
					vtun_stream << "        route " << GlobalConfig->pathToRoute << ";" << "\n";
					vtun_stream << "        ppp " << GlobalConfig->pathToPppd << ";" << "\n";
					vtun_stream << "}" << "\n";
					vtun_stream << "" << "\n";
// 					vtun_stream << "default {" << "\n";
// 					vtun_stream << "}" << "\n";
					vtun_stream << "" << "\n";
     					vtun_stream <<  GlobalConfig->currentProfile->getVtunProfile() << " {" << "\n";
					vtun_stream << "" << "\n";
  					vtun_stream << "	# Password" << "\n";
					vtun_stream << "	passwd "<< GlobalConfig->TmpPassword << ";" << "\n";
					vtun_stream << "" << "\n";
//   					vtun_stream << "	# IP tunnel" << "\n";
// 					vtun_stream << "	type  tun;" << "\n";
// 					vtun_stream << "" << "\n";
					vtun_stream << "        up {" << "\n";
					if (GlobalConfig->currentProfile->getUseVirtualIP())
					{
						vtun_stream << "                # use virtual ip addresses" << "\n";
						vtun_stream << "                ifconfig \"%% "  << GlobalConfig->currentProfile->getLocalVirtualIP() <<  " pointopoint " << GlobalConfig->currentProfile->getRemoteVirtualIP() << "\";" << "\n";
					}
					else
					{
						vtun_stream << "                # IP address will be assigned by the server" << "\n";
						vtun_stream << "                ppp \"noauth noipdefault\";" << "\n";
					}
					//TODO implement pipe

					vtun_stream << "#               route \"add 192.168.10.200 gw 192.168.10.253\";" << "\n";
					vtun_stream << "        };" << "\n";
					vtun_stream << "" << "\n";
					vtun_stream << "        down {" << "\n";
					vtun_stream << "" << "\n";
					vtun_stream << "        };" << "\n";

					vtun_stream << "}" << "\n";

				}
				vtun_file.close();

				VtundProcess = new QProcess ( this );
// 				VtundProcess->setCommunication ( QProcess::Stdin|QProcess::Stdout|QProcess::Stderr|QProcess::DupStderr );
				VtundProcess->addArgument ( GlobalConfig->pathToVtund );
				VtundProcess->addArgument ( "-n" );
				VtundProcess->addArgument ( "-f" );
				VtundProcess->addArgument ( tmpPath + "vtun." + GlobalConfig->currentProfile->getName() + ".conf" ); // default
				VtundProcess->addArgument ( GlobalConfig->currentProfile->getVtunProfile() );
				VtundProcess->addArgument ( GlobalConfig->currentProfile->getGateway() );
				

				connect ( VtundProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_vtun() ) );
				connect( VtundProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_vtun() ) );
				connect( VtundProcess, SIGNAL( processExited() ), this, SLOT( vtun_exited() ) );

				
				GlobalConfig->appendLogEntry ( i18n( "Trying to connect to server \"%1\" with ...\n" ).arg( GlobalConfig->currentProfile->getGateway()) ,GlobalConfig->info);
				slotStatusMsg ( i18n ( "Connecting..." ), ID_CONNECTION_MSG );


				if ( !VtundProcess->start(env) )
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "vtund" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "vtund" ) , GlobalConfig->error );
					disconnectClicked();
				}
				else
				{
					ConnectingProcess = VpnAccountData::vtun;
					GlobalConfig->status = GlobalConfig->connecting;
					mw->buttonDisconnect->setEnabled ( true );
					this->DisconnectAction->setEnabled ( true );
					mw->buttonConnect->setEnabled ( false );
					this->ConnectAction->setEnabled ( false );

				}

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

void KVpnc::disconnectClicked()
{
	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( i18n ( "Disconnect requested" ), GlobalConfig->debug );

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

	if ( GlobalConfig->status == GlobalConfig->connected )
	{
		prevConnectionState = 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() )
			{
				disconnect ( ConnectionStatusCheckProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_connectionStatusCheck() ) );
				disconnect ( ConnectionStatusCheckProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_connectionStatusCheck() ) );

				ConnectionStatusCheckProcess->tryTerminate();
				QTimer::singleShot ( 5000, ConnectionStatusCheckProcess, SLOT ( kill() ) );

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

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

			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 );
				QString Vpnc_pid = "";
				if ( pidFile.open ( IO_ReadOnly ) )
				{
					Vpnc_pid = QString(pidFile.readAll()).stripWhiteSpace();
				}


				if ( ConnectProcess != 0 )
				{
					if ( ConnectProcess->isRunning() )
					{
						disconnect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readOutputFrom_vpnc() ) );
						disconnect ( ConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readOutputFrom_vpnc() ) );
						disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );

						ConnectProcess->kill();
						sleep(1);
						if (ConnectProcess->isRunning())
							ConnectProcess->kill();
						sleep(1);
						if (ConnectProcess->isRunning())
							ConnectProcess->kill();
						sleep(1);
						if (ConnectProcess->isRunning())
							ConnectProcess->kill();
					}
				}

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

					if ( !Vpnc_pid.isEmpty() )
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "Vpnc pid file found, killing process %1" ).arg ( Vpnc_pid ) , GlobalConfig->debug );
						stream << GlobalConfig->pathToKill << " -TERM " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -TERM " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -KILL " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -KILL " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -KILL " << Vpnc_pid << " > /dev/null 2>&1\n";
						QFile(GlobalConfig->Vpnc_pid_file).remove();
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "No vpnc pid file found, using \"killall\" for killing vpnc." ), GlobalConfig->debug );
						stream << GlobalConfig->pathToKillall << " -TERM vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -TERM vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -KILL vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -KILL vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -KILL vpnc" << " > /dev/null 2>&1\n";
					}

					if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "Restoring default route before connection..." ), GlobalConfig->debug );

						QString OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
						stream << GlobalConfig->pathToIp + " route del default > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToIp + " route add $(cat \"" + OldDefaultroute + "\")\n";
						// 						stream << GlobalConfig->pathToIp + " route add $(cat \"/var/run/vpnc/defaultroute\")\n";
					}
					//					stream << GlobalConfig->pathToIp+" route del $(cat \"" + VpncGateway + "\")\n";

					// fix broken vpnc: remove route of vpngatewayAddNetworkRouteDialog
					stream << GlobalConfig->pathToRoute << " del " + GlobalConfig->TmpGatewayIP << "\n";

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


// 					if (!restoreResolvConf())
// 					GlobalConfig->appendLogEntry(i18n("Restore of %1 has been failed!").arg(""),GlobalConfig->error);

					stream << GlobalConfig->pathToIp + " route flush cache\n";

					file.close();

					DisconnectProcess = new QProcess ();
					DisconnectProcess->addArgument ( GlobalConfig->InterpreterShell );
					DisconnectProcess->addArgument ( VpncDisconnectScript );
	
					connect ( DisconnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_disconnect() ) );
					connect ( DisconnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_disconnect() ) );
	
					if ( !DisconnectProcess->start(env) )
					{
						KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "vpnc_disconnect" ) );
					}

				}	

				setGuiStatus ( disconnected );
				durationTimer.stop();
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				connectionEnded();
			}

			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
			{
				tmpPath = locateLocal ( "data", "kvpnc/" );
				QString CiscoVpncDisconnectScript = tmpPath + "vpnclient-disconnect." + GlobalConfig->currentProfile->getID() + ".sh";
				// write vpnc connect script

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

// 					if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
// 					{
// 						if ( GlobalConfig->KvpncDebugLevel > 2 )
// 							GlobalConfig->appendLogEntry ( i18n ( "Restoring default route before connection..." ), GlobalConfig->debug );
// 
// 						QString OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
// 						stream << GlobalConfig->pathToIp + " route del default > /dev/null 2>&1\n";
// 						stream << GlobalConfig->pathToIp + " route add $(cat \"" + OldDefaultroute + "\")\n";
// 						// 						stream << GlobalConfig->pathToIp + " route add $(cat \"/var/run/vpnc/defaultroute\")\n";
// 					}
// 					//					stream << GlobalConfig->pathToIp+" route del $(cat \"" + VpncGateway + "\")\n";
					stream << "chmod u+w  /etc/resolv.conf\n";
					stream << "if [ -s \"$dnsdev\" ] && [ -e /sbin/resolvconf ] ; then\n";
					stream << "	/sbin/resolvconf -d `cat $dnsdev`\n";
					stream << "else\n";
					stream << "	cat " + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " > /etc/resolv.conf\n";
					stream << "fi\n";

					stream << GlobalConfig->pathToIp + " route flush cache\n";

				}
				file.close();

				DisconnectProcess = new QProcess ();
				DisconnectProcess->addArgument ( GlobalConfig->InterpreterShell );
				DisconnectProcess->addArgument ( CiscoVpncDisconnectScript );

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

				if ( !DisconnectProcess->start(env) )
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "vpnc_disconnect" ) );
				}
				disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );


				if ( CiscoVpncProcess != 0 && CiscoVpncProcess->isRunning() )
					CiscoVpncProcess->tryTerminate();
				sleep ( 1 );
				if ( CiscoVpncProcess != 0 && CiscoVpncProcess->isRunning() )
					CiscoVpncProcess->kill();

				setGuiStatus ( disconnected );
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				connectionEnded();
			}

			// racoon
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_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;
				//        }
				//       }
				//      }
				//     }



				QFile file2 ( tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh" );
				QTextStream stream2 ( &file2 );
				if ( file2.open ( IO_WriteOnly ) )
				{
					stream2 <<  "#!"<< GlobalConfig->InterpreterShell << "\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 ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write successful." ).arg ( "setkey (remove)" ) , GlobalConfig->debug );
				}
				else
				{
					// 					KMessageBox::error( this, i18n( "\"%1\" write failed!" ).arg( "setkey (remove)" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write failed!" ).arg ( "setkey (remove)" ) , GlobalConfig->error );
				}

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
// 					if (QFile("/var/run/l2tpd.pid").exists())
// 					{
// 						if (GlobalConfig->KvpncDebugLevel > 1)
// 							GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),GlobalConfig->debug);
// 						QFile L2tpdControlFile ( "/var/run/l2tp-control" );
// 						QTextStream stream( &L2tpdControlFile );
// 						if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
// 							stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
// 							L2tpdControlFile.close();
// 						}
// 					}
// 					else
// 					{
						if ( L2tpdProcess != 0 && L2tpdProcess->isRunning() )
						{
						L2tpdProcess->kill();
						if (L2tpdProcess->isRunning())
							L2tpdProcess->tryTerminate();
						sleep(1);
						if (L2tpdProcess != 0  && L2tpdProcess->isRunning())
							L2tpdProcess->kill();
// 					}
				}

				if ( RacoonTailProcess != 0 )
				{
					// 					terminateConnection( RacoonTailProcess );
					RacoonTailProcess->kill();
				}

				if ( RacoonProcess != 0 )
				{
					// 					terminateConnection( RacoonProcess );
					RacoonProcess->kill();
				}

				removeSetkey();
				delRouteRacoon();
				removeIptablesRacoon();

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
					// remove kvpnc entries from pap-secerets
					QFile PapSecretsFile ( "/etc/ppp/pap-secrets" );
					QTextStream stream ( &PapSecretsFile );
					if ( PapSecretsFile.open ( IO_ReadOnly ) )
					{
						QString line = "";
						QString chapsecret_content = "";
						bool kvpnc_start_marker_found = false;
						bool kvpnc_end_marker_found = false;
						while ( !stream.atEnd() )
						{
							line = stream.readLine(); // line of text excluding '\n'
							if ( line == "# --- generated by kvpnc. Do not edit it." )
							{
								kvpnc_end_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
							}
							if ( line == "# +++ generated by kvpnc. Do not edit it." )
							{
								kvpnc_start_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
							}

							if ( kvpnc_start_marker_found == false )
							{
								chapsecret_content += line;
								chapsecret_content += '\n';
							}
						}
						PapSecretsFile.close();
						if ( PapSecretsFile.remove() )
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
							// 							ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
							if ( PapSecretsFile.open ( IO_WriteOnly ) )
							{
								stream.setDevice ( &PapSecretsFile );
								stream << chapsecret_content;
								PapSecretsFile.close();
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
								Utils ( GlobalConfig, this ).doChmod ( PapSecretsFile.name(), "go-rwx" );
							}
							else
							{
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( PapSecretsFile.name() ), GlobalConfig->error );
							}
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 remove failed" ).arg ( PapSecretsFile.name() ), GlobalConfig->error );
						}

					}
					else
					{
						GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!" ).arg ( PapSecretsFile.name() ), GlobalConfig->error );
					}
				}

				setGuiStatus ( disconnected );
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				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(env) )
				//      KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg("killall -3 racoon") );
				//     else {
				//      RacoonTailProcess->tryTerminate();
				//      if ( GlobalConfig->KvpncDebugLevel > 0 )
				//       GlobalConfig->appendLogEntry( i18n( "\"%1\" was successful." ).arg("killall -3 racoon"), GlobalConfig->debug );
				//     }

				}
			}
			// freeswan
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_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;

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
// 					if (QFile("/var/run/l2tpd.pid").exists())
// 					{
// 						if (GlobalConfig->KvpncDebugLevel > 1)
// 							GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),GlobalConfig->debug);
// 						QFile L2tpdControlFile ( "/var/run/l2tp-control" );
// 						QTextStream stream( &L2tpdControlFile );
// 						if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
// 							stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
// 							L2tpdControlFile.close();
// 						}
// 					}
// 					else
					{
						if ( L2tpdProcess != 0 && L2tpdProcess->isRunning() )
						{
						L2tpdProcess->kill();
						if (L2tpdProcess->isRunning())
							L2tpdProcess->tryTerminate();
						sleep(1);
						if (L2tpdProcess != 0  && L2tpdProcess->isRunning())
							L2tpdProcess->kill();
						}
					}
				}

				if ( IpsecTailProcess != 0 )
					IpsecTailProcess->kill();

				delRouteIpsec();
				removeIptablesFreeswan();

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

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

				if ( !DisconnectProcess->start(env) )
				{
					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() )
					{
						if ( originalIpsecConfFile.open ( IO_ReadOnly ) )
						{
							originalIpsecConfFileContent = QString ( originalIpsecConfFile.readAll() );
							originalIpsecConfFile.close();
						}
					}

					QFile backupOriginalIpsecConfFile ( "/etc/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( IpsecType ), GlobalConfig->debug );

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

					QFile backupOriginalIpsecSecretFile ( "/etc/ipsec.secrets" );
					stream.setDevice ( &backupOriginalIpsecSecretFile );
					if ( backupOriginalIpsecSecretFile.open ( IO_WriteOnly ) )
					{
						stream << originalIpsecSecretFileContent;
						backupOriginalIpsecSecretFile.close();
					}
					stream.unsetDevice();
				}
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
			}
			// pptp
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
			{

				disconnect ( PptpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_pptp() ) );
				disconnect ( PptpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_pptp() ) );
				OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>


				QProcess *pptpdKillProcess = new QProcess ( this );
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "No pid file, trying to terminate %1 with killall..." ).arg ( "pptp" ), GlobalConfig->debug );
				pptpdKillProcess->addArgument(GlobalConfig->pathToKillall);
				pptpdKillProcess->addArgument("-TERM");
				pptpdKillProcess->addArgument("pptp");

				if(!pptpdKillProcess->start(env))
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "killall" ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "killall" ) , GlobalConfig->debug );
				}
				sleep(2);
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "kill %1 with killall..." ).arg ( "pptp" ), GlobalConfig->debug );
				pptpdKillProcess->addArgument(GlobalConfig->pathToKillall);
				pptpdKillProcess->addArgument("-KILL");
				pptpdKillProcess->addArgument("pptp");

				if(!pptpdKillProcess->start(env))
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "killall" ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "killall" ) , GlobalConfig->debug );
				}

				while (PptpProcess != 0 && PptpProcess->isRunning())
				{
					sleep(1);
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "pppd" ) , GlobalConfig->debug );
					GlobalConfig->appPointer->processEvents();
				}

				durationTimer.stop();

				// write pppd.<profile>.down
				QFile downfile ( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down" );
				QTextStream downstream ( &downfile );
				if ( downfile.open ( IO_WriteOnly ) )
				{
					downstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
					downstream << "# generated by kvpnc. Do not edit it." << "\n";
					downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					downstream << "chmod u+w  /etc/resolv.conf\n";
					if (QFile("/sbin/resolvconf").exists() && QFile("/etc/init.d/resolvconf").exists())
					{
						downstream << "rm -f  /etc/resolv.conf\n";
						downstream << "ln -s /etc/resolvconf/run/resolv.conf  /etc/resolv.conf\n";
						downstream << "/etc/init.d/resolvconf start\n";
						downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
					}
					else
						downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
					if ( ! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute() )
					{
						downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";
					}
					
					downstream << "DEFAULT_GW=`cat "  << OldDefaultroute << " | cut -f 3 -d ' '` " << "\n";
					downstream << "DEFAULT_DEV=`cat "  << OldDefaultroute << " | cut -f 5 -d ' '` " << "\n";
					downstream << GlobalConfig->pathToIp + " route del " + GlobalConfig->currentProfile->getGateway() + "/32 via $DEFAULT_GW dev $DEFAULT_DEV" + "\n";
					
					downfile.close();

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

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

						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) finished." ).arg ( "PppdDownScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down"), GlobalConfig->debug );

						if ( ! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute() )
							if ( GlobalConfig->KvpncDebugLevel > 1 )
								GlobalConfig->appendLogEntry ( i18n ( "Default route was restored." ), GlobalConfig->debug );

						if (Utils(GlobalConfig).resolvConfAvailable())
							if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "resolvconf was started again." ), GlobalConfig->debug );
					}

				}
				else
				{
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" could not written." ).arg ( i18n("pppd down file") ) , GlobalConfig->error );

				}
				
				if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
				{
					// remove kvpnc entries from chap-secerets
					QFile ChapSecretsFile ( "/etc/ppp/chap-secrets" );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					QTextStream stream ( &ChapSecretsFile );
					if ( ChapSecretsFile.open ( IO_ReadOnly ) )
					{
						QString line = "";
						QString chapsecret_content = "";
						bool kvpnc_start_marker_found = false;
						bool kvpnc_end_marker_found = false;
						while ( !stream.atEnd() )
						{
							line = stream.readLine(); // line of text excluding '\n'
							if ( line == "# --- generated by kvpnc. Do not edit it." )
							{
								kvpnc_end_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							}
							if ( line == "# +++ generated by kvpnc. Do not edit it." )
							{
								kvpnc_start_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							}
	
							if ( kvpnc_start_marker_found == false )
							{
								chapsecret_content += line;
								chapsecret_content += '\n';
							}
						}
						ChapSecretsFile.close();
						if ( ChapSecretsFile.remove() )
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							// 							ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
							if ( ChapSecretsFile.open ( IO_WriteOnly ) )
							{
								stream.setDevice ( &ChapSecretsFile );
								stream << chapsecret_content;
								ChapSecretsFile.close();
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							}
							else
							{
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->error );
							}
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								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 );
					}
				}
				if (GlobalConfig->currentProfile->getAuthMethod() == "pap")
				{
					// remove kvpnc entries from pap-secerets
					QFile papSecretsFile ( "/etc/ppp/pap-secrets" );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					QTextStream stream ( &papSecretsFile );
					if ( papSecretsFile.open ( IO_ReadOnly ) )
					{
						QString line = "";
						QString papsecret_content = "";
						bool kvpnc_start_marker_found = false;
						bool kvpnc_end_marker_found = false;
						while ( !stream.atEnd() )
						{
							line = stream.readLine(); // line of text excluding '\n'
							if ( line == "# --- generated by kvpnc. Do not edit it." )
							{
								kvpnc_end_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							}
							if ( line == "# +++ generated by kvpnc. Do not edit it." )
							{
								kvpnc_start_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							}
	
							if ( kvpnc_start_marker_found == false )
							{
								papsecret_content += line;
								papsecret_content += '\n';
							}
						}
						papSecretsFile.close();
						if ( papSecretsFile.remove() )
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							// 							papSecretsFile.setName("/etc/ppp/pap-secrets2");
							if ( papSecretsFile.open ( IO_WriteOnly ) )
							{
								stream.setDevice ( &papSecretsFile );
								stream << papsecret_content;
								papSecretsFile.close();
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							}
							else
							{
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
							}
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 remove failed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
						}
	
					}
					else
					{
						GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
					}
				}	
				setGuiStatus ( disconnected );
				GlobalConfig->status = GlobalConfig->disconnected;
				connectCounter = 0;
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
// 				connectionEnded();

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

				// 				if (  GlobalConfig->currentProfile->getConnectionType() ==  VpnAccountData::openvpn && GlobalConfig->currentProfile->getUseSmartcard() || GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
				{
					// 					delete managementhandler;
				}

				if ( OpenvpnProcess != 0 )
				{
					managementhandler->closeConnection();
					OpenvpnProcess->tryTerminate();
					QTimer::singleShot ( 5000, OpenvpnProcess, SLOT ( kill() ) );
				}

				// 				terminateConnection( OpenvpnProcess );
				// 				DisconnectProcess = new QProcess ();
				// 				DisconnectProcess->addArgument( GlobalConfig->pathToKillall );
				// 				DisconnectProcess->addArgument( "openvpn" );
				//
				// 				connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
				// 				connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );
				//
				// 				if ( !DisconnectProcess->start(env) ) {
				// 					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "killall openvpn" ) );
				// 				}
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				connectionEnded();
				
			}
			// vtun
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
			{

				if ( VtundProcess != 0 )
				{
					VtundProcess->tryTerminate();
					QTimer::singleShot ( 5000, VtundProcess, SLOT ( kill() ) );
				}

				// 				terminateConnection( VtundProcess );
				// 				VtundProcess = new QProcess ();
				// 				VtundProcess->addArgument( GlobalConfig->pathToKillall );
				// 				VtundProcess->addArgument( "openvpn" );
				//
				// 				connect( VtundProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
				// 				connect( VtundProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );
				//
				// 				if ( !DisconnectProcess->start(env) ) {
				// 					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "killall vtund" ) );
				// 				}
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				connectionEnded();
				
			}

		}
		// 		ConnectingProcess = 0L;

		setGuiStatus ( disconnected );

		if ( GlobalConfig->currentProfile->getExecuteCmdAfterDisconnect() )
			executeCommandAfterDisconnect();

	}
	else if ( GlobalConfig->status == GlobalConfig->connecting )
	{
		prevConnectionState = 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 ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
			{
				if (ConnectProcess != 0)
				{

				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 );
				QString Vpnc_pid = "";
				if ( pidFile.open ( IO_ReadOnly ) )
				{
					Vpnc_pid = QString(pidFile.readAll()).stripWhiteSpace();
				}

// 				if ( ConnectProcess != 0 )
// 				{
// 					if ( ConnectProcess->isRunning() )
// 					{
// 						disconnect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readOutputFrom_vpnc() ) );
// 						disconnect ( ConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readOutputFrom_vpnc() ) );
// 
// 						ConnectProcess->kill();
// 						sleep(1);
// 						if (ConnectProcess->isRunning())
// 							ConnectProcess->kill();
// 						sleep(1);
// 						if (ConnectProcess->isRunning())
// 							ConnectProcess->kill();
// 						sleep(1);
// 						if (ConnectProcess->isRunning())
// 							ConnectProcess->kill();
// 
// 					}
// 				}

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

					if ( !Vpnc_pid.isEmpty() )
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "Vpnc pid file found, killing process %1" ).arg ( Vpnc_pid ) , GlobalConfig->debug );
						stream << GlobalConfig->pathToKill << " -TERM " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -TERM " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -KILL " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -KILL " << Vpnc_pid << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKill << " -KILL " << Vpnc_pid << " > /dev/null 2>&1\n";
						QFile(GlobalConfig->Vpnc_pid_file).remove();
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "No vpnc pid file found, using \"killall\" for killing vpnc." ), GlobalConfig->debug );
						stream << GlobalConfig->pathToKillall << " -TERM vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -TERM vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -KILL vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -KILL vpnc" << " > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToKillall << " -KILL vpnc" << " > /dev/null 2>&1\n";
					}

					if ( !GlobalConfig->currentProfile->getKeepDefaultRoute() )
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "Restoring default route before connection..." ), GlobalConfig->debug );

						QString OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
						stream << GlobalConfig->pathToIp + " route del default > /dev/null 2>&1\n";
						stream << GlobalConfig->pathToIp + " route add $(cat \"" + OldDefaultroute + "\")\n";
						// 						stream << GlobalConfig->pathToIp + " route add $(cat \"/var/run/vpnc/defaultroute\")\n";
					}
					//					stream << GlobalConfig->pathToIp+" route del $(cat \"" + VpncGateway + "\")\n";

					// fix broken vpnc: remove route of vpngatewayAddNetworkRouteDialog
					stream << GlobalConfig->pathToRoute << " del " + GlobalConfig->TmpGatewayIP << "\n";

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


// 					if (!restoreResolvConf())
// 					GlobalConfig->appendLogEntry(i18n("Restore of %1 has been failed!").arg(""),GlobalConfig->error);

					stream << GlobalConfig->pathToIp + " route flush cache\n";

					file.close();

					DisconnectProcess = new QProcess ();
					DisconnectProcess->addArgument ( GlobalConfig->InterpreterShell );
					DisconnectProcess->addArgument ( VpncDisconnectScript );
	
					connect ( DisconnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_disconnect() ) );
					connect ( DisconnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_disconnect() ) );
	
					if ( !DisconnectProcess->start(env) )
					{
						KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "vpnc_disconnect" ) );
					}
				}	

				disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );

				if ( ConnectProcess != 0 && ConnectProcess->isRunning() )
					ConnectProcess->tryTerminate();
				sleep ( 1 );
				if ( ConnectProcess != 0 && ConnectProcess->isRunning() )
// 					ConnectProcess->kill();

				setGuiStatus ( disconnected );
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				timer.stop();
				connectionEnded();
				}

			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
			{
				if (CiscoVpncProcess != 0)
				{
					CiscoVpncProcess->kill();
					CiscoVpncProcess->tryTerminate();
					QTimer::singleShot ( 5000, CiscoVpncProcess, SLOT ( kill() ) );
				}
			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_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;

				if ( IpsecTailProcess != 0 )
					IpsecTailProcess->kill();

				delRouteIpsec();
				removeIptablesFreeswan();

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

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

				if ( !DisconnectProcess->start(env) )
				{
					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() )
					{
						if ( originalIpsecConfFile.open ( IO_ReadOnly ) )
						{
							originalIpsecConfFileContent = QString ( originalIpsecConfFile.readAll() );
							originalIpsecConfFile.close();
						}
					}

					QFile backupOriginalIpsecConfFile ( "/etc/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( IpsecType ), GlobalConfig->debug );

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

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

				}
			}
			else if ( ConnectingProcess == VpnAccountData::racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
			{

				QFile file2 ( tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh" );
				QTextStream stream2 ( &file2 );
				if ( file2.open ( IO_WriteOnly ) )
				{
					stream2 <<  "#!"<< GlobalConfig->InterpreterShell << "\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 ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write successful." ).arg ( "setkey (remove)" ) , GlobalConfig->debug );
				}
				else
				{
					// 					KMessageBox::error( this, i18n( "\"%1\" write failed!" ).arg( "setkey (remove)" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write failed!" ).arg ( "setkey (remove)" ) , GlobalConfig->error );
				}

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
// 					if (QFile("/var/run/l2tpd.pid").exists())
// 					{
// 						if (GlobalConfig->KvpncDebugLevel > 1)
// 							GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),GlobalConfig->debug);
// 						QFile L2tpdControlFile ( "/var/run/l2tp-control" );
// 						QTextStream stream( &L2tpdControlFile );
// 						if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
// 							stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
// 							L2tpdControlFile.close();
// 						}
// 					}
// 					else
// 					{
// 						if (QFile("/var/run/l2tpd.pid").exists())
// 						{
// 							if (GlobalConfig->KvpncDebugLevel > 1)
// 								GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),GlobalConfig->debug);
// 							QFile L2tpdControlFile ( "/var/run/l2tp-control" );
// 							QTextStream stream( &L2tpdControlFile );
// 							if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
// 								stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
// 								L2tpdControlFile.close();
// 							}
// 							else
// 							{
								if ( L2tpdProcess != 0 && L2tpdProcess->isRunning() )
								{
									L2tpdProcess->kill();
									if (L2tpdProcess->isRunning())
										L2tpdProcess->tryTerminate();
									sleep(1);
									if (L2tpdProcess != 0  && L2tpdProcess->isRunning())
										L2tpdProcess->kill();
								}
// 							}
// 						}
// 					}
				}

				if ( RacoonTailProcess != 0 )
				{
					// 					terminateConnection( RacoonTailProcess );
					RacoonTailProcess->kill();
				}

				if ( RacoonProcess != 0 )
				{
					// 					terminateConnection( RacoonProcess );
					RacoonProcess->kill();
				}

				removeSetkey();
				delRouteRacoon();
				removeIptablesRacoon();

				// remove kvpnc entries from pap-secerets
				QFile PapSecretsFile ( "/etc/ppp/pap-secrets" );
				QTextStream stream ( &PapSecretsFile );
				if ( PapSecretsFile.open ( IO_ReadOnly ) )
				{
					QString line = "";
					QString chapsecret_content = "";
					bool kvpnc_start_marker_found = false;
					bool kvpnc_end_marker_found = false;
					while ( !stream.atEnd() )
					{
						line = stream.readLine(); // line of text excluding '\n'
						if ( line == "# --- generated by kvpnc. Do not edit it." )
						{
							kvpnc_end_marker_found = true;
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
						}
						if ( line == "# +++ generated by kvpnc. Do not edit it." )
						{
							kvpnc_start_marker_found = true;
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
						}

						if ( kvpnc_start_marker_found == false )
						{
							chapsecret_content += line;
							chapsecret_content += '\n';
						}
					}
					PapSecretsFile.close();
					if ( PapSecretsFile.remove() )
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
						// 							ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
						if ( PapSecretsFile.open ( IO_WriteOnly ) )
						{
							stream.setDevice ( &PapSecretsFile );
							stream << chapsecret_content;
							PapSecretsFile.close();
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( PapSecretsFile.name() ), GlobalConfig->debug );
							Utils ( GlobalConfig, this ).doChmod ( PapSecretsFile.name(), "go-rwx" );
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( PapSecretsFile.name() ), GlobalConfig->error );
						}
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "File %1 remove failed" ).arg ( PapSecretsFile.name() ), GlobalConfig->error );
					}
				}
				else
				{
					GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!" ).arg ( PapSecretsFile.name() ), GlobalConfig->error );
				}

				if ( RacoonTailProcess != 0 )
				{
					// 					terminateConnection( RacoonTailProcess );
					RacoonTailProcess->kill();
				}

				if ( RacoonProcess != 0 )
				{
					// 					terminateConnection( RacoonProcess );
					RacoonProcess->kill();
				}

				removeSetkey();
				delRouteRacoon();
				removeIptablesRacoon();

			}
			else if ( ConnectingProcess == VpnAccountData::pptp )
			{
				disconnect ( PptpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_pptp() ) );
				disconnect ( PptpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_pptp() ) );

				QProcess *pptpdKillProcess = new QProcess ( this );
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "No pid file, trying to terminate %1 with killall..." ).arg ( "pptp" ), GlobalConfig->debug );
				pptpdKillProcess->addArgument(GlobalConfig->pathToKillall);
				pptpdKillProcess->addArgument("-TERM");
				pptpdKillProcess->addArgument("pptp");
				
				if(!pptpdKillProcess->start(env))
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "killall" ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "killall" ) , GlobalConfig->debug );
				}
				sleep(2);
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "kill %1 with killall..." ).arg ( "pptp" ), GlobalConfig->debug );
				pptpdKillProcess->addArgument(GlobalConfig->pathToKillall);
				pptpdKillProcess->addArgument("-KILL");
				pptpdKillProcess->addArgument("pptp");
				
				if(!pptpdKillProcess->start(env))
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "killall" ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "killall" ) , GlobalConfig->debug );
				}

				while (PptpProcess != 0 && PptpProcess->isRunning())
				{
					sleep(1);
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "pppd" ) , GlobalConfig->debug );
					GlobalConfig->appPointer->processEvents();
				}

				// write pppd.<profile>.down
				QFile downfile ( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down" );
				QTextStream downstream ( &downfile );
				if ( downfile.open ( IO_WriteOnly ) )
				{
					downstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
					downstream << "# generated by kvpnc. Do not edit it." << "\n";
					downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					downstream << "chmod u+w  /etc/resolv.conf\n";
					if (QFile("/sbin/resolvconf").exists() && QFile("/etc/init.d/resolvconf").exists())
					{
						downstream << "rm -f  /etc/resolv.conf\n";
						downstream << "ln -s /etc/resolvconf/run/resolv.conf  /etc/resolv.conf\n";
						downstream << "/etc/init.d/resolvconf start\n";
						downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
					}
					else
						downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
					if ( ! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute() )
					{
						downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";
					}
					if ( ! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute() )
					{
						downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";
					}

				}
				downfile.close();

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

				if ( !pppdDownProcess->start(env) )
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "PppdDownScript" ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "PppdDownScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down") , GlobalConfig->debug );
					while ( pppdDownProcess->isRunning() )
						parent->QApplication::processEvents();

					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) finished." ).arg ( "PppdDownScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down"), GlobalConfig->debug );

					if ( ! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute() )
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "Default route was restored." ), GlobalConfig->debug );

					if (Utils(GlobalConfig).resolvConfAvailable())
						if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "resolvconf was started again." ), GlobalConfig->debug );
				}


				if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
				{
					// remove kvpnc entries from chap-secerets
					QFile ChapSecretsFile ( "/etc/ppp/chap-secrets" );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					QTextStream stream ( &ChapSecretsFile );
					if ( ChapSecretsFile.open ( IO_ReadOnly ) )
					{
						QString line = "";
						QString chapsecret_content = "";
						bool kvpnc_start_marker_found = false;
						bool kvpnc_end_marker_found = false;
						while ( !stream.atEnd() )
						{
							line = stream.readLine(); // line of text excluding '\n'
							if ( line == "# --- generated by kvpnc. Do not edit it." )
							{
								kvpnc_end_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							}
							if ( line == "# +++ generated by kvpnc. Do not edit it." )
							{
								kvpnc_start_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							}
	
							if ( kvpnc_start_marker_found == false )
							{
								chapsecret_content += line;
								chapsecret_content += '\n';
							}
						}
						ChapSecretsFile.close();
						if ( ChapSecretsFile.remove() )
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							// 							ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
							if ( ChapSecretsFile.open ( IO_WriteOnly ) )
							{
								stream.setDevice ( &ChapSecretsFile );
								stream << chapsecret_content;
								ChapSecretsFile.close();
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
							}
							else
							{
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->error );
							}
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								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 );
					}
				}
				if (GlobalConfig->currentProfile->getAuthMethod() == "pap")
				{
					// remove kvpnc entries from pap-secerets
					QFile papSecretsFile ( "/etc/ppp/pap-secrets" );
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					QTextStream stream ( &papSecretsFile );
					if ( papSecretsFile.open ( IO_ReadOnly ) )
					{
						QString line = "";
						QString papsecret_content = "";
						bool kvpnc_start_marker_found = false;
						bool kvpnc_end_marker_found = false;
						while ( !stream.atEnd() )
						{
							line = stream.readLine(); // line of text excluding '\n'
							if ( line == "# --- generated by kvpnc. Do not edit it." )
							{
								kvpnc_end_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							}
							if ( line == "# +++ generated by kvpnc. Do not edit it." )
							{
								kvpnc_start_marker_found = true;
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							}
	
							if ( kvpnc_start_marker_found == false )
							{
								papsecret_content += line;
								papsecret_content += '\n';
							}
						}
						papSecretsFile.close();
						if ( papSecretsFile.remove() )
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							// 							papSecretsFile.setName("/etc/ppp/pap-secrets2");
							if ( papSecretsFile.open ( IO_WriteOnly ) )
							{
								stream.setDevice ( &papSecretsFile );
								stream << papsecret_content;
								papSecretsFile.close();
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
							}
							else
							{
								if ( GlobalConfig->KvpncDebugLevel > 2 )
									GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
							}
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 remove failed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
						}
	
					}
					else
					{
						GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
					}
				}	
				setGuiStatus ( disconnected );
				GlobalConfig->status = GlobalConfig->disconnected;
				connectCounter = 0;
				connectionEnded();
			}
			else if ( ConnectingProcess == VpnAccountData::openvpn )
			{
				// 				if (  GlobalConfig->currentProfile->getConnectionType() ==  VpnAccountData::openvpn && GlobalConfig->currentProfile->getUseSmartcard() || GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
				{
					// 					delete managementhandler;
				}
				if ( OpenvpnProcess != 0 )
				{
// 					managementhandler->closeConnection();
					OpenvpnProcess->tryTerminate();
					QTimer::singleShot ( 5000, OpenvpnProcess, SLOT ( kill() ) );
				}

				// 				DisconnectProcess = new QProcess ();
				// 				DisconnectProcess->addArgument( GlobalConfig->pathToKillall );
				// 				DisconnectProcess->addArgument( "openvpn" );
				//
				// 				connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
				// 				connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );
				//
				// 				if ( !DisconnectProcess->start(env) ) {
				// 					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "killall openvpn" ) );
				// 				}
				connectionEnded();
				
			}
			else if ( ConnectingProcess == VpnAccountData::vtun )
			{

				if ( VtundProcess != 0 )
				{
					VtundProcess->tryTerminate();
					QTimer::singleShot ( 5000, VtundProcess, SLOT ( kill() ) );
				}

				// 				terminateConnection( VtundProcess );
				// 				VtundProcess = new QProcess ();
				// 				VtundProcess->addArgument( GlobalConfig->pathToKillall );
				// 				VtundProcess->addArgument( "openvpn" );
				//
				// 				connect( VtundProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
				// 				connect( VtundProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );
				//
				// 				if ( !DisconnectProcess->start(env) ) {
				// 					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "killall vtund" ) );
				// 				}
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				connectionEnded();
				
			}

		
		
		//connectionEnded();
		setGuiStatus ( disconnected );
		ConnectingProcess = -1;
	}
	else
	{
		prevConnectionState = disconnected;
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "Not connected.\n" ), GlobalConfig->debug );
		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 */
	// 	QString iface = "eth2";
	// 	if ( Utils(GlobalConfig,this).isValidNetworkDevice(iface) )
	// 		std::cout << iface <<" is a valid network interface" << "\n";
	// 	else
	// 		std::cout << iface << " is not valid network interface" << "\n";
	//
	// QString iface2 = "eth3";
	// 	if ( Utils(GlobalConfig,this).isValidNetworkDevice(iface2) )
	// 		std::cout << iface2 <<" is a valid network interface" << "\n";
	// 	else
	// 		std::cout << iface2 << " is not valid network interface" << "\n";
	/*
		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();
		QString netliststring="";
		for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
			QString aa = QString( *it );
			netliststring+=" ";
			netliststring+=aa;
		}

		mw->DebugOutput->append( "All network interfaces:"+netliststring );

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

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

		QString interfaceip = "Interface IP of eth1:2: " + iface.getInterfaceIP( "eth1:2" );
		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 eth1:1: " + iface.getGatewayOfInterface("eth1:1");
		mw->DebugOutput->append( gatewayofinterface );

		mw->DebugOutput->append( "www.sun.de => "+Utils(GlobalConfig).resolveName("www.sun.de") );
	*/
	/*
	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;

	// 	bool ret = Utils(GlobalConfig).getNeedsPassphrase("/etc/ipsec.d/private/crissi.pem");
	//
	// 	if (ret)
	// 		mw->DebugOutput->append("private key needs a passprase ");
	// 	else
	// 		mw->DebugOutput->append("private key dont need a passprase ");

	/*
	QString testfilename="sfsd/::::( *#v v###\\";
	QString cleanedUpName = Utils(this->GlobalConfig).removeSpecialCharsForFilename( testfilename);
	cQString("testfilename: \"%1\", cleaned up: \"%2\"").arg(testfilename).arg(cleanedUpName));
	*/

// 	GlobalConfig->exportKvpncConfig("./kvpnc_export.xml");
// 	importIpsecProfileClicked();
}

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

void KVpnc::donateClicked()
{
	QString donateurl = "http://home.gna.org/kvpnc/paypal.html";
	QString browser = QString ( KConfigGroup ( KGlobal::config(), "General" ).readEntry ( "BrowserApplication" ) ).remove ( "!", "" );

	if ( browser.isEmpty() )
		browser = "konqueror";

	// 	KRun * run = new KRun( KURL( bugreporturl ),0,false,true );
	// 	if ( run )
	// 		;

	DonateProcess = new QProcess ( this );
	DonateProcess->addArgument ( browser );
	DonateProcess->addArgument ( donateurl );

	// 			connect( DonateProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_bugreport() ) );
	// 			connect( DonateProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_bugreport() ) );

	if ( !DonateProcess->start(env) )
	{
		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( i18n ( "donate" ) ), GlobalConfig->error );
		KMessageBox::error ( this, i18n ( "\"%1\" with %2 start failed!" ).arg ( i18n ( "donate" ) ).arg ( browser ) );
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( i18n ( "donate" ) ), GlobalConfig->debug );
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "URL \"%1\" with browser  \"%2\" called." ).arg ( donateurl ).arg ( browser ), GlobalConfig->debug );
	}
}

void KVpnc::reportBugClicked()
{
	QString bugreporturl = "https://gna.org/bugs/?group=kvpnc";
	QString browser = QString ( KConfigGroup ( KGlobal::config(), "General" ).readEntry ( "BrowserApplication" ) ).remove ( "!", "" );

	if ( browser.isEmpty() )
		browser = "konqueror";

	// 	KRun * run = new KRun( KURL( bugreporturl ),0,false,true );
	// 	if ( run )
	// 		;

	BugReportProcess = new QProcess ( this );
	BugReportProcess->addArgument ( browser );
	BugReportProcess->addArgument ( bugreporturl );

	// 			connect( BugReportProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_bugreport() ) );
	// 			connect( BugReportProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_bugreport() ) );

	if ( !BugReportProcess->start(env) )
	{
		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( i18n ( "bugreport" ) ), GlobalConfig->error );
		KMessageBox::error ( this, i18n ( "\"%1\" with %2 start failed!" ).arg ( i18n ( "bugreport" ) ).arg ( browser ) );
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( i18n ( "bugreport" ) ), GlobalConfig->debug );

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "URL \"%1\" with browser  \"%2\" called." ).arg ( bugreporturl ).arg ( browser ), GlobalConfig->debug );
	}

}

void KVpnc::readOutputFrom_vpnc()
{


	//mw->DebugOutput->append( "readOutputFrom_vpnc!\n" );
	while ( ConnectProcess->canReadLineStdout() )
	{
		ProcessMsg_connect = ConnectProcess->readLineStdout();
		// 	ProcessMsg_connect = QString( ConnectProcess->readStdout() );


		if ( deviceaddrstr2addr )
		{
			deviceaddrstr = ProcessMsg_connect;

			// 			if (GlobalConfig->KvpncDebugLevel > 0)
			//    this->GlobalConfig->appendLogEntry ( QString ( "deviceaddrstr: " + deviceaddrstr ),GlobalConfig->debug);
			deviceaddr = "addr: " + QString ( deviceaddrstr.simplifyWhiteSpace ().section ( ' ', 1, 1 ) ).section ( ':', 1, 1 );
			// 			if (GlobalConfig->KvpncDebugLevel > 0)
			//    this->GlobalConfig->appendLogEntry ( deviceaddr,GlobalConfig->debug); //
			deviceaddrstr2addr = false;
			//disconnect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readOutputFrom_vpnc() ) );
			//disconnect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readOutputFrom_vpnc() ) );
		}

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



			QString GrpPassStr = "";
			GrpPassStr = GlobalConfig->TmpGroupPassword;


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

		}

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

			QString UserPassStr = GlobalConfig->TmpPassword;
			ConnectProcess->writeToStdin ( UserPassStr );
			ConnectProcess->writeToStdin ( "\n" );

		}


		//"Enter Username and Password"

		// 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 = GlobalConfig->TmpGatewayIP;
			ConnectProcess->writeToStdin ( GatewayStr );
			ConnectProcess->writeToStdin ( "\n" );
		}

		// requesting IPSec ID
		//Enter IPSec ID for
		if ( ProcessMsg_connect.find ( "Enter IPSec ID", 0, FALSE ) > -1 || ProcessMsg_connect.find ( "Enter IPSec ID for", 0, FALSE ) > -1  )
		{
			if ( GlobalConfig->KvpncDebugLevel > 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 for", 0, FALSE ) > -1 )&& !ProcessMsg_connect.find ( "Enter Username and Password", 0, FALSE ) > -1  )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[vpnc] " + i18n ( "Username requested, send it...\n" ), GlobalConfig->debug );

			QString UsernameStr;
			UsernameStr = GlobalConfig->TmpUsername;

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

		// using interface tun0
		if ( ProcessMsg_connect.find ( "using interface", 0, FALSE ) > -1 )
		{
			VpncDevice = ProcessMsg_connect.section ( ' ', 2, 2 ); // using interface tun0 -> tun0
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( VpncDevice ), GlobalConfig->debug );
		}

		//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 );
				TunnelInterfaceIP = ProcessMsg_connect.section (' ',2,2);

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel IP: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
		}

		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 ( ProcessMsg_connect.find ( "tun0", 0, FALSE ) > -1 )
			GlobalConfig->appendLogEntry ( i18n ( "line: %1\n" ).arg ( ProcessMsg_connect ), GlobalConfig->debug );


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

			sec = hour = min = 0;

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

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

			setFirewallAfterConnect();
			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 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			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;
			connectClicked();
		}

// 		quick mode response rejected: (ISAKMP_N_INVALID_PAYLOAD_TYPE)(1)
		if ( ProcessMsg_connect.find ( "quick mode response rejected:", 0, FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			KMessageBox::error ( this, i18n ( "Connection rejected because wrong settings sent to the VPN server. Please check your settings." ) ) ;
			GlobalConfig->appendLogEntry ( i18n ( "Connection rejected because wrong settings sent to the VPN server. Please check your settings." )  , GlobalConfig->error );
			abort = true;
			AuthRetry = false;
			disconnect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readOutputFrom_vpnc() ) );
			timer.stop();
			connectClicked();
		}

		if ( ProcessMsg_connect.find ( "authentication unsuccessful", 0, FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			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 ( readOutputFrom_vpnc() ) );
			timer.stop();
			connectClicked();
		}

		// no ip for gateway
		if ( ProcessMsg_connect.find ( "vpnc: unknown host `<Replace with your gateway IP address>' ", 0, FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			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 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			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 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			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 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			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 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			KMessageBox::error ( this, i18n ( "Socket creation failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Socket creation failed" ) , GlobalConfig->error );
			abort = true;
		}

		if ( ProcessMsg_connect.find ( "receiving packet: Connection refused", 0, FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			KMessageBox::error ( this, i18n ( "Connection to the Cisco server was refused" ) );
			GlobalConfig->appendLogEntry ( i18n ( "receiving packet: Connection refused" ) , GlobalConfig->error );
			abort = true;
		}

		// binding to port failed
		if ( ProcessMsg_connect.find ( "binding to port", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "Address already in use", 0 , FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			// 		if ( GlobalConfig->KvpncDebugLevel > 0 )
			// 			GlobalConfig->appendLogEntry( i18n( "Binding to port failed. Another vpnc is running, terminate it and try reconnect ." ), GlobalConfig->debug );
			GlobalConfig->appendLogEntry ( QString ( "binding" + ProcessMsg_connect ), 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->KvpncDebugLevel > 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 <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
			// 				stream << "# generated by kvpnc. Do not edit it." << "\n";
			// 				stream << "\n";
			// 				if (!GlobalConfig->currentProfile->getKeepDefaultRoute())
			// 				{
			// 					stream << GlobalConfig->pathToIp+" route del default > /dev/null 2>&1\n";
			// 					stream << GlobalConfig->pathToIp+" route add $(cat \"" + OldDefaultroute + "\")\n";
			// 				}
			// 				//stream << GlobalConfig->pathToIp+" route del $(cat \"" + VpncGateway + "\")\n";
			//					stream << "chmod u+w  /etc/resolv.conf\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 << GlobalConfig->pathToIp+" route flush cache\n";
			// 			}
			// 			file.close();
			//
			// 			DisconnectProcess = new QProcess ();
			// 			DisconnectProcess->addArgument( GlobalConfig->InterpreterShell );
			// 			DisconnectProcess->addArgument( VpncDisconnectScript );
			//
			// 			connect( DisconnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
			// 			connect( DisconnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );
			//
			// 			if ( !DisconnectProcess->start(env) )
			// 			{
			// 				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();

			QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( 500 );
			GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
			int pid = -1;
			QString Name = "";
			if ( !NameAndPid.isEmpty() )
			{
				pid = NameAndPid.section ( '/', 0, 0 ).toInt();
				Name = NameAndPid.section ( '/', 1, 1 );
				KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( 500 ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
			}
			else
				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
			abort = true;
		}

		// binding to port 500: Address already in use
		// 	if ( ProcessMsg_connect.find( "Address already in use", 0 , FALSE ) > -1 )
		// 	{

		//int PortToListen = ProcessMsg_connect.section(' ',3,3).section(':',0,0).toInt(); // binding to port 500: Address already in use -> 500

		// netstat -npltu  | grep ':500'
		// tcp        0      0 0.0.0.0:500              0.0.0.0:*               LISTEN     4272/racoon
		// 4272 is pid


		// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
		// 				GlobalConfig->appendLogEntry( i18n( "Binding to port failed. Another program is running at this port, 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->KvpncDebugLevel > 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();
		// 			}

		// 		KMessageBox::error( this, i18n( "Address already in use" ) );
		// 		GlobalConfig->appendLogEntry(i18n( "Address already in use" ) ,GlobalConfig->error);
		// 		abort = true;
		// 	}


		if ( ProcessMsg_connect.find ( "Network is unreachable", 0 , FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			KMessageBox::error ( this, i18n ( "No network reachable" ) );
			GlobalConfig->appendLogEntry ( i18n ( "No network reachable" ) , GlobalConfig->error );
			terminateConnection ( ConnectProcess );
		}


		if ( ProcessMsg_connect.find ( "response was invalid",0 , FALSE) > -1 &&  ProcessMsg_connect.find ( "ISAKMP_N_INVALID_EXCHANGE_TYPE", 0, FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			KMessageBox::error ( this, i18n ( "Invalid ISAKMP exchange type received" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Invalid ISAKMP exchange type received" ) , GlobalConfig->error );
			abort = true;
			doContinue = false;
		}

		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 );
			}
			timer.stop();
			disconnectClicked();
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[vpnc] " + i18n ( "Trying again...\n" ), GlobalConfig->debug );
			connectClicked();
		}

		if ( ProcessMsg_connect.find ( "Passcode for VPN", 0, FALSE ) > -1 )
		{
			if ( GlobalConfig->currentProfile->getUseXauthInteractive() )
			{
				GlobalConfig->TmpXauthInterPasscode = "";
				EnterXauthInteractivePasscodeDialog dlg ( this, i18n ( "Enter Xauth interactive passcode" ) );
				dlg.main->SavePasswordCheckBox->hide();
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( "[vpnc] " + i18n ( "Passcode for Xauth interactive requested...\n" ), GlobalConfig->debug );
				dlg.exec();
				if ( !dlg.main->PasswordEdit->text().isEmpty() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( "[vpnc] " + i18n ( "Got passcode for Xauth interactive from enter Xauth interactive passcode dialog...\n" ), GlobalConfig->debug );
					GlobalConfig->TmpXauthInterPasscode = dlg.main->PasswordEdit->text();

					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( "[vpnc] " + i18n ( "Send passcode for Xauth interactive...\n" ), GlobalConfig->debug );
					ConnectProcess->writeToStdin ( GlobalConfig->TmpXauthInterPasscode );
					ConnectProcess->writeToStdin ( "\n" );
				}
			}
		}

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

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

	}
}

void KVpnc::readOutputFrom_ciscovpnc()
{
	bool abort=false;
	bool connectSuccess = false;
	bool terminatedByClient=false;

	//mw->DebugOutput->append( "readOutputFrom_vpnc!\n" );
	QString line2 = QString( CiscoVpncProcess->readStdout() );
	QStringList lines = QStringList::split( '\n', line2 );
	for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
// 	while ( CiscoVpncProcess->canReadLineStdout() )
	{
// 		QString ProcessMsg_connect = CiscoVpncProcess->readLineStdout();
// 			QString ProcessMsg_connect = QString( CiscoVpncProcess->readStdout() );
		QString ProcessMsg_connect = *it;

		if ( GlobalConfig->KvpncDebugLevel> 3 )
			GlobalConfig->appendLogEntry ( QString("[vpnclient raw]: ")+ProcessMsg_connect , GlobalConfig->debug );


		if ( ProcessMsg_connect.find( "illegal read", 0 , FALSE ) > -1)
		{ }

		else if ( ProcessMsg_connect.find( "The profile specified could not be read.", 0 , FALSE ) > -1)
		{
			KMessageBox::error(0,i18n("Profile missing. Please contact the KVpnc author."),i18n("Profile missing"));
			GlobalConfig->appendLogEntry(i18n("Profile file missing. Please contact the KVpnc author."),GlobalConfig->error);
			abort=true;
		}

		else if ( ProcessMsg_connect.find( "Secure VPN Connection terminated locally by the Client", 0 , FALSE ) > -1)
		{
			GlobalConfig->appendLogEntry(i18n("Secure VPN connection terminated locally by the client."),GlobalConfig->error);
			terminatedByClient=true;
			KMessageBox::error(0,i18n("Secure VPN connection terminated locally by the client. Please check your settings (Certificate password, e.g.)."),i18n("Connection terminated"));
   				GlobalConfig->appendLogEntry(i18n("Secure VPN connection terminated locally by the client. Please check your settings (Certificate password, e.g.)"),GlobalConfig->error);
			abort=true;
		}

		// binding to port failed
		if ( ProcessMsg_connect.find( "bind: Address already in use", 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 );
			GlobalConfig->appendLogEntry ( QString ( "binding" + ProcessMsg_connect ), GlobalConfig->debug );

			QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( 500 );
			GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
			int pid = -1;
			QString Name = "";
			if ( !NameAndPid.isEmpty() )
			{
				pid = NameAndPid.section ( '/', 0, 0 ).toInt();
				Name = NameAndPid.section ( '/', 1, 1 );
				KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( 500 ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
			}
			else
				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
			abort = true;
		}

		if ( ProcessMsg_connect.find( "Reason: Failed to establish a VPN connection.", 0 , FALSE ) > -1)
		{
			if (terminatedByClient)
			{
				KMessageBox::error(0,i18n("Secure VPN connection terminated locally by the client. Please check your settings (Certificate password, e.g.)."),i18n("Connection terminated"));
   				GlobalConfig->appendLogEntry(i18n("Secure VPN connection terminated locally by the client. Please check your settings (Certificate password, e.g.)"),GlobalConfig->error);
			abort=true;
			}
		}

		if ( ProcessMsg_connect.find ( "The VPN sub-system is busy or has failed.", 0, FALSE ) > -1 )
		{
			abort = true;
		}

		else if ( ProcessMsg_connect.find( "Reason: Remote peer is no longer responding.", 0 , FALSE ) > -1)
		{
			KMessageBox::error(0,i18n ( "Timeout while connecting to %1." ).arg ( GlobalConfig->currentProfile->getGateway(),i18n("Connection terminated")));
   			GlobalConfig->appendLogEntry ( i18n ( "Timeout while connecting to %1." ).arg ( GlobalConfig->currentProfile->getGateway() ), GlobalConfig->error );
			abort=true;
		}

		if ( ProcessMsg_connect.find ( "Reason: A connection is already in the process of being established.", 0, FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "There is already an instance of %1 running!" ).arg ( "vpnclient" ) );
			GlobalConfig->appendLogEntry ( i18n ( "There is already an instance of %1 running!" ).arg ( "vpnclient" ) , GlobalConfig->error );
			abort = true;
		}

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

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

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

		// requesting password
		if ( ProcessMsg_connect.find ( "Password [", 0, FALSE ) > -1 )
		{

			if ( GlobalConfig->VpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[vpnclient] " + i18n ( "User password requested, send it...\n" ), GlobalConfig->debug );

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

			if ( GlobalConfig->VpncDebugLevel > 3 )
				GlobalConfig->appendLogEntry ( "[vpnclient] " + i18n ( "User password: %1\n" ).arg(UserPassStr), GlobalConfig->debug );


			CiscoVpncProcess->writeToStdin ( UserPassStr );
			CiscoVpncProcess->writeToStdin ( "\n" );
		}
		if ( ProcessMsg_connect.find ( "Authenticating user.", 0, FALSE ) > -1 )
		{
			if (GlobalConfig->AuthRetryCount > 1)
			{
			timer.stop();
			connectCounter=0;
			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			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;
			connectClicked();
			}
			else
			{
				// nothing here, its first normal try
				GlobalConfig->AuthRetryCount++;
			}
		}
		if ( ProcessMsg_connect.find ( "Save Password (Y/N)", 0, FALSE ) > -1 )
		{
			CiscoVpncProcess->writeToStdin ( "Y" );
			CiscoVpncProcess->writeToStdin ( "\n" );
		}

		if ( ProcessMsg_connect.find ( "Reason: A connection is already in the process of being established.", 0, FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Reason: A connection is already in the process of being established." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Reason: A connection is already in the process of being established." )  , GlobalConfig->error );
			abort = true;
		}

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

			QString PrivKeyPassStr = "";
			// 		if (GlobalConfig->currentProfile->getSavePsk())
			PrivKeyPassStr = GlobalConfig->currentProfile->getPrivateKeyPass();
			// 		else
			// 			PrivKeyPassStr = TmpPrivKeyPassStr;
			if (PrivKeyPassStr.isEmpty())
			{
				GlobalConfig->TmpPrivateKeyPass = "";
				QString pass="";
				EnterXauthInteractivePasscodeDialog dlg( 0, i18n( "Enter certificate password" ) );
				dlg.main->DescriptionLabel->setText( i18n( "Enter certificate password to unlock certificate:" ) );
				dlg.main->LabelPassword->setText( i18n( "Certificate password:" ) );
				dlg.main->SavePasswordCheckBox->setText( i18n( "Save certificate password" ) );
// 				dlg.resize(QSize(dlg.width()+20,dlg.height()));
				dlg.main->PasswordEdit->setFocus();
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( "[vpnclient] " + i18n( "Password for certificate requested...\n" ), GlobalConfig->debug );
				if ( dlg.exec() )
				{
	
					pass = dlg.main->PasswordEdit->text();

					if ( !pass.isEmpty() )
					{
	
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry( "[vpnclient] " + i18n( "cerificate password got from user" ), GlobalConfig->debug );

						if ( GlobalConfig->KvpncDebugLevel > 6 )
							GlobalConfig->appendLogEntry ( i18n ( "Send certificate password: %1" ).arg ( pass ), KVpncConfig::debug );
						
						if ( dlg.main->SavePasswordCheckBox->isChecked() )
						{
							GlobalConfig->currentProfile->setSavePrivateKeyPassword( true );
							GlobalConfig->currentProfile->setPrivateKeyPass( QString( pass ) );
						}
	
						GlobalConfig->TmpPrivateKeyPass = QString( pass );
	
						// 												if ( GlobalConfig->KvpncDebugLevel > 5 )
						// 				GlobalConfig->appendLogEntry( "[vpnclient]: private key password: " + GlobalConfig->TmpPrivateKeyPass, GlobalConfig->debug );
	
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry( "[vpnclient] " + i18n( "Send certificate password..." ), GlobalConfig->debug );
	
						CiscoVpncProcess->writeToStdin ( GlobalConfig->TmpPrivateKeyPass );
						CiscoVpncProcess->writeToStdin ( "\n" );
					}
					else
					{
						GlobalConfig->appendLogEntry( "[vpnclient] certificate password empty, stop.", GlobalConfig->error );
						return;
					}
				}
				else
				{
					GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because password enter dialog aborted." ), GlobalConfig->info );
					disconnectClicked();
				}
			}
			else 
			{
				if (CiscoVpncProcess != 0 && CiscoVpncProcess->isRunning() )
				{

					if ( GlobalConfig->KvpncDebugLevel > 6 )
						GlobalConfig->appendLogEntry ( i18n ( "Send certificate password: %1" ).arg ( PrivKeyPassStr ), KVpncConfig::debug );
						
					CiscoVpncProcess->writeToStdin ( PrivKeyPassStr );
					CiscoVpncProcess->writeToStdin ( "\n" );
				}
				return ;
			}
		}
		
		if ( ProcessMsg_connect.find ( "Reason: User authentication failed.", 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 ( CiscoVpncProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readOutputFrom_ciscovpnc() ) );
			timer.stop();
			connectClicked();
		}

		if ( ProcessMsg_connect.find ( "Your VPN connection is secure.", 0, FALSE ) > -1 )
			connectSuccess = true;

		if ( ProcessMsg_connect.find ( "Client address: ", 0, FALSE ) > -1 )
		{
// 			NetworkInterface iface ( GlobalConfig, parent );
// 			TunnelInterfaceIP = iface.getInterfaceIP ( CiscoVpncDevice );

			TunnelInterfaceIP = ProcessMsg_connect.section(':',1,1).stripWhiteSpace();
// 			NetworkInterface iface ( GlobalConfig, parent );
// 			TunnelInterfaceIP = iface.getInterfaceIP ( CiscoVpncDevice );
		

		}

		if (ProcessMsg_connect.find ("VPN tunnel information:",0,FALSE) > -1)
		{
// 			Client address: 192.168.201.59
		}
		if (ProcessMsg_connect.find ("Local LAN Access is disabled",0,FALSE) > -1)
		{
			GlobalConfig->appendLogEntry ( i18n ( "Local LAN access is disabled (forced by server). This means you cant access to your local LAN." ), KVpncConfig::info );
		}

		if (ProcessMsg_connect.find ("Local LAN Access is enabled",0,FALSE) > -1)
		{
// 			GlobalConfig->appendLogEntry ( i18n ( "Local LAN access is enabled." ).arg ( PrivKeyPassStr ), KVpncConfig::info );
		}

		if (ProcessMsg_connect.find ("Encryption:",0,FALSE) > -1)
		{
			QString Encryption = ProcessMsg_connect.section(':',1,1).stripWhiteSpace();
			if (GlobalConfig->KvpncDebugLevel > 2)
				GlobalConfig->appendLogEntry(i18n("Encrypion algorithm used: %1").arg(Encryption),GlobalConfig->debug);
		}

		if (ProcessMsg_connect.find ("Authentication:",0,FALSE) > -1)
		{
			QString Authentication = ProcessMsg_connect.section(':',1,1).stripWhiteSpace();
			if (GlobalConfig->KvpncDebugLevel > 2)
				GlobalConfig->appendLogEntry(i18n("Authentication algorithm used: %1").arg(Authentication),GlobalConfig->debug);
		}


		if ( connectSuccess )
		{
			GlobalConfig->appendLogEntry ( "[vpnclient] " + i18n ( "Connection established." ) , GlobalConfig->success );

			sec = hour = min = 0;

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

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

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

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

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

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

		if ( abort )
		{
			timer.stop();
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "vpnclient" ) , GlobalConfig->debug );
			terminateConnection ( CiscoVpncProcess );
			return ;
		}
/*
Contacting the gateway at
Username



VPN tunnel information.
Client address: 192.168.88.11
Server address: 194.95.17.10
Encryption: 128-bit AES
Authentication: HMAC-SHA
IP Compression: None
NAT passthrough is active on port UDP 10000
Local LAN Access is disabled

Disconnecting the VPN connection.

*/
	}
}

void KVpnc::wroteToStdin_vpncConfig()
{
	ConnectProcess ->closeStdin();
}

void KVpnc::readFromStdout_racoon()
{
	//while ( RacoonProcess->canReadLineStdout() ) {
	//  ProcessMsg_connect = RacoonProcess->readLineStdout();
	QString ProcessMsg_connect = QString ( RacoonProcess->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 );
	// 			}
	//
	//if (GlobalConfig->KvpncDebugLevel > 0)
	// 			GlobalConfig->appendLogEntry( "[ping] " + ProcessMsg_connect, GlobalConfig->debug );
	// 		}
	// 	}
	//
	// 	// normal
	// 	else {
	if ( GlobalConfig->KvpncDebugLevel > 2 )
		GlobalConfig->appendLogEntry ( "[racoon] " + ProcessMsg_connect, GlobalConfig->debug );
	// 	}
	//}
}

void KVpnc::readFromStderr_racoon()
{

	bool abort = false;
	// while ( RacoonProcess->canReadLineStderr() ) {
	//  ProcessMsg_connect = RacoonProcess->readLineStderr();
	QString ProcessMsg_connect = QString ( RacoonProcess->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 );
	}
	else if ( ProcessMsg_connect.find ( "no default route, %defaultroute cannot cope!!!", 0, FALSE ) > -1 )
	{
		KMessageBox::error ( this, i18n ( "No default route found, nesessary for %1!" ).arg ( IpsecType ) );
		GlobalConfig->appendLogEntry ( i18n ( "No default route found, nesessary for %1!" ).arg ( IpsecType ) , GlobalConfig->error );
		abort = true;
	}
	else if ( ProcessMsg_connect.find ( "SIOCADDRT: File exists", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry ( "[racoon err] " + i18n ( "setting route failed: route still exists" ), GlobalConfig->error );
	}
	else if ( ProcessMsg_connect.find ( "SIOCDELRT: File exists", 0, FALSE ) > -1 )
	{
		GlobalConfig->appendLogEntry ( "[racoon err] " + i18n ( "deleting route failed: route dont exists" ), GlobalConfig->error );
	}
	else if ( ProcessMsg_connect.find ( "fatal parse failure", 0, FALSE ) > -1 || ProcessMsg_connect.find ( "failed to parse configuration file", 0, FALSE ) > -1 || 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 ( "racoon" ) );
		GlobalConfig->appendLogEntry ( i18n ( "Error in generated configuration file for \%1\", please contact KVpnc team." ).arg ( "racoon" ) , GlobalConfig->error );
		abort = true;
	}
	else 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 ( "racoon" ) );
		GlobalConfig->appendLogEntry ( i18n ( "Could not bind to listen socket (still %1 running?)" ).arg ( "racoon" ) , GlobalConfig->error );
		abort = true;
	}
	else if ( ProcessMsg_connect.find ( "ERROR: fatal parse failure", 0 , FALSE ) > -1 )
	{
		//KMessageBox::error( this, i18n( "ERROR: fatal parse failure" ) );
		GlobalConfig->appendLogEntry ( i18n ( "[racoon err]: fatal parse failure" ) , GlobalConfig->error );
		// 		abort = true;
		abort = true;
	}

	// 	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 );
	// 			}
	// 		}
	// 	}

	if ( abort )
	{
		GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "racoon" ) , GlobalConfig->error );
		disconnectClicked();
	}

}

void KVpnc::readFromStdout_racoon_helper()
{
	//while ( ConnectProcess->canReadLineStdout() ) {
	//  ProcessMsg_connect = ConnectProcess->readLineStdout();
	QString ProcessMsg_connect = QString ( ConnectProcess->readStdout() );
	GlobalConfig->appendLogEntry ( "[racoon helper] " + ProcessMsg_connect, GlobalConfig->success );
	//}
}

void KVpnc::readFromStderr_racoon_helper()
{

	bool abort = false;
	// while ( ConnectProcess->canReadLineStderr() ) {
	//  ProcessMsg_connect = ConnectProcess->readLineStderr();
	QString ProcessMsg_connect = QString ( ConnectProcess->readStderr() );
	GlobalConfig->appendLogEntry ( "[racoon helper err] " + ProcessMsg_connect, GlobalConfig->error );

	if ( ProcessMsg_connect.find ( "libipsec: syntax error while parsing", 0, FALSE ) > -1 )
	{
		KMessageBox::error ( this, i18n ( "Error in generated configuration file for \%1\", please contact KVpnc team." ).arg ( "setkey" ) );
		GlobalConfig->appendLogEntry ( i18n ( "libipsec has found syntax error while parsing." ) , GlobalConfig->error );
		abort = true;
	}
	if ( abort )
	{
		GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "racoon" ) , GlobalConfig->error );
		disconnectClicked();
	}

}

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

		bool NormalMsg = true;
		bool ErrorMsg = false;
		bool abort = false;

		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 ( "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 );
				}
			}
		}
		else
		{
	// FATAL ERROR:
			if ( ProcessMsg_connect.find ( "failed to bind", 0, FALSE ) > -1|| ProcessMsg_connect.find ("Address already in use", 0, FALSE ) > -1)
			{
				QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( 500 );
				GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
				int pid = -1;
				QString Name = "";
				if ( !NameAndPid.isEmpty() )
				{
					pid = NameAndPid.section ( '/', 0, 0 ).toInt();
					Name = NameAndPid.section ( '/', 1, 1 );
					KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( 500 ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
				}
				else
					KMessageBox::error ( this, i18n ( "Port binding failed" ) );
				GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
				abort = true;
			}
	
			if ( ProcessMsg_connect.find ( "IPsec apparently already running", 0, FALSE ) > -1 )
			{
				NormalMsg = false;
				GlobalConfig->appendLogEntry ( i18n ( "IPsec seems to be already running" ), GlobalConfig->error );
	
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Trying to kill %1 and restart it." ).arg ( "ipsec" ), GlobalConfig->debug );
				disconnectClicked();
				setGuiStatus ( disconnected );
	
				KillProcess = new QProcess ( this );
				KillProcess->addArgument ( GlobalConfig->pathToKillall );
				KillProcess->addArgument ( "_plutorun" );
	
				// 			connect( KillProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStderr_ipsec() ) );
				// 			connect( KillProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_ipsec() ) );
	
				if ( !KillProcess->start(env) )
				{
					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();
				}
			}
			else if ( ProcessMsg_connect.find ( "no default route, %defaultroute cannot cope!!!", 0, FALSE ) > -1 )
			{
				KMessageBox::error ( this, i18n ( "No default route found, nesessary for %1!" ).arg ( IpsecType ) );
				GlobalConfig->appendLogEntry ( i18n ( "No default route found, nessesary for %1!" ).arg ( IpsecType ) , GlobalConfig->error );
				abort = true;
				ErrorMsg = true;
			}
		}

		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[ipsec] " + ProcessMsg_connect, GlobalConfig->debug );
			// 		if (GlobalConfig->KvpncDebugLevel > 0)
			// 			GlobalConfig->appendLogEntry( "out: " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[ipsec err] " + ProcessMsg_connect, GlobalConfig->error );
		}

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

void KVpnc::readFromStderr_ipsec()
{
	bool abort = false;
	while ( ConnectProcess->canReadLineStderr() )
	{
		ProcessMsg_connect = ConnectProcess->readLineStderr();
		// 	QString ProcessMsg_connect = QString( ConnectProcess->readStderr() );

		if ( ProcessMsg_connect.find ( "failed to bind", 0, FALSE ) > -1||  ProcessMsg_connect.find ("FATAL ERROR: bind() failed in find_raw_ifaces(). Errno 98: Address already in use", 0, FALSE ) > -1 )
		{
			QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( 500 );
			GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
			int pid = -1;
			QString Name = "";
			if ( !NameAndPid.isEmpty() )
			{
				pid = NameAndPid.section ( '/', 0, 0 ).toInt();
				Name = NameAndPid.section ( '/', 1, 1 );
				KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( 500 ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
			}
			else
				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "no default route, %defaultroute cannot cope!!!", 0, FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "No default route found, nesessary for %1!" ).arg ( IpsecType ) );
			GlobalConfig->appendLogEntry ( i18n ( "No default route found, nesessary for %1!" ).arg ( IpsecType ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "SIOCADDRT: File exists", 0, FALSE ) > -1 )
		{
			// 		GlobalConfig->appendLogEntry( "[ipsec err] "+i18n( "setting route failed: route still exists" ), GlobalConfig->error );
			// 		abort=true;
		}
		else if ( ProcessMsg_connect.find ( "SIOCDELRT: File exists", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[ipsec err] " + i18n ( "deleting route failed: route dont exists" ), GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "we only support version 2", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[ipsec err] " + i18n ( "only freeswan version 1.x is supported " ), GlobalConfig->error );
			abort = true;
		}

		else if ( ProcessMsg_connect.find ( "error loading RSA private key file", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[ipsec err] " + i18n ( "RSA private key file could not be loaded." ), GlobalConfig->error );
			abort = true;
		}


		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 ( "[ipsec err] " + ProcessMsg_connect, GlobalConfig->error );
		}

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

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

		// binding to port failed
		if ( ProcessMsg_connect.find ( "ERROR: failed to bind to address", 0 , FALSE ) > -1 )
		{

			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
			{
				if ( L2tpdProcess != 0 && L2tpdProcess->isRunning() )
					L2tpdProcess->kill();
			}

			QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( 500 );
			GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
			int pid = -1;
			QString Name = "";
			if ( !NameAndPid.isEmpty() )
			{
				pid = NameAndPid.section ( '/', 0, 0 ).toInt();
				Name = NameAndPid.section ( '/', 1, 1 );

				if ( Name == "racoon" )
				{
					if ( GlobalConfig->doKillRacoonIfStillRunning )
					{
						QProcess killracoonprocess ( this );
						killracoonprocess.addArgument ( GlobalConfig->pathToKillall );
						killracoonprocess.addArgument ( "racoon" );

						if ( !killracoonprocess.start() )
						{
							GlobalConfig->appendLogEntry ( i18n ( "%1 could not be killed." ).arg ( "racoon" ) , GlobalConfig->error );
							GlobalConfig->appendLogEntry ( QString ( "[racoon err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg ( "racoon" ) ) , GlobalConfig->debug );
							abort = true;
						}
						else
						{
							while ( killracoonprocess.isRunning() )
								// 								parent->processEvents();
								usleep ( 500 );

							sleep ( 2 );

							// restart racoon
							// 						if ( RacoonProcess != 0)
							// 							RacoonProcess->kill();


							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 );

							if ( !RacoonProcess->start(env) )
							{
								if ( GlobalConfig->KvpncDebugLevel > 0 )
									GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "racoon" ), GlobalConfig->error );

								GlobalConfig->appendLogEntry ( QString ( "[racoon err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg ( "racoon" ) ) , GlobalConfig->debug );
								abort = false;
							}
							else
							{
								if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
								{
									start_l2tpd();
									if ( GlobalConfig->KvpncDebugLevel > 0 )
										GlobalConfig->appendLogEntry ( i18n ( "%1 was already running. %2 and %3 are killed and restarted." ).arg ( "racoon" ).arg ( "racoon" ).arg ( "l2tpd" ), GlobalConfig->debug );
								}
								else
								{
									if ( GlobalConfig->KvpncDebugLevel > 0 )
										GlobalConfig->appendLogEntry ( i18n ( "%1 was already running. It was killed and restarted." ).arg ( "racoon" ), GlobalConfig->debug );
								}
							}
						}
					}
					else
					{
						KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( 500 ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
						GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
						abort = true;
					}
				}
				else
				{
					KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( 500 ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
					abort = true;
				}
			}
			else
			{
				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
				GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
				abort = true;
			}

		}
		else if ( ProcessMsg_connect.find ( "ERROR: couldn't find the pskey for", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "The pre shared key couldn't not found, check PSK settings." ) );
			GlobalConfig->appendLogEntry ( i18n ( "PSK is missing, aborting." ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: failed to process packet.", 0 , FALSE ) > -1 )
		{
			// 		KMessageBox::error( this, i18n( "failed to process packet" ) );
			GlobalConfig->appendLogEntry ( i18n ( "failed to process packet" ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: phase1 negotiation failed.", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Phase 1 negotiation of IPSec connection has been failed." ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: reject the packet, received unexpecting payload type 0", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "ERROR: reject the packet, received unexpecting payload type 0" ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: unknown notify message", 0 , FALSE ) > -1 )
		{
			// 			KMessageBox::error( this, i18n( "ERROR: unknown notify message, no phase2 handle found. " ) );
			GlobalConfig->appendLogEntry ( i18n ( "ERROR: unknown notify message, no phase2 handle found. " ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: phase2 negotiation failed due to time up waiting for phase1", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Phase 2 negotiation of IPSec connection has been failed. Please check encryption and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "ERROR: phase2 negotiation failed due to time up waiting for phase1" ) , GlobalConfig->error );

			abort = true;
		}

		else if ( ProcessMsg_connect.find ( "ERROR: the peer's certificate is not verified", 0 , FALSE ) > -1 )
		{
			// 			KMessageBox::error( this, i18n( "ERROR: the peer's certificate is not verified" ) );
			GlobalConfig->appendLogEntry ( i18n ( "ERROR: the peer's certificate is not verified" ) , GlobalConfig->error );

			abort = true;
		}

		else if ( ProcessMsg_connect.find ( "IPsec-SA established", 0 , FALSE ) > -1 )
		{
			racoon_tunnel_state++;
			if ( racoon_tunnel_state == 1 )
			{
				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "First tunnel is now up, waiting for second one..." ), GlobalConfig->debug );
			}
			else if ( racoon_tunnel_state == 2 )
			{

				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "Second tunnel is now up." ), GlobalConfig->debug );
				GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "Low level IPsec connection established." ), GlobalConfig->success );

				doIptablesRacoon();
				addRouteRacoon();

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
				{
					GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "Connection established." ), GlobalConfig->success );

					sec = hour = min = 0;

					GlobalConfig->status = GlobalConfig->connected;

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

					doIptablesRacoon();
					addRouteRacoon();

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

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

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

			}
		}
		else if ( GlobalConfig->KvpncDebugLevel > 2 )
		{
			if ( ProcessMsg_connect.find ( "ERROR", 0 , FALSE ) == -1 )
				GlobalConfig->appendLogEntry ( "[racoon] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		if ( ProcessMsg_connect.find ( "ERROR", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[racoon err] " + ProcessMsg_connect, GlobalConfig->error );
		}
		if ( abort )
		{
			GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "racoon" ) , GlobalConfig->error );
			disconnectClicked();
		}

	}
}

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

void KVpnc::readOutputFromTail_ipsec()
{
	// 	QString ProcessMsg_connect = QString( IpsecTailProcess->readStdout() );
	while ( IpsecTailProcess->canReadLineStdout() )
	{
		bool NormalMsg = true;
		bool ErrorMsg = false;
		QString ProcessMsg_connect = IpsecTailProcess->readLineStdout() + "\n";
		//        QString ProcessMsg_connect = IpsecTailProcess->readStdout();
		bool abort = false;

// 		// binding to port failed
// 		if ( ProcessMsg_connect.find ( "ERROR: failed to bind to address", 0 , FALSE ) > -1 )
// 		{

			// 			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_ipsec )
			// 			{
			// 				if (IpsecProcess != 0 && IpsecProcess->isRunning())
			// 					IpsecProcess->kill();
			// 			}
			//
			// 			if (GlobalConfig->doKillIpsecIfStillRunning)
			// 			{
			// 					QProcess killipsecprocess(this);
			// 					killipsecprocess.addArgument(GlobalConfig->pathToKillall);
			// 					killipsecprocess.addArgument("ipsec");
			//
			// 					if (!killipsecprocess.start())
			// 					{
			// 						GlobalConfig->appendLogEntry( i18n( "%1 could not be killed." ).arg("ipsec") ,GlobalConfig->error);
			// 						GlobalConfig->appendLogEntry ( QString( "[ipsec err] " + i18n( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg("ipsec") ) , GlobalConfig->debug );
			// 						abort = true;
			// 					}
			// 					else
			// 					{
			// 						while (killipsecprocess.isRunning())
			// 							parent->processEvents();
			//
			// 						// restart ipsec
			// // 						if ( IpsecProcess != 0)
			// // 							IpsecProcess->kill();
			//
			//
			// 						putenv( ( char* ) ( "LC_ALL=C" ) );
			// 						IpsecProcess = new QProcess ( this );
			// 						IpsecProcess->addArgument( GlobalConfig->pathToIpsec );
			// 						IpsecProcess->addArgument( "-F" ); // foreground we want :)
			// 						IpsecProcess->addArgument( "-f" );
			// 						IpsecProcess->addArgument( tmpPath + "ipsec." + GlobalConfig->currentProfile->getName() + ".conf" );
			// 						IpsecProcess->addArgument( "-l" ); // logfile (we get content with tail process)
			// 						IpsecProcess->addArgument( tmpPath + "ipsec." + GlobalConfig->currentProfile->getName() + ".log" );
			// 						if ( GlobalConfig->KvpncDebugLevel > 0 )
			// 							GlobalConfig->appendLogEntry ( "ipsec: " + GlobalConfig->pathToIpsec + " -f " + tmpPath + "/ipsec" + GlobalConfig->currentProfile->getName() + ".conf", GlobalConfig->debug );
			//
			// 						if ( !IpsecProcess->start(env) )
			// 						{
			// 							if ( GlobalConfig->KvpncDebugLevel > 0 )
			// 								GlobalConfig->appendLogEntry ( i18n( "\"%1\" start failed!" ).arg( "l2tpd" ), GlobalConfig->error );
			//
			// 							GlobalConfig->appendLogEntry ( QString( "[ipsec err] " + i18n( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg("ipsec") ) , GlobalConfig->debug );
			// 							abort=false;
			// 						}
			// 						else
			// 						{
			// 							if ( GlobalConfig->KvpncDebugLevel > 0 )
			// 								GlobalConfig->appendLogEntry ( i18n( "%1 was already running. It was killed and restarted." ).arg( "ipsec" ), GlobalConfig->debug );
			// 						}
			// 					}
			// 			}
			// 			else
// 			{
// 				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
// 				GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
// 				abort = true;
// 			}
// 		}


		if ( ProcessMsg_connect.find ( "failed to bind", 0, FALSE ) > -1|| ProcessMsg_connect.find ("Address already in use", 0, FALSE ) > -1)
		{
			QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( 500 );
			GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
			int pid = -1;
			QString Name = "";
			if ( !NameAndPid.isEmpty() )
			{
				pid = NameAndPid.section ( '/', 0, 0 ).toInt();
				Name = NameAndPid.section ( '/', 1, 1 );
				KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( 500 ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
			}
			else
				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
			abort = true;
		}

		else if ( ProcessMsg_connect.find ( "IPsec apparently already running", 0, FALSE ) > -1 )
		{
			NormalMsg = false;
			GlobalConfig->appendLogEntry ( i18n ( "IPsec seems to be already running" ), GlobalConfig->error );

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Trying to kill %1 and restart it." ).arg ( "ipsec" ), GlobalConfig->debug );
			disconnectClicked();
			setGuiStatus ( disconnected );

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

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

			if ( !KillProcess->start(env) )
			{
				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();
			}
		}
		else if ( ProcessMsg_connect.find ( "no default route, %defaultroute cannot cope!!!", 0, FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "No default route found, nesessary for %1!" ).arg ( IpsecType ) );
			GlobalConfig->appendLogEntry ( i18n ( "No default route found, nessesary for %1!" ).arg ( IpsecType ) , GlobalConfig->error );
			abort = true;
			ErrorMsg = true;
		}

		else if ( ProcessMsg_connect.find ( "ignoring informational payload, type NO_PROPOSAL_CHOSEN", 0 , FALSE ) > -1 )
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Wrong connection parameters used. Please verify the connection settings." ) );
				GlobalConfig->appendLogEntry ( i18n ( "Peer reported that we use wrong connection parameters." ) , GlobalConfig->error );
				abort = true;
				stopContinue = true;
			}
		}
		else if ( ProcessMsg_connect.find ( "perhaps peer likes no proposal", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "ignoring informational payload, type INVALID_ID_INFORMATION", 0 , FALSE ) > -1 )
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Wrong connection parameters used. Please verify the connection settings." ) );
				GlobalConfig->appendLogEntry ( i18n ( "Peer reported that we use wrong connection parameters." ) , GlobalConfig->error );
				abort = true;
				stopContinue = true;
			}
		}
		else if ( ProcessMsg_connect.find ( "cannot initiate connection with ID wildcards", 0 , FALSE ) > -1 )
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Cannot initiate connection with ID wildcards. Please verify the connection settings." ) );
				GlobalConfig->appendLogEntry ( i18n ( "Cannot initiate connection with ID wildcards." ) , GlobalConfig->error );
				abort = true;
				stopContinue = true;
			}
		}


		// 		else if ( ProcessMsg_connect.find( "Can not opportunistically initiate", 0 , FALSE ) > -1 )
		// 		{
		// 			if ( !stopContinue )
		// 			{
		// 				KMessageBox::error( this, i18n( "Can not opportunistically initiate. Please verify the connection settings." ) );
		// 				GlobalConfig->appendLogEntry( i18n( "Can not opportunistically initiate." ) , GlobalConfig->error );
		// 				abort = true;
		// 				stopContinue = true;
		// 			}
		// 		}


		else if ( ProcessMsg_connect.find ( "unable to locate my private key", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Private key could not be found. Please check certificate settings." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Private key could not be found. Please check certificate settings." ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "SMARTCARD support is deactivated in pluto/Makefile", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "Smartcard not supported", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "SMARTCARD support is deactivated. Please enable smartcard support in %1 package" ).arg ( IpsecType ) );
			GlobalConfig->appendLogEntry ( i18n ( "SMARTCARD support is deactivated. Please enable smartcard support in %1 package" ).arg ( IpsecType ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Unsupported card", 0 , FALSE ) > -1 &&  ProcessMsg_connect.find ( "pkcs15", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Unsupported card found. Please use a smartcard with openct support. This is a Openswan limitation, sorry." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Unsupported card found. Please use a smartcard with openct support. This is a Openswan limitation, sorry." ) , GlobalConfig->error );
			abort = true;
		}

		else if ( ProcessMsg_connect.find ( "we require peer to have ID", 0 , FALSE ) > -1 && ProcessMsg_connect.find ( "but peer declares", 0 , FALSE ) > -1 )
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Wrong ID \"%1\" from peer got, we expect \"%2\". Please verify the connection settings. Hint: try to disable PFS." ).arg ( ProcessMsg_connect.section ( '\'', 3, 3 ) ).arg ( ProcessMsg_connect.section ( '\'', 1, 1 ) ) );
				GlobalConfig->appendLogEntry ( i18n ( "Wrong ID \"%1\" from peer got, we expect \"%2\". Please verify the connection settings." ).arg ( ProcessMsg_connect.section ( '\'', 3, 3 ) ).arg ( ProcessMsg_connect.section ( '\'', 1, 1 ) ) , GlobalConfig->error );
				abort = true;
				stopContinue = true;
			}
		}


		else if ( ProcessMsg_connect.find ( "IPsec SA established", 0 , FALSE ) > -1 )
		{
			abort = false;
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			{
				GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Connection established." ), GlobalConfig->success );
			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
			{
				GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec connection established." ), GlobalConfig->success );
			}

			doIptablesFreeswan();
			addRouteIpsec();

			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
			{
				start_l2tpd();
			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			{
				sec = hour = min = 0;

				GlobalConfig->status = GlobalConfig->connected;

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


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

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

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

		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[ipsec] " + ProcessMsg_connect, GlobalConfig->debug );
			// 		if (GlobalConfig->KvpncDebugLevel > 0)
			// 			GlobalConfig->appendLogEntry( "out: " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[ipsec err] " + ProcessMsg_connect, GlobalConfig->error );
		}

		if ( abort )
		{
			GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "ipsec" ) , GlobalConfig->error );
			disconnectClicked();
		}

	}
}

void KVpnc::readFromStdout_pptp()
{
	while ( PptpProcess != 0 && PptpProcess->canReadLineStdout() )
	{
		ProcessMsg_connect = PptpProcess->readLineStdout();
		// 			ProcessMsg_connect = QString( PptpProcess->readStdout() );
		//if ( !ProcessMsg_connect.isEmpty() )

		GlobalConfig->appendLogEntry ( "[pppd] " + ProcessMsg_connect, GlobalConfig->debug );

		bool abort = false;
		bool connectSuccess = 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;
		}
		else if ( ProcessMsg_connect.find ( "Connection terminated.", 0 , FALSE ) > -1 )
		{
			//KMessageBox::error( this, i18n( "Connection has been terminated." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Connection has been terminated." ), GlobalConfig->info );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Modem hangup", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "Modem hung up", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Remote modem has hung up. Connection was terminated." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Remote modem has hung up. Connection was terminated." ) , GlobalConfig->error );
			abort = true;
		}
		else 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;
		}
		else 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;
		}
		else 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;
		}
		else if ( ProcessMsg_connect.find ( "Call manager exited with error", 0 , FALSE ) > -1 )
		{
			//KMessageBox::error( this, i18n( "Call manager exited with a error." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Call manager exited with error." ) , GlobalConfig->error );
			abort = true;
		}
		else 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;
		}
		else if ( ProcessMsg_connect.find ( "Using interface", 0 , FALSE ) > -1 )
		{
			PppdDevice = ProcessMsg_connect.right ( ProcessMsg_connect.length() - 16 );
			if ( GlobalConfig->PppdDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( PppdDevice ), GlobalConfig->debug );
			GlobalConfig->currentProfile->setNetworkDevice ( PppdDevice );
			//
			//
			// 		NetworkInterface iface(GlobalConfig,parent);
			// 		TunnelInterfaceIP = iface.getInterfaceIP( PppdDevice );
			// 		if (GlobalConfig->VpncDebugLevel > 0 )
			// 			GlobalConfig->appendLogEntry( "[pppd] "+i18n( "Tunnel IP:" ).arg(TunnelInterfaceIP) , GlobalConfig->debug);
			//

			abort = false;
		}
		else 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;
		}
		else if ( ProcessMsg_connect.find ( "Modem hangup", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Remote modem has hung up. Connection was terminated." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Remote modem has hung up. Connection was terminated." ) , GlobalConfig->error );
			abort = true;
		}
		else 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;
		}
		else if ( ProcessMsg_connect.find ( "CHAP authentication succeeded", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "CHAP authentication succeeded.\n" ), GlobalConfig->debug );
			abort = false;
		}
		else if ( ProcessMsg_connect.find ( "MPPE 128-bit stateless compression enabled", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "MPPE 128-bit stateless compression enabled.\n" ), GlobalConfig->debug );
			abort = false;
		}
		else if ( ProcessMsg_connect.find ( "local", 0 , FALSE ) > -1 )
		{
// 						if (GlobalConfig->KvpncDebugLevel > 0)
// 						GlobalConfig->appendLogEntry ( i18n( "adr: %1\n" ).arg( ProcessMsg_connect), GlobalConfig->debug);
			TunnelInterfaceIP = ProcessMsg_connect.simplifyWhiteSpace().section ( ' ', 3, 3 );
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
			abort = false;
		}
		else if ( ProcessMsg_connect.find ( "remote IP address", 0, FALSE ) > -1 )
			connectSuccess = true;

		if ( abort )
		{
			if ( GlobalConfig->KvpncDebugLevel > 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 password entries
			if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
			{
				// remove kvpnc entries from chap-secerets
				QFile ChapSecretsFile ( "/etc/ppp/chap-secrets" );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/chap-secrets" ), GlobalConfig->debug );
				QTextStream stream ( &ChapSecretsFile );
				if ( ChapSecretsFile.open ( IO_ReadOnly ) )
				{
					QString line = "";
					QString chapsecret_content = "";
					bool kvpnc_start_marker_found = false;
					bool kvpnc_end_marker_found = false;
					while ( !stream.atEnd() )
					{
						line = stream.readLine(); // line of text excluding '\n'
						if ( line == "# --- generated by kvpnc. Do not edit it." )
						{
							kvpnc_end_marker_found = true;
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
						}
						if ( line == "# +++ generated by kvpnc. Do not edit it." )
						{
							kvpnc_start_marker_found = true;
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
						}

						if ( kvpnc_start_marker_found == false )
						{
							chapsecret_content += line;
							chapsecret_content += '\n';
						}
					}
					ChapSecretsFile.close();
					if ( ChapSecretsFile.remove() )
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
						// 							ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
						if ( ChapSecretsFile.open ( IO_WriteOnly ) )
						{
							stream.setDevice ( &ChapSecretsFile );
							stream << chapsecret_content;
							ChapSecretsFile.close();
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->error );
						}
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							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 );
				}
			}
			if (GlobalConfig->currentProfile->getAuthMethod() == "pap")
			{
				// remove kvpnc entries from pap-secerets
				QFile papSecretsFile ( "/etc/ppp/pap-secrets" );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1").arg("/etc/ppp/chap-secrets" ), GlobalConfig->debug );
				QTextStream stream ( &papSecretsFile );
				if ( papSecretsFile.open ( IO_ReadOnly ) )
				{
					QString line = "";
					QString papsecret_content = "";
					bool kvpnc_start_marker_found = false;
					bool kvpnc_end_marker_found = false;
					while ( !stream.atEnd() )
					{
						line = stream.readLine(); // line of text excluding '\n'
						if ( line == "# --- generated by kvpnc. Do not edit it." )
						{
							kvpnc_end_marker_found = true;
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
						}
						if ( line == "# +++ generated by kvpnc. Do not edit it." )
						{
							kvpnc_start_marker_found = true;
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
						}

						if ( kvpnc_start_marker_found == false )
						{
							papsecret_content += line;
							papsecret_content += '\n';
						}
					}
					papSecretsFile.close();
					if ( papSecretsFile.remove() )
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
						// 							papSecretsFile.setName("/etc/ppp/pap-secrets2");
						if ( papSecretsFile.open ( IO_WriteOnly ) )
						{
							stream.setDevice ( &papSecretsFile );
							stream << papsecret_content;
							papSecretsFile.close();
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->debug );
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 2 )
								GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
						}
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "File %1 remove failed" ).arg ( "/etc/ppp/pap-secrets" ), GlobalConfig->error );
					}

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


			return ;
		}
		// success
		else if ( connectSuccess )
		{

			sec = hour = min = 0;

			GlobalConfig->status = GlobalConfig->connected;

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

			GlobalConfig->appendLogEntry ( i18n ( "Connection established." ), GlobalConfig->success );

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );

			// 			GlobalConfig->appendLogEntry( QString("connectstring: "+ProcessMsg_connect), GlobalConfig->debug );

			QString pppdev = "";
			if ( !PppdDevice.isEmpty() )
				pppdev = PppdDevice;
			else
				pppdev = "ppp0";


			// write pppd.<profile>.up
			QFile pppdupfile ( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up" );
			QTextStream pppdupstream ( &pppdupfile );
			if ( pppdupfile.open ( IO_WriteOnly ) )
			{
				pppdupstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
				pppdupstream << "# generated by kvpnc. Do not edit it." << "\n";
				pppdupstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
				pppdupstream << "cat /etc/resolv.conf > " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << "\n";

				if (Utils(GlobalConfig).resolvConfAvailable())
				{
					pppdupstream << "/etc/init.d/resolvconf stop\n";
					pppdupstream << "rm /etc/resolv.conf\n";
				}

				pppdupstream << "echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
				pppdupstream << "echo >> /etc/resolv.conf\n";
				if ( GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty() )
					pppdupstream << "echo \"nameserver " << GlobalConfig->currentProfile->getDnsServer() + "\" >> /etc/resolv.conf\n";
				if ( GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
					pppdupstream << "echo \"search " << GlobalConfig->currentProfile->getSearchDomainInResolvConf() + "\" >> /etc/resolv.conf\n";

				pppdupstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() + " >> /etc/resolv.conf\n";

				pppdupstream << "chmod u-w  /etc/resolv.conf\n";

				if ( ! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute() )
				{
					pppdupstream << GlobalConfig->pathToIp << " route show | grep default > " << OldDefaultroute << "\n";
				}

				pppdupstream << "DEFAULT_GW=`"+GlobalConfig->pathToIp + " route show | grep default | cut -f 3 -d ' '` "+"\n";
				pppdupstream << "DEFAULT_DEV=`"+GlobalConfig->pathToIp + " route show | grep default | cut -f 5 -d ' '` "+"\n";
				pppdupstream << GlobalConfig->pathToIp + " route add " + GlobalConfig->currentProfile->getGateway() + "/32 via $DEFAULT_GW dev $DEFAULT_DEV" + "\n";
				pppdupstream << GlobalConfig->pathToIp + " route replace default dev " + pppdev + "\n";

				if ( !TmpDns1.isEmpty() && !TmpDns2.isEmpty() )
				{
					pppdupstream << "echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
					pppdupstream << "echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";
					pppdupstream << "echo \"nameserver " << TmpDns1 << "\" >> /etc/resolv.conf" << "\n";
					if ( !TmpDns2.isEmpty() )
						pppdupstream << "echo \"nameserver " << TmpDns2 << "\" >> /etc/resolv.conf" << "\n";
					pppdupstream << "chmod u-w  /etc/resolv.conf\n";
				}

			}
			pppdupfile.close();

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

			if ( !pppdUpProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" (%2) start failed!" ).arg ( "PppdUpScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up") );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) started." ).arg ( "PppdUpScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up") , GlobalConfig->debug );
				while ( pppdUpProcess->isRunning() )
					parent->QApplication::processEvents();

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) finished." ).arg ( "PppdUpScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up") , GlobalConfig->debug );
			}

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

	// do replace default route (pppd 2.4.2 doesnt support it)
	//ip route replace default dev ppp0


	// 		NetworkInterface iface( GlobalConfig , parent );
	// 		if (iface.interfaceExist(pppdev))
	// 		{
	// 			TunnelInterfaceIP = iface.getInterfaceIP( pppdev );
	// 			if (GlobalConfig->KvpncDebugLevel > 0)
	// 				GlobalConfig->appendLogEntry ( i18n( "Tunnel interface IP address: %1").arg(pppdev ), GlobalConfig->debug );
	// 		}


// 			if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
// 			{
// 				QString ReplaceDefaultRouteScript = tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".pppdDelDefaultRouteProcess.sh";
// 				QFile ReplaceDefaultRouteFile ( ReplaceDefaultRouteScript );
// 				QTextStream stream ( &ReplaceDefaultRouteFile );
// 				if ( ReplaceDefaultRouteFile.open ( IO_WriteOnly ) )
// 				{
// 
// 					stream << "#!"<< GlobalConfig->InterpreterShell << "\n";
// 					stream << GlobalConfig->pathToIp << " route del $(cat " << OldDefaultroute << ")" << "\n";
// 
// 					pppdDelDefaultRouteProcess = new QProcess ( this );
// 					pppdDelDefaultRouteProcess->addArgument ( GlobalConfig->InterpreterShell );
// 					pppdDelDefaultRouteProcess->addArgument ( ReplaceDefaultRouteScript );
// 
// 					if ( !pppdDelDefaultRouteProcess->start(env) )
// 					{
// 						KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "pppdDelDefaultRouteProcess" ) );
// 					}
// 					else
// 					{
// 						if ( GlobalConfig->KvpncDebugLevel > 0 )
// 							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "pppdDelDefaultRouteProcess" ) , GlobalConfig->debug );
// 					}
// 				}
// 			}



	if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() && ! pppdHasReplacedefaultrouteSupport)
	{
		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";
			file.close();
			ReplaceDefaultRouteProcess = new QProcess ( this );
			ReplaceDefaultRouteProcess->addArgument ( GlobalConfig->InterpreterShell );
			ReplaceDefaultRouteProcess->addArgument ( PppdReplaceDefaultRouteScript );
			if ( !ReplaceDefaultRouteProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" %2 start failed!" ).arg ( i18n ( "pppd replace route process" )).arg( tmpPath + "pppd_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh")   );
				// 			disconnectClicked();
				// 			setGuiStatus(disconnected);
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) started." ).arg ( i18n ( "pppd replace route process" )).arg( tmpPath + "pppd_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh") , GlobalConfig->debug );
			}
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n ( "Could not write: \"%1\" (%2)!" ).arg ( i18n ( "pppd replace route script" )).arg(PppdReplaceDefaultRouteScript), GlobalConfig->error );
		}


	}

	// 	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(env) )
	// 	{
	// 		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 );

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

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

	}






		}
		// 		GlobalConfig->appPointer->processEvents();
	}
}

void KVpnc::readFromStderr_pptp()
{
	while ( PptpProcess != 0 && PptpProcess->canReadLineStderr() )
	{
		ProcessMsg_connect = PptpProcess->readLineStderr();
		// 					ProcessMsg_connect = QString( PptpProcess->readStderr() );
		// 		if ( !ProcessMsg_connect.isEmpty() )

		bool abort = false;

		if ( ProcessMsg_connect.find ( "DNS address", 0, FALSE ) || ProcessMsg_connect.find ( "Script /etc/ppp/ip-up started", 0, FALSE ) )
			GlobalConfig->appendLogEntry ( "[pppd] " + ProcessMsg_connect, GlobalConfig->debug );
		else
			GlobalConfig->appendLogEntry ( "[pppd err] " + ProcessMsg_connect, GlobalConfig->error );

		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;
		}
		else 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;
		}
		else 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;
		}
		else if ( ProcessMsg_connect.find ( "Connection terminated.", 0 , FALSE ) > -1 )
		{
			//   KMessageBox::error( this, i18n( "Connection has been terminated." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Connection has been terminated." ), GlobalConfig->info );
			abort = true;
		}
		else 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;
		}
		else 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;
		}
		else 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;
		}
		else 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;
		}
		else if ( ProcessMsg_connect.find ( "local IP address", 0 , FALSE ) > -1 )
		{
			TunnelInterfaceIP = ProcessMsg_connect.simplifyWhiteSpace().section ( ' ', 3, 3 );
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
			abort = false;
		}
		else if ( ProcessMsg_connect.find ( "No auth is possible sent", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "No password was send. Please check if there is a password set in user settings." ) );
			GlobalConfig->appendLogEntry ( i18n ( "No password was send. Please check if there is a password set in user settings." ) , GlobalConfig->error );
			abort = true;
		}

		GlobalConfig->appendLogEntry ( QString ( "[pppd err] " + ProcessMsg_connect ) , GlobalConfig->error );

		if ( abort )
		{
			if ( GlobalConfig->KvpncDebugLevel > 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 );
			return ;
		}
		// 		GlobalConfig->appPointer->processEvents();
	}
}

void KVpnc::readOutput_openvpn()
{

	QString ProcessMsg = "";
	bool stderr = false;
	bool connectSuccess = false;
	QString NetworkDevice = "";

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


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

			if (!ProcessMsg.isEmpty() && GlobalConfig->KvpncDebugLevel > 4 )
			{
				GlobalConfig->appendLogEntry ( "[openvpn raw]: "+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->error );
		else
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[openvpn] " + ProcessMsg, GlobalConfig->debug );

		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 ( "[ECONNREFUSED]: Connection refused", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Connection has been refused. Terminate." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Connection has been refused. 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 ( "ERROR: could not read Auth username/password from management interface", 0, FALSE ) > -1 )
		{
			;
			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 ( "Username and password could not read from management interface!" ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg.find ( "ERROR: could not read eToken token username/password/ok from management interface", 0, FALSE ) > -1 )
		{
			;
			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 ( "eToken password could not read from management interface!" ) , 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 ( "not found", 0, FALSE ) > -1 && ProcessMsg.find ( "Message hash algorithm", 0, FALSE ) > -1 )
		{
			QString hash_algo= ProcessMsg.section("'",1,1);
			KMessageBox::error( this, i18n ( "Hash algorithm \"%1\"not found! Please choose another one." ).arg(hash_algo) );
			GlobalConfig->appendLogEntry ( i18n ( "Hash algorithm \"%1\"not found! Please choose another one." ).arg(hash_algo) , 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;

			GlobalConfig->appendLogEntry ( i18n ( "Local network type is %1 but remote network type is %2. This will be fixed." ).arg ( "tun" ).arg ( "tap" ), GlobalConfig->info );
			GlobalConfig->currentProfile->setTunnelDeviceType ( "tap" );
			disconnectClicked();
			connectClicked();
		}
		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;

			GlobalConfig->appendLogEntry ( i18n ( "Local network type is %1 but remote network type is %2. This will be fixed." ).arg ( "tap" ).arg ( "tun" ), GlobalConfig->info );
			GlobalConfig->currentProfile->setTunnelDeviceType ( "tun" );
			disconnectClicked();
			connectClicked();
		}
		else if ( ProcessMsg.find ( "connect to " + QString ( GlobalConfig->currentProfile->getHttpProxy() + ":" + QString().setNum ( GlobalConfig->currentProfile->getHttpProxyPort() ) + " failed" ), 0, FALSE ) > -1 )
		{
			// 			else if ( ProcessMsg.find( "Connection refused", 0, FALSE ) > -1 ) {
			// 				if ( ProcessMsg.find( "failed", 0, FALSE ) > -1 ) {
			GlobalConfig->appendLogEntry ( i18n ( "Connection to HTTP proxy (%1:%2) failed!" ).arg ( GlobalConfig->currentProfile->getHttpProxy() ).arg ( GlobalConfig->currentProfile->getHttpProxyPort() ) , GlobalConfig->error );
			KMessageBox::error ( this, i18n ( "Connection to HTTP proxy (%1:%2) failed!" ).arg ( GlobalConfig->currentProfile->getHttpProxy() ).arg ( GlobalConfig->currentProfile->getHttpProxyPort() ) );
			abort = true;
			// 			}
		}
		else if ( ProcessMsg.find ( "SIGTERM[soft,init_instance] received", 0, FALSE ) > -1 )
		{

			GlobalConfig->appendLogEntry ( i18n ( "Connection was rejected (wrong HTTP proxy auth data?)." ).arg ( GlobalConfig->currentProfile->getHttpProxy() ).arg ( GlobalConfig->currentProfile->getHttpProxyPort() ) , GlobalConfig->error );
			KMessageBox::error ( this, i18n ( "Connection was rejected (wrong HTTP proxy auth data?)." ) );
			abort = true;
		}

		else if ( ProcessMsg.find ( "MANAGEMENT: Cannot bind TCP socket", 0, FALSE ) > -1 )
		{

// 			GlobalConfig->appendLogEntry ( i18n ( "The management port cant bind, please try again later." ).arg ( GlobalConfig->currentProfile->getHttpProxy() ).arg ( GlobalConfig->currentProfile->getHttpProxyPort() ) , GlobalConfig->error );
// 			KMessageBox::error ( this, i18n ( "The management port cant bind, please try again later." ) );
			QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( GlobalConfig->OpenvpnManagementPort );
			GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
			int pid = -1;
			QString Name = "";
			if ( !NameAndPid.isEmpty() )
			{
				pid = NameAndPid.section ( '/', 0, 0 ).toInt();
				Name = NameAndPid.section ( '/', 1, 1 );
				KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( GlobalConfig->OpenvpnManagementPort ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
			}
			else
				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );

			abort = true;
		}

		else if ( ProcessMsg.find ( QString("MANAGEMENT: Socket bind failed on local address 127.0.0.1:"+QString().setNum(GlobalConfig->OpenvpnManagementPort)+": Address already in use"), 0, FALSE ) > -1 )
		{

// 			GlobalConfig->appendLogEntry ( i18n ( "The management port cant bind, please try again later." ) ) , GlobalConfig->error );
// 			KMessageBox::error ( this, i18n ( "The management port cant bind, please try again later." ) );

			QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( GlobalConfig->OpenvpnManagementPort );
			GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" ).arg ( NameAndPid ) , GlobalConfig->debug );
			int pid = -1;
			QString Name = "";
			if ( !NameAndPid.isEmpty() )
			{
				pid = NameAndPid.section ( '/', 0, 0 ).toInt();
				Name = NameAndPid.section ( '/', 1, 1 );
				KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." ).arg ( QString().setNum ( GlobalConfig->OpenvpnManagementPort ) ).arg ( Name ).arg ( QString().setNum ( pid ) ) );
			}
			else
			{
				KMessageBox::error ( this, i18n ( "Port binding failed" ) );
				GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , GlobalConfig->error );
			}
			abort = true;
			// 			managementhandler->closeConnection();
		}


		else if ( ProcessMsg.find( "TLS key negotiation failed to occur within 60 seconds", 0 , FALSE ) > -1 || ProcessMsg.find( "TLS Error: TLS handshake failed", 0 , FALSE ) > -1)
		{
			KMessageBox::error( this, i18n( "TLS key negotiation failed to occur within 60 seconds" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , 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;
			if (PrivKeyPassStr.isEmpty())
			{
				GlobalConfig->TmpPrivateKeyPass = "";
				QString pass="";
				EnterXauthInteractivePasscodeDialog dlg( 0, i18n( "Enter private key password" ) );
				dlg.main->DescriptionLabel->setText( i18n( "Enter private key password to unlock private key:" ) );
				dlg.main->LabelPassword->setText( i18n( "Private key password:" ) );
				dlg.main->SavePasswordCheckBox->setText( i18n( "Save private key password" ) );
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( "[openvpn] " + i18n( "Password for private key requested...\n" ), GlobalConfig->debug );
				if ( dlg.exec() )
				{
	
					pass = dlg.main->PasswordEdit->text();
					if ( !pass.isEmpty() )
					{
	
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry( "OpenvpnManagementHandler: " + i18n( "private key password got from user" ), GlobalConfig->debug );
	
						if ( dlg.main->SavePasswordCheckBox->isChecked() )
						{
							GlobalConfig->currentProfile->setSavePrivateKeyPassword( true );
							GlobalConfig->currentProfile->setPrivateKeyPass( QString( pass ) );
						}
	
						GlobalConfig->TmpPrivateKeyPass = QString( pass );
	
						// 												if ( GlobalConfig->KvpncDebugLevel > 5 )
						// 				GlobalConfig->appendLogEntry( "OpenvpnManagementHandler: private key password: " + GlobalConfig->TmpPrivateKeyPass, GlobalConfig->debug );
	
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry( "OpenvpnManagementHandler: " + i18n( "Send private key password..." ), GlobalConfig->debug );
	
						OpenvpnProcess->writeToStdin ( PrivKeyPassStr );
						OpenvpnProcess->writeToStdin ( "\n" );
					}
					else
					{
						GlobalConfig->appendLogEntry( "OpenvpnManagementHandler: password empty, stop.", GlobalConfig->error );
						return;
					}
				}
			}
			else 
			{
				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 = GlobalConfig->TmpUsername;

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "OpenVPN Auth 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 ( "OpenVPN Auth Pass: " + GlobalConfig->TmpPassword , GlobalConfig->debug );


				OpenvpnProcess->writeToStdin ( GlobalConfig->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 ( "Authenticate/Decrypt packet error: cipher final failed", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Authentication has been failed because decryption failure. Please check OpenVPN settings." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Authentication has been failed because decryption failure. Please check OpenVPN settings." ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg.find ( "'auth' is used inconsistently", 0 , FALSE ) > -1 )
		{
			QString LocalAuth = ProcessMsg.section ( '=', 1, 1 ).section ( ',', 0, 0 ).section ( ' ', 1, 1 ).remove ( "'" );
			QString PeerAuth = ProcessMsg.section ( '=', 2, 2 ).section ( ' ', 1, 1 ).remove ( "'" );
			// 			KMessageBox::error( this, i18n( "Wrong authentication method used. We use \"%1\" but peer want \"%2\". Please change it in %3 settings." ).arg( LocalAuth ).arg( PeerAuth ).arg( i18n( "OpenVPN" ) ) );
			// 			GlobalConfig->appendLogEntry( i18n( "Wrong authentication method used. We use \"%1\" but peer want \"%2\". Please change it in %3 settings." ).arg( LocalAuth ).arg( PeerAuth ).arg( i18n( "OpenVPN" ) ) , GlobalConfig->error );
			// 			abort = true;

			GlobalConfig->appendLogEntry ( i18n ( "Wrong authentication method used. We use \"%1\" but peer want \"%2\", this will be fixed." ).arg ( LocalAuth ).arg ( PeerAuth ).arg ( i18n ( "OpenVPN" ) ) , GlobalConfig->info );
			GlobalConfig->currentProfile->setAuthenticationAlgorithm ( PeerAuth );
			disconnectClicked();
			connectClicked();
		}
		else if ( ProcessMsg.find ( "WARNING: 'cipher' is used inconsistently", 0 , FALSE ) > -1 )
		{

			// example: WARNING: 'cipher' is used inconsistently, local='cipher BF-CBC', remote='cipher AES-128-CBC'
			QString LocalCipher = ProcessMsg.section ( '=', 1, 1 ).section ( ',', 0, 0 ).section ( ' ', 1, 1 ).remove ( "'" );
			QString PeerCipher = ProcessMsg.section ( '=', 2, 2 ).section ( ' ', 1, 1 ).remove ( "'" );
			// 			KMessageBox::error( this, i18n( "Wrong cipher used. We use \"%1\" but peer want \"%2\". Please change it in %3 settings." ).arg( LocalCipher ).arg( PeerCipher ).arg( i18n( "OpenVPN" ) ) );
			// 			GlobalConfig->appendLogEntry( i18n( "Wrong chiper used. We use \"%1\" but peer want \"%2\". Please change it in %3 settings." ).arg( LocalCipher ).arg( PeerCipher ).arg( i18n( "OpenVPN" ) ) , GlobalConfig->error );
			// 			abort = true;

			GlobalConfig->appendLogEntry ( i18n ( "Wrong chipher used. We use \"%1\" but peer want \"%2\", this will be fixed." ).arg ( LocalCipher ).arg ( PeerCipher ).arg ( i18n ( "OpenVPN" ) ) , GlobalConfig->info );
			GlobalConfig->currentProfile->setUserdefiniedCipher ( PeerCipher );
			GlobalConfig->currentProfile->setUseUserdefiniedCipher ( true );
			disconnectClicked();
			connectClicked();
		}
		else if ( ProcessMsg.find ( "Options error: Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]", 0 , FALSE ) > -1 )
		{
			// 			KMessageBox::error( this, i18n( "OpenVPN configuration error. Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]" ) );
			// 			GlobalConfig->appendLogEntry( i18n( "OpenVPN configuration error. Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]" ), GlobalConfig->error );
			//				abort = true;
			GlobalConfig->appendLogEntry ( i18n ( "OpenVPN configuration error. Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]" ), GlobalConfig->info );
			abort = false;
		}
		else if ( ProcessMsg.find ( "Options error: Unrecognized option or missing parameter", 0 , FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "OpenVPN configuration error. Unrecognized option or missing parameter" ) );
			GlobalConfig->appendLogEntry( i18n( "OpenVPN configuration error. Unrecognized option or missing parameter" ), GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg.find ( "TCP connection established", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[openvpn]: "+i18n( "Low level connection to %1 established." ).arg(GlobalConfig->currentProfile->getGateway()), GlobalConfig->info );
		}
		else if ( ProcessMsg.find ( "UDP connection established", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry( "[openvpn]: "+i18n( "Low level connection to %1 established." ).arg(GlobalConfig->currentProfile->getGateway()),GlobalConfig->info );
		}
		// 		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;
		}

		else if ( ProcessMsg.find ( "Need 'token-insertion-request' confirmation MSG:Please insert SLOT", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Need token to be insert. Please insert token in SLOT...." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Need token to be insert. Please insert token in SLOT...." ), GlobalConfig->error );
			abort = true;
		}

		else if ( ProcessMsg.find ( "process exiting", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "%1 is shutting down." ).arg ( "openvpn" ), GlobalConfig->debug );

			connectionEnded();
			setGuiStatus ( disconnected );
		}
		else if ( ProcessMsg.find ( "Initialization Sequence Completed", 0, FALSE ) > -1 )
		{
			connectSuccess = true;
		}
		else if ( ProcessMsg.find ( "pointopoint", 0, FALSE ) > -1 )
		{
			// TUN/TAP device tun0 opened
			NetworkDevice = ProcessMsg.section ( ' ', -2, -2 ); // tun0
			OpenvpnDevice = ProcessMsg.section ( ' ', -6, -6 ); // tun0
			TunnelInterfaceIP = ProcessMsg.section ( ' ', -5, -5 ); // ip
			NetworkInterface iface ( GlobalConfig, parent );
			// 		TunnelInterfaceIP = iface.getInterfaceIP( OpenvpnDevice );

			if ( GlobalConfig->KvpncDebugLevel > 0 )
			{
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( OpenvpnDevice ), GlobalConfig->debug );
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
			}
		}

		// success
		if ( connectSuccess )
		{

			GlobalConfig->appendLogEntry ( i18n ( "Connection established." ), GlobalConfig->success );

			sec = hour = min = 0;

			GlobalConfig->status = GlobalConfig->connected;

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

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[openvpn] " + i18n ( "Using %1 as tunnel device." ).arg ( OpenvpnDevice ) , GlobalConfig->debug );

			setFirewallAfterConnect();
			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();
			}
		}

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

			disconnectClicked();

			return ;
		}


	}

	while ( OpenvpnProcess->canReadLineStderr() )
	{
		ProcessMsg = QString ( OpenvpnProcess->readLineStderr() );


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

			if (!ProcessMsg.isEmpty() && GlobalConfig->KvpncDebugLevel > 2 )
			{
				GlobalConfig->appendLogEntry ( "[openvpn stderr raw]: "+ProcessMsg, GlobalConfig->debug );
			}
		}
}

void KVpnc::readFromStdout_l2tpd()
{
	while ( L2tpdProcess->canReadLineStdout() )
	{
		bool NormalMsg = true;
		bool ErrorMsg = false;
		ProcessMsg_connect = L2tpdProcess->readLineStdout();
		// 			ProcessMsg_connect = QString( L2tpdProcess->readStdout() );
		//if ( !ProcessMsg_connect.isEmpty() )


		bool abort = false;
		bool connectSuccess = false;


		

		if ( ProcessMsg_connect.find ( "init_network: Unable to bind socket. Terminating", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "Unable to bind socket: Address already in use", 0 , FALSE ) > -1 )
		{
			bool kill_l2tpd=true;
			
			QString deamon="xl2tpd";
			if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
			{
				deamon="xl2tpd";
				if ( !GlobalConfig->doKillXl2tpdIfStillRunning )
				{
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg ( deamon ) ) , GlobalConfig->debug );
					abort = true;
					kill_l2tpd=false;
				}
			}
			else
			{
				deamon="l2tpd";
				if ( !GlobalConfig->doKillL2tpdIfStillRunning )
				{
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg ( deamon ) ) , GlobalConfig->debug );
					abort = true;
					kill_l2tpd=false;
				}
			}

			if (kill_l2tpd == true)
			{
				QProcess killl2tpdprocess ( this );
				killl2tpdprocess.addArgument ( GlobalConfig->pathToKillall );
				if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
					killl2tpdprocess.addArgument ( "xl2tpd" );
				else
					killl2tpdprocess.addArgument ( "l2tpd" );

				if ( !killl2tpdprocess.start() )
				{
					GlobalConfig->appendLogEntry ( i18n ( "%1 could not be killed." ).arg ( "l2tpd" ) , GlobalConfig->error );
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg(deamon) ) , GlobalConfig->debug );
					abort = true;
				}
				else
				{
					while ( killl2tpdprocess.isRunning() )
						usleep ( 500 );
					// 							parent->processEvents();

					// restart l2tpd
					// 						if ( L2tpdProcess != 0)
					// 							L2tpdProcess->kill();

					sleep ( 1 );

					L2tpdProcess = new QProcess ( this );
					//
					if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
					{
						if (GlobalConfig->KvpncDebugLevel > 1)
							GlobalConfig->appendLogEntry(i18n("Using %1.").arg("xl2tpd"),GlobalConfig->debug);
						L2tpdProcess->addArgument ( GlobalConfig->pathToXl2tpd );
					}
					else
					{
						if (GlobalConfig->KvpncDebugLevel > 1)
							GlobalConfig->appendLogEntry(i18n("Using %1.").arg("l2tpd"),GlobalConfig->debug);
						L2tpdProcess->addArgument ( GlobalConfig->pathToL2tpd );
					}
					L2tpdProcess->addArgument ( "-p" );
					L2tpdProcess->addArgument ( "/var/run/l2tpd" + GlobalConfig->currentProfile->getName() + ".pid" );
					L2tpdProcess->addArgument ( "-c" );
					L2tpdProcess->addArgument ( tmpPath + "l2tpd." + GlobalConfig->currentProfile->getName() + ".conf" );
					L2tpdProcess->addArgument ( "-s" );
					L2tpdProcess->addArgument ( tmpPath + "l2tp-secrets" + GlobalConfig->currentProfile->getName() );
					L2tpdProcess->addArgument ( "-D" );

					if ( !L2tpdProcess->start(env) )
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "l2tpd" ), GlobalConfig->error );
						KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "l2tpd" ) );
						setGuiStatus ( disconnected );
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "%1 was already running. It was killed and restarted." ).arg ( "l2tpd" ), GlobalConfig->info );
					}

					abort = false;
				}

			}
		}



		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[l2tpd] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[l2tpd err] " + ProcessMsg_connect, GlobalConfig->error );
		}

		if ( abort )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "pppd" ) , GlobalConfig->debug );
			//terminateConnection ( L2tpdProcess );
			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;
				bool kvpnc_end_marker_found = false;
				while ( !stream.atEnd() )
				{
					line = stream.readLine(); // line of text excluding '\n'
					if ( line == "# --- generated by kvpnc. Do not edit it." )
					{
						kvpnc_end_marker_found = true;
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					}
					if ( line == "# +++ generated by kvpnc. Do not edit it." )
					{
						kvpnc_start_marker_found = true;
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					}

					if ( kvpnc_start_marker_found == false )
					{
						chapsecret_content += line;
						chapsecret_content += '\n';
					}
				}
				ChapSecretsFile.close();
				if ( ChapSecretsFile.remove() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully removed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					// 							ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
					if ( ChapSecretsFile.open ( IO_WriteOnly ) )
					{
						stream.setDevice ( &ChapSecretsFile );
						stream << chapsecret_content;
						ChapSecretsFile.close();
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "File %1 sucessfully rewritten" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->debug );
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed" ).arg ( "/etc/ppp/chap-secrets" ), GlobalConfig->error );
					}
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						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 );
			}
			return ;
		}
		// success
		if ( connectSuccess )
		{

			sec = hour = min = 0;

			GlobalConfig->status = GlobalConfig->connected;

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


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

			sleep ( 2 );

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

			//FIXME make it better
			PppdDevice = "ppp0";
			NetworkInterface iface ( GlobalConfig, parent );
			if ( iface.interfaceExist ( PppdDevice ) )
			{
				TunnelInterfaceIP = iface.getInterfaceIP ( PppdDevice );
				GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( PppdDevice ), GlobalConfig->debug );
				if ( !TunnelInterfaceIP.isEmpty() )
					GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
			}


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

void KVpnc::readFromStderr_l2tpd()
{
	while ( L2tpdProcess->canReadLineStderr() )
	{
		bool NormalMsg = true;
		bool ErrorMsg = false;
		ProcessMsg_connect = L2tpdProcess->readLineStderr();
		// 		// 					ProcessMsg_connect = QString( L2tpdProcess->readStderr() );
		// 		// 		if ( !ProcessMsg_connect.isEmpty() )
		//
		bool abort = false;
		bool connectSuccess = false;

		//
		if ( ProcessMsg_connect.length() > 3 )
		{
			// 		GlobalConfig->appendLogEntry ( QString( "[l2tpd err] " + ProcessMsg_connect ) , GlobalConfig->error );


			if ( ProcessMsg_connect.find ( "Maximum retries exceeded for tunnel", 0 , FALSE ) > -1 )
			{
				ErrorMsg=true;
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "Maximum retries of L2TP connect try exceeded for tunnel, waiting a moment..." ) ) , GlobalConfig->debug );
				// 			abort=true;
			}

			else if ( ProcessMsg_connect.find ( "l2tp_call:Connecting to host", 0 , FALSE ) > -1 )
			{
				NormalMsg=true;
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "l2tp_call:Connecting to host" ) ) , GlobalConfig->debug );
				// 			abort=true;
			}

			else if ( ProcessMsg_connect.find ( "maximum retries exceeded.", 0 , FALSE ) > -1 )
			{
				ErrorMsg=true;
				GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Maximum of L2TP connect retries exceeded, giving up." ) ) , GlobalConfig->debug );
				abort = true;
			}

			else if ( ProcessMsg_connect.find ( "init_network: Unable to bind socket. Terminating", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "Unable to bind socket: Address already in use", 0 , FALSE ) > -1 )
			{
				ErrorMsg=true;
				bool kill_l2tpd=true;
				
				QString deamon="xl2tpd";
				if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
				{
					deamon="xl2tpd";
					if ( !GlobalConfig->doKillXl2tpdIfStillRunning )
					{
						GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg ( deamon ) ) , GlobalConfig->debug );
						abort = true;
						kill_l2tpd=false;
					}
				}
				else
				{
					deamon="l2tpd";
					if ( !GlobalConfig->doKillL2tpdIfStillRunning )
					{
						GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg ( deamon ) ) , GlobalConfig->debug );
						abort = true;
						kill_l2tpd=false;
					}
				}

				if (kill_l2tpd == true)
				{
					QProcess killl2tpdprocess ( this );
					killl2tpdprocess.addArgument ( GlobalConfig->pathToKillall );
					if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
						killl2tpdprocess.addArgument ( "xl2tpd" );
					else
						killl2tpdprocess.addArgument ( "l2tpd" );

					if ( !killl2tpdprocess.start() )
					{
						GlobalConfig->appendLogEntry ( i18n ( "%1 could not be killed." ).arg ( "l2tpd" ) , GlobalConfig->error );
						GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." ).arg(deamon) ) , GlobalConfig->debug );
						abort = true;
					}
					else
					{
						while ( killl2tpdprocess.isRunning() )
							usleep ( 500 );
						// 							parent->processEvents();

						// restart l2tpd
						// 						if ( L2tpdProcess != 0)
						// 							L2tpdProcess->kill();

						sleep ( 1 );

						L2tpdProcess = new QProcess ( this );
						//
						if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
						{
							if (GlobalConfig->KvpncDebugLevel > 1)
								GlobalConfig->appendLogEntry(i18n("Using %1.").arg("xl2tpd"),GlobalConfig->debug);
							L2tpdProcess->addArgument ( GlobalConfig->pathToXl2tpd );
						}
						else
						{
							if (GlobalConfig->KvpncDebugLevel > 1)
								GlobalConfig->appendLogEntry(i18n("Using %1.").arg("l2tpd"),GlobalConfig->debug);
							L2tpdProcess->addArgument ( GlobalConfig->pathToL2tpd );
						}
						L2tpdProcess->addArgument ( "-p" );
						L2tpdProcess->addArgument ( "/var/run/l2tpd" + GlobalConfig->currentProfile->getName() + ".pid" );
						L2tpdProcess->addArgument ( "-c" );
						L2tpdProcess->addArgument ( tmpPath + "l2tpd." + GlobalConfig->currentProfile->getName() + ".conf" );
						L2tpdProcess->addArgument ( "-s" );
						L2tpdProcess->addArgument ( tmpPath + "l2tp-secrets" + GlobalConfig->currentProfile->getName() );
						L2tpdProcess->addArgument ( "-D" );

						if ( !L2tpdProcess->start(env) )
						{
							if ( GlobalConfig->KvpncDebugLevel > 0 )
								GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "l2tpd" ), GlobalConfig->error );
							KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "l2tpd" ) );
							setGuiStatus ( disconnected );
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 0 )
								GlobalConfig->appendLogEntry ( i18n ( "%1 was already running. It was killed and restarted." ).arg ( "l2tpd" ), GlobalConfig->debug );
						}

						abort = false;
					}

				}
			}

			// control_finish: Connection established to 192.168.10.222, 1701.  Local: 55406, Remote: 37911.
			else if ( ProcessMsg_connect.find ( "Connection established", 0 , FALSE ) > -1 )
			{
				NormalMsg=true;
				GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "Low level connection to %1 established." ).arg ( GlobalConfig->currentProfile->getGateway() ) ) , GlobalConfig->success );
				abort = false;
			}

			else if ( ProcessMsg_connect.find ( "Call established", 0 , FALSE ) > -1 )
			{
				NormalMsg=true;
				GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "L2TP connection to %1 established." ).arg ( GlobalConfig->currentProfile->getGateway() ) ) , GlobalConfig->success );
				abort = false;
				if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
				{
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "L2TP tunnel to %1 established." ).arg ( GlobalConfig->currentProfile->getGateway() ) ) , GlobalConfig->success );

					abort = false;
					connectSuccess = true;
				}
			}

			else if ( ProcessMsg_connect.find ( "Connecting to host", 0 , FALSE ) > -1 )
			{
				NormalMsg=true;
				if (GlobalConfig->KvpncDebugLevel > 1)
					GlobalConfig->appendLogEntry(i18n("%1 is connecting to host %2...").arg("l2tpd").arg(GlobalConfig->currentProfile->getGateway()),GlobalConfig->debug);
			}

			else if ( ProcessMsg_connect.find ( "Call established with", 0 , FALSE ) > -1 )
			{
				NormalMsg=true;
				{
					abort = false;
					connectSuccess = true;
				}
			}
			else if ( ProcessMsg_connect.find ( "Call established with", 0 , FALSE ) > -1
								|| ProcessMsg_connect.find ( "Listening on IP address", 0 , FALSE ) > -1 
								|| ProcessMsg_connect.find ( "Calling on tunnel", 0 , FALSE ) > -1  )
			{
				NormalMsg=true;
				abort = false;
			}


			else if ( GlobalConfig->status != GlobalConfig->connected && ProcessMsg_connect.find ( "check_control: control, cid =", 0 , FALSE ) > -1 )
			{
				NormalMsg=true;
				// cid is greather than 0
				if ( ProcessMsg_connect.section ( ',', 1, 1 ).section ( '=', 1, 1 ).stripWhiteSpace() != "0" )       // check_control: control, cid = 17467, Ns = 2, Nr = 4
				{
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "L2TP tunnel to %1 established." ).arg ( GlobalConfig->currentProfile->getGateway() ) ) , GlobalConfig->success );

					abort = false;
					connectSuccess = true;
				}
			}


			if ( connectSuccess )
			{
				sec = hour = min = 0;

				GlobalConfig->status = GlobalConfig->connected;

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


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

				sleep ( 2 );

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

				//FIXME make it better
				PppdDevice = "ppp0";
				NetworkInterface iface ( GlobalConfig, parent );
				if ( iface.interfaceExist ( PppdDevice ) )
				{
					TunnelInterfaceIP = iface.getInterfaceIP ( PppdDevice );
					GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( PppdDevice ), GlobalConfig->debug );
					if ( !TunnelInterfaceIP.isEmpty() )
						GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
				}


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


		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[l2tpd] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[l2tpd err] " + ProcessMsg_connect, GlobalConfig->error );
		}
			if ( abort )
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "l2tpd" ) , GlobalConfig->debug );
				disconnectClicked();
				GlobalConfig->status = GlobalConfig->disconnected;
				setGuiStatus ( disconnected );
				return ;
			}
			GlobalConfig->appPointer->processEvents();
		}
	}
}

void KVpnc::readFromStdout_vtun()
{
	while ( VtundProcess->canReadLineStdout() )
	{
		bool NormalMsg = true;
		bool ErrorMsg = false;
		ProcessMsg_connect = VtundProcess->readLineStdout();
		// 			ProcessMsg_connect = QString( VtundProcess->readStdout() );
		//if ( !ProcessMsg_connect.isEmpty() )


		bool abort = false;
		bool connectSuccess = false;


		
/*
		if ( ProcessMsg_connect.find ( "init_network: Unable to bind socket. Terminating", 0 , FALSE ) > -1  )
		{

		}*/

		if ( ProcessMsg_connect.find("Connection refused(111)",0,FALSE) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Connection refused." ) );
			GlobalConfig->appendLogEntry(i18n("Connection refused."),GlobalConfig->error);
			abort=true;
			ErrorMsg=true;
		}
		else if ( ProcessMsg_connect.find(" Exit ",0,FALSE) > -1 )
		{
			GlobalConfig->appendLogEntry(i18n("%1 has been exited."),GlobalConfig->error);
			abort=true;
			ErrorMsg=true;
		}


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

		}
		// success
		if ( connectSuccess )
		{

			sec = hour = min = 0;

			GlobalConfig->status = GlobalConfig->connected;

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


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

			sleep ( 2 );

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

// 			//FIXME make it better
// 			PppdDevice = "ppp0";
// 			NetworkInterface iface ( GlobalConfig, parent );
// 			if ( iface.interfaceExist ( PppdDevice ) )
// 			{
// 				TunnelInterfaceIP = iface.getInterfaceIP ( PppdDevice );
// 				GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( PppdDevice ), GlobalConfig->debug );
// 				if ( !TunnelInterfaceIP.isEmpty() )
// 					GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
// 			}


			if ( GlobalConfig->currentProfile->getUseConnectionStatusCheck() )
			{
				startConnectionStatusCheck();
			}
		}
// 		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[vtun] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else
// 		if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[vtun err] " + ProcessMsg_connect, GlobalConfig->error );
		}
	}
}

void KVpnc::readFromStderr_vtun()
{
	while ( VtundProcess->canReadLineStderr() )
	{
		bool NormalMsg = true;
		bool ErrorMsg = false;
		ProcessMsg_connect = VtundProcess->readLineStderr();
		// 		// 					ProcessMsg_connect = QString( L2tpdProcess->readStderr() );
		// 		// 		if ( !ProcessMsg_connect.isEmpty() )
		//
		bool abort = false;
		bool connectSuccess = false;

		if ( ProcessMsg_connect.find("Session ",0,FALSE) > -1 && ProcessMsg_connect.find("opened",0,FALSE) > -1)
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Session opened."),GlobalConfig->debug);
		}
		if ( ProcessMsg_connect.find("compression ",0,FALSE) > -1 && ProcessMsg_connect.find("initialized",0,FALSE) > -1)
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Compression initialized."),GlobalConfig->debug);
		}
		if ( ProcessMsg_connect.find("UDP ",0,FALSE) > -1 && ProcessMsg_connect.find("initialized",0,FALSE) > -1)
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("UDP initialized."),GlobalConfig->debug);
		}
		if ( ProcessMsg_connect.find("encryption ",0,FALSE) > -1 && ProcessMsg_connect.find("initialized",0,FALSE) > -1)
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Encryption initialized."),GlobalConfig->debug);

			// FIXME only if encryption is activated (always!?)
			connectSuccess=TRUE;
		}
		if ( ProcessMsg_connect.find("Connection refused(111)",0,FALSE) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Connection refused." ) );
			GlobalConfig->appendLogEntry(i18n("Connection refused."),GlobalConfig->error);
			abort=true;
			ErrorMsg=true;
		}
// // 		if ( ProcessMsg_connect.find(" Exit ",0,FALSE) > -1 )
// // 		{
// // 			GlobalConfig->appendLogEntry(i18n("%1 has been exited.").arg("vtund"),GlobalConfig->error);
// // 			abort=true;
// // 			ErrorMsg=true;
// // 		}
		if ( ProcessMsg_connect.find("Connection denied by ",0,FALSE) > -1 )
		{
			GlobalConfig->appendLogEntry(i18n("Connection denied. Password wrong?"),GlobalConfig->error);
			abort=true;
			ErrorMsg=true;
		}
		if ( ProcessMsg_connect.find("Connection closed by other side",0,FALSE) > -1 )
		{
			GlobalConfig->appendLogEntry(i18n("Connection was closed by the remote host. Please check your settings."),GlobalConfig->error);
			abort=true;
			ErrorMsg=true;
		}
		if ( ProcessMsg_connect.find("syntax error",0,FALSE) > -1 || ProcessMsg_connect.find("No hosts defined",0,FALSE) > -1)
		{
			KMessageBox::error ( this, i18n ( "Syntax error in config detected. Please report that to the KVpnc maintainer." ) );
			GlobalConfig->appendLogEntry(i18n("Syntax error in config detected. Please report that to the KVpnc maintainer."),GlobalConfig->error);
			abort=true;
			ErrorMsg=true;
		}

		if ( ProcessMsg_connect.find("allocate pseudo tty",0,FALSE) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Can't allocate pseudo tty.\nPlease check that your kernel has LEGACY PTY=y or recompile patched vtun. You can get the patch for UNIX98 PTS here: %1" ).arg(QString("http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=451931") ));
			GlobalConfig->appendLogEntry(i18n("Can't allocate pseudo tty."),GlobalConfig->error);
			abort=true;
			ErrorMsg=true;
		}

// 			else if ( GlobalConfig->status != GlobalConfig->connected && ProcessMsg_connect.find ( "check_control: control, cid =", 0 , FALSE ) > -1 )
// 			{
// 				NormalMsg=true;
// 				// cid is greather than 0
// 				if ( ProcessMsg_connect.section ( ',', 1, 1 ).section ( '=', 1, 1 ).stripWhiteSpace() != "0" )       // check_control: control, cid = 17467, Ns = 2, Nr = 4
// 				{
// 					GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "L2TP tunnel to %1 established." ).arg ( GlobalConfig->currentProfile->getGateway() ) ) , GlobalConfig->success );
// 
// 					abort = false;
// 					connectSuccess = true;
// 				}
// 			}


		// success
		if ( connectSuccess )
		{

			GlobalConfig->appendLogEntry ( i18n ( "Connection established." ), GlobalConfig->success );

			sec = hour = min = 0;

			GlobalConfig->status = GlobalConfig->connected;

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

			setFirewallAfterConnect();
			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();
			}
		}
		
// 		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[vtun] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else
// 		if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[vtun err] " + ProcessMsg_connect, GlobalConfig->error );
		}

		if ( abort )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "vtund" ) , GlobalConfig->debug );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );
			return ;
		}
		GlobalConfig->appPointer->processEvents();
		}
}

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 );
		}
		else 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 > 3 )
			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_disconnect()
{
	while ( DisconnectProcess->canReadLineStdout() )
	{
		ProcessMsg_connect = DisconnectProcess->readLineStdout();
		//ProcessMsg_connect = QString( DisconnectProcess->readStdout() );

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

	}
}

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

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[disconnect 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;
			}
		}
	}

	else 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;
			}
		}
	}
	if ( testPppdReplacedefaultroute )
	{
		if ( msg.contains ( "unrecognized option 'replacedefaultroute'" ) || pppdHasReplacedefaultrouteSupport == false  )
		{
			pppdHasReplacedefaultrouteSupport = false;
		}
		else
		{
			pppdHasReplacedefaultrouteSupport = true;
		}
	}

	if ( testPppdRequireMppe128 )
	{
		if ( msg.contains ( "unrecognized option 'require-mppe-128'" ) )
		{
			pppdHasRequireMppe128Support = false;
		}
		else
		{
			pppdHasRequireMppe128Support = true;
		}
	}

}

void KVpnc::readCiscoVpncTestProcessOutput()
{
	QString msg = "";
	while ( TestCiscoVpncProcess->canReadLineStdout())
	{
		msg = QString ( TestCiscoVpncProcess->readLineStdout() );

		if (GlobalConfig->KvpncDebugLevel > 3)
			GlobalConfig->appendLogEntry ( i18n ( "msg: %1" ).arg(msg), GlobalConfig->debug );
	
		if ( msg == "" )
			return ;
		if ( msg.find( "The VPN module is not loaded.", 0 , FALSE ) > -1)
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry ( i18n ( "Virtual interface of cisco client is not present" ), GlobalConfig->debug );
			ciscoVpncRunning = false;
			return;
		}
		else if ( msg.find( "cisco_ipsec", 0 , FALSE ) > -1)
			{
				if (GlobalConfig->KvpncDebugLevel > 1)
					GlobalConfig->appendLogEntry ( i18n ( "Virtual interface of cisco client is present" ), GlobalConfig->debug );
				ciscoVpncRunning = true;
				return;
			}
		}
}

void KVpnc::terminateConnection ( QProcess *proc )
{
	if ( proc->isRunning() )
	{
		proc->tryTerminate();
		proc->tryTerminate();
		proc->tryTerminate();

		//		QTimer::singleShot( 5000, proc, SLOT( kill() ) );

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

}

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

	if ( prevConnectionState == 1 )  //connecting
		GlobalConfig->appendLogEntry ( i18n ( "Successful connect try canceled." ) , GlobalConfig->success );
	else
		GlobalConfig->appendLogEntry ( i18n ( "Successful disconnected." ) , GlobalConfig->success );


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

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

		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
		{
			QFile file ( QString("/etc/opt/cisco-vpnclient/Profiles/")+QString("kvpnc_")+QString(GlobalConfig->currentProfile->getName()+".pcf") );
			file.remove();
		}

		else 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_racoon.sh" );
			file.remove();
			file.setName ( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_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

		else 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

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

		}

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

		}

	}

	if ( prevConnectionState != 1 )  // connected
	{
		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;
	GlobalConfig->TmpPassword = "";
	GlobalConfig->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 while connecting to %1. %2 connect process will be killed.!" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( "vpnc" ), GlobalConfig->error );

		if (ConnectProcess != 0 && ConnectProcess->isRunning())
			ConnectProcess->kill();
		if (CiscoVpncProcess != 0 && CiscoVpncProcess->isRunning())
			CiscoVpncProcess->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 );
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "Connection failed (timeout)." ), GlobalConfig->debug );
		disconnectClicked();
		slotStatusMsg ( i18n ( "Timeout while connecting to %1. %2 connect process will be killed.!" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( "vpnc" ), ID_FLASH_MSG );
		slotStatusMsg ( i18n ( "Disconnected" ), ID_CONNECTION_MSG );
		QToolTip::remove
			( KVpncDock );
		QToolTip::add
			( KVpncDock, i18n ( "Disconnected" ) );
		connectCounter = 0;
		setGuiStatus ( disconnected );
		KMessageBox::error ( this, i18n ( "Timeout while connecting to %1 (%2) after %3s. Please check if the VPN server is reachable and the settings  (UDP/TCP, local port, UDP encapsulation port) are correct. Maybe the timeout must be increased too." ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->currentProfile->getName() ).arg ( GlobalConfig->tryConnectTimeout ) );
	}
	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()
{
	GlobalConfig->appPointer->setOverrideCursor( QCursor(Qt::WaitCursor) );
	GlobalConfig->appendLogEntry(i18n("Saving profiles and global options..."),GlobalConfig->info);
	this->slotStatusMsg ( i18n ( "Saving profiles and global options..." ), ID_STATUS_MSG );
	if ( !GlobalConfig->AccountList->isEmpty() )
	{
		GlobalConfig->saveOptions();
		GlobalConfig->appendLogEntry(i18n("Profiles saved."),GlobalConfig->info);
		this->slotStatusMsg ( i18n ( "Profiles saved." ), ID_FLASH_MSG );
	}
	saveGuiOptions();
	this->slotStatusMsg ( i18n ( "Global options saved." ), ID_FLASH_MSG );
	GlobalConfig->appendLogEntry(i18n("Global options saved."),GlobalConfig->info);
	this->slotStatusMsg ( i18n ( "Ready." ), ID_STATUS_MSG );
	GlobalConfig->appPointer->restoreOverrideCursor();
}

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;

					this->ExportOpenvpnProfileAction->setEnabled ( FALSE );

					QString type = ""; // visible name
					QString bin = "";  // executable name

					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "connectionType raw: %1" ).arg ( QString().setNum(GlobalConfig->currentProfile->getConnectionType()) ), KVpncConfig::debug );

					if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
					{
						type = "vpnc";
						bin = "vpnc";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
					{
						type = "ciscovpnc";
						bin = "vpnclient";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
					{
						type = "ipsec";
						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";
						this->ExportOpenvpnProfileAction->setEnabled ( TRUE );
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
					{
						type = "l2tpd (racoon)";
						bin = "racoon, l2tpd | xl2tpd";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
					{
						type = "l2tpd (ipsec)";
						bin = "ipsec, l2tpd | xl2tpd";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
					{
						type = "vtun";
						bin = "vtund";
					}
					else
					{
						type = "other";
						bin = "";
					}

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

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

					if ( !GlobalConfig->ToolList->isEmpty() )
					{

						bool UseSmartcardOk=true;
						if ( GlobalConfig->currentProfile->getUseSmartcard() )
						{
							ToolInfo *Pkcs11ToolInfo = Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "pkcs11-tool" );
							if ( Pkcs11ToolInfo->found )
								UseSmartcardOk=true;
							else
								UseSmartcardOk=false;
						}

						if ( type != "pptp" && type != "l2tpd (racoon)" && type != "l2tpd (ipsec)" )
						{
							if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, bin ) != 0 && Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, bin )->found )
							{
								if ( !GlobalConfig->currentProfile->getUseSmartcard() )
								{
									// program is installed
									this->ConnectAction->setEnabled ( TRUE );
									mw->buttonConnect->setEnabled ( TRUE );

									if ( GlobalConfig->KvpncDebugLevel > 2 )
										GlobalConfig->appendLogEntry ( i18n ( "The required daemon (%1) is available, connect will be enabled." ).arg ( bin ), KVpncConfig::info );
								}
								else
								{
									if ( UseSmartcardOk == false )
									{
										this->ConnectAction->setEnabled ( FALSE );
										mw->buttonConnect->setEnabled ( FALSE );
										GlobalConfig->appendLogEntry ( i18n ( "The required helper program (%1) isn't available, connect will be disabled." ).arg ( "pkcs11-tool" ), KVpncConfig::error );
									}
									else
									{
										this->ConnectAction->setEnabled ( TRUE );
										mw->buttonConnect->setEnabled ( TRUE );
										if ( GlobalConfig->KvpncDebugLevel > 2 )
											GlobalConfig->appendLogEntry ( i18n ( "The required daemon (%1) and helper program (%2) is available, connect will be enabled." ).arg ( bin ).arg ( "pkcs11-tool" ), KVpncConfig::info );
									}
								}
							}
							else
							{
								this->ConnectAction->setEnabled ( FALSE );
								mw->buttonConnect->setEnabled ( FALSE );
								GlobalConfig->appendLogEntry ( i18n ( "The required daemon (%1) isn't available, connect will be disabled." ).arg ( bin ), KVpncConfig::error );
							}
						}
						else
						{
							if ( type == "l2tpd (racoon)" )
							{
								bool racoon_and_l2tpd_available = false;
								bool racoon_and_xl2tpd_available = false;
								if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "racoon" )->found)
								{
									if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "l2tpd" )->found)
										racoon_and_l2tpd_available = true;
									if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "xl2tpd" )->found)
										racoon_and_xl2tpd_available = true;
								}
								if ( racoon_and_l2tpd_available )
								{
									// programs are installed
									if ( GlobalConfig->KvpncDebugLevel > 2 )
										GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) are available, connect will be enabled." ).arg ( "racoon" ).arg ( "l2tpd" ), KVpncConfig::info );

									this->ConnectAction->setEnabled ( TRUE );
									mw->buttonConnect->setEnabled ( TRUE );
								}
								if ( racoon_and_xl2tpd_available )
								{
									// programs are installed
									if ( GlobalConfig->KvpncDebugLevel > 2 )
										GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) are available, connect will be enabled." ).arg ( "racoon" ).arg ( "xl2tpd" ), KVpncConfig::info );

									this->ConnectAction->setEnabled ( TRUE );
									mw->buttonConnect->setEnabled ( TRUE );
								}
								if ( racoon_and_l2tpd_available==false &&  racoon_and_xl2tpd_available==false )
								{
									GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) are not available, connect will be disabled." ).arg ( "racoon" ).arg ( "l2tpd/xl2tpd" ), KVpncConfig::error );
								}
							}
							if ( type == "l2tpd (ipsec)" )
							{
								bool ipsec_and_l2tpd_available = false;
								bool ipsec_and_xl2tpd_available = false;
								if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "ipsec" )->found)
								{
									if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "l2tpd" )->found)
										ipsec_and_l2tpd_available = true;
									if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "xl2tpd" )->found)
										ipsec_and_xl2tpd_available = true;
								}

								QString deamon="";
								if (ipsec_and_l2tpd_available)
									deamon="l2tpd";
								else
									deamon="xl2tpd";
								if ( ipsec_and_l2tpd_available || ipsec_and_xl2tpd_available )
								{
									if ( !GlobalConfig->currentProfile->getUseSmartcard() )
									{
										
										// programs are installed
										if ( GlobalConfig->KvpncDebugLevel > 2 )
											GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) are available, connect will be enabled." ).arg ( "ipsec" ).arg ( deamon ), KVpncConfig::info );

										this->ConnectAction->setEnabled ( TRUE );
										mw->buttonConnect->setEnabled ( TRUE );
									}
									else
									{
										if ( GlobalConfig->currentProfile->getUseSmartcard() )
										{
											if ( UseSmartcardOk == false )
											{
												this->ConnectAction->setEnabled ( FALSE );
												mw->buttonConnect->setEnabled ( FALSE );
												GlobalConfig->appendLogEntry ( i18n ( "The required helper program (%1) isn't available, connect will be disabled." ).arg ( "pkcs11-tool" ), KVpncConfig::error );
											}
											else
											{
												this->ConnectAction->setEnabled ( TRUE );
												mw->buttonConnect->setEnabled ( TRUE );
												if ( GlobalConfig->KvpncDebugLevel > 2 )
													GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) and helper program (%3) is available, connect will be enabled." ).arg ( "ipsec" ).arg ( deamon ).arg ( "pkcs11-tool" ), KVpncConfig::info );
											}
										}
									}
								}
								else
								{
									GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) are not available, connect will be disabled." ).arg ( "ipsec" ).arg ( "l2tpd/xl2tpd" ), KVpncConfig::error );
								}
							}
							if ( type == "pptp" )
							{
								bool pppd_and_pptp_available = false;
								if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "pppd" )->found)
								{
									if (Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "pptp" )->found)
										pppd_and_pptp_available = true;
								}
								if ( pppd_and_pptp_available )
								{
									// programs are installed
									if ( GlobalConfig->KvpncDebugLevel > 2 )
										GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 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 daemons (%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 IP;
	if (GlobalConfig->showInterfaceIPinTooltip)
	{
		if ( TunnelInterfaceIP.isEmpty() )
		{
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
			{
				NetworkInterface iface ( GlobalConfig, parent );
				TunnelInterfaceIP = iface.getInterfaceIP ( OpenvpnDevice );
			}
			// 		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon ) {
			// 			NetworkInterface iface( GlobalConfig, parent );
			//
			// 			//FIXME
			// 			TunnelInterfaceIP = iface.getInterfaceIP( "ppp0" );
			// 		}
		}
	
		IP = TunnelInterfaceIP;
		if ( IP.isEmpty() )
			IP = "none";
	}
	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 Username="";

	if (!GlobalConfig->currentProfile->getUserName().isEmpty())
		Username = GlobalConfig->currentProfile->getUserName();
	else
		Username = GlobalConfig->TmpUsername;

	if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
	{
		TypeString =  i18n("Cisco (free)");
		StatusMsg = i18n ( "Connected: %2@%1, [%3], %4" ).arg ( Username ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( TypeString ).arg ( durationString );
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
	{
		TypeString = i18n("Cisco (propritary)");
		StatusMsg = i18n ( "Connected: %2@%1, [%3], %4" ).arg ( Username ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( TypeString ).arg ( durationString );
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp )
	{
		TypeString =  i18n("PPTP");
		StatusMsg = i18n ( "Connected: %2@%1 [%3], %4" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( TypeString ).arg ( durationString );
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan ||
	          (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() == true) ||
	          GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon ||
	          GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon ||
	          GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan
	        )
	{
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			TypeString =  i18n("*S/WAN");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			TypeString =  i18n("racoon");
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
		{
			TypeString =  i18n("L2TP (racoon)");
			StatusMsg = i18n ( "Connected: %2@%1 [%3], %4" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( TypeString ).arg ( durationString );
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
		{
			TypeString = IpsecType;
			StatusMsg = i18n ( "Connected: %2@%1 [%3], %4" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( TypeString ).arg ( durationString );
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		{
			TypeString =  i18n("OpenVPN");
			StatusMsg = i18n ( "Connected: %2@%1 [%3], %4" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( TypeString ).arg ( durationString );
		}

	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
	{
		TypeString =  i18n("OpenVPN");
		StatusMsg = i18n ( "Connected: %1, [%2], %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( TypeString ).arg ( durationString );
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
	{
		TypeString =  i18n("Vtun");
		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 || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
		ToolTipMsg += i18n ( "IPSec ID: %1\n" ).arg ( GlobalConfig->currentProfile->getID() );

	if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp ||
	        GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan ||
	        ( 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 ( GlobalConfig->TmpUsername );

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

	if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn && GlobalConfig->currentProfile->getUseHttpProxy() )
	{
		ToolTipMsg += i18n ( "HTTP proxy: %1:%2\n" ).arg ( GlobalConfig->currentProfile->getHttpProxy() ).arg ( QString().setNum ( GlobalConfig->currentProfile->getHttpProxyPort() ) );
		if ( GlobalConfig->currentProfile->getUseHttpProxyAuth() )
		{
			ToolTipMsg += i18n ( "HTTP proxy type: %1\n" ).arg ( GlobalConfig->currentProfile->getHttpProxyAuthType().upper() );
			ToolTipMsg += i18n ( "HTTP proxy user: %1\n" ).arg ( GlobalConfig->currentProfile->getHttpProxyUser() );
		}
	}

	if (GlobalConfig->showConnectionTimeInTooltip)
		ToolTipMsg += i18n ( "Duration: %1\n" ).arg ( durationString );

	QToolTip::add ( KVpncDock, ToolTipMsg );


	if (!isHidden())
		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;
	}
	}
	*/
// 	if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
// 	{
// 		int connecttime_seconds = sec + min * 60 + hour * 60 * 60;
// 		int PeerTimeout = GlobalConfig->currentProfile->getPeerTimeout();
// 		if ( PeerTimeout > 0 && connecttime_seconds > PeerTimeout )
// 		{
// 			GlobalConfig->appendLogEntry ( i18n ( "Peer timeout value (%1 s) reached. Reconnecing..." ).arg ( PeerTimeout ), GlobalConfig->info );
// 			disconnectClicked();
// 			sleep ( 2 );
// 			connectClicked();
// 		}
// 	}
}

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 = "";
		QString DeamonString = "";

		QString Username = GlobalConfig->currentProfile->getUserName();

		if (Username.isEmpty())
			Username=GlobalConfig->TmpUsername;

		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 || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
		{
			if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
			{
				TypeString = i18n("Cisco (free)");
				DeamonString = "vpnc";
			}
			else
			{
				TypeString =  i18n("Cisco (propritary)");
				DeamonString = "vpnclient";
			}
			if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk)
			{
				ToolTipMsg = i18n ( "\nstatus: connected\nserver: %1\nuser: %2\nIPSec ID: %3\nduration: %4\nprofile: %5" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( GlobalConfig->currentProfile->getUserName() ).arg ( GlobalConfig->currentProfile->getID() ).arg ( durationString ).arg ( GlobalConfig->currentProfile->getName() ) + " [" + TypeString + "]";

				ConnectMsg = i18n ( "Connected: %2@%1, %3 [%4]" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( durationString ).arg ( TypeString );

				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 ) ) + " [" + TypeString + "]";
			}
			if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert)
			{
				ToolTipMsg = i18n ( "\nstatus: connected\nserver: %1\nuser: %2\nIPSec ID: %3\nduration: %4\nprofile: %5" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( durationString ).arg ( GlobalConfig->currentProfile->getName() ) + " [" + TypeString + "]";

				ConnectMsg = i18n ( "Connected: %2@%1, %3 [%4]" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( durationString ).arg ( TypeString );

				LogMsg = i18n ( "Successful connected to server: \"%1\", user: \"%2\" at %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( QDateTime::currentDateTime().toString ( Qt::TextDate ) ) + " [" + TypeString + "]";
			}
		}


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

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

			QString TypeString2 = " [" + i18n ( "%1" ).arg ( TypeString ) + QString ( "]" );
			LogMsg = i18n ( "Successful connected to server \"%1\"\nuser: \"%2\" at %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( QString ( QDateTime::currentDateTime().toString ( Qt::TextDate ) ) + TypeString2 );
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
		{
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
			{
				TypeString =  i18n("racoon");
				DeamonString = "racoon";
				ConnectMsg = i18n ( "Policy was successful activated, daemon (%1) is running and tunnel is up." ).arg ( DeamonString );
			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			{
				TypeString = IpsecType; // openswan, strongswan, ...
				DeamonString = "ipsec";
				ConnectMsg = i18n ( "Policy was successful activated and daemon (%1) is running." ).arg ( DeamonString );
			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
			{
				TypeString =  i18n("L2TP (racoon)");
				if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
					DeamonString = "racoon, xl2tpd";
				else
					DeamonString = "racoon, l2tpd";
				ToolTipMsg = i18n ( "status: connected\nserver: %1\nuser: %2\nduration: %3\nprofile %4" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( durationString ).arg ( GlobalConfig->currentProfile->getName() ) + " [" + TypeString + "]";

				ConnectMsg = i18n ( "Connected: %2@%1, %3 [%4]" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( durationString ).arg ( TypeString );
			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
			{
				TypeString = IpsecType;
				if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
					DeamonString = "ipsec, xl2tpd";
				else
					DeamonString = "ipsec, l2tpd";
				ToolTipMsg = i18n ( "status: connected\nserver: %1\nuser: %2\nduration: %3\nprofile %4" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( Username ).arg ( durationString ).arg ( GlobalConfig->currentProfile->getName() ) + " [" + TypeString + "]";

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

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

		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		{
			TypeString =  i18n("OpenVPN");
			DeamonString = "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() + " [" + TypeString + "]" );

			LogMsg = i18n ( "Successful connected to server \"%1\" at %2, profile \"%3\"" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( QDateTime::currentDateTime().toString ( Qt::TextDate ) ).arg ( GlobalConfig->currentProfile->getName() ) + " [" + TypeString + "]";
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
		{
			TypeString =  i18n("Vtun");
			DeamonString = "vtun";
			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() + " [" + TypeString + "]" );

			LogMsg = i18n ( "Successful connected to server \"%1\" at %2, profile \"%3\"" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( QDateTime::currentDateTime().toString ( Qt::TextDate ) ).arg ( GlobalConfig->currentProfile->getName() ) + " [" + TypeString + "]";
		}

		KVpncDock->setStatus ( connected );
		GlobalConfig->status = GlobalConfig->connected;
		statusColorLabel->setPixmap ( *connectedStatusPixmap );
		mw->buttonConnect->setEnabled ( false );
		mw->buttonDisconnect->setEnabled ( true );
		mw->SessionCombo->setEnabled ( false );
		ConnectAction->setEnabled ( false );
		DisconnectAction->setEnabled ( true );
		PreferencesAction->setEnabled ( false );
		ProfileManagerAction->setEnabled ( false );
		NewProfileWizardAction->setEnabled ( false );
		PrefAction ->setEnabled ( false );

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

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

		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 );
		GlobalConfig->status = GlobalConfig->connecting;
		mw->SessionCombo->setEnabled ( false );
		PreferencesAction->setEnabled ( false );
		ProfileManagerAction->setEnabled ( false );
		NewProfileWizardAction->setEnabled ( false );
		PrefAction ->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 );
		PreferencesAction->setEnabled ( true );
		ProfileManagerAction->setEnabled ( true );
		NewProfileWizardAction->setEnabled ( true );
		PrefAction ->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 );

		if ( prevConnectionState == GlobalConfig->connected )
			KNotifyClient::event ( topLevelWidget() ->winId(), i18n ( "Connection finished" ), i18n ( "Connection \"%1\" finished" ).arg ( GlobalConfig->currentProfile->getName() ) );
		else if ( prevConnectionState == GlobalConfig->connecting )
			KNotifyClient::event ( topLevelWidget() ->winId(), i18n ( "Connect try canceled" ), i18n ( "Connect try to \"%1\" canceled" ).arg ( GlobalConfig->currentProfile->getName() ) );
	}
}

void KVpnc::importKvpncSettingsClicked()
{
	QString filename = KFileDialog::getOpenFileName(QString("."), QString("*.xml *.kvpnc"), 0,i18n ( "KVpnc settings import"));
	
	if ( !filename.isEmpty() )
	{
		bool ret = GlobalConfig->importKvpncConfig(filename);
		if (ret == true)
		{
			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() );
			}
			if ( !mw->SessionCombo->isEnabled() )
				mw->SessionCombo->setEnabled ( TRUE );

			this->ConnectAction->setEnabled ( true );

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

		}

	}
}

void KVpnc::exportKvpncSettingsClicked()
{
	QString filename = KFileDialog::getOpenFileName(QString("."), QString("*.xml *.kvpnc"), 0,i18n ( "KVpnc settings export"));
	
	if ( !filename.isEmpty() )
	{
		GlobalConfig->exportKvpncConfig(filename);
// 		KMessageBox::information( 0, i18n( "Export was successful." ), i18n( "Export success" ) );
	}
}

void KVpnc::importProfileClicked ( QString file )
{

	ImportProfileDialog dlg ( GlobalConfig, this, i18n ( "Import profile" ), file );
	dlg.exec();
	dlg.resize ( 800, dlg.height() );

	bool importOK = dlg.importOk;
	bool ok = false;
	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:" ), QString ( account->getName() + "_2" ), &ok ) );


				}
				nameOk = true;
			}
			nameOk = true;
		}

		if ( 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;
		}
		else
		{
			KMessageBox::information ( 0, i18n ( "Import was canceled." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Import was canceled." ), GlobalConfig->info );
			slotStatusMsg ( i18n ( "Import was canceled." ), ID_FLASH_MSG );
		}
	}
}

void KVpnc::importProfileClicked()
{
	importProfileClicked ( "" );
}

void KVpnc::importOpenvpnProfileClicked()
{
	importOpenvpnProfileClicked ( "" );
}

void KVpnc::importOpenvpnProfileClicked ( QString file )
{

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

		VpnAccountData * it;
		bool nameOk = false;
		bool ok = true;
		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" ) );

					QString newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( account->getName() + "_2" ), &ok );
					if ( ok == false )
					{
						KMessageBox::information ( 0, i18n ( "Import was canceled." ) );
						GlobalConfig->appendLogEntry ( i18n ( "Import was canceled." ), GlobalConfig->info );
						slotStatusMsg ( i18n ( "Import was canceled." ), ID_FLASH_MSG );
						return ;
					}
					else
					{
						it = GlobalConfig->AccountList->first();
						account->setName ( newName );
						nameOk = true;
					}
				}
				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::importIpsecProfileClicked ()
{
	QString filename = KFileDialog::getOpenFileName(QString("."), QString("*.ipsec *.conf"), 0,i18n ( "Ipsec settings import"));
	
	if ( !filename.isEmpty() )
	{
		bool ret = GlobalConfig->importIpsecConfig (filename);
		if (ret == true)
		{
			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() );
			}
			if ( !mw->SessionCombo->isEnabled() )
				mw->SessionCombo->setEnabled ( TRUE );

			this->ConnectAction->setEnabled ( true );

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

		}

	}

}

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

void KVpnc::addRouteRacoon()
{

	// 	if ( ConnectProcess->normalExit () )
	{
		// 		disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( addRouteRacoon() ) );
		// 		disconnect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoon_helper() ) );
		// 		disconnect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoon_helper() ) );


		tmpPath = locateLocal ( "data", "kvpnc/" );
		QString RacoonRouteSetScript = tmpPath + "/set_route." + GlobalConfig->currentProfile->getName() + ".sh";
		NetworkInterface iface ( GlobalConfig, parent );
		QString defaultinterface = iface.getDefaultInterface();
		QString dev = "lo";

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

		tmpInterface = iface.getDefaultInterface();

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

		QFile RacoonSetRouteScript ( RacoonRouteSetScript );
		QTextStream stream ( &RacoonSetRouteScript );
		if ( RacoonSetRouteScript.open ( IO_WriteOnly ) )
		{
			if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
			{
				stream << GlobalConfig->pathToIp << " route show  | grep 'default via' > " + tmpPath + "/defaultroute_before." + GlobalConfig->currentProfile->getName() << "\n";
				stream << GlobalConfig->pathToRoute << " del default" << "\n";

				stream << GlobalConfig->pathToRoute << " add default gw " << GlobalConfig->currentProfile->getGateway() << " " << iface.getDefaultInterface() << "\n";
			}
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
				stream << GlobalConfig->pathToRoute << " add -net " << RemoteNet << " " << dev << "\n";
			RacoonSetRouteScript.close();

			RouteProcess = new QProcess ( this );
			RouteProcess->addArgument ( GlobalConfig->InterpreterShell );
			RouteProcess->addArgument ( RacoonRouteSetScript );

			connect ( RouteProcess, SIGNAL ( readyReadStdout () ), this, SLOT ( readFromStdout_route() ) );
			connect ( RouteProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_route() ) );

			if ( !RouteProcess->start(env) )
			{
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "route (racoon)" ) );
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "route (racoon)" ) , GlobalConfig->error );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
				{
					if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
						GlobalConfig->appendLogEntry ( i18n ( "route (%1): route add default gw " ).arg ( "racoon" ) + GlobalConfig->currentProfile->getGateway() + " " + tmpInterface, GlobalConfig->debug );
					if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
						GlobalConfig->appendLogEntry ( i18n ( "route (%1): route add -net " ).arg ( "racoon" ) + RemoteNet + " " + tmpInterface, GlobalConfig->debug );
				}
			}
		}
	}
}

void KVpnc::delRouteRacoon()
{

	// 	if ( DisconnectProcess != 0 )
	{
		disconnect ( DisconnectProcess, SIGNAL ( processExited () ), this, SLOT ( delRouteRacoon() ) );

		tmpPath = locateLocal ( "data", "kvpnc/" );
		QString RacoonRouteSetScript = tmpPath + "/remove_route." + GlobalConfig->currentProfile->getName() + ".sh";
		NetworkInterface iface ( GlobalConfig, parent );
		QString dev = "lo";

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

		tmpInterface = iface.getDefaultInterface();

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

		QFile RacoonSetRouteScript ( RacoonRouteSetScript );
		QTextStream stream ( &RacoonSetRouteScript );
		if ( RacoonSetRouteScript.open ( IO_WriteOnly ) )
		{
			if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
			{
				stream << GlobalConfig->pathToRoute << " del default" << "\n";
				stream << GlobalConfig->pathToIp << " route add `cat " + tmpPath + "/defaultroute_before." + GlobalConfig->currentProfile->getName() << "`" << "\n";
			}
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
				stream << GlobalConfig->pathToRoute << " del -net " << RemoteNet << " " << dev << "\n";
			RacoonSetRouteScript.close();

			RouteProcess = new QProcess ( this );
			RouteProcess->addArgument ( GlobalConfig->InterpreterShell );
			RouteProcess->addArgument ( RacoonRouteSetScript );

			connect ( RouteProcess, SIGNAL ( readyReadStdout () ), this, SLOT ( readFromStdout_route() ) );
			connect ( RouteProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_route() ) );
			// 			connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesRacoon() ) );

			if ( !RouteProcess->start(env) )
			{
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "del route (racoon)" ) );
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "del route (racoon)" ) , GlobalConfig->error );

			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
				{
					if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
						GlobalConfig->appendLogEntry ( i18n ( "route (%1): route del default gw " ).arg ( "racoon" ) + GlobalConfig->currentProfile->getGateway() + " " + tmpInterface, GlobalConfig->debug );
					if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
						GlobalConfig->appendLogEntry ( i18n ( "route (%1): route del -net " ).arg ( "racoon" ) + 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(env) )
	{
		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" ) );
		IptablesProcess = new QProcess ( this );
		IptablesProcess->addArgument ( GlobalConfig->InterpreterShell );
		IptablesProcess->addArgument ( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_racoon.sh" );

		// 		connect( IptablesProcess, SIGNAL( processExited () ), this, SLOT( doRacoon() ) );

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

void KVpnc::doTailRacoonLog()
{



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

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

	if ( !RacoonTailProcess->start(env) )
	{
		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 );

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "Policy was successful activated and daemon (%1) is running, waiting for coming up tunnel..." ).arg ( "racoon" ), GlobalConfig->debug );



		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
		{
			sleep ( 5 );

			//     /* first: kick up the tunnel */
			putenv ( ( char* ) ( "LC_ALL=C" ) );
			PingProcess = new QProcess ( this );
			QString PathToPing = "";
			ToolInfo* Tool = Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "ping" );
			PathToPing = Tool->PathToExec;

			PingProcess->addArgument ( PathToPing );
			// 		PingProcess->addArgument( "/bin/ping" );
			//PingProcess->addArgument( "-b" );
			PingProcess->addArgument ( "-c" );
			PingProcess->addArgument ( "1" );

			// FIXME ipv4 specific, problematic with specical netmask: 192.168.5.0 -> 192.168.5.1
			QString IPforKickup = GlobalConfig->currentProfile->getRemoteNetAddr().section ( '.', 0, 2 ) + ".1";
			PingProcess->addArgument ( IPforKickup );

			// 		connect( PingProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_ping() ) );
			// 		connect( PingProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_ping() ) );

			if ( !PingProcess->start(env) )
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ping -c1 " + IPforKickup ) );
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( i18n ( "ping for kick up the tunnel (%1)..." ).arg ( IPforKickup ) ).arg ( "racoon" ), GlobalConfig->debug );
			}
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
		{
			start_l2tpd();
		}
		// 		else
		// 		{
		// 			// 			disconnectClicked();
		// 		}
		// 		GlobalConfig->appendLogEntry( "[racoon] " + i18n( "Connection established." ), GlobalConfig->success );
		//
		// 		sec = hour = min = 0;
		//
		// 		GlobalConfig->status = GlobalConfig->connected;
		//
		// 		connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
		// 		durationTimer.start( 1000, FALSE );
		// 		setGuiStatus( connected );
		//
		//		setFirewallAfterConnect();
		// 		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(env) )
		{
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "racoon" ) );
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "racoon" ) , GlobalConfig->error );
			disconnectClicked();
		}
		else
		{
			racoon_tunnel_state = 0;
			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::doTailIpsecLog()
{

	putenv ( ( char* ) ( "LC_ALL=C" ) );
	IpsecTailProcess = new QProcess ( this );
	IpsecTailProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
	IpsecTailProcess->addArgument ( "tail" );
	IpsecTailProcess->addArgument ( "-n" );
	IpsecTailProcess->addArgument ( "100" );
	IpsecTailProcess->addArgument ( "-f" );
	IpsecTailProcess->addArgument ( tmpPath + "ipsec." + GlobalConfig->currentProfile->getName() + ".log" );

	connect ( IpsecTailProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readOutputFromTail_ipsec() ) );

	if ( !IpsecTailProcess->start(env) )
	{
		KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "tail -f " + tmpPath + "ipsec." + GlobalConfig->currentProfile->getName() + ".log" ) );
		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "tail -f " + tmpPath + "ipsec." + GlobalConfig->currentProfile->getName() + ".log" ) , GlobalConfig->error );
		disconnectClicked();
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "tail -f " + tmpPath + "ipsec." + GlobalConfig->currentProfile->getName() + ".log" ), GlobalConfig->debug );

		else
		{
			// 			disconnectClicked();
		}
	}
}

void KVpnc::removeIptablesRacoon()
{
	// 	if ( DisconnectProcess != 0 )
	{
		// 		if ( DisconnectProcess )
		// 			disconnect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesRacoon() ) );

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

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

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

	// 	connect( RemoveSetkeyProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_remove_setkey() ) );
	// 	connect( RemoveSetkeyProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_remove_setkey() ) );
	// 	connect( RemoveSetkeyProcess, SIGNAL( processExited () ), this, SLOT( delRouteRacoon() ) );

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

	// 	connectionEnded();
}

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 = new QProcess ( this );
		ConnectProcess->addArgument ( GlobalConfig->InterpreterShell );
		ConnectProcess->addArgument ( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh" );

		if ( !ConnectProcess->start(env) )
		{
			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" ).arg ( GlobalConfig->currentProfile->getName() ), GlobalConfig->debug );

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

void KVpnc::addRouteIpsec()
{
	tmpPath = locateLocal ( "data", "kvpnc/" );
	QString IpsecRouteSetScript = tmpPath + "/set_route." + GlobalConfig->currentProfile->getName() + ".sh";
	NetworkInterface iface ( GlobalConfig, parent );
	QString defaultinterface = iface.getDefaultInterface();
	QString dev = "lo";

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

	if ( iface.interfaceExist ( "ipsec0" ) )
		tmpInterface = "ipsec0";
	else
		tmpInterface = iface.getDefaultInterface();

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

	QFile IpsecSetRouteScript ( IpsecRouteSetScript );
	QTextStream stream ( &IpsecSetRouteScript );
	if ( IpsecSetRouteScript.open ( IO_WriteOnly ) )
	{
		if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
		{
			stream << GlobalConfig->pathToIp << " route show  | grep 'default via' > " + tmpPath + "/defaultroute_before." + GlobalConfig->currentProfile->getName() << "\n";
			stream << GlobalConfig->pathToRoute << " del default" << "\n";

			stream << GlobalConfig->pathToRoute << " add default gw " << GlobalConfig->currentProfile->getGateway() << " " << iface.getDefaultInterface() << "\n";
		}
		// 					stream << GlobalConfig->pathToRoute << " add -net " << RemoteNet << " " << dev << "\n"; // set by opnswan
		IpsecSetRouteScript.close();

		RouteProcess = new QProcess ( this );
		RouteProcess->addArgument ( GlobalConfig->InterpreterShell );
		RouteProcess->addArgument ( IpsecRouteSetScript );

		connect ( RouteProcess, SIGNAL ( readyReadStdout () ), this, SLOT ( readFromStdout_route() ) );
		connect ( RouteProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_route() ) );

		if ( !RouteProcess->start(env) )
		{
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "route (%1)" ).arg ( IpsecType ) );
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "route (%1)" ).arg ( IpsecType ) , GlobalConfig->error );
			// 			disconnectClicked();
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
			{
				if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
					GlobalConfig->appendLogEntry ( i18n ( "route (%1): route add default gw " ).arg ( "ipsec" ) + GlobalConfig->currentProfile->getGateway() + " " + tmpInterface, GlobalConfig->debug );
				// 							GlobalConfig->appendLogEntry ( i18n( "route (%1): route add -net " ).arg("ipsec") + RemoteNet << " " + tmpInterface, GlobalConfig->debug );
			}
		}
	}
}

void KVpnc::delRouteIpsec()
{
	tmpPath = locateLocal ( "data", "kvpnc/" );
	QString IpsecRouteSetScript = tmpPath + "/remove_route." + GlobalConfig->currentProfile->getName() + ".sh";
	NetworkInterface iface ( GlobalConfig, parent );
	QString dev = "lo";

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

	if ( iface.interfaceExist ( "ipsec0" ) )
		tmpInterface = "ipsec0";
	else
		tmpInterface = iface.getDefaultInterface();

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

	QFile IpsecSetRouteScript ( IpsecRouteSetScript );
	QTextStream stream ( &IpsecSetRouteScript );
	if ( IpsecSetRouteScript.open ( IO_WriteOnly ) )
	{
		stream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
		if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
		{
			stream << GlobalConfig->pathToRoute << " del default" << "\n";
			stream << GlobalConfig->pathToIp << " route add `cat " + tmpPath + "/defaultroute_before." + GlobalConfig->currentProfile->getName() << "`" << "\n";
		}

		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
			stream << GlobalConfig->pathToRoute << " del -net " << RemoteNet << " " << dev << "\n";
		IpsecSetRouteScript.close();

		RouteProcess = new QProcess ( this );
		RouteProcess->addArgument ( GlobalConfig->InterpreterShell );
		RouteProcess->addArgument ( IpsecRouteSetScript );

		connect ( RouteProcess, SIGNAL ( readyReadStdout () ), this, SLOT ( readFromStdout_route() ) );
		connect ( RouteProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_route() ) );

		if ( !RouteProcess->start(env) )
		{
			// 			KMessageBox::error( this, i18n( "\"%1\" start failed!" ).arg( "del route ("+IpsecType+")" ) );
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "del route (" + IpsecType + ")" ) , GlobalConfig->error );
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "route (ipsec): route del started." ), GlobalConfig->debug );
		}
	}
}

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

		putenv ( ( char* ) ( "LC_ALL=C" ) );
		DisconnectProcess = new QProcess ( this );
		DisconnectProcess->addArgument ( GlobalConfig->InterpreterShell );
		DisconnectProcess->addArgument ( tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh" );
		if ( !DisconnectProcess->start(env) )
		{
			// 			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 );
		}
	}
}

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(env) )
	{
		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(env) )
		{
			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(env);
		}
	}
}

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( GlobalConfig->InterpreterShell );
	//   ConnectProcess->addArgument( VpncConnectScript );
	//
	//   connect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readOutputFrom_vpnc() ) );
	//
	//   if ( !ConnectProcess->start(env) ) {
	//    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::ipsecStarted()
{
	disconnect ( IpsecProcess, SIGNAL ( processExited () ), this, SLOT ( ipsecStarted() ) );


	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Starting connection \"%1\"..." ).arg ( GlobalConfig->currentProfile->getName() ) , GlobalConfig->debug );

	/* Kick up the connection */
	IpsecProcess = new QProcess ( this );
	//
	IpsecProcess->addArgument ( GlobalConfig->pathToFreeswan );
	IpsecProcess->addArgument ( "auto" );
	// 	if ( GlobalConfig->enableFreeswanVerbose )
	// 		IpsecProcess->addArgument( "--verbose" );
	IpsecProcess->addArgument ( "--up" );
	IpsecProcess->addArgument ( GlobalConfig->currentProfile->getName() );


	connect ( IpsecProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStderr_ipsec() ) );
	connect ( IpsecProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsec() ) );
	// 			connect( IpsecProcess, SIGNAL( processExited () ), this, SLOT( doRouteFreeswan() ) );

	if ( !IpsecProcess->start(env) )
	{
		KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ipsec: connection" ) );
		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ipsec: connection" ) , GlobalConfig->error );
		// 		disconnectClicked();
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "ipsec: connection" ) , GlobalConfig->debug );
	}
}

void KVpnc::pppdStarted()
{
// 	disconnect ( PptpProcess, SIGNAL( processExited () ), this, SLOT( pppdStarted() ) );
// 	disconnect ( pppdUpProcess, SIGNAL ( processExited () ), this, SLOT ( pppdStarted() ) );

// 	if ( GlobalConfig->KvpncDebugLevel > 0 )
// 		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( "PppdUpScript" ), GlobalConfig->debug );

}

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(env) )
	{
		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...

			while ( userID.left ( 1 ) == " " )
				userID = userID.right ( userID.length() - 1 );

		}
		else
		{
			issuerID = ProcessMsg.section ( '=', 1 ); // issuer= /C=DE... => /C=DE...
			while ( issuerID.left ( 1 ) == " " )
				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::manageCiscoCertClicked()
{
	ManageCiscoCert dlg ( this, i18n ( "Manage Cisco certificates..." ).ascii(), GlobalConfig );
	//int result =
	dlg.exec();
}

void KVpnc::enrollCiscoCertClicked()
{
	CiscoCertificateEnrollment dlg ( this, i18n ( "Enroll certificate..." ).ascii(), GlobalConfig );
	//int result =
	dlg.exec();
}

void KVpnc::showProfileManagerClicked()
{
	showProfilesOnly=true;
	slotSettings();
}

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 ( GlobalConfig->InterpreterShell );
			CmdBeforeConnectProcess->addArgument ( CmdBeforeConnectScript );

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Executing command before connect:\n%1" ).arg ( cmd ), GlobalConfig->debug );
			if ( !CmdBeforeConnectProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( CmdBeforeConnectScript ) );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "CmdBeforeConnectScript" ), GlobalConfig->debug );
				while ( CmdBeforeConnectProcess->isRunning() )
					parent->QApplication::processEvents();

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( "CmdBeforeConnectScript" ), GlobalConfig->debug );
			}
		}
		else
		{
			// file could not written
		}
	}
}

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 ( GlobalConfig->InterpreterShell );
			CmdAfterConnectProcess->addArgument ( CmdAfterConnectScript );


			if ( GlobalConfig->KvpncDebugLevel > 2 )
			{
				disconnect ( CmdAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_CmdAfterConnect() ) );
				disconnect ( CmdAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_CmdAfterConnect() ) );
				connect ( CmdAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_CmdAfterConnect() ) );
				connect ( CmdAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_CmdAfterConnect() ) );
			}

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Sleeping %1s before executing command after connect..." ).arg ( QString().setNum(GlobalConfig->currentProfile->getCommandAfterConnectDelayTime()) ), GlobalConfig->debug );
			sleep(GlobalConfig->currentProfile->getCommandAfterConnectDelayTime());

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Executing command after connect:\n%1" ).arg ( cmd ), GlobalConfig->debug );
			if ( !CmdAfterConnectProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( CmdAfterConnectScript ) );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "CmdAfterConnectScript" ), GlobalConfig->debug );
				while ( CmdAfterConnectProcess->isRunning() )
					parent->QApplication::processEvents();

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( "CmdAfterConnectScript" ), GlobalConfig->debug );
			}

		}
		else
		{
			// file could not written
		}

	}
}

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 ) )
		{
			file.close();
		
		

			CmdBeforeDisconnectProcess = new QProcess ( this );
			CmdBeforeDisconnectProcess->addArgument ( GlobalConfig->InterpreterShell );
			CmdBeforeDisconnectProcess->addArgument ( CmdBeforeDisconnectScript );

			if ( !CmdBeforeDisconnectProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( CmdBeforeDisconnectScript ) );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "CmdBeforeDisconnectScript" ) , GlobalConfig->debug );
				while ( CmdBeforeDisconnectProcess->isRunning() )
				{
					usleep ( 500 );
					// 				parent->QApplication::processEvents();
				}
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( "CmdBeforeDisconnectScript" ), GlobalConfig->debug );
			}

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Executing command before disconnect:\n%1" ).arg ( cmd ), GlobalConfig->debug );
		}
		else
		{
			// file could not written
		}
	}
}

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 ( GlobalConfig->InterpreterShell );
			CmdAfterDisconnectProcess->addArgument ( CmdAfterDisconnectScript );

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Executing command after disconnect:\n%1" ).arg ( cmd ), GlobalConfig->debug );
			if ( !CmdAfterConnectProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( CmdAfterDisconnectScript ) );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "CmdAfterDisconnectScript" ), GlobalConfig->debug );
				while ( CmdAfterDisconnectProcess->isRunning() )
				{
					usleep ( 500 );
					// 				parent->QApplication::processEvents();
				}

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( "CmdAfterDisconnectScript" ), GlobalConfig->debug );
			}
		}
		else
		{
			// file could not written
		}
	}
}

void KVpnc::setFirewallAfterConnect()
{
		
		// write firewall after connect script
		QString SetFirewallAfterConnectScript = tmpPath + "firewall_after_connect_script." + GlobalConfig->currentProfile->getName();
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "setFirewallAfterConnectScript: " + SetFirewallAfterConnectScript + "\n", GlobalConfig->debug );
		QFile file ( SetFirewallAfterConnectScript );
		QTextStream stream ( &file );
		if ( file.open ( IO_WriteOnly ) )
		{
			if (GlobalConfig->currentProfile->getFixPathMtuDiscoveryProblem() && Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "iptables" )->found )
			{
				// 	iptables --append FORWARD --protocol tcp --tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu
				// see http://pptpclient.sourceforge.net/howto-diagnosis.phtml#connections_freeze
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n("Insert rule for fixing path MTU discovery problem"), GlobalConfig->debug );

				stream << "\n";
				stream << GlobalConfig->pathToIptables << " --append FORWARD --protocol tcp --tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu" << "\n";
			}
			file.close();

			SetFirewallAfterConnectProcess = new QProcess ( this );
			SetFirewallAfterConnectProcess->addArgument ( GlobalConfig->InterpreterShell );
			SetFirewallAfterConnectProcess->addArgument ( SetFirewallAfterConnectScript );


// 			if ( GlobalConfig->KvpncDebugLevel > 2 )
// 			{
// 				disconnect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_setFirewallAfterConnect() ) );
// 				disconnect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_setFirewallAfterConnect() ) );
// 				connect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_setFirewallAfterConnect() ) );
// 				connect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_setFirewallAfterConnect() ) );
// 			}


// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
// 				GlobalConfig->appendLogEntry ( i18n ( "Set firewall after connect:\n%1" ).arg ( cmd ), GlobalConfig->debug );
			if ( !SetFirewallAfterConnectProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( SetFirewallAfterConnectScript ) );
// 				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "SetFirewallAfterConnectScript" ), GlobalConfig->debug );
				while ( SetFirewallAfterConnectProcess->isRunning() )
				{
					sleep(1);
					parent->QApplication::processEvents();
				}

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( "SetFirewallAfterConnectScript" ), GlobalConfig->debug );
			}

		}
		else
		{
			// file could not written
		}

}

void KVpnc::setFirewallBeforeDisconnect()
{
		// write firewall after connect script
		QString SetFirewallBeforeDisconnect = tmpPath + "firewall_after_connect_script." + GlobalConfig->currentProfile->getName();
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "SetFirewallBeforeDisconnect: " + SetFirewallBeforeDisconnect + "\n", GlobalConfig->debug );
		QFile file ( SetFirewallBeforeDisconnect );
		QTextStream stream ( &file );
		if ( file.open ( IO_WriteOnly ) )
		{
			// see http://pptpclient.sourceforge.net/howto-diagnosis.phtml#connections_freeze
			if (GlobalConfig->currentProfile->getFixPathMtuDiscoveryProblem() && Utils ( GlobalConfig ).getToolInfo ( GlobalConfig, "iptables" )->found )
			{

				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n("Remove rule for fixing path MTU discovery problem"), GlobalConfig->debug );

				stream << "\n";
				stream << GlobalConfig->pathToIptables << " --delete FORWARD --protocol tcp --tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu" << "\n";
			}
			file.close();

			SetFirewallAfterConnectProcess = new QProcess ( this );
			SetFirewallAfterConnectProcess->addArgument ( GlobalConfig->InterpreterShell );
			SetFirewallAfterConnectProcess->addArgument ( SetFirewallBeforeDisconnect );


// 			if ( GlobalConfig->KvpncDebugLevel > 2 )
// 			{
// 				disconnect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_setFirewallBeforeDisconnect() ) );
// 				disconnect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_setFirewallBeforeDisconnect() ) );
// 				connect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_setFirewallBeforeDisconnect() ) );
// 				connect ( SetFirewallAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_setFirewallBeforeDisconnect() ) );
// 			}


// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
// 				GlobalConfig->appendLogEntry ( i18n ( "Set firewall before disconnect:\n%1" ).arg ( cmd ), GlobalConfig->debug );
			if ( !SetFirewallAfterConnectProcess->start(env) )
			{
				KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( SetFirewallBeforeDisconnect ) );
// 				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "setFirewallBeforeDisconnect" ), GlobalConfig->debug );
				while ( SetFirewallAfterConnectProcess->isRunning() )
				{
					sleep(1);
					parent->QApplication::processEvents();
				}

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( "setFirewallBeforeDisconnect" ), GlobalConfig->debug );
			}

		}
		else
		{
			// file could not written
		}

}

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(env) )
	{
		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->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() );
		}

		// 		if ( !GlobalConfig->lastProfile.isEmpty() ) {
		// 		mw->SessionCombo->setCurrentItem( 1 );
		if ( GlobalConfig->currentProfile != 0 )
			sessionToggled ( GlobalConfig->currentProfile->getName() );
		else
			sessionToggled ( GlobalConfig->AccountList->first()->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(GlobalConfig->pathToIfconfig);
	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(env) )
	{
	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();

		int count=1;

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

		NetworkInterface iface ( GlobalConfig, parent );
		QString defaultinterface = iface.getDefaultInterface();


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

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			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 ) )
		{
			stream << "#!"<< GlobalConfig->InterpreterShell << "\n";
			for ( QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end();++it )
			{
				Routes += "\t"+QString().setNum(count)+": ";
				count++;
				QString net = ( *it ).section ( '#', 0, 0 );

				QString Gateway = QString ( *it ).section ( '#', 1, 1 );
				QString GatewayString = "";
				QString Interface = QString ( *it ).section ( '#', 2, 2 );
				QString InterfaceString = "";
				bool extended = false;
				Routes += net;
				if ( !Gateway.isEmpty() && Gateway != "-" )
				{
					GatewayString += "gateway ";
					GatewayString += Gateway;
					Routes +=  " " + i18n ( "over gateway" ) + " " + Gateway + "\n";
					extended = true;
				}
				if ( !Interface.isEmpty() && Interface != "-" )
				{
					InterfaceString += Interface;
					if ( Interface != "default" )
						dev = Interface;
					Routes += " " + i18n ( "over interface" ) + " " + dev + "\n";
					extended = true;
				}
				if ( extended == false )
					Routes += net;
				Routes += "\n";

				if ( net.find ( "/32" ) > 0 )
					stream << GlobalConfig->pathToRoute << " add " << net << GatewayString << " " << dev << "\n";
				else
					stream << GlobalConfig->pathToRoute << " add -net " << net << " " << GatewayString << " " << dev << "\n";

			}
			file.close();
			RouteProcess = new QProcess ( this );
			RouteProcess->addArgument ( GlobalConfig->InterpreterShell );
			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(env) )
			{
				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 > 1 )
				{
					GlobalConfig->appendLogEntry ( i18n ( "Adding the following additional network routes:" ), GlobalConfig->debug );
					GlobalConfig->appendLogEntry ( Routes , GlobalConfig->debug );
				}
				while ( RouteProcess->isRunning() )
				{
					usleep ( 500 );
					// 					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();
		int count=1;

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


		if ( GlobalConfig->KvpncDebugLevel > 1 )
			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 ) )
		{
			stream << "#!"<< GlobalConfig->InterpreterShell << "\n";
			for ( QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end();++it )
			{
				Routes += "\t"+QString().setNum(count)+": ";
				count++;

				QString net = ( *it ).section ( '#', 0, 0 );

				QString Gateway = QString ( *it ).section ( '#', 1, 1 );
				QString GatewayString = "";
				QString Interface = QString ( *it ).section ( '#', 2, 2 );
				QString InterfaceString = "";
				bool extended = false;
				Routes += net;
				if ( !Gateway.isEmpty() && Gateway != "-" )
				{
					GatewayString += "gw ";
					GatewayString += Gateway;
					Routes += " " + i18n ( "over gateway" ) + " " + Gateway + "\n";
					extended = true;
				}
				if ( !Interface.isEmpty() && Interface != "-" )
				{
					InterfaceString += Interface;
					if ( Interface != "default" )
						dev = Interface;
					Routes += " " + i18n ( "over interface" ) + " " + dev + "\n";
					extended = true;
				}
				if ( extended == false )
					Routes += net;

				Routes += "\n";

				if ( net.find ( "/32" ) > 0 )
					stream << GlobalConfig->pathToRoute << " del " << net << GatewayString << " " << dev << "\n";
				else
					stream << GlobalConfig->pathToRoute << " del -net " << net << " " << GatewayString << " " << dev << "\n";

			}
			file.close();
			RouteProcess = new QProcess ( this );
			RouteProcess->addArgument ( GlobalConfig->InterpreterShell );
			RouteProcess->addArgument ( tmpPath + "delAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh" );
			tmpInterface = dev;

			if ( !RouteProcess->start(env) )
			{
				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 > 1 )
				{
					GlobalConfig->appendLogEntry ( i18n ( "Removing the following additional network routes:" ), GlobalConfig->debug );
					GlobalConfig->appendLogEntry ( Routes , GlobalConfig->debug );
				}
				while ( RouteProcess->isRunning() )
				{
					usleep ( 500 );
					parent->processEvents();
				}
			}

		}
	}
}

void KVpnc::showLogViewer()
{
	LogViewerDialog dlg ( this, parent , GlobalConfig, i18n ( "Log Viewer" ),150 );
	LogViewerAction->setChecked ( true );
	dlg.show();
	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->debug );
	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 ( GlobalConfig->InterpreterShell );
	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->getConnectionStatusInterval() ) );
	ConnectionStatusCheckProcess->addArgument ( QString().setNum ( GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount() ) );
	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(env) )
	{
		//KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "ping_check.sh" ) );
		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ping_check.sh" ) , GlobalConfig->error );
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "ping_check.sh" ), GlobalConfig->debug );
	}
}

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 ( GlobalConfig->InterpreterShell );
	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() );
		if ( originalResolvConfFileContent.length() > 0 )
		{
			originalResolvConfFile.close();
			QFile backupOriginalResolvConfFile ( "/etc/resolv.conf" );
			QTextStream stream ( &backupOriginalResolvConfFile );
			if ( backupOriginalResolvConfFile.open ( IO_WriteOnly ) )
			{
				stream << originalResolvConfFileContent;
				backupOriginalResolvConfFile.close();
				originalResolvConfFile.remove();
			}
		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n ( "Warning: %1 has size 0, dont restoring it." ).arg ( "/etc/resolv.conf" ), KVpncConfig::debug );
		}
	}

	// 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 > /dev/null 2>&1\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 ( GlobalConfig->InterpreterShell );
				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() )
					{
						usleep ( 500 );
						// 						parent->processEvents();
					}
				}
				break;
			}
		}
		backupOriginalRouteFile.close();
	}
}

bool KVpnc::backupResolvConf()
{
	bool success=true;
	QString ResolvConfBackupProfile = tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName();

	if ( GlobalConfig->KvpncDebugLevel > 2 )
		GlobalConfig->appendLogEntry ( i18n ( "Backup file of %1: %1" ).arg ( "resolv.conf" ).arg ( ResolvConfBackupProfile ), GlobalConfig->debug );

	QFile ResolvConfBackupProfileFile ( ResolvConfBackupProfile + ".sh" );
	QTextStream ResolvConfBackupProfileStream ( &ResolvConfBackupProfileFile );
	if ( ResolvConfBackupProfileFile.open ( IO_WriteOnly ) )
	{
		ResolvConfBackupProfileStream << "# generated by kvpnc. Do not edit it." << "\n";
		ResolvConfBackupProfileStream << "\n";
		ResolvConfBackupProfileStream << "cat /etc/resolv.conf > " + ResolvConfBackupProfile + "\n";
		ResolvConfBackupProfileFile.close();
		QProcess ResolvConfBackupProfileProcess ( this );
		ResolvConfBackupProfileProcess.addArgument ( GlobalConfig->InterpreterShell );
		ResolvConfBackupProfileProcess.addArgument ( ResolvConfBackupProfile + ".sh" );
		if ( !ResolvConfBackupProfileProcess.start() )
		{
			// 				if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "Backup process of %1 could not be started." ).arg ( "resolv.conf" ), GlobalConfig->error );
			success=false;
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "%1 backup process started." ).arg ( "resolv.conf" ), GlobalConfig->debug );
			while (ResolvConfBackupProfileProcess.isRunning())
			{ 
				// nothing here
			}
		}
	}
	return success;
}

bool KVpnc::restoreResolvConf()
{
	bool success=true;
	QString ResolvConfBackupProfile = tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName();

	if ( GlobalConfig->KvpncDebugLevel > 2 )
		GlobalConfig->appendLogEntry ( i18n ( "Restore file of %1: %1" ).arg ( "resolv.conf" ).arg ( ResolvConfBackupProfile ), GlobalConfig->debug );

	QFile ResolvConfRestoreProfileFile ( ResolvConfBackupProfile + ".sh" );
	QTextStream ResolvConfRestoreProfileStream ( &ResolvConfRestoreProfileFile );
	if ( ResolvConfRestoreProfileFile.open ( IO_WriteOnly ) )
	{
		ResolvConfRestoreProfileStream << "# generated by kvpnc. Do not edit it." << "\n";
		ResolvConfRestoreProfileStream << "\n";
		ResolvConfRestoreProfileStream << "chmod u+w  /etc/resolv.conf" << "\n";
		ResolvConfRestoreProfileStream << "cat " + ResolvConfBackupProfile + " > /etc/resolv.conf\n";
		ResolvConfRestoreProfileFile.close();
		QProcess ResolvConfRestoreProfileProcess ( this );
		ResolvConfRestoreProfileProcess.addArgument ( GlobalConfig->InterpreterShell );
		ResolvConfRestoreProfileProcess.addArgument ( ResolvConfBackupProfile + ".sh" );
		if ( !ResolvConfRestoreProfileProcess.start() )
		{
			// 				if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "Restore process of %1 could not be started." ).arg ( "resolv.conf" ), GlobalConfig->error );
			success=false;
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "Restore process of %1 started." ).arg ( "resolv.conf" ), GlobalConfig->debug );
			while (ResolvConfRestoreProfileProcess.isRunning())
			{ 
				// nothing here
			}
		}
	}

	return success;
}

void KVpnc::showNewProfileWizardClicked()
{
	NewProfileWizard wizard ( GlobalConfig );
	if ( wizard.exec() == QDialog::Accepted && 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;
			bool ok = 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" ) );
						QString newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( account->getName() += "_2" ), &ok );
						if ( ok == false )
						{
							KMessageBox::information ( 0, i18n ( "Import was canceled." ) );
							GlobalConfig->appendLogEntry ( i18n ( "Import was canceled." ), GlobalConfig->info );
							slotStatusMsg ( i18n ( "Import was canceled." ), ID_FLASH_MSG );
							return ;
						}
						else
						{
							it = GlobalConfig->AccountList->first();
							account->setName ( newName );
							nameOk = true;
						}

					}
					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() );
				if ( GlobalConfig->AccountList->at ( i ) ->getName() == account->getName() )
					GlobalConfig->currentProfile = GlobalConfig->AccountList->at ( i );
			}
			mw->SessionCombo->setCurrentText ( account->getName() );
			setProfile ( account->getName() );

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

			this->ConnectAction->setEnabled ( true );
			mw->SessionCombo->setCurrentText ( account->getName() );
			sessionToggled ( account->getName() );
			mw->SessionCombo->setCurrentText ( 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();

			if ( wizard.connectaftercreating )
			{
				if ( wizard.daemonavailable )
				{
					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 daemon is not available, skipping connecting." ).arg ( mw->SessionCombo->currentText() ) , GlobalConfig->debug );
				}
			}
		}
		else
		{
			KMessageBox::information ( 0, i18n ( "Import was unsuccessful." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Import was unsuccessful." ), GlobalConfig->info );
			slotStatusMsg ( i18n ( "Import was unsuccessful." ), ID_FLASH_MSG );
		}
	}
	else
	{
		slotStatusMsg ( i18n ( "Creating new profile canceled." ), ID_FLASH_MSG );
		GlobalConfig->appendLogEntry ( i18n ( "Creating new profile canceled." ), GlobalConfig->info );
	}
}

void KVpnc::exportOpenvpnProfileClicked()
{
	if ( !GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		return ;

	QString filename = KInputDialog::getText ( i18n ( "OpenVPN export" ), i18n ( "Enter filename for export profile %1:" ).arg ( GlobalConfig->currentProfile->getName() ), "", 0, this );
	if ( !filename.isEmpty() )
	{
		// write openvpn.<profile>.conf
		QFile openvpn_file ( filename );
		QTextStream openvpn_stream ( &openvpn_file );
		if ( openvpn_file.open ( IO_WriteOnly ) )
		{
			openvpn_stream << "# generated by kvpnc" << "\n";
			openvpn_stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
			openvpn_stream << "# verbosity" << "\n";
			openvpn_stream << "verb " << GlobalConfig->OpenvpnDebugLevel << "\n\n";

			QString certPath = "/etc/openvpn";
			if ( !GlobalConfig->currentProfile->getCertPath().isEmpty() )
				certPath = GlobalConfig->currentProfile->getCertPath();

			openvpn_stream << "# change to prefix" << "\n";
			openvpn_stream << "cd " << certPath << "\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";

			if ( GlobalConfig->currentProfile->getDisableLzoCompression() == false )
			{
				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";

				if ( GlobalConfig->currentProfile->getUseMssfix() )
				{
					openvpn_stream << "\n";
					openvpn_stream << "# userdefinied packet size" << "\n";
					openvpn_stream << "mssfix " << GlobalConfig->currentProfile->getMssfix() << "\n\n";
				}

				if ( GlobalConfig->currentProfile->getUseFragment() )
				{
					openvpn_stream << "\n";
					openvpn_stream << "# userdefinied packet size for fragmentation" << "\n";
					openvpn_stream << "fragment " << GlobalConfig->currentProfile->getFragment() << "\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 << GlobalConfig->pathToIfconfig << " " << 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 << "# disable ping restart\n";
			openvpn_stream << "ping-restart 0\n";



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

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

			//  					openvpn_stream << "# keepalive\n";
			// //  					openvpn_stream << "keepalive 10000\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";
				QString direction="";
				if (GlobalConfig->currentProfile->getAuthenticationDirection() != "none")
					direction= GlobalConfig->currentProfile->getAuthenticationDirection();
				openvpn_stream << "tls-auth " << GlobalConfig->currentProfile->getTlsAuthFile() << " " << direction << "\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();
		KMessageBox::information ( 0, i18n ( "Export of profile %1 was sucessful." ).arg ( GlobalConfig->currentProfile->getName() ), i18n ( "Export successful" ) );
	}
}

void KVpnc::pptpProcessExited()
{
// 	GlobalConfig->appendLogEntry ( i18n ( "Connection has been terminated." ), GlobalConfig->info );
// 	disconnectClicked();

// 	if (QFile("/sbin/resolvconf").exists() && QFile("/etc/init.d/resolvconf").exists())
// 	{
// 
// 			QFile downfile ( tmpPath + "pptpd." + GlobalConfig->currentProfile->getName() + ".down" );
// 			QTextStream downstream ( &downfile );
// 			if ( downfile.open ( IO_WriteOnly ) )
// 			{
// 				downstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
// 				downstream << "# generated by kvpnc. Do not edit it." << "\n";
// 				downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
// 	
// 				if (QFile("/sbin/resolvconf").exists() && QFile("/etc/init.d/resolvconf").exists())
// 					downstream << "/etc/init.d/resolvconf start\n";
// 				downfile.close();
// 			
// 			QProcess *pppdDownProcess = new QProcess ( this );
// 			pppdDownProcess->addArgument ( GlobalConfig->InterpreterShell );
// 			pppdDownProcess->addArgument ( tmpPath + "pptpd." + GlobalConfig->currentProfile->getName() + ".down" );
// 
// 			if ( !pppdDownProcess->start(env) )
// 			{
// 				KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "PptpdDownScript" ) );
// 			}
// 			else
// 			{
// 
// 			}
// 		}
// 	}
}

void KVpnc::vtun_exited()
{
// 	GlobalConfig->appendLogEntry(i18n("%1 has been exited.").arg("vtund"),GlobalConfig->error);
// 	sleep(2);
// 	if (GlobalConfig->status == GlobalConfig->connecting || GlobalConfig->connected)
// 		disconnectClicked();
}

void KVpnc::prepareL2tpd()
{


	// write l2tpd.conf
	QFile L2tpdConfigFile ( tmpPath + "l2tpd." + GlobalConfig->currentProfile->getName() + ".conf" );
	QTextStream stream ( &L2tpdConfigFile );
	if ( L2tpdConfigFile.open ( IO_WriteOnly ) )
	{
		stream << "[global]" << "\n";

		if ( !LocalIP.isEmpty() )
			stream << "listen-addr = " << LocalIP << "\n";
		// 		stream << "listen-addr = 127.0.0.1" <<"\n";
		stream << "[lac " << GlobalConfig->currentProfile->getName() << "]" << "\n";
		stream << "lns = " << GlobalConfig->currentProfile->getGateway() << "\n";
		stream << "redial = yes" << "\n";
		stream << "redial timeout = 20" << "\n";
		stream << "max redials = 15" << "\n";
		// 				stream << "hidden bit = yes" << "\n";
		stream << "length bit = yes" << "\n";
		stream << "require pap = no" << "\n";
		stream << "require chap = yes" << "\n";
		stream << "name = " << GlobalConfig->currentProfile->getUserName() << "\n";
		stream << "pppoptfile = " << tmpPath + "options." + GlobalConfig->currentProfile->getName() + ".l2tpd" << "\n";
		stream << "autodial = yes" << "\n";
		L2tpdConfigFile.close();
	}
	else
	{
		GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed!" ).arg ( "l2tpd config file" ), GlobalConfig->error );
		stopContinue = true;
	}


	// write options.l2tpd
	QFile L2tpdPppdOptionsFile ( tmpPath + "options." + GlobalConfig->currentProfile->getName() + ".l2tpd" );
	stream.setDevice ( &L2tpdPppdOptionsFile );
	if ( L2tpdPppdOptionsFile.open ( IO_WriteOnly ) )
	{
		stream << "noauth" << "\n";
		stream << "user " << GlobalConfig->currentProfile->getUserName() << "\n";
		stream << "ipcp-accept-local" << "\n";
		stream << "ipcp-accept-remote" << "\n";
		// 				stream << "crtscts" << "\n";
		stream << "idle 1800" << "\n";
		stream << "lock" << "\n";
		// 				stream << "proxyarp" << "\n";
		// 				stream << "connect-delay 5000" << "\n";
		// 				stream << "persist" << "\n";
		// 				stream << "hide-password" << "\n";
		// 				if (!GlobalConfig->currentProfile->getUseDnsServer())
		// 					stream << "usepeerdns" << "\n";
		// 				stream << "asyncmap 0" << "\n";
		// 				stream << "crtscts" << "\n";
		// 				stream << "lock" << "\n";
		// 				stream << "lcp-echo-interval 10" << "\n";
		// 				stream << "lcp-echo-failure 3" << "\n";
		// 				stream << "noipx" << "\n";

		QString deamon="";
		if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
		{
			if ( GlobalConfig->enableDebugXl2tpd )	
				stream << "debug" << "\n";
		}
		else
		{
			if ( GlobalConfig->enableDebugL2tpd )	
				stream << "debug" << "\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() && pppdHasReplacedefaultrouteSupport )
				{
					stream << "replacedefaultroute\n";
				}
			}
			stream << "\n";
		}

		if ( GlobalConfig->currentProfile->getUseMtu() )
		{
			stream << "mtu " << GlobalConfig->currentProfile->getMtu() << "\n";
			stream << "mru " << GlobalConfig->currentProfile->getMru() << "\n";
		}

		L2tpdPppdOptionsFile.close();
	}
	else
	{
		GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed!" ).arg ( i18n ( "l2tpd options file for pppd" ) ), GlobalConfig->error );
		stopContinue = true;
	}


	// write l2tp secrets file
	QString L2tpSecrets = tmpPath + "l2tp-secrets" + GlobalConfig->currentProfile->getName();

	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( i18n ( "l2tp secrets file: %1" ).arg ( tmpPath + "l2tp-secrets" + GlobalConfig->currentProfile->getName() ), GlobalConfig->debug );
	QFile L2tpdSecretsFile ( L2tpSecrets );
	stream.setDevice ( &L2tpdSecretsFile );
	if ( L2tpdSecretsFile.open ( IO_WriteOnly | IO_WriteOnly ) )
	{
		stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
		stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";

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

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

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

		stream << "* " << GlobalConfig->currentProfile->getGateway() + " \"" << GlobalConfig->TmpPassword << "\" *\n";
		stream << GlobalConfig->currentProfile->getGateway() << " \"" << GlobalConfig->TmpPassword << "\" *\n";

		stream << "# --- generated by kvpnc. Do not edit it." << "\n";
		L2tpdSecretsFile.close();
		Utils ( GlobalConfig, this ).doChmod ( L2tpdSecretsFile.name(), "go-rwx" );

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

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

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


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

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

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

		QString Username = GlobalConfig->currentProfile->getUserName();
		if ( Username.isEmpty() )
			Username = GlobalConfig->TmpUsername;

		QString Password = GlobalConfig->currentProfile->getUserPassword();
		if ( Password.isEmpty() )
			Password = GlobalConfig->TmpPassword;

		stream << Username << "  " << GlobalConfig->currentProfile->getGateway() << " \"" << Password << "\" *" << "\n";

		stream << "# --- generated by kvpnc. Do not edit it." << "\n";
		PapSecretsFile.close();
		Utils ( GlobalConfig, this ).doChmod ( PapSecretsFile.name(), "go-rwx" );
	}
	else
	{
		GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed!" ).arg ( "pppd secrets file" ), GlobalConfig->error );
		stopContinue = true;
	}

}

void KVpnc::start_l2tpd()
{
// 	bool control_interface_success=true;
// 	if (QFile("/var/run/l2tpd.pid").exists())
// 	{
// 		if (GlobalConfig->KvpncDebugLevel > 1)
// 			GlobalConfig->appendLogEntry(i18n("Using control interface for starting l2tp connection"),GlobalConfig->debug);
// 		QFile L2tpdControlFile ( "/var/run/l2tp-control" );
// 		QTextStream stream( &L2tpdControlFile );
// 		if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
// 			stream << "c " << GlobalConfig->currentProfile->getName() << "\n";
// 			L2tpdControlFile.close();
// 		}
// 		else
// 		{
// 			control_interface_success=false;
// 			GlobalConfig->appendLogEntry(i18n("Starting l2tp connection via control interface has been failed"),GlobalConfig->error);
// 		}
// 	}
// 	if (!QFile("/var/run/l2tpd.pid").exists() || control_interface_success==false)
// 	{
		if (GlobalConfig->KvpncDebugLevel > 1)
			GlobalConfig->appendLogEntry(i18n("Starting l2tpd manually"),GlobalConfig->debug);
		sleep ( 2 );
	
		// start l2tpd
		L2tpdProcess = new QProcess ( this );
		//

		QString deamon="";
		if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Using %1.").arg("xl2tpd"),GlobalConfig->debug);
			deamon="xl2tpd";
			L2tpdProcess->addArgument ( GlobalConfig->pathToXl2tpd );
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Using %1.").arg("l2tpd"),GlobalConfig->debug);
			deamon="l2tpd";
			L2tpdProcess->addArgument ( GlobalConfig->pathToL2tpd );
		}
		L2tpdProcess->addArgument ( "-p" );
		L2tpdProcess->addArgument ( "/var/run/l2tpd" + GlobalConfig->currentProfile->getName() + ".pid" );
		L2tpdProcess->addArgument ( "-c" );
		L2tpdProcess->addArgument ( tmpPath + "l2tpd." + GlobalConfig->currentProfile->getName() + ".conf" );
		L2tpdProcess->addArgument ( "-s" );
		L2tpdProcess->addArgument ( tmpPath + "l2tp-secrets" + GlobalConfig->currentProfile->getName() );
		L2tpdProcess->addArgument ( "-D" );
	
		if ( GlobalConfig->KvpncDebugLevel > 2 )
		{
			QString cmdline = "";
			QStringList cmdarguments = L2tpdProcess->arguments();
			for ( QStringList::Iterator it = cmdarguments.begin(); it != cmdarguments.end(); ++it )
			{
				cmdline += " " + QString ( *it );
			}
			GlobalConfig->appendLogEntry ( "\""+deamon+"\" cmd line: " + cmdline , GlobalConfig->debug );
		}
	
		connect ( L2tpdProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_l2tpd() ) );
		connect ( L2tpdProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_l2tpd() ) );
	
		if ( !L2tpdProcess->start(env) )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( deamon ), GlobalConfig->error );
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( deamon ) );
			setGuiStatus ( disconnected );
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "l2tpd" ), GlobalConfig->debug );
	
		}
//  	}
}

bool KVpnc::checkCiscoVpncStatus()
{
	ciscoVpncRunning = false;
	TestCiscoVpncProcess = new QProcess ( this );
	TestCiscoVpncProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
	TestCiscoVpncProcess->addArgument ( GlobalConfig->InterpreterShell );
	TestCiscoVpncProcess->addArgument ( "/etc/init.d/vpnclient_init" );
	TestCiscoVpncProcess->addArgument ( "status" );

	connect ( TestCiscoVpncProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
	connect ( TestCiscoVpncProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );

	if ( !TestCiscoVpncProcess->start ( env ) )
	{
		GlobalConfig->appendLogEntry ( i18n ( "unable to start proc (%1)!" ).arg ( i18n ( "Test Cisco vpnclient" ) ) , KVpncConfig::error );
		return false;
	}
	else
	{
		while ( TestCiscoVpncProcess->isRunning() )
			parent->processEvents();
		delete TestCiscoVpncProcess;

		disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
		disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
	}
	return ciscoVpncRunning;
}

void KVpnc::startCiscoVpnc()
{
	TestCiscoVpncProcess = new QProcess ( this );
	TestCiscoVpncProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
	TestCiscoVpncProcess->addArgument ( GlobalConfig->InterpreterShell );
	TestCiscoVpncProcess->addArgument ( "/etc/init.d/vpnclient_init" );
	TestCiscoVpncProcess->addArgument ( "start" );

//	connect ( TestCiscoVpncProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
//	connect ( TestCiscoVpncProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );

	if ( !TestCiscoVpncProcess->start ( env ) )
	{
		GlobalConfig->appendLogEntry ( i18n ( "unable to start proc (%1)!" ).arg ( i18n ( "Start Cisco vpnclient" ) ) , KVpncConfig::error );
		return;
	}
	else
	{
		if (GlobalConfig->KvpncDebugLevel > 1)
			GlobalConfig->appendLogEntry ( i18n ( "proc (%1) started." ).arg ( i18n ( "Start Cisco vpnclient" ) ) , KVpncConfig::debug );
		while ( TestCiscoVpncProcess->isRunning() )
			parent->processEvents();

		delete TestCiscoVpncProcess;
// 		disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
// 		disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
	}
}

void KVpnc::sendFeedbackMail()
{
	FeedbackDialog = new KFeedbackDialog ( "crissi99@gmx.de", "feedback_mail" );
	connect ( FeedbackDialog->form(), SIGNAL ( mailSent() ), this, SLOT ( feedbackMailSent() ) );

	KFeedbackQuestionList * list = FeedbackDialog->form() ->questionList();

	KFeedbackQuestion * question = list->addQuestion ( i18n ( "What is your general opinion about this program?" ), "general_opinion", true, true );

	question->addAnswer ( i18n ( "It's one of my favourites" ), "1/8_favourite" );
	question->addAnswer ( i18n ( "I like it" ), "2/8_like_it" );
	question->addAnswer ( i18n ( "It's sometimes useful"	), "3/8_sometimes_useful" );
	question->addAnswer ( i18n ( "It's average" ), "4/8_average" );
	question->addAnswer ( i18n ( "Nice try, but this could be done better"	), "5/8_nice_try" );
	question->addAnswer ( i18n ( "It's poor"	), "6/8_poor"	);
	question->addAnswer ( i18n ( "It's useless"	), "7/8_useless" );
	question->addAnswer ( i18n ( "It's crap" ), "8/8_crap"	);

	question = list->addQuestion ( i18n ( "Which features of this program do you like?" ), "features_liked", false );
	addFeatureList ( question );

	question = list->addQuestion ( i18n ( "Which features don't you like?" ), "features_not_liked", false );
	addFeatureList ( question );

	question = list->addQuestion ( i18n ( "Which features do you never use?" ), "features_never_used", false );
	addFeatureList ( question );

	question = list->addQuestion ( i18n ( "What is your favourite feature?" ), "favourite_feature", true );
	addFeatureList ( question );

	question = list->addQuestion ( i18n ( "Are there features you are missing?" ), "features_missing", true );
	question->addAnswer ( i18n ( "Yes, a lot! (please add comment below)"	), "1/4_lots"	);
	question->addAnswer ( i18n ( "Some (please add comment below)"	), "2/4_some"	);
	question->addAnswer ( i18n ( "None"	), "3/4_none"	);
	question->addAnswer ( i18n ( "It has too many features already!"	), "4/4_too_many_already"	);

	question = list->addQuestion ( i18n ( "How do you rate the stability of this program?" ), "stability", true, true );
	question->addAnswer ( i18n ( "Rock solid"	), "1/5_rock_solid"	);
	question->addAnswer ( i18n ( "Good"	), "2/5_good"	);
	question->addAnswer ( i18n ( "Average"	), "3/5_average"	);
	question->addAnswer ( i18n ( "Poor"	), "4/5_poor"	);
	question->addAnswer ( i18n ( "It keeps crashing all the time"	), "5/5_keeps_crashing"	);

	question = list->addQuestion ( i18n ( "How do you rate the performance of this program?" ), "performance", true );
	question->addAnswer ( i18n ( "Great"	), "1/5_great"	);
	question->addAnswer ( i18n ( "Good"	), "2/5_good"	);
	question->addAnswer ( i18n ( "Average"	), "3/5_average"	);
	question->addAnswer ( i18n ( "Poor"	), "4/5_poor"	);
	question->addAnswer ( i18n ( "It's so slow it drives me nuts"	), "5/5_drives_me_nuts"	);

	question = list->addQuestion ( i18n ( "What is your experience with computers in general?" ), "computer_experience", true );
	question->addAnswer ( i18n ( "Expert"	), "1/5_expert"	);
	question->addAnswer ( i18n ( "Fair"	), "2/5_fair"	);
	question->addAnswer ( i18n ( "Average"	), "3/5_average"	);
	question->addAnswer ( i18n ( "Learning"	), "4/5_learning"	);
	question->addAnswer ( i18n ( "Newbie"	), "5/5_newbie"	);

	question = list->addQuestion ( i18n ( "What is your experience with Unix/Linux systems?" ), "unix_experience", true );
	question->addAnswer ( i18n ( "Expert"	), "1/5_expert"	);
	question->addAnswer ( i18n ( "Fair"	), "2/5_fair"	);
	question->addAnswer ( i18n ( "Average"	), "3/5_average"	);
	question->addAnswer ( i18n ( "Learning"	), "4/5_learning"	);
	question->addAnswer ( i18n ( "Newbie"	), "5/5_newbie"	);

	question = list->addQuestion ( i18n ( "Did you have trouble figuring out how to work with this program in general?" ),
	                               "learning_curve", true, true );
	question->addAnswer ( i18n ( "No problem"	), "1/5_no_problem"	);
	question->addAnswer ( i18n ( "Some"	), "2/5_some_problems"	);
	question->addAnswer ( i18n ( "I'm still learning"	), "3/5_still_learing"	);
	question->addAnswer ( i18n ( "I didn't have a clue what to do at first"	), "4/5_no_clue_at_first"	);
	question->addAnswer ( i18n ( "I still don't have a clue what to do"	), "5/5_still_no_clue"	);

	question = list->addQuestion ( i18n ( "Where do you use this program most?" ), "usage_where", true );
	question->addAnswer ( i18n ( "At work"	), "at_work"	);
	question->addAnswer ( i18n ( "At home"	), "at_home"	);
	question->addAnswer ( i18n ( "At university / school"	), "university"	);

	question = list->addQuestion ( i18n ( "What is your primary role there?"	), "primary_role", true );
	question->addAnswer ( i18n ( "Home user"	), "home_user"	);
	question->addAnswer ( i18n ( "Student"	), "student"	);
	question->addAnswer ( i18n ( "Educational (teacher / professor)"	), "educational"	);
	question->addAnswer ( i18n ( "Non-computer related work"	), "non_computer"	);
	question->addAnswer ( i18n ( "Developer"	), "developer"	);
	question->addAnswer ( i18n ( "System administrator"	), "sysadmin"	);

	question = list->addQuestion ( i18n ( "Do you have any other roles there?" ), "other_roles", false );
	question->addAnswer ( i18n ( "Home user"	), "home_user"	);
	question->addAnswer ( i18n ( "Student"	), "student"	);
	question->addAnswer ( i18n ( "Educational (teacher / professor)"	), "educational"	);
	question->addAnswer ( i18n ( "Non-computer related work"	), "non_computer"	);
	question->addAnswer ( i18n ( "Developer"	), "developer"	);
	question->addAnswer ( i18n ( "System administrator"	), "sysadmin"	);

	question = list->addQuestion ( i18n ( "How did you get to know this program?" ), "first_contact", true );
	question->addAnswer ( i18n ( "In a menu on my machine"	), "menu"	);
	question->addAnswer ( i18n ( "Somebody told me about it"	), "told"	);
	question->addAnswer ( i18n ( "On the internet"	), "internet"	);
	question->addAnswer ( i18n ( "Printed magazine / book"	), "print_media"	);
	question->addAnswer ( i18n ( "Other (please add comment below)"	), "other"	);

	list->addYesNoQuestion ( i18n ( "Would you recommend this program to a friend?" ), "recommend", true );

	if ( ! FeedbackDialog->isVisible() )
		FeedbackDialog->show();
}

void KVpnc::addFeatureList ( KFeedbackQuestion * )
{
	//     question->addAnswer( i18n( "The directory tree display in general"			),	"tree_view"		);
	//     question->addAnswer( i18n( "Percentage bars as graphical display of relative sizes" ),	"percentage_bars" 	);
	//     question->addAnswer( i18n( "Files apart from directories in a separate <Files> item"),	"files_item"		);

}

void KVpnc::feedbackMailSent()
{
	GlobalConfig->feedbackMailSent = true;
}

#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::doImportPcf ( QString file )
{
	importProfileClicked ( file );
}

void KVpnc::doImportOpenvpnConfig()
{
	importOpenvpnProfileClicked ( "" );
}

void KVpnc::doImportOpenvpnConfig ( QString file )
{
	importOpenvpnProfileClicked ( file );
}

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" );
					int major = tool->Version.section ( '.', 0, 0 ).toInt();
					int minor = tool->Version.section ( '.', 1, 1 ).toInt();
					//					int subminor=tool->Version.section('.',2,2).toInt();

					if ( major >= 2 && minor >= 1 )
						usability += ", " + i18n ( "pcks11 support" );
				}
				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();
}

void KVpnc::doSendFeedbackMail()
{
	sendFeedbackMail();
}

QStringList KVpnc::getProfileTypes()
{
	QStringList ProfileTypes;

	ProfileTypes.append ( "Cisco (vpnc)" );
	ProfileTypes.append ( "IPSec (racoon)" );
	ProfileTypes.append ( "IPSec (FreeSWAN/Openswan/strongSwan)" );
	ProfileTypes.append ( "PPTP" );
	ProfileTypes.append ( "OpenVPN" );
	ProfileTypes.append ( "L2TP (racoon)" );
	ProfileTypes.append ( "L2TP (freeswan)" );
	ProfileTypes.append ( "Vtun");
	return ProfileTypes;
}
