/*************************************************************************
*  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 "vpntypesinfodialog.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;
	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" );
	RenameSessionAction = new KAction ( i18n ( "&Rename Profile..." ), "view_detailed", Key_D, this, SLOT ( renameSessionClicked() ), actionCollection(), "renameSession" );
	// 	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/strongSwan 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 ( "&Support KVpnc..." ), "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_I, this, SLOT ( toolsInfoClicked() ), actionCollection(), "toolsinfo" );
	VpnTypesInfoAction = new KToggleAction ( i18n ( "Show &VPN types Info" ), "info", CTRL + Key_T, this, SLOT ( vpnTypesInfoClicked() ), actionCollection(), "vpntypesinfo" );
	// // 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 );

}

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 )
	{
		if (GlobalConfig->KvpncDebugLevel > 4)
			GlobalConfig->appendLogEntry(i18n("Profile list has been changed, updating GUI..."), GlobalConfig->debug);
		GlobalConfig->saveOptions();
		saveGuiOptions();
		if ( GlobalConfig->AccountList->isEmpty() )
		{
// 			GlobalConfig->currentProfile = 0L;
			mw->SessionCombo->setEnabled ( FALSE );
			ConnectAction->setEnabled ( false );
			mw->buttonConnect->setEnabled ( FALSE );
			mw->SessionCombo->clear();
		}
		else
		{
			QString Name = "";
			if ( GlobalConfig->currentProfile != 0 )
				Name = GlobalConfig->currentProfile->getName();
			if ( Name != mw->SessionCombo->currentText() )
				GlobalConfig->currentProfile = oldProfile; // restore from beforNme calling pref dialog

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

	}
	if (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;
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n( "quitCalled()" ), 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 if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
			TypeString = i18n("SSH");
		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();
		}
	}
	if ( GlobalConfig->status == GlobalConfig->connecting )
	{
		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 > 1 )
			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 if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
			TypeString = i18n("SSH");
		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();

			//KMainWindow::closeEvent( e );
			disconnectClicked();
			tmpPath = locateLocal ( "data", "kvpnc/" );
			QFile file ( tmpPath + "kvpnc_running" );
			file.remove();
			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();
				}
			}
			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()
{
	if ( GlobalConfig->KvpncDebugLevel > 1 )
		GlobalConfig->appendLogEntry ( i18n ( "queryExit recieved (reciever: %1)." ).arg("kvpnc"), GlobalConfig->debug );
	kdDebug() << "KVpnc::queryExit()" << endl;
	
	if ( GlobalConfig->status == GlobalConfig->connecting || GlobalConfig->status == GlobalConfig->connected )
	{
		disconnectClicked();
	}
	
	if ( !kapp->sessionSaving() )
	{
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "KVpnc::queryExit(): dont saving session"), GlobalConfig->debug );
		kdDebug ( "KVpnc::queryExit(): dont saving session" );
	}
	else
	{
		kdDebug ( "KVpnc::queryExit(): saving session" );
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "KVpnc::queryExit(): dont saving session"), GlobalConfig->debug );
// 		GlobalConfig->saveOptions();
// 		saveGuiOptions();
		
	}
	return true;
}

bool KVpnc::queryClose()
{
	if ( kapp->sessionSaving() )
	{
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "KVpnc::queryClose()"), GlobalConfig->debug );

		return true;
	}
	else
	{
		if ( !GlobalConfig->hideOnCloseInfo )
			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::restore(KConfig *config, int i)
{
	readPropertiesInternal(config,i);
}

void KVpnc::restore()
{
	KConfig *config = parent->sessionConfig();

	if (!config)
		return;

	return;
}

void KVpnc::saveProperties( KConfig* c )
{
  QString saveDir = KGlobal::dirs()->saveLocation( "appdata", "sessions/" + qApp->sessionId() + "/", true );

  c = new KSimpleConfig( saveDir + "list", false );
  c->setGroup( "Saved Session" );

  delete c;
}

void KVpnc::readProperties( KConfig* c )
{
  QString saveDir = KGlobal::dirs()->saveLocation( "appdata", "sessions/" + qApp->sessionId() + "/", true );
  c = new KSimpleConfig( saveDir + "list", true );
  c->setGroup( "Saved Session" );
  delete c;
}

void KVpnc::connectClicked()
{
	ConnectAction->setEnabled(false);
	
	TunnelInterfaceIP = i18n ( "None" );

	bool ok = true; // if ok we will run process
	bool useL2tpAfterFirstConnection = false;
	stopContinue = false;
	ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( "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";
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
		TypeString = "SSH";

	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 ( "/etc/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 ( "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 ( "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 ( AuthRetry )
				askUsernamePass = true;

			bool requestUsername= false;
			bool requestGroupPassword=true;

			if (!GlobalConfig->haveUserData)
			{
				if ( !GlobalConfig->currentProfile->getSavePsk() )
					askUsernamePass = true;
	
				if ( GlobalConfig->currentProfile->getAllowEmptyGroupPassword() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
					askUsernamePass = true;
	
				if ( GlobalConfig->currentProfile->getUserName().isEmpty() )
					askUsernamePass = true;
	
				if ( GlobalConfig->currentProfile->getUserPassword().isEmpty() )
					askUsernamePass = true;
	
	
				
				requestUsername = GlobalConfig->currentProfile->getUserPassword().isEmpty();
				if ( AuthRetry )
				{
					askUsernamePass = true;
					requestUsername = true;
				}
				
				if (GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
					requestGroupPassword=false;
			}
			else
			{
				if (GlobalConfig->KvpncDebugLevel > 4 )
					GlobalConfig->appendLogEntry ( i18n ( "User data already collected." ), GlobalConfig->debug );
			}
			
			if ( askUsernamePass )
			{
				EnterUsernamePasswordDialog dlg ( this, i18n ( "Enter Account Data" ), requestGroupPassword, requestUsername );

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

				if (!GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
				{
					dlg.main->LabelGroupPassword->setText ( i18n ( "Enter group password:" ) );
					
					if ( !GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
					{
						dlg.main->PSKLineEdit->setText ( GlobalConfig->currentProfile->getPreSharedKey() );
					}
				}
				else
				{
					dlg.main->PSKLineEdit->hide();
					dlg.main->LabelGroupPassword->hide();
					dlg.main->PSKLineEdit->setText ( GlobalConfig->currentProfile->getPreSharedKey() );
				}

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

				if ( !dlg.main->UsernameEdit->text().isEmpty() )                //go straight to pw if username present
				{
					if (!GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
					{
						if ( !dlg.main->PSKLineEdit->text().isEmpty() )
							dlg.main->PasswordEdit->setFocus();
						else
							dlg.main->PSKLineEdit->setFocus();
					}
					else
						dlg.main->PasswordEdit->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;

					bool askGroupPass=false;

    					 if (GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty() && !GlobalConfig->currentProfile->getAllowEmptyGroupPassword() )
						askGroupPass=true;

					if ( GlobalConfig->TmpGroupPassword.isEmpty() && !GlobalConfig->currentProfile->getAllowEmptyGroupPassword() || askGroupPass)
					{
						GlobalConfig->appendLogEntry ( i18n ( "Group 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 (!GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
					{
						if ( dlg.main->SavePskCheckBox->isChecked() )
						{
							GlobalConfig->currentProfile->setSavePsk ( true );
							GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
							needSave=true;
						}
						else
						{
							GlobalConfig->currentProfile->setSavePsk( false );
						}
					}
					else
					{
						GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey(); 
					}

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

					GlobalConfig->haveUserData=true;
				}
				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->getReplaceDefaultRoute() )
				{
					stream << "		mkdir -p /var/run/vpnc\n";
					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->getReplaceDefaultRoute() )
					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->getReplaceDefaultRoute() )
				{
					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->getReplaceDefaultRoute() )
				{
					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";
				if (GlobalConfig->currentProfile->getUseDnsUpdate() == true)
				{
					stream << "    if [ -x /sbin/resolvconf ] ; then\n";
					stream << "        mkdir -p /var/run/vpnc\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 << "        ) > /var/run/vpnc/resolvconf\n";
					stream << "       cat /var/run/vpnc/resolvconf | /sbin/resolvconf -a $TUNDEV\n";
					stream << "       cat /var/run/vpnc/resolvconf | /sbin/resolvconf -u\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";

				}
				else
				{
					stream << "        return\n";
				}
				stream << "}\n";
				stream << "\n";
				stream << "reset_resolvconf() {\n";
				stream << "\n";
				if (GlobalConfig->currentProfile->getUseDnsUpdate() == true)
				{
// 					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";
				}
				else
				{
// 					stream << "        return\n";
					stream << "	cat " + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " > /etc/resolv.conf\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->TmpUsername + "\n";

				if ( ( vpnc_version_minor == 3 && vpnc_version_minor >= 2 ) || ( vpnc_version_minor > 3 ) )
					vpncConfig += "Xauth password " + GlobalConfig->TmpPassword + "\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 ******";
						if (configstring.find("IPSec secret",0) > -1)
							configstring = "IPSec secret ******";
						
						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 ) || (vpnc_version_major >= 1 ))
					{
						ConnectProcess->addArgument ( "--natt-mode" );
						ConnectProcess->addArgument ( "none" );
					}	
					else
					{
						ConnectProcess->addArgument ( "--disable-natt" );
					}
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Disabling NAT-T." ), 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 >= 5 ) || ( vpnc_version_major > 0 ))
				{
					if (GlobalConfig->currentProfile->getUseDpdIdleTimeout())
					{
						ConnectProcess->addArgument ( "--dpd-idle" );
						ConnectProcess->addArgument ( QString().setNum(GlobalConfig->currentProfile->getDpdIdleTimeout() ));
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "Using DPD idle timeout: %1." ).arg(GlobalConfig->currentProfile->getDpdIdleTimeout()), GlobalConfig->debug );
					}
					else
					{
						// disabling DPD (Dead Peer Detection)
						ConnectProcess->addArgument ( "--dpd-idle" );
						ConnectProcess->addArgument ( "0" );
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "Disabling DPD idle timeout." ), GlobalConfig->debug );
					}
				}

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

                if (GlobalConfig->currentProfile->getUseDnsUpdate())
                {
                    setenv("DNS_UPDATE", "Yes", 1);
                    *env << "DNS_UPDATE=Yes";
                }
                else
                {
                    setenv("DNS_UPDATE", "NO", 1);
                    *env << "DNS_UPDATE=NO";
                }
				
				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 ( "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 ( AuthRetry )
				askUsernamePass = true;

			if (!GlobalConfig->haveUserData)
			{
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && !GlobalConfig->currentProfile->getSavePsk() )
					askUsernamePass = true;
				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;
	
			}
			else
			{
				if (GlobalConfig->KvpncDebugLevel > 4 )
					GlobalConfig->appendLogEntry ( i18n ( "User data already collected." ), GlobalConfig->debug );
			}

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

				if (!GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
				{
					dlg.main->LabelGroupPassword->setText ( i18n ( "Enter group password:" ) );

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

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

				if (!GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
				{
					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();
					}
				}
				else
					dlg.main->PasswordEdit->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 (GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty() && !GlobalConfig->currentProfile->getAllowEmptyGroupPassword() )
						askGroupPass=true;
					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 (!GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
					{
						if ( dlg.main->SavePskCheckBox->isChecked() && askGroupPass )
						{
							GlobalConfig->currentProfile->setSavePsk ( true );
							GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
							needSave=true;
						}
						else
						{
							GlobalConfig->currentProfile->setSavePsk( false );
						}
					}
					else
					{
						GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey();
					}

					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();
					}
					GlobalConfig->haveUserData=true;
				}
				else
				{
					ok = false;
					AuthRetry = false;
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because account data dialog aborted." ), GlobalConfig->debug );
					setGuiStatus ( disconnected );
					return;
				}
    				GlobalConfig->TmpPassword= GlobalConfig->currentProfile->getUserPassword();
				GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey();
				GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
			}


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

				if (GlobalConfig->currentProfile->getUseUdp())
 					stream << "TunnelingMode=0" << "\n";
				else
				{
					stream << "TunnelingMode=1" << "\n";
					if (GlobalConfig->currentProfile->getUseUdpPort())
 						stream << "TcpTunnelingPort=" << GlobalConfig->currentProfile->getUdpPort() << "\n";
				}
				
				if (GlobalConfig->currentProfile->getCiscoNatMode() == "none")
					stream << "EnableNat=0" << "\n";
				else
				{
					stream << "EnableNat=1" << "\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=" << GlobalConfig->currentProfile->getDpdIdleTimeout() << "\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 ( "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 ( "l2tpd" )->found == false && Utils ( GlobalConfig ).getToolInfo ( "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;
			}
		}

		RacoonProcess = 0L;
		RacoonctlProcess = 0L;

		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." ).arg ( "esp4" ), GlobalConfig->info );
// 			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." ).arg ( "ah4" ), GlobalConfig->info );
// 			ok = false;
		}


		if (ok==false)
			return;

		bool askUsernamePass = false;
		bool askPsk = false;

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

		// L2TP/XAUTH
		if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
		{
			if (!GlobalConfig->haveUserData)
			{
				GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
				GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();
	
				if (GlobalConfig->TmpPassword.isEmpty() || GlobalConfig->TmpUsername.isEmpty())
					askUsernamePass=true;
	
				if ( !GlobalConfig->currentProfile->getPskIsInFile() )
					GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey();
				else
				{
					QFile PskFile ( GlobalConfig->currentProfile->getPreSharedKeyFile() );
					if ( PskFile.open ( IO_ReadOnly ) )
					{
						QString PskFileContent = QString ( PskFile.readAll() );
						PskFile.close();
						GlobalConfig->TmpGroupPassword = PskFileContent;
					}
				}
				GlobalConfig->WaitingForXauth=false;
				GlobalConfig->haveUserData=true;
			}
			else
			{
				if (GlobalConfig->KvpncDebugLevel > 4 )
					GlobalConfig->appendLogEntry ( i18n ( "User data already collected." ), GlobalConfig->debug );
			}
		}

		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/" + GlobalConfig->TmpGatewayIP + "-" + LocalIP + "/require;" << "\n";
					// 					stream << "spdadd " << LocalIP << "[any] " << Remote << "[1701] udp -P out ipsec esp/tunnel/" + LocalIP + "-" + GlobalConfig->TmpGatewayIP + "/require;" << "\n";
				}
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon || ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid) )
				{
					// 										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";

					if ( GlobalConfig->currentProfile->getUseRemoteNetwork()  )
					{
						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";
					}
					else
					{
						stream << "spdadd " + LocalIP + " " + GlobalConfig->TmpGatewayIP+"/32" + " any -P out ipsec esp/transport//require;" << "\n";
						stream << "spdadd " + GlobalConfig->TmpGatewayIP+"/32" + " " + LocalIP + " any -P in ipsec esp/transport//require;" << "\n";
					}

				}


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

					stream << "spdadd " + LocalIP + "[1701] " + Remote + "[any] udp -P in ipsec esp/transport//require;" << "\n";
					stream << "spdadd " + Remote + "[any] " + LocalIP + "[1701] udp -P  out ipsec esp/transport//require;" << "\n";
					stream << "spdadd " + LocalIP + "[1701] " + Remote + "[any] udp -P fwd ipsec esp/transport//require;" << "\n";

					// 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 + "-" + GlobalConfig->TmpGatewayIP + "/require;" << "\n";
							stream << "spdadd " + net + " " + LocalIP + " any -P in ipsec esp/tunnel/" + GlobalConfig->TmpGatewayIP + "-" + LocalIP + "/require;" << "\n";
						}
					}
				}
			}
			file.close();

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

				stream << "\n";
				if (GlobalConfig->RacoonDebugLevel != "none")
					stream << "log " + GlobalConfig->RacoonDebugLevel << ";" << "\n"; // FIXME: validate racoon version

				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert ||  GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid )
					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";

// 				stream << "#option of controlling racoon by racoonctl tool is enabled" << "\n";
				stream << "listen {" << "\n";
				stream << "	adminsock \"/var/run/racoon/racoon.sock\" \"root\" \"operator\" 0660;" << "\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";
					if (!GlobalConfig->currentProfile->getCaCertificate().isEmpty())
						stream << "  ca_type x509 \"" << GlobalConfig->currentProfile->getCaCertificate() << "\";" << "\n";
					
					// FIXME make it dynamiclly
					stream << "  proposal_check obey;" << "\n";
					
					if (GlobalConfig->currentProfile->getVerifyCaCert())
						stream << "  verify_cert on;" << "\n";
					else
						stream << "  verify_cert off;" << "\n";
// 					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";
// 						}
				}

				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid )
				{
					if (!GlobalConfig->currentProfile->getCaCertificate().isEmpty())
						stream << "  ca_type x509 \"" << GlobalConfig->currentProfile->getCaCertificate() << "\";" << "\n";
					
					// FIXME make it dynamiclly
					stream << "  proposal_check obey;" << "\n";
					
					if (GlobalConfig->currentProfile->getVerifyCaCert())
						stream << "  verify_cert on;" << "\n";
					else
						stream << "  verify_cert off;" << "\n";
				}

				if ( GlobalConfig->currentProfile->getUseUdp() )
				{
					stream << "  nat_traversal on;" << "\n";
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Using NAT-T." ), GlobalConfig->debug );
				}
				else
				{
					stream << "  nat_traversal off;" << "\n";
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Disabling NAT-T." ), GlobalConfig->debug );
				}

				// FIXME make it dynamiclly
				stream << "  ike_frag on;" << "\n";

				if ( GlobalConfig->currentProfile->getUseModeConfig() )
				{
					stream << "  mode_cfg on;" << "\n";
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry ( i18n ( "Using Mode Config." ), GlobalConfig->debug );
				}

// 				stream << "  #IKE first phase starting script" << "\n";
				stream << "  script \""+tmpPath+"racoon-"+ProfileName+".phase1-up.sh\" phase1_up;" << "\n";
// 				stream << "\n";
// 				stream << "  #IKE first phase ending script" << "\n";
				stream << "  script \""+tmpPath+"racoon-"+ProfileName+".phase1-down.sh\" phase1_down;" << "\n";

				QString RemoteIDType = GlobalConfig->currentProfile->getRemoteIDType();

				if( RemoteIDType == "asn1dn")
				{
						stream << "  peers_identifier asn1dn;" << "\n";
				}
				if( RemoteIDType == "address")
				{
						if (!GlobalConfig->currentProfile->getSpecialRemoteID().isEmpty())
							stream << "  peers_identifier address \"" << GlobalConfig->currentProfile->getSpecialRemoteID() << "\";" << "\n";
						else
							stream << "  peers_identifier address;" << "\n";
				}
				if( RemoteIDType == "fqdn")
					stream << "  peers_identifier fqdn \"" << GlobalConfig->currentProfile->getSpecialRemoteID() << "\";" << "\n";
				if( RemoteIDType == "keyid")
					stream << "  peers_identifier keyid \"" << GlobalConfig->currentProfile->getSpecialRemoteID() << "\";" << "\n";
				if( RemoteIDType == "user_fqdn")
					stream << "  peers_identifier user_fqdn \"" << GlobalConfig->currentProfile->getSpecialRemoteID() << "\";" << "\n";

				QString LocalIDType = GlobalConfig->currentProfile->getLocalIDType();

				if( LocalIDType == "asn1dn")
				{
					if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
						stream << "  my_identifier asn1dn;" << "\n";
					if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk ||  GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid )
						stream << "  my_identifier asn1dn " << Utils(GlobalConfig).getHostname() << ";" << "\n";
				}
				if( LocalIDType == "address")
				{
					if (!GlobalConfig->currentProfile->getSpecialLocalID().isEmpty())
						stream << "  my_identifier address \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
					else
						stream << "  my_identifier address" << ";" << "\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";

				// 				stream << "  passive on;" << "\n";
				if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
				{
// 					stream << "  # XAUTH" << "\n";
// 					stream << "  xauth_login \"" << GlobalConfig->TmpUsername << "\";" <<"\n";
					if ( GlobalConfig->KvpncDebugLevel > 3 )
						GlobalConfig->appendLogEntry ( i18n ( "Using XAUTH." ), GlobalConfig->debug );
				}
				
				stream << "  proposal {" << "\n";

// 				stream << "    # for phase 1" << "\n";
				stream << "    encryption_algorithm " << GlobalConfig->currentProfile->getIpsecIke() << ";" << "\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";
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid )
					stream << "    authentication_method hybrid_rsa_client;" << "\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;


				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon || ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid) )
					stream << "sainfo anonymous {" << "\n";
				else
				{
					if ( GlobalConfig->currentProfile->getUseRemoteNetwork()  )
						stream << "sainfo address " << LocalIP << "/32 any address " << RemoteNet << " any {" << "\n";
					else
						stream << "sainfo address " << LocalIP << "/32 any address " << GlobalConfig->TmpGatewayIP << "/32 any {" << "\n";
				}


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

					pfs_group = GlobalConfig->currentProfile->getPerfectForwardSecrety();
					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";


// 				Utils::IpsecAlgos KernelCrypto = Utils ( GlobalConfig ).getKernelCrypto();
// 				// phase 2 encr algos from kernel
// 				QString EncrAlgos="";
// 				for ( QStringList::Iterator it = KernelCrypto.IpsecEspEncryptionAlgorithms.begin(); it != KernelCrypto.IpsecEspEncryptionAlgorithms.end(); ++it )
// 				{
// 					if (EncrAlgos.length() > 0)
// 						EncrAlgos+=",";
// 					EncrAlgos+= QString(*it );
// 				}
// 
// 
// 				// phase 2 auth algos from kernel
// 				QString AuthAlgos="";
// 				for ( QStringList::Iterator it = KernelCrypto.IpsecEspAuthenticationAlgorithms.begin(); it != KernelCrypto.IpsecEspAuthenticationAlgorithms.end(); ++it )
// 				{
// 					if (AuthAlgos.length() > 0)
// 						AuthAlgos+=",";
// 					AuthAlgos+= QString(*it );
// 				}
// 
// 
// 				stream << "  encryption_algorithm " << EncrAlgos << ";"<<"\n";
// 				stream << "  authentication_algorithm " << AuthAlgos << ";"<< "\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();
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write failed!" ).arg ( file.name() ), GlobalConfig->error );
				setGuiStatus ( disconnected );
				return;
			}

			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();
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write failed!" ).arg ( file1.name() ), GlobalConfig->error );
				setGuiStatus ( disconnected );
				return;
			}


			QFile upfile ( tmpPath+"racoon-"+ProfileName+".phase1-up.sh" );
			QTextStream upstream ( &upfile );
			if ( upfile.open ( IO_WriteOnly ) )
			{
				upstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
				upstream << "# generated by kvpnc. Do not edit it." << "\n";
				upstream << "# profile: " + ProfileName << "\n";
				upstream << "" << "\n";
				upstream << "echo \"STATE: phase1 up\"" << "\n";
				if (GlobalConfig->currentProfile->getUseModeConfig())
				{
					upstream << "echo \"# modecfg data\" >  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// An IPv4 internal address obtained by ISAKMP mode config
					upstream << "echo \"INTERNAL_ADDR4=$INTERNAL_ADDR4\" >>  " << tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// An IPv4 internal netmask obtained by ISAKMP mode config
					upstream << "echo \"INTERNAL_NETMASK4=$INTERNAL_NETMASK4\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// An IPv4 internal netmask obtained by ISAKMP mode config, in CIDR notation
					upstream << "echo \"INTERNAL_CIDR4=$INTERNAL_CIDR4\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// The first internal DNS server IPv4 address obtained by ISAKMP mode config.
					upstream << "echo \"INTERNAL_DNS4=$INTERNAL_DNS4\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// A list of internal DNS servers IPv4 address obtained by ISAKMP mode config, separated by spaces
					upstream << "echo \"INTERNAL_DNS4_LIST=$INTERNAL_DNS4_LIST\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// The first internal WINS server IPv4 address obtained by ISAKMP mode config
					upstream << "echo \"INTERNAL_WINS4=$INTERNAL_WINS4\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// A list of internal WINS servers IPv4 address obtained by ISAKMP mode config, separated by spaces
					upstream << "echo \"INTERNAL_WINS4_LIST=$INTERNAL_WINS4_LIST\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// The space separated list of IPv4 addresses and masks (address slash mask) that define the networks to be encrypted (as opposed to the default where all the traffic should be encrypted) ; obtained by ISAKMP mode config ; SPLIT_INCLUDE and SPLIT_LOCAL are mutually exclusive
					upstream << "echo \"SPLIT_INCLUDE=$SPLIT_INCLUDE\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// The space separated list of IPv4 addresses and masks (address slash mask) that define the networks to be considered local, and thus excluded from the tunnels ; obtained by ISAKMP mode config
					upstream << "echo \"SPLIT_LOCAL=$SPLIT_LOCAL\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";
					upstream << "\n";
					// The DNS default domain name obtained by ISAKMP mode config
					upstream << "echo \"DEFAULT_DOMAIN=$DEFAULT_DOMAIN\" >>  "<< tmpPath << "/racoon-" << ProfileName << ".modecfg" << "\n";


					// listing known IP addresses and setting PATH environment variable
					// internal address in local network
					upstream << "echo \"internal address: ${INTERNAL_ADDR4}\"" << "\n";

					// current global IP address
					upstream << "echo \"local address: ${LOCAL_ADDR}\"" << "\n";

					// VPN gateway IP address
					upstream << "echo \"remote address: $REMOTE_ADDR\"" << "\n";
					upstream << "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin" << "\n";

					if (GlobalConfig->currentProfile->getUseModeConfig())
					{
						// defining variable to hold the name of virtual network interface
						upstream << "if="+tmpInterface << "\n";

						// adding internal IP address to virtual network interface
						upstream << "" << GlobalConfig->pathToIp << " address add dev ${if} ${INTERNAL_ADDR4}" << "\n";
					}

					// deleting default route
// 					upstream << "" << GlobalConfig->pathToIp << " route del default" << "\n";

					// adding route to VPN gateway
					upstream << "" << GlobalConfig->pathToIp << " route add ${REMOTE_ADDR} via " << GlobalConfig->TmpGatewayIP << "\n";

					// adding default route with new source address
// 					upstream << "ip route add default via " << GlobalConfig->TmpGatewayIP << " src ${INTERNAL_ADDR4}" << "\n";

					// deleting existing route towards local network
// 					upstream << "ip route delete 192.168.112.0/24 via " << GlobalConfig->TmpGatewayIP << " dev "+tmpInterface+"" << "\n";

 					// deleting existing route towards Internet
// 					upstream << "ip route delete 192.168.111.0/24 dev "+tmpInterface+"" << "\n";

					// setting SPs form local network address towards all other IP addresses through tunnel
					// from roadwarrior client to VPN gateway, and vice verse, and also deleting the forwarding SP
					upstream << "echo \"\"" << "\n";
// 					upstream << "spdadd ${INTERNAL_ADDR4}/32[any] 0.0.0.0/0[any] any" << "\n";
// 					upstream << "  -P out ipsec esp/tunnel/${LOCAL_ADDR}-${REMOTE_ADDR}/require;" << "\n";
// 					upstream << "spdadd 0.0.0.0/0[any] ${INTERNAL_ADDR4}[any] any" << "\n";
// 					upstream << "  -P in ipsec esp/tunnel/${REMOTE_ADDR}-${LOCAL_ADDR}/require;" << "\n";
// 					upstream << "\" | " << GlobalConfig->pathToSetkey << " -c" << "\n";
// 					upstream << "echo \"" << "\n";
// 					upstream << "spddelete 0.0.0.0/0[any] ${INTERNAL_ADDR4}[any] any" << "\n";
// 					upstream << "  -P fwd ipsec esp/tunnel/${REMOTE_ADDR}-${LOCAL_ADDR}/require;" << "\n";
// 					upstream << "\" | setkey -c" << "\n";

					upstream << "echo \"STATE: upscript finished\"" << "\n";


				}

				upfile.close();
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write failed!" ).arg ( upfile.name() ), GlobalConfig->error );
				setGuiStatus ( disconnected );
				return;
			}


			QFile downfile ( tmpPath+"racoon-"+ProfileName+".phase1-down.sh" );
			QTextStream downstream ( &downfile );
			if ( downfile.open ( IO_WriteOnly ) )
			{
				downstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
				downstream << "# generated by kvpnc. Do not edit it." << "\n";
				downstream << "# profile: " + ProfileName << "\n";
				downstream << "" << "\n";
				downstream << "echo \"STATE: phase1 down\"" << "\n";

				// listing known IP addresses and setting PATH environment variable
				downstream << "echo \"----------------\"" << "\n";
				downstream << "echo \"internal address: ${INTERNAL_ADDR4}\"" << "\n";
				downstream << "echo \"local address: ${LOCAL_ADDR}\"" << "\n";
				downstream << "echo \"remote address: $REMOTE_ADDR\"" << "\n";
				downstream << "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin" << "\n";

				if (GlobalConfig->currentProfile->getUseModeConfig())
				{
					// defining variable to hold the name of virtual network interface
					downstream << "if="+tmpInterface << "\n";

					// deleting internal IP address from virtual network interface
					downstream << "ip address delete ${INTERNAL_ADDR4} dev ${if}" << "\n";
				}
				
				// deleting route towards VPN gateway" << "\n";
				downstream << "ip route delete ${REMOTE_ADDR} via " << GlobalConfig->TmpGatewayIP << "" << "\n";

				// adding default route through network interface
 				//downstream << "ip route add default dev "+tmpInterface+"" << "\n";

				// adding routes towards local network and Internet
				// downstream << "ip route add 192.168.112.0/24 via " << GlobalConfig->TmpGatewayIP << " dev "+tmpInterface+"" << "\n";
				//downstream << "ip route add 192.168.111.0/24 dev "+tmpInterface+" src ${LOCAL_ADDR}" << "\n";

				// flushing SPD and SAD
				downstream << GlobalConfig->pathToSetkey << " -F" << "\n";
				downstream << GlobalConfig->pathToSetkey << " -FP" << "\n";

				downstream << "echo \"STATE: downscript finished\"" << "\n";


				downfile.close();
			}
			else
			{
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write failed!" ).arg ( downfile.name() ), GlobalConfig->error );
				setGuiStatus ( disconnected );
				return;
			}

			Utils ( GlobalConfig, this ).doChmod ( tmpPath+"racoon-"+ProfileName+".phase1-up.sh","a+x"  );
			Utils ( GlobalConfig, this ).doChmod ( tmpPath+"racoon-"+ProfileName+".phase1-down.sh" ,"a+x" );

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

			doChmodPskFile();

			OpenL2tpProcess=0L;
			L2tpdProcess=0L;

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

// 				doRacoon();
			}
		}
		else
		{
			disconnectClicked();
		}
	} // racoon

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

		if (GlobalConfig->currentConnectRetry > GlobalConfig->maxConnectRetry)
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( i18n ( "Max connect retries (%1) reached, stopping." ).arg(QString().setNum(GlobalConfig->maxConnectRetry)), GlobalConfig->debug );
			return;
		}

		//setGuiStatus(connecting);

		// looking for ipsec

		if ( Utils ( GlobalConfig ).getToolInfo ( "ipsec" )->found == false )
		{
			KMessageBox::error ( this, i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "ipsec (" + IpsecType + ")" ).arg ( GlobalConfig->pathToIpsec ) );
			GlobalConfig->appendLogEntry ( i18n ( "Unable to find \"%1\" at \"%2\"!" ).arg ( "ipsec (" + IpsecType + ")" ).arg ( GlobalConfig->pathToIpsec ), GlobalConfig->error );
			ok = false;
			setGuiStatus ( disconnected );
			return ;
		}
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
		{
			if ( Utils ( GlobalConfig ).getToolInfo ( "l2tpd" )->found == false && Utils ( GlobalConfig ).getToolInfo ( "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->haveUserData)
		{
			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && ( GlobalConfig->currentProfile->getSavePsk() == false || GlobalConfig->currentProfile->getPreSharedKey().isEmpty() ) && GlobalConfig->currentProfile->getAllowEmptyPrivateKeyPassword() == false )
			{
				askUsernamePass = false;
				askPsk = true;
			}
		}

		// L2TP/XAUTH
		if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
		{
			GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
			GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();

			if (GlobalConfig->TmpPassword.isEmpty() || GlobalConfig->TmpUsername.isEmpty())
				askUsernamePass=true;

			if ( !GlobalConfig->currentProfile->getPskIsInFile() )
				GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey();
			else
			{
				QFile PskFile ( GlobalConfig->currentProfile->getPreSharedKeyFile() );
				if ( PskFile.open ( IO_ReadOnly ) )
				{
					QString PskFileContent = QString ( PskFile.readAll() );
					PskFile.close();
					GlobalConfig->TmpGroupPassword = PskFileContent;
				}
			}
			GlobalConfig->WaitingForXauth=false;
		}



		if ( AuthRetry )
			askUsernamePass = true;

		if (!GlobalConfig->haveUserData)
		{
	
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan && ( !GlobalConfig->currentProfile->getSaveUserPassword() && GlobalConfig->currentProfile->getUserName().isEmpty() || GlobalConfig->currentProfile->getUserPassword().isEmpty() ) )
				askUsernamePass = true;
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 4 )
				GlobalConfig->appendLogEntry ( i18n ( "User data already collected." ), GlobalConfig->debug );
		}

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

				if ( !GlobalConfig->TmpUsername.isEmpty() )
				{
					dlg.main->UsernameEdit->setText ( GlobalConfig->TmpUsername );
					if (!GlobalConfig->currentProfile->getDontSaveUsername())
						dlg.main->SaveUsernameCheckBox->setChecked(true);
				}
				else
					dlg.main->UsernameEdit->setFocus();
				dlg.main->LabelGroupPassword->setText ( i18n ( "PSK:" ) );

				if ( !GlobalConfig->TmpPassword.isEmpty() )
				{
					dlg.main->PasswordEdit->setText ( GlobalConfig->TmpPassword );
					if (GlobalConfig->currentProfile->getSaveUserPassword())
						dlg.main->SaveUsernameCheckBox->setChecked(true);
				}
				else
					if ( !GlobalConfig->TmpUsername.isEmpty() )
						dlg.main->PasswordEdit->setFocus();
			}
			else
			{
				GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
				GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserName();
			}
			if ( askPsk )
			{
				if ( !GlobalConfig->currentProfile->getPreSharedKey().isEmpty() )
				{
					dlg.main->PSKLineEdit->setText ( GlobalConfig->currentProfile->getPreSharedKey() );
					if (GlobalConfig->currentProfile->getSavePsk())
						dlg.main->SavePskCheckBox->setChecked(true);
				}
				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();
					dlg.main->SavePasswordCheckBox->hide();
					dlg.main->SaveUsernameCheckBox->hide();
				}
				else
				{
					GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
					GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserName();
				}
			}
			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();

				// FIXME
				if ( askPsk || AuthRetry )
				{
					if(( GlobalConfig->currentProfile->getSavePsk() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty() ) && GlobalConfig->TmpGroupPassword.isEmpty() )
					{
						GlobalConfig->appendLogEntry ( i18n ( "PSK is empty!" ), GlobalConfig->error );
						ok = false;
					}
				}
				if (askUsernamePass)
				{
					if ( dlg.main->SavePasswordCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSaveUserPassword ( true );
						GlobalConfig->currentProfile->setUserPassword ( GlobalConfig->TmpPassword );
					}
					else
					{
						GlobalConfig->currentProfile->setSaveUserPassword( false );
					}
				}
				if (askPsk)
				{
					if ( dlg.main->SavePskCheckBox->isChecked() )
					{
						GlobalConfig->currentProfile->setSavePsk ( true );
						
						if ( !GlobalConfig->currentProfile->getPskIsInFile() )
							GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
						else
						{
							QFile PskFile ( GlobalConfig->currentProfile->getPreSharedKeyFile() );
							if ( PskFile.open ( IO_WriteOnly ) )
							{
								QTextStream stream;
								stream.setDevice ( &PskFile );
								stream << GlobalConfig->TmpGroupPassword;
								PskFile.close();
							}
						}
						
					}
					else
					{
						GlobalConfig->currentProfile->setSavePsk( 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();
				}
				GlobalConfig->haveUserData=true;
			}
			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 )
		{

		backupDefaultRoute();

		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" || GlobalConfig->currentProfile->getNetworkDevice() == "" )
		{
			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="";
		if (!RemoteNetAddr.isEmpty())
			RemoteNet = RemoteNetAddr + "/" + RemoteNetMask;
		QString LocalNetAddr = LocalIP;
		QString LocalNetMask = "/32";
		QString LocalNet="";

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

		startStopIpsec(true);
		backupIpsecSystemConfig();
		
		QString IpsecPrefix = "/etc";

		// write /etc/ipsec.secrets
		QFile IpsecSecretsFile ( IpsecPrefix + "/ipsec.secrets" ); // warning: static
		QTextStream stream ( &IpsecSecretsFile );
		if ( IpsecSecretsFile.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() )
				{
					if (!(IpsecToolInfo->Version.contains ( "strongSwan" ) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()))
					{
						// normal
						stream << ": PSK \"" + GlobalConfig->currentProfile->getPreSharedKey() + "\"\n";
					}
					else if ((IpsecToolInfo->Version.contains ( "Openswan" ) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()))
					{
						// XAUTH openswan
						stream << GlobalConfig->currentProfile->getGateway()  <<" @" << GlobalConfig->currentProfile->getID() << "  : PSK \""+GlobalConfig->currentProfile->getPreSharedKey()+"\"\n";
					}
					else if ((IpsecToolInfo->Version.contains ( "strongSwan" ) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()))
					{
						// XAUTH strongSwan
						stream << ": PSK \"" + GlobalConfig->currentProfile->getPreSharedKey() + "\"\n";
						stream << ": XAUTH \""+GlobalConfig->TmpUsername+"\" \""+GlobalConfig->TmpPassword+"\""+"\n";
					}
				}
				else
				{
					QFile PskFile ( GlobalConfig->currentProfile->getPreSharedKeyFile() );
					if ( PskFile.open ( IO_ReadOnly ) )
					{
						QString PskFileContent = QString ( PskFile.readAll() );
						PskFile.close();
						if (!GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
						{
							// normal
							stream << ": PSK \"" + PskFileContent + "\"\n";
						}
						else
						{
							// XAUTH
							stream << GlobalConfig->currentProfile->getGateway()  <<" @" << GlobalConfig->currentProfile->getID() << "  : PSK \""+PskFileContent+"\"\n";
						}
					}
				}

			}
			IpsecSecretsFile.close();

			if (GlobalConfig->KvpncDebugLevel > 6)
			{
				GlobalConfig->appendLogEntry(i18n("---- %1 ---").arg(IpsecSecretsFile.name()),GlobalConfig->debug);
				GlobalConfig->appendLogEntry(QString(IpsecSecretsFile.readAll()),GlobalConfig->debug);
				GlobalConfig->appendLogEntry(i18n("---- end ---"),GlobalConfig->debug);
			}

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

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

				stream.setDevice ( &IpsecConfigFile );
				stream << "# generated by kvpnc. Do not edit it." << "\n";
				stream << "# profile: " + ProfileName << "\n";
				stream << "# right: remote" << "\n";
				stream << "# left: local" << "\n";
				stream << "" << "\n";

				if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry(i18n("IPSec version: %1.%2.%3").arg(QString::number(IpsecMajor)).arg(QString::number(IpsecMinor)).arg(QString::number(IpsecSubMinor)),GlobalConfig->debug);

// 				if ( realversion.find ( "2.", 0, -1 ) > -1 )
				if ( !IpsecType.contains ( "free" )) // only version 2
				{
					stream << "version 2" << "\n";
				}

				stream << "config setup" << "\n";
				if (GlobalConfig->currentProfile->getNetworkDevice() == "default")
					stream << "    interfaces=%defaultroute" << "\n";
				else
					stream << "    interfaces=\"ipsec0=" << tmpInterface << "\"" << "\n";

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

				if (GlobalConfig->currentProfile->getUseVirtualSubnetworks())
				{
					if (!GlobalConfig->currentProfile->getVirtualSubnetworks().isEmpty())
						stream << "    virtual_private=" << GlobalConfig->currentProfile->getVirtualSubnetworks().replace(" virtual_private=","") << "\n";
				}


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

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

				if ( realversion.find ( "1.", 0, -1 ) > -1 )
				{
					if (!IpsecToolInfo->Version.contains ( "strongSwan" ))
						stream << "    plutoload=%search" << "\n";
					if (!IpsecToolInfo->Version.contains ( "strongSwan" ))
						stream << "    plutostart=%search" << "\n";
					if (IpsecToolInfo->Version.contains ( "strongSwan", false ))
						stream << "    plutostart=yes" << "\n";
				}
				stream << "" << "\n";
				stream << "conn %default" << "\n";
				stream << "    keyingtries=" << GlobalConfig->currentProfile->getMaxConnectTries() << "\n";
				stream << "    #keylife=1200s" << "\n";
				stream << "    #ikelifetime=1200s" << "\n";
				stream << "\n";

				// our connection
				stream << "conn " << GlobalConfig->currentProfile->getName() << "\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 )
				{
					if (!(IpsecToolInfo->Version.contains ( "strongSwan" ) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()))
						stream << "    authby=secret" << "\n";
					if ((IpsecToolInfo->Version.contains ( "strongSwan" ) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()))
						stream << "    authby=xauthpsk" << "\n";
				}
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
					stream << "    type=transport" << "\n"; // we have to use tunnel mode

					if (GlobalConfig->currentProfile->getIpsecVpnMode() == "tunnel")
					{
						GlobalConfig->currentProfile->setIpsecVpnMode("transport");
						GlobalConfig->appendLogEntry ( i18n("IPsec vpn mode was set to \"tunnel\" but must be \"transport\" for use with L2TP. This was temporary fixed."), GlobalConfig->info );
					}
				}
				else
				{
					stream << "    type=" << GlobalConfig->currentProfile->getIpsecVpnMode() << "\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";
				if (GlobalConfig->currentProfile->getUseCustomIke())
					stream << "    ike=" << GlobalConfig->currentProfile->getIpsecIke() << "\n";

				if (GlobalConfig->currentProfile->getUseCustomEsp())
					stream << "    esp=" << GlobalConfig->currentProfile->getIpsecEsp()  << "\n";

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

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

				if (!GlobalConfig->currentProfile->getPerfectForwardSecrety().isEmpty())
				{
					stream << "    pfsgroup=" << GlobalConfig->currentProfile->getPerfectForwardSecrety() << "\n";
				}


// 				stream << "    auto=start" << "\n";
				stream << "    left=" + LocalIP << "\n"; // local ip
// 				stream << "    left=%defaultroute" << "\n"; // iface to default route
				// 				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";
// 					else
// 					{
// 						if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
// 							rightid = getX509CertificateID ( GlobalConfig->currentProfile->getX509Certificate(), false ); // remote
// 					}

// 					if ( !GlobalConfig->currentProfile->getUseSpecialLocalID() )
					if (GlobalConfig->currentProfile->getLocalIDType() == i18n("Certificate ID") )
					{
						if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert && !GlobalConfig->currentProfile->getUseSmartcard() )
							leftid = getX509CertificateID ( GlobalConfig->currentProfile->getX509Certificate(), true ); // local
						else
							leftid = "asn1dn";
						stream << "    leftid=\"" + leftid + "\""<< "\n";
					}
					else
					{
						stream << "    leftid=\"" + GlobalConfig->currentProfile->getSpecialLocalID()<< "\""<< "\n";
					}

				}
				if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
				{
					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";
					if ( GlobalConfig->currentProfile->getUseSpecialLocalID() && !GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
					{
						
						if(GlobalConfig->currentProfile->getLocalIDType() == "asn1dn")
							stream << "    leftid=\"asn1dn\""<< "\n";
						else
							stream << "    leftid=\"" + GlobalConfig->currentProfile->getSpecialLocalID()<< "\""<< "\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->getUseVirtualIP())
				{
					if (!GlobalConfig->currentProfile->getRemoteVirtualIP().isEmpty())
						stream << "    rightsubnet=" << GlobalConfig->currentProfile->getRemoteVirtualIP() << "\n";
				}
				else
				{
					if (GlobalConfig->currentProfile->getUseRemoteNetwork() && !RemoteNetAddr.isEmpty())
						stream << "    rightsubnet=" << RemoteNet << "\n";
				}

				if (!LocalNet.isEmpty())
					stream << "    leftsubnet=" << LocalNet << "\n";

				if (GlobalConfig->currentProfile->getUseLeftSourceIp())
				{
					if (!GlobalConfig->currentProfile->getLeftSourceIp().isEmpty())
						stream << "    leftsourceip=" << GlobalConfig->currentProfile->getLocalVirtualIP() << "\n";
				}
				if (GlobalConfig->currentProfile->getUseRightSourceIp())
				{
					if (!GlobalConfig->currentProfile->getRightSourceIp().isEmpty())
						stream << "    rightsourceip=" << GlobalConfig->currentProfile->getRemoteVirtualIP() << "\n";
				}




				// XAUTH
				if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
				{
					QString LocalID = GlobalConfig->currentProfile->getSpecialLocalID();
//       					if (!LocalID.find( "@", 0 , FALSE ) > -1)
// 						LocalID="@"+LocalID;
					if (IpsecToolInfo->Version.contains ( "Openswan" , false))
					{
					 	stream << "    leftxauthclient=yes" << "\n";
					 	stream << "    rightxauthserver=yes" << "\n";
					}
					if (IpsecToolInfo->Version.contains ( "strongSwan", false ))
    					{
						stream << "    xauth=client" << "\n";
					}
					stream << "    leftid=" << LocalID << "\n";

					// later
// 					stream << "    modecfgpull=no" << "\n";
				}

				stream << "    auto=add" << "\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";
				}

				IpsecConfigFile.close();
				if (GlobalConfig->KvpncDebugLevel > 6)
				{
					GlobalConfig->appendLogEntry(IpsecPrefix + "/ipsec.conf",GlobalConfig->debug);
					GlobalConfig->appendLogEntry("---------------------",GlobalConfig->debug);
					QString IpsecContent="";
					QFile file( IpsecPrefix + "/ipsec.conf" );
					if ( file.open( IO_ReadOnly ) ) {
						QTextStream stream( &file );
						QString line;
						while ( !stream.atEnd() ) {
							line = stream.readLine(); // line of text excluding '\n'
							GlobalConfig->appendLogEntry(line,GlobalConfig->debug);
						}
						file.close();
					}
					GlobalConfig->appendLogEntry("---------------------",GlobalConfig->debug);
				}
			}
			else
			{
				GlobalConfig->appendLogEntry(i18n("%1 could not opened. Stop.").arg(IpsecConfigFile.name()),GlobalConfig->error);
				setGuiStatus(disconnected);
				return;
			}

			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
			QFile file ( 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();
			}
			else
			{
				GlobalConfig->appendLogEntry(i18n("%1 could not opened. Stop.").arg(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh"),GlobalConfig->error);
				setGuiStatus(disconnected);
				return;
			}
			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";
				}
				
			}
			else
			{
				GlobalConfig->appendLogEntry(i18n("%1 could not opened. Stop.").arg(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh"),GlobalConfig->error);
				setGuiStatus(disconnected);
				return;
			}

			if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
			{
				// write psk.<profile>.key
				QFile Pskfile ( tmpPath + "psk." + ProfileName + ".key" );
				stream.setDevice ( &Pskfile );
				if ( Pskfile.open ( IO_WriteOnly ) )
				{
					stream << GlobalConfig->currentProfile->getPreSharedKey() << "\n";
					Pskfile.close();
				}
				else
				{
					GlobalConfig->appendLogEntry(i18n("%1 could not opened. Stop.").arg(Pskfile.name()),GlobalConfig->error);
				}
				
				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 ( useL2tpAfterFirstConnection )
				prepareL2tpd();

			IpsecPhase1Up=false;
			IpsecPhase2Up=false;


// 			startStopIpsec(false);

			ConnectProcess = new QProcess ( this );
			//
			ConnectProcess->addArgument ( GlobalConfig->pathToIpsec );

			if (IpsecToolInfo->Version.contains ( "Openswan" , false))
			{

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

				ConnectProcess->addArgument ( "setup" );
				ConnectProcess->addArgument ( "start" );
			}
			if (IpsecToolInfo->Version.contains ( "strongSwan", false ) /*&&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 )*/ )
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
// 					GlobalConfig->appendLogEntry ( "[" + IpsecType + "] " + i18n ( "Starting [strongswan] starter in foreground..." ), GlobalConfig->debug );
				GlobalConfig->appendLogEntry ( "[" + IpsecType + "] " + i18n ( "Starting ipsec..." ), GlobalConfig->debug );


// 				ConnectProcess->addArgument ( "starter" );
// 				ConnectProcess->addArgument ( "--nofork");
// 				QFile("/var/run/pluto.pid").remove();
// 				QFile("/var/run/starter.pid").remove();
// 				ConnectProcess->addArgument ( "setup" );
				ConnectProcess->addArgument ( "start" );
			}

			connect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsec() ) );
			connect ( ConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsec() ) );
// 			connect ( ConnectProcess, SIGNAL ( normalExit () ), this, SLOT ( ipsecStarted() ) );

			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->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "IPsec daemon (%1) started.").arg(IpsecType), GlobalConfig->debug);

				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;

				GlobalConfig->currentConnectRetry++;

				int currentConnectCounter=0;
				while (ConnectProcess->isRunning() /*&& currentConnectCounter <= 500*/ )
				{
					if ( GlobalConfig->KvpncDebugLevel > 8 )
					{
						if (IpsecToolInfo->Version.contains ( "strongSwan", false ))
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running, waiting" ).arg ( "ipsec start" ) , GlobalConfig->debug );
						else
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running, waiting" ).arg ( "ipsec setup start" ) , GlobalConfig->debug );
					}
					currentConnectCounter++;
					if (GlobalConfig->appPointer->hasPendingEvents ())
						GlobalConfig->appPointer->processEvents();
					usleep(500);
				}

// 				if (currentConnectCounter > 500)
// 				{
// 					if ( GlobalConfig->KvpncDebugLevel >3 )
// 						if (IpsecToolInfo->Version.contains ( "strongSwan", false ))
// 							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running but needs too long, stopping" ).arg ( "ipsec start" ) , GlobalConfig->debug );
// 						else
// 							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running but needs too long, stopping" ).arg ( "ipsec setup start" ) , GlobalConfig->debug );
// 					disconnectClicked();
// 					return;
// 				}
				ipsecStarted();
			}
		}
		else
		{
			GlobalConfig->appendLogEntry(i18n("%1 could not opened. Stop.").arg(IpsecSecretsFile.name()),GlobalConfig->error);
			setGuiStatus(disconnected);
			return;
		}

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

		// looking for pppd
		if ( Utils ( GlobalConfig ).getToolInfo ( "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;
		// 		}


		Utils::PppdCapabilities pppdcap = Utils ( GlobalConfig ).checkPppdCapabilities();
		pppdHasReplacedefaultrouteSupport = pppdcap.pppdHasReplacedefaultrouteSupport;

		if ( GlobalConfig->currentProfile->getRequireMppe())
		{
			if  (!pppdcap.pppdHasMppeRequiredSupport && !pppdcap.pppdHasRequireMppeSupport )
			{
				GlobalConfig->appendLogEntry ( i18n ( "pppd: (%1) has no MPPE support. STOP." ) .arg ( GlobalConfig->pathToPppd ), GlobalConfig->error );
				ok=false;
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 3 )
				{
					if (pppdcap.pppdHasMppeRequiredSupport)
						GlobalConfig->appendLogEntry ( i18n ( "pppd: (%1) has MPPE support: %2" ) .arg ( GlobalConfig->pathToPppd ).arg("mppe required"), GlobalConfig->debug );
					 else if (pppdcap.pppdHasRequireMppeSupport )
						GlobalConfig->appendLogEntry ( i18n ( "pppd: (%1) has MPPE support: %2" ) .arg ( GlobalConfig->pathToPppd ).arg("require-mppe"), GlobalConfig->debug );
				}
			}
		}

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

		if (!GlobalConfig->haveUserData)
		{
			if ( !GlobalConfig->currentProfile->getSaveUserPassword() || GlobalConfig->currentProfile->getUserPassword().isEmpty() || GlobalConfig->currentProfile->getUserName().isEmpty() || askUsernamePass  )
			{
				
				EnterUsernamePasswordDialog dlg ( this, i18n ( "Enter Account Data" ), false, requestUsername ); // only password
	
				if ( !GlobalConfig->currentProfile->getSaveUserPassword() )
				{
					dlg.main->PasswordEdit->setText ( GlobalConfig->currentProfile->getUserPassword() );
					dlg.main->SavePasswordCheckBox->setChecked(true);
				}
	
				dlg.main->UsernameEdit->setText ( GlobalConfig->currentProfile->getUserName() );
				if ( !dlg.main->UsernameEdit->text().isEmpty() )                //go straight to pw if username present
				{
					dlg.main->PasswordEdit->setFocus();
					dlg.main->SaveUsernameCheckBox->setChecked(true);
				}
	
				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 );
				}
			}
			else
			{
						if ( !GlobalConfig->currentProfile->getSaveUserPassword() && ! GlobalConfig->currentProfile->getUserPassword().isEmpty() )
						{
							GlobalConfig->TmpPassword =  GlobalConfig->currentProfile->getUserPassword() ;
						}
			
						
						if ( !GlobalConfig->currentProfile->getDontSaveUsername() && ! GlobalConfig->currentProfile->getUserName().isEmpty() )                //go straight to pw if username present
						{
							GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
						}
			}
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 4 )
				GlobalConfig->appendLogEntry ( i18n ( "User data already collected." ), 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 :(
			}

			GlobalConfig->OldDefaultDev =  iface.getDefaultInterface();
			GlobalConfig->OldDefaultGw = iface.getGatewayOfDefaultInterface();

			if ( GlobalConfig->KvpncDebugLevel > 3 )
				GlobalConfig->appendLogEntry ( i18n ( "Old default device: %1, old default gw: %2" ).arg (GlobalConfig->OldDefaultDev  ).arg(GlobalConfig->OldDefaultGw), GlobalConfig->debug );

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

					stream << pppdcap.RequireMppeOption;
					if (!pppdcap.MppeOptionsInALine)
						stream << "\n";

					if ( GlobalConfig->currentProfile->getAllowStatefulMode() )
					{
						stream << pppdcap.RequireStatefulOption;
						if (!pppdcap.MppeOptionsInALine)
							stream << "\n";
					}
					else
					{
						stream << pppdcap.RequireStatelessOption;
						if (!pppdcap.MppeOptionsInALine)
							stream << "\n";
					}



					if ( GlobalConfig->currentProfile->getRefuse128BitEncryption() )
					{
						stream << pppdcap.Refuse128BitMppeOption;
						if (!pppdcap.MppeOptionsInALine)
							stream << "\n";
					}
					else
					{
						stream << pppdcap.Require128BitMppeOption;
						if (!pppdcap.MppeOptionsInALine)
							stream << "\n";
					}


					if ( GlobalConfig->currentProfile->getRefuse40BitEncryption() )
					{
						stream << pppdcap.Refuse40BitMppeOption;
						if (!pppdcap.MppeOptionsInALine)
							stream << "\n";
					}


					stream << "\n";
				}
				else
				{
					stream << "# disable MPPE encryption\n";
					stream << pppdcap.RefuseMppeOption;
					if (!pppdcap.MppeOptionsInALine)
						stream << "\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 << "\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->getReplaceDefaultRoute() )
				{
					stream << "# dont set defaultroute\n";
					stream << "nodefaultroute";
					stream << "\n";
				}
				else
				{
					if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
					{
						stream << "# set defaultroute\n";
						stream << "defaultroute\n";
						if ( pppdcap.pppdHasReplacedefaultrouteSupport )
							stream << "replacedefaultroute\n";
					}
					stream << "\n";
				}


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

				if ( GlobalConfig->currentProfile->getUseMru() )
				{
					stream << "# userdefined MRU\n";
					stream << "mru " + QString().setNum ( GlobalConfig->currentProfile->getMru() ) + "\n";
					stream << "\n";
				}
				else
				{
					stream << "# default MRU\n";
					stream << "mru 1200" << "\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 ( !pppdcap.oldPppdStyle || pppdcap.pppdHasRequireMppe128Support )
						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->getDisableHeaderCompression() )
				{
					stream << "# disable TCP header compression\n";
					stream << "novj\n";
					stream << "\n";
				}

				if ( GlobalConfig->currentProfile->getDisableMagicNumberNegotiation() )
				{
					stream << "# disable magic number negotiation\n";
					stream << "nomagic\n";
					stream << "\n";
				}

				if ( GlobalConfig->currentProfile->getDisableIpx() )
				{
					stream << "# disable IPX\n";
					stream << "noipx\n";
					stream << "\n";
				}

				if ( GlobalConfig->currentProfile->getDisableProtocolFieldCompression() )
				{
					stream << "# disable protocol field compression\n";
					stream << "nopcomp\n";
					stream << "\n";
				}

				if ( GlobalConfig->currentProfile->getDisableAdressControlCompression() )
				{
					stream << "# disable adress control compression\n";
					stream << "noaccomp\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";
				}

				stream << "# kernel level debug\n";
				stream << "kdebug " << GlobalConfig->PppdKernelLogLevel << "\n";


				if (GlobalConfig->currentProfile->getRequireEap())
				{
					stream << "# force EAP\n";
					stream << "require-eap\n";
				}
				else
				{
					stream << "# refuse EAP\n";
					stream << "refuse-eap\n";
				}

				file.close();
/*
				if (GlobalConfig->currentProfile->getAuthMethod() != "chap" && GlobalConfig->currentProfile->getAuthMethod() != "chap")
					GlobalConfig->currentProfile->setAuthMethod("chap");*/
				Utils::PppdCapabilities pppdcap = Utils ( GlobalConfig ).checkPppdCapabilities();
				pppdHasReplacedefaultrouteSupport = pppdcap.pppdHasReplacedefaultrouteSupport;


				QFile pppdbackupdefaultroutefile ( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh" );
				QTextStream pppdbackupdefaultroutestream ( &pppdbackupdefaultroutefile );
				if ( pppdbackupdefaultroutefile.open ( IO_WriteOnly ) )
				{
					pppdbackupdefaultroutestream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
					pppdbackupdefaultroutestream << "# generated by kvpnc. Do not edit it." << "\n";
					pppdbackupdefaultroutestream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
					pppdbackupdefaultroutestream << GlobalConfig->pathToIp << " route show | grep default | head -n1 > " << OldDefaultroute << "\n";	
					pppdbackupdefaultroutefile.close();
				}
				
	
	
				QProcess *backupDefaultRouteProcess = new QProcess ( this );
				backupDefaultRouteProcess->addArgument ( GlobalConfig->InterpreterShell );
				backupDefaultRouteProcess->addArgument ( tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh" );
	
				if ( !backupDefaultRouteProcess->start(env) )
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" (%2) start failed!" ).arg ( "PppdBackupDefaultRouteScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh") );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) started." ).arg ( "PppdBackupDefaultRouteScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh") , GlobalConfig->debug );
					while ( backupDefaultRouteProcess->isRunning() )
						parent->QApplication::processEvents();
	
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) finished." ).arg ( "PppdBackupDefaultRouteScript" ).arg(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up") , GlobalConfig->debug );
				}


				if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
				{

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

					if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
					{
						stream << "# use chap" << "\n";
						stream << pppdcap.RequireAuthChapOption << "\n";
					}

					if (GlobalConfig->currentProfile->getAuthMethod() == "mschap")
					{
						stream << "# use mschap" << "\n";
						stream << pppdcap.RequireAuthMschapOption << "\n";
					}

					if (GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
					{
						stream << "# use mschap-v2" << "\n";
						stream << pppdcap.RequireAuthMschapv2Option << "\n";
					}


					stream << "\n";

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

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


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

					stream << "# use pap" << "\n";
					stream << pppdcap.RequireAuthPapOption << "\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 ( "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 = false;
			bool requestGrouppassword = false;
			bool needSave=false;


			if (!GlobalConfig->haveUserData)
			{
				requestUsername = GlobalConfig->currentProfile->getUserName().isEmpty();
				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 ( AuthRetry )
			{
				askUsernamePass = true;
				requestUsername = 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() && requestGrouppassword )
						{
							GlobalConfig->currentProfile->setSavePsk ( true );
							GlobalConfig->currentProfile->setPreSharedKey ( GlobalConfig->TmpGroupPassword );
							needSave=true;
						}
						else
						{
							GlobalConfig->currentProfile->setSavePsk( false );
						}

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

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

					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() && requestUsername )
						{
							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->SavePskCheckBox->isChecked() && requestGrouppassword )
						{
							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 );
						}
						else
						{
							GlobalConfig->currentProfile->setSaveUserPassword( false );
						}

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

				}

				if (needSave)
					saveSessionClicked();


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

				AuthRetry = false;
				GlobalConfig->haveUserData=true;

				// 				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";
					}
					
					if (GlobalConfig->currentProfile->getDisableBind())
					{
						openvpn_stream << "# dont listen" << "\n";
						openvpn_stream << "nobind" << "\n\n";
					}

					// openvpn > 2.1-rc9 we need script security parameter (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=494998)
					ToolInfo *OpenvpnToolInfo = Utils ( GlobalConfig ).getToolInfo ( "openvpn" ) ;
					int OpenvpnMajor = OpenvpnToolInfo->Version.section(".",0,0).toInt();
					QString OpenvpnMinor = OpenvpnToolInfo->Version.section(".",1,1);
					if (GlobalConfig->OpenvpnNeedSecurityParameter || OpenvpnMajor == 2 && (OpenvpnMinor == "1_rc9" || OpenvpnMinor == "1_rc10" || OpenvpnMinor == "1_rc11") || (OpenvpnMajor > 2 && OpenvpnMinor.toInt() >= 2))
					{
						if (GlobalConfig->KvpncDebugLevel > 3)
							GlobalConfig->appendLogEntry( i18n("OpenVPN >= 2.1-rc9 detected, adding script security parameter to config."),GlobalConfig->info );

						openvpn_stream << "# script security: allow program exec" << "\n";
						openvpn_stream << "script-security 2" << "\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::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::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 << "# userdefined packet size" << "\n";
							openvpn_stream << "mssfix " << GlobalConfig->currentProfile->getMssfix() << "\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";

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

					if ( GlobalConfig->currentProfile->getUseRenegSec() )
					{
						openvpn_stream << "# reneg-sec size" << "\n";
						openvpn_stream << "reneg-sec " << GlobalConfig->currentProfile->getRenegSec();
					}

					if ( GlobalConfig->currentProfile->getUseTunnelPing() )
					{
						openvpn_stream << "# ping through tunnel" << "\n";
						openvpn_stream << "ping " << GlobalConfig->currentProfile->getTunnelPing();
					}

					if ( GlobalConfig->currentProfile->getUseTunnelPingRestart() )
					{
						openvpn_stream << "# restart after tunnel ping failed" << "\n";
						openvpn_stream << "ping-restart " << GlobalConfig->currentProfile->getTunnelPingRestart();
					}


					if ( GlobalConfig->currentProfile->getUseFragment() )
					{
						openvpn_stream << "\n";
						openvpn_stream << "# userdefined packet size for fragmentation" << "\n";
						openvpn_stream << "fragment " << GlobalConfig->currentProfile->getFragment() << "\n\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->getReplaceDefaultRoute() )
					{
						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";
					openvpn_stream << "\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";
							// 							openvpn_stream << "auth-user-pass " << OpenvpnSecrectPath << "\n\n";

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

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

					if ( GlobalConfig->currentProfile->getAllowIpAddressChangeOfPeer() )
						openvpn_stream << "float" << "\n";
				}
				openvpn_file.close();

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

				// 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 << "dns_found=0" << "\n";
					upstream << "domain_found=0" << "\n";
					upstream << "" << "\n";
					upstream << "# Convert ENVs to an array" << "\n";
					upstream << "" << "\n";
// 					upstream << "export > /tmp/a.txt" << "\n";
// 					upstream << "echo \"-------\" >> /tmp/a.txt" << "\n";
// 					upstream << "set >> /tmp/a.txt" << "\n";
// 					upstream << "echo $foreign_option_0 > /tmp/a.txt" << "\n";
// 					upstream << "echo $foreign_option_1 >> /tmp/a.txt" << "\n";
// 					upstream << "echo $foreign_option_2 >> /tmp/a.txt" << "\n";
// 					upstream << "echo $foreign_option_3 >> /tmp/a.txt" << "\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 << "if [ -x /sbin/resolvconf ] ; then\n";
					upstream << "		echo > "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "		nameserver_found=0" << "\n";
					upstream << "		for i in \"${dns[@]}\"; do" << "\n";
					upstream << "			echo \"nameserver ${i}\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "			nameserver_found=1" << "\n";
					upstream << "		done" << "\n";
					upstream << "		if [ \"$nameserver_found\" = \"0\" ]; then" << "\n";
					upstream << "			echo \"# old nameserver\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "			cat   "+tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName()+" | grep nameserver >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "		fi" << "\n";
					upstream << "else" << "\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 << "dns_found=1" << "\n";
					upstream << "fi" << "\n";
					upstream << "" << "\n";
					upstream << "if [ -n \"${domain}\" ]; then" << "\n";
					upstream << "if [ -x /sbin/resolvconf ] ; then\n";
					upstream << "		echo domain \"${domain}\n\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "else" << "\n";
					upstream << "	sed -i -e \"$j,1 i search ${domain}\" /etc/resolv.conf || die" << "\n";
					upstream << "fi" << "\n";
					upstream << "domain_found=1" << "\n";
					upstream << "fi" << "\n";
					upstream << "if [ \"$dns_found\" = \"0\" ]; then" << "\n";
					upstream << "if [ -x /sbin/resolvconf ] ; then\n";
					upstream << "		cat "+tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName()+" |  grep  nameserver >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "else" << "\n";
					upstream << "		cat "+tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName()+" |  grep  nameserver >> /etc/resolv.conf" <<"\n";
					upstream << "fi" << "\n";
					upstream << "fi" << "\n";
					upstream << "if [ \"$domain_found\" = \"0\" ]; then" << "\n";
					upstream << "if [ -x /sbin/resolvconf ] ; then\n";
					upstream << "		echo > /dev/null\n";
					upstream << "		cat "+tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName()+" |  grep  domain >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
					upstream << "else" << "\n";
					upstream << "cat "+tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName()+" |  grep  domain >> /etc/resolv.conf" <<"\n";
					upstream << "fi" << "\n";
					upstream << "fi" << "\n";

					upstream << "if [ -x /sbin/resolvconf ] ; then\n";
					upstream << "		cat   "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << " | /sbin/resolvconf -a $dev\n";
					upstream << "		cat   "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << " | /sbin/resolvconf -u\n";
// 					upstream << "		cat "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << " > /tmp/resolv "<< "\n";

// 					upstream << "echo \"dev: ${dev}\" > /tmp/resolvup.txt" << "\n";
// 					upstream << "cat   "+tmpPath + "/openvpn.resolvconf.tmp >> "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
					upstream << "		rm -f   "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() <<"\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 <<  "#!"<< 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";
					downstream << "if [ -x /sbin/resolvconf ] ; then\n";
					downstream << "	dev=$1\n";
					downstream << "	if [ -z $dev ] ; then\n";
					if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
						downstream << "		dev=\"tun0\"\n";
					else
						downstream << "		dev=\"tap0\"\n";
					downstream << "	fi\n";
					downstream << "	/sbin/resolvconf -d $dev\n";
					downstream << "else" << "\n";
					downstream << "	cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
					downstream << "fi" << "\n";

					QString OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
					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";
					}


					downstream << "exit 0";
				}
				downfile.close();

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

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

						while (backupDefaultRouteProcess.isRunning())
						{
							if ( GlobalConfig->KvpncDebugLevel > 8 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running, waiting" ).arg (i18n ( "Default route backup process" ) ) , GlobalConfig->debug );
							if (GlobalConfig->appPointer->hasPendingEvents ())
								GlobalConfig->appPointer->processEvents();
							usleep(500);
						}

					}
				}
				else
				{
					// 			if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because default route could not be backuped." ), GlobalConfig->error );
					return ;
				}

				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 ( "openvpn" ) ->Version.section ( '.', 0, 0 ).toInt();
					int minor = Utils ( GlobalConfig, this ).getToolInfo ( "openvpn" ) ->Version.section ( '.', 1, 1 ).toInt();
					int subminor = Utils ( GlobalConfig, this ).getToolInfo ( "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() ) );
					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 ( "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->haveUserData)
		{
	
		// 	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 );
			}

		}
		else
		{
					if ( !GlobalConfig->currentProfile->getSaveUserPassword() && ! GlobalConfig->currentProfile->getUserPassword().isEmpty() )
					{
						GlobalConfig->TmpPassword =  GlobalConfig->currentProfile->getUserPassword() ;
					}
		
					
					if ( !GlobalConfig->currentProfile->getDontSaveUsername() && ! GlobalConfig->currentProfile->getUserName().isEmpty() )                //go straight to pw if username present
					{
						GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
					}
		}

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

		AuthRetry = false;
		GlobalConfig->haveUserData=true;

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

					GlobalConfig->currentConnectRetry++;

				}

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

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

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

		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "ssh: %1" ) .arg ( GlobalConfig->pathToSsh ) , 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->haveUserData)
		{
	// 		if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
			{
				if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
				{
					if ( GlobalConfig->currentProfile->getUserPassword().isEmpty() )
						askUsernamePass = true;
					else
						GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();
				}
				if ( GlobalConfig->currentProfile->getUserName().isEmpty() )
					requestUsername = true;
				else
					GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
	
				if ( AuthRetry )
				{
					askUsernamePass = true;
					requestUsername = false;
				}
			}
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 4 )
				GlobalConfig->appendLogEntry ( i18n ( "User data already collected." ), GlobalConfig->debug );
		}

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

			if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
			{
				if ( GlobalConfig->currentProfile->getSaveUserPassword() )
					dlg.main->PasswordEdit->setText ( GlobalConfig->currentProfile->getUserPassword() );
			}
			else
			{
				dlg.main->PasswordEdit->hide();
				dlg.main->LabelPassword->hide();
				dlg.main->SavePasswordCheckBox->hide();
			}
			dlg.main->UsernameEdit->setText ( GlobalConfig->currentProfile->getUserName() );
			
			if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
			{
				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->currentProfile->getAuthWithUsernameAndPassword() )
				{
					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 );
			}

		}
		else
		{
					if ( !GlobalConfig->currentProfile->getSaveUserPassword() && ! GlobalConfig->currentProfile->getUserPassword().isEmpty() )
					{
						GlobalConfig->TmpPassword =  GlobalConfig->currentProfile->getUserPassword() ;
					}
		
					
					if ( !GlobalConfig->currentProfile->getDontSaveUsername() && ! GlobalConfig->currentProfile->getUserName().isEmpty() )                //go straight to pw if username present
					{
						GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
					}
		}

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

		AuthRetry = false;
		GlobalConfig->haveUserData=true;

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

				SshProcess = new KProcess;
				*SshProcess << GlobalConfig->pathToSsh ;
// 				SshProcess->setExecutable(GlobalConfig->pathToSsh);
/*
connect(m_process, SIGNAL(processExited(KProcess*)),
 this, SLOT(slotProcessExited(KProcess*)));*/

// 			QString AskPassScript= tmpPath+"ssh."+GlobalConfig->currentProfile->getName()+".askpass.sh";
// 
// 			QFile askpassfile (AskPassScript );
// 			QTextStream stream ( &askpassfile );
// 			if ( askpassfile.open ( IO_WriteOnly ) )
// 			{
// 				stream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
// 				stream << "# generated by kvpnc. Do not edit it." << "\n";
// 				stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
// 				stream << "echo $1" << "\n";
// 				stream << "echo " << GlobalConfig->TmpPassword << "\n";
// 				stream << "" << "\n";
// 
// 				askpassfile.close();
// 			}
// 			else
// 			{
// 				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" write failed!" ).arg ( askpassfile.name() ), GlobalConfig->error );
// 				setGuiStatus ( disconnected );
// 				return;
// 			}
// 
// 			Utils ( GlobalConfig, this ).doChmod (AskPassScript,"a+x"  );
// 			Utils ( GlobalConfig, this ).doChmod (AskPassScript,"go-rw"  );

						QString sshdev = "";
						if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
							sshdev = "tun0";
						else
							sshdev ="tap0";

				// FIXME make it dynamiclly
				if (GlobalConfig->currentProfile->getUseSshConfigRemoteScript() && !GlobalConfig->currentProfile->getSshConfigRemoteScript().isEmpty() )
				{
				*SshProcess <<  "-w0" ;
				}
				else
				{
					*SshProcess <<  "-w0:0" ;
				}
				
				if (GlobalConfig->SshDebugLevel > 0)
				{
					QString SshDebug="-";
					for (int i=0;i<GlobalConfig->SshDebugLevel;i++)
						SshDebug+="v";
					*SshProcess << SshDebug;
				}

				// using ssh key
				if (! GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
				{
					if (GlobalConfig->currentProfile->getPreSharedKey().isEmpty())
					{
						KMessageBox::error( this, i18n( "No SSH key file specified!" ) );
						GlobalConfig->appendLogEntry(i18n( "No SSH key file specified!" ),GlobalConfig->error);
						disconnectClicked();
						return;
					}

					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Using keyfile: %1" ).arg(GlobalConfig->currentProfile->getPreSharedKey()), GlobalConfig->debug );
					*SshProcess <<  " -i" ;
					*SshProcess <<  GlobalConfig->currentProfile->getPreSharedKey();
				}

/*
				*SshProcess <<  "-t" ;
				*SshProcess <<  "-t" ;*/

				*SshProcess <<  "-n" ;

				// login name
				*SshProcess <<  "-l" ;
				*SshProcess <<  GlobalConfig->TmpUsername ;



				if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Using tunnel device type: %1" ).arg("TUN"), GlobalConfig->debug );
				}
				if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tap" )
				{
 					*SshProcess <<  "-o" << "Tunnel=ethernet";
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Using tunnel device type: %1" ).arg("TAP"), GlobalConfig->debug );
				}
				

				if (GlobalConfig->currentProfile->getUseRemotePort())
				{
					*SshProcess <<  "-p" ;
					*SshProcess <<  QString().setNum(GlobalConfig->currentProfile->getRemotePort() );
				}

				*SshProcess <<  GlobalConfig->TmpGatewayIP ;


				// FIXME add detection on server and make it dynamiclly
				if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
				{
					if (!GlobalConfig->currentProfile->getUseSshConfigRemoteScript())
					{
						*SshProcess <<  "/sbin/ifconfig "+sshdev+" " + GlobalConfig->currentProfile->getRemoteVirtualIP() + " pointopoint " + GlobalConfig->currentProfile->getLocalVirtualIP() + " up ; /bin/echo ssh_is_up" ;
					}
					else
					{
						if (!GlobalConfig->currentProfile->getSshConfigRemoteScript().isEmpty())
						{
							*SshProcess << GlobalConfig->currentProfile->getSshConfigRemoteScript() + " tun "+GlobalConfig->currentProfile->getRemoteVirtualIP()+" "+GlobalConfig->currentProfile->getLocalVirtualIP()+" ; /bin/echo ssh_is_up" ;

							if ( GlobalConfig->KvpncDebugLevel > 3 )
								GlobalConfig->appendLogEntry(i18n( "Using %1 as %2." ).arg(GlobalConfig->currentProfile->getSshConfigRemoteScript()).arg(i18n("ssh config remote script")),GlobalConfig->debug);
						}
						else
						{
							KMessageBox::error( this, i18n( "%1 is empty!" ).arg(i18n("ssh config remote script") ));
							GlobalConfig->appendLogEntry(i18n( "%1 is empty!" ).arg(i18n("ssh config remote script")),GlobalConfig->error);
							disconnectClicked();
							return;
						}
					}
				}

				if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tap" )
				{
					if (!GlobalConfig->currentProfile->getUseSshConfigRemoteScript())
					{
						*SshProcess <<  "/sbin/ifconfig "+sshdev+" " + GlobalConfig->currentProfile->getLocalVirtualIP() + " netmask "+GlobalConfig->currentProfile->getRemoteVirtualIP()+" up ; /bin/echo ssh_is_up" ;
					}
					else
					{
						if (!GlobalConfig->currentProfile->getSshConfigRemoteScript().isEmpty())
						{
							*SshProcess << GlobalConfig->currentProfile->getSshConfigRemoteScript() + " tap ; /bin/echo ssh_is_up" ;
							if ( GlobalConfig->KvpncDebugLevel > 3 )
								GlobalConfig->appendLogEntry(i18n( "Using %1 as %2." ).arg(GlobalConfig->currentProfile->getSshConfigRemoteScript()).arg(i18n("ssh config remote script")),GlobalConfig->debug);
						}
						else
						{
							KMessageBox::error( this, i18n( "%1 is empty!" ).arg(i18n("ssh config remote script") ));
							GlobalConfig->appendLogEntry(i18n( "%1 is empty!" ).arg(i18n("ssh config remote script")),GlobalConfig->error);
							disconnectClicked();
							return;
						}
					}
				}

				if ( GlobalConfig->KvpncDebugLevel > 3 )
				{
					QString args = "";
					QValueList<QCString> list = SshProcess->args();
					QValueList<QCString>::Iterator it = list.begin();
					while ( it != list.end() )
					{
						args += QString ( " " + *it ) ;
						++it;
					}
					GlobalConfig->appendLogEntry ( i18n ( "%1 arguments: %1" ).arg ("ssh").arg( args ), GlobalConfig->debug );
				}


				connect( SshProcess, SIGNAL ( receivedStdout(KProcess *, char *, int ) ), this, SLOT ( readFromStdout_ssh(KProcess *, char *, int ) ) );
				connect( SshProcess, SIGNAL( receivedStderr(KProcess *, char *, int ) ), this, SLOT( readFromStderr_ssh(KProcess *, char *, int ) ) );
// 				connect( SshProcess, SIGNAL( processExited() ), this, SLOT( sshExited() ) );
				
				GlobalConfig->appendLogEntry ( i18n( "Trying to connect to server \"%1\" with ...\n" ).arg( GlobalConfig->currentProfile->getGateway()) ,GlobalConfig->info);
				slotStatusMsg ( i18n ( "Connecting..." ), ID_CONNECTION_MSG );

				SshProcess->setEnvironment   ("LC_ALL", "C"  );
				SshProcess->setEnvironment   ( "LANG","C" );
				SshProcess->setEnvironment   ( "PATH","/bin:/usr/bin:/usr/sbin:/sbin" );
//  				SshProcess->setEnvironment   ( "SSH_ASKPASS",AskPassScript );

				ToolInfo *KsshaskpassInfo = Utils( GlobalConfig ).getToolInfo ( "ksshaskpass" );
				ToolInfo *GnomeaskpassInfo = Utils( GlobalConfig ).getToolInfo ( "gnome-ssh-askpass" );

				if (KsshaskpassInfo->found)
				{
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry(i18n( "%1 will be used." ).arg("ksshaskpass"),GlobalConfig->debug);
					SshProcess->setEnvironment   ( "SSH_ASKPASS",GlobalConfig->pathToKsshAskpass);
				}
				else if (GnomeaskpassInfo->found)
				{
					SshProcess->setEnvironment   ( "SSH_ASKPASS",GlobalConfig->pathToGnomeSshAskpass);
					if ( GlobalConfig->KvpncDebugLevel > 0 )
						GlobalConfig->appendLogEntry(i18n( "%1 will be used." ).arg("gnome-ssh-askpass"),GlobalConfig->debug);
				}
				else
				{
					KMessageBox::error( this, i18n( "No ssh askpass program found!" ) );
					GlobalConfig->appendLogEntry(i18n( "No ssh askpass program found!" ),GlobalConfig->error);
					disconnectClicked();
					return;
				}

// 				SshProcess->setUsePty(KProcess::All  ,true);

// 				if ( !SshProcess->start(KProcess::NotifyOnExit,KProcess::Communication(KProcess::All)))
// 				if ( !SshProcess->start(KProcess::RunMode(KProcess::NotifyOnExit),KProcess::Communication(KProcess::All)))
				if ( !SshProcess->start(KProcess::NotifyOnExit, KProcess::All))
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "ssh" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ssh" ) , GlobalConfig->error );
					disconnectClicked();
				}
				else
				{
					ConnectingProcess = VpnAccountData::ssh;
					GlobalConfig->status = GlobalConfig->connecting;
					mw->buttonDisconnect->setEnabled ( true );
					this->DisconnectAction->setEnabled ( true );
					mw->buttonConnect->setEnabled ( false );
					this->ConnectAction->setEnabled ( false );

					GlobalConfig->currentConnectRetry++;

					SshProcess->writeStdin   ( QString(GlobalConfig->TmpPassword+'\n').ascii(),GlobalConfig->TmpPassword.length()+1);

				}

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

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

	DisconnectAction->setEnabled(false);

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

			/* type selection */
			// cisco
			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->getReplaceDefaultRoute() )
					{
						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 `echo $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();
			}
			// vpnclient
			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 setkey( "/usr/sbin/setkey" );
				//      if ( setkey.exists() )
				//       GlobalConfig->pathToSetkey = "/usr/sbin/setkey";
				//      else {
				//       setkey.setName( "/usr/local/sbin/setkey" );
				//       if ( setkey.exists() )
				//        GlobalConfig->pathToSetkey = "/usr/local/sbin/setkey";
				//       else {
				//        setkey.setName( "/usr/bin/setkey" );
				//        if ( setkey.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 ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
					{
						if ( L2tpdProcess != 0L && L2tpdProcess->isRunning() )
						{

							disconnect (this, SIGNAL(L2tpdStdoutRecieved()), this, SLOT( processStdout_l2tpd()));
							disconnect (this, SIGNAL(L2tpdStderrRecieved()), this, SLOT( processStderr_l2tpd()));

							L2tpdProcess->kill();
							if (L2tpdProcess->isRunning())
								L2tpdProcess->tryTerminate();
							sleep(1);
							if (L2tpdProcess != 0L  && L2tpdProcess->isRunning())
								L2tpdProcess->kill();
						}
					}
					if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
					{
						if ( OpenL2tpProcess != 0L && OpenL2tpProcess->isRunning() )
						{

							disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_openl2tp() ) );
							disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_openl2tp() ) );

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

							if (QFile("/var/run/openl2tpd.pid").exists())
								QFile("/var/run/openl2tpd.pid").remove();

							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "slhc", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "slhc" ).arg ( "/etc/modprobe.conf" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "slhc" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "ppp_generic", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppox", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "pppox" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppox" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppol2tp", parent ,true))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}

							startStopOpenl2tp(true);
							sleep(2);
							startStopOpenl2tp();

						}
					}
// 					}
				}

				stopRacoon();

				if ( RacoonTailProcess != 0 && RacoonTailProcess->isRunning() )
				{
					disconnect ( RacoonTailProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_tail_racoon() ) );
					disconnect ( RacoonTailProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_tail_racoon() ) );
					// 					terminateConnection( RacoonTailProcess );

					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Trying to terminate \"%1\"..." ).arg ( "racoon tail" ) , GlobalConfig->debug );

					RacoonTailProcess->tryTerminate();
					
					while (RacoonTailProcess != 0 && RacoonTailProcess->isRunning() )
					{
						sleep(1);
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "Killing \"%1\"..." ).arg ( "racoon tail" ) , GlobalConfig->debug );
						RacoonTailProcess->kill();
					}
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" killed" ).arg ( "racoon tail" ) , GlobalConfig->debug );

				}

				if ( RacoonProcess != 0 && RacoonProcess->isRunning() )
				{
// 					disconnect ( RacoonProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_racoon() ) );
// 					disconnect ( RacoonProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_racoon() ) );

					// 					terminateConnection( RacoonProcess );
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Trying to terminate \"%1\"..." ).arg ( "racoon" ) , GlobalConfig->debug );
					RacoonProcess->tryTerminate();
					while (RacoonProcess != 0 && RacoonProcess->isRunning() )
					{
						sleep(1);
						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "Killing \"%1\"..." ).arg ( "racoon" ) , GlobalConfig->debug );

						RacoonProcess->kill();
					}
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" killed" ).arg ( "racoon tail" ) , GlobalConfig->debug );

				}

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

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon && ( GlobalConfig->currentProfile->getL2tpDaemon() == "l2tpd" ||  GlobalConfig->currentProfile->getL2tpDaemon() == "l2tpd") )
				{
					// remove kvpnc entries from secrets file
					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 );
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				durationTimer.stop();
				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 )
			{
				
				// 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 ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
					{
						if ( L2tpdProcess != 0L && L2tpdProcess->isRunning() )
						{

							L2tpdProcess->kill();
							if (L2tpdProcess->isRunning())
								L2tpdProcess->tryTerminate();
							sleep(1);
							if (L2tpdProcess != 0L  && L2tpdProcess->isRunning())
								L2tpdProcess->kill();
						}
					}
					if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
					{
						if ( OpenL2tpProcess != 0L && OpenL2tpProcess->isRunning() )
						{
							disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_openl2tp() ) );
							disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_openl2tp() ) );
							OpenL2tpProcess->tryTerminate();
							sleep(1);
							if (OpenL2tpProcess->isRunning())
								OpenL2tpProcess->tryTerminate();
							sleep(1);
							if (OpenL2tpProcess != 0L  && OpenL2tpProcess->isRunning())
								OpenL2tpProcess->kill();

							if (QFile("/var/run/openl2tpd.pid").exists())
								QFile("/var/run/openl2tpd.pid").remove();

							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "slhc", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "slhc" ).arg ( "/etc/modprobe.conf" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "slhc" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "ppp_generic", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppox", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "pppox" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppox" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppol2tp", parent ,true))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}

							startStopOpenl2tp(true);
							sleep(2);
							startStopOpenl2tp();

						}
					}

					}
				}

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

				putenv ( ( char* ) ( "LC_ALL=C" ) );
				IpsecWhackDeleteProcess = new QProcess ( this );
				IpsecWhackDeleteProcess->addArgument ( GlobalConfig->pathToIpsec );
				IpsecWhackDeleteProcess->addArgument ( "whack" );
				IpsecWhackDeleteProcess->addArgument ( "--name" );
				IpsecWhackDeleteProcess->addArgument ( GlobalConfig->currentProfile->getName() );
				IpsecWhackDeleteProcess->addArgument ( "--delete" );

				connect ( IpsecWhackDeleteProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhackdelete() ) );
				connect ( IpsecWhackDeleteProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhackdelete() ) );

				if ( !IpsecWhackDeleteProcess->start(env) )
				{
					KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --delete" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --delete" ) , GlobalConfig->error );
				}
				else
				{
					int tryCounter=0;
					while (IpsecWhackDeleteProcess !=0 && IpsecWhackDeleteProcess->isRunning())
					{
						tryCounter++;
      if (tryCounter ==20)
						{
							tryCounter=0;
							if ( GlobalConfig->KvpncDebugLevel > 8 )
								GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg  ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --delete" ), GlobalConfig->debug);
						}
						usleep(500);
					}
				}

				DisconnectProcess = new QProcess ( this );
				DisconnectProcess->addArgument ( GlobalConfig->pathToIpsec );
				if (!IpsecType.contains( "strongSwan" ) )
				{
					DisconnectProcess->addArgument ( "setup" );
					DisconnectProcess->addArgument ( "stop" );
				}
// 				if (IpsecType.contains( "strongSwan" ) &&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 ) )
// 				if ( ! IpsecType.contains ( "free" ) && ( (IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4))
				if (IpsecType.contains( "strongSwan" ))
				{
					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) )
				{
					if (!IpsecType.contains( "strongSwan" ) )
					{
						KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ipsec setup stop" ) );
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ipsec setup stop" ) , GlobalConfig->error );
					}
					if ( ! IpsecType.contains ( "free" ) && ( (IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4))
					{
						KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ipsec stop" ) );
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ipsec stop" ) , GlobalConfig->error );
					}
				}
				else
				{
				int tryCounter=0;
				while (DisconnectProcess !=0 && DisconnectProcess->isRunning())
				{
						tryCounter++;
//      						if (tryCounter ==20)
						{
							tryCounter=0;
							if ( GlobalConfig->KvpncDebugLevel > 8 )
							{
								if (!IpsecType.contains( "strongSwan" ) )
									GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "ipsec setup stop" ), GlobalConfig->debug );
								if (IpsecType.contains( "strongSwan" ) &&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 ) )
									GlobalConfig->appendLogEntry (i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "ipsec stop" ), GlobalConfig->debug );
							}
					}
					usleep(500);
				}

				}

				delRouteIpsec();
				removeIptablesFreeswan();
				disconnect ( &durationTimer, SIGNAL ( timeout() ), this, SLOT ( slotDurationEvent() ) );
				setGuiStatus ( disconnected );
				durationTimer.stop();
				GlobalConfig->currentConnectRetry=0;
				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();


				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan)
				{
					// remove kvpnc entries from secrets file
					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 );
					}
				}


				// start ipsec with restored config again
// 				startStopIpsec(true);
				startStopIpsec(false,true);

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

				ToolInfo *PptpInfo = Utils ( GlobalConfig ).getToolInfo ( "pptp" );
				QString pptpversion = PptpInfo->Version.section ( ' ', 1, 1 ).section ( '/', 0, 0 ).right ( PptpInfo->Version.section ( ' ', 1, 1 ).section ( '/', 0, 0 ).length() - 1 );
				int PptpMajor= pptpversion.section('.',0,0).toInt();
				int PptpMinor= pptpversion.section('.',1,1).toInt();
				int PptpSubMinor= pptpversion.section('.',2,2).toInt();

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

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

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

				int killcounter=0;
				while (PptpProcess != 0 && PptpProcess->isRunning() && killcounter < 5)
				{
					sleep(1);
					killcounter++;
					if ( GlobalConfig->KvpncDebugLevel > 8 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "pptp" ) , GlobalConfig->debug );
					GlobalConfig->appPointer->processEvents();
				}
				
				if (killcounter >= 5)
				{
					pptpdKillProcess->kill();
					pptpdKillProcess->clearArguments();
					pptpdKillProcess->addArgument(GlobalConfig->pathToKillall);
					pptpdKillProcess->addArgument("-9");
					pptpdKillProcess->addArgument(GlobalConfig->pathToPptp);
					
					if(!pptpdKillProcess->start(env))
					{
						KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( QString(GlobalConfig->pathToKillall+" -SIGKILL "+GlobalConfig->pathToPptp ) ) );
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( QString(GlobalConfig->pathToKillall+" -SIGKILL "+GlobalConfig->pathToPptp ) ) , GlobalConfig->debug );
					}

					while (PptpProcess != 0 && PptpProcess->isRunning())
					{
						sleep(1);
						if ( GlobalConfig->KvpncDebugLevel > 8 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "pptp" ) , 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";
					downstream << "if [ -x /sbin/resolvconf ] ; then\n";
					downstream << "	dev=$1\n";
					downstream << "	if [ -z $dev ] ; then\n";
					downstream << "		dev=\"ppp0\"\n";
					downstream << "	fi\n";
					downstream << "	/sbin/resolvconf -d $dev\n";

					downstream << "	nameserver=\"$(cat /etc/resolv.conf | grep nameserver | head -n1 | sed -e 's/nameserver //')\"\n";
					downstream << "	if [ -z $nameserver ] ; then\n";
					downstream << "		nameserver=\"$(cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " | grep nameserver | head -n1 | sed -e 's/nameserver //')\"\n";
					downstream << "	fi" << "\n";

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

					if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
					{
// 						downstream << GlobalConfig->pathToIp + " route del " + GlobalConfig->currentProfile->getGateway() + "/32 via " << GlobalConfig->OldDefaultGw << " dev " << GlobalConfig->OldDefaultDev << "\n";
							downstream << GlobalConfig->pathToRoute << " del default" << "\n";
						if ( ! pppdHasReplacedefaultrouteSupport  )
						{
							downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";
						}

						if ( GlobalConfig->KvpncDebugLevel > 3 )
							GlobalConfig->appendLogEntry ( i18n ( "Removing extra route: %1 over %2 gw %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg(GlobalConfig->OldDefaultDev).arg( GlobalConfig->OldDefaultGw), GlobalConfig->debug );

						downstream << GlobalConfig->pathToIp + " route del " + GlobalConfig->currentProfile->getGateway() + "/32 via " << GlobalConfig->OldDefaultGw << " dev " << GlobalConfig->OldDefaultDev << "\n";

					}

					if (GlobalConfig->NewDefaultGw != "0.0.0.0")
					{
						QString pppdev = "";
						if ( !PppdDevice.isEmpty() )
							pppdev = PppdDevice;
						else
							pppdev = "ppp0";

						if ( GlobalConfig->KvpncDebugLevel > 3 )
							GlobalConfig->appendLogEntry ( i18n ( "Removing extra route: %1 over %2 gw %3" ).arg ( "0.0.0.0" ).arg( GlobalConfig->NewDefaultGw ).arg( pppdev ), GlobalConfig->debug );
						downstream << GlobalConfig->pathToIp + " route del 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << pppdev << "\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 restored the old /etc/resolv.conf." ), GlobalConfig->debug );
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 1 )
								GlobalConfig->appendLogEntry ( i18n ( "/etc/resolv.conf was restored." ), GlobalConfig->debug );
						}
					}

				}
				else
				{
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" could not written." ).arg ( i18n("pppd down file") ) , GlobalConfig->error );
				}
				
				if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
				{
					// 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 && OpenvpnProcess->isRunning())
				{
					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();
				
			}
			// ssh
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
			{

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

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


				// write ssh.<profile>.down
				QFile downfile ( tmpPath + "ssh." + 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";
					downstream << "if [ -x /sbin/resolvconf ] ; then\n";
					downstream << "	dev=$1\n";
					downstream << "	if [ -z $dev ] ; then\n";
					if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
						downstream << "		dev=\"tun0\"\n";
					else
						downstream << "		dev=\"tap0\"\n";
					downstream << "	fi\n";
					downstream << "	/sbin/resolvconf -d $dev\n";
					downstream << "else" << "\n";
					downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
					downstream << "fi" << "\n";

					if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
					{
						downstream << GlobalConfig->pathToIp + " route del " + GlobalConfig->currentProfile->getGateway() + "/32 via " << GlobalConfig->OldDefaultGw << " dev " << GlobalConfig->OldDefaultDev << "\n";
						downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";

						if ( GlobalConfig->KvpncDebugLevel > 3 )
							GlobalConfig->appendLogEntry ( i18n ( "Removing extra route: %1 over %2 gw %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg(GlobalConfig->OldDefaultDev).arg( GlobalConfig->OldDefaultGw), GlobalConfig->debug );

						downstream << GlobalConfig->pathToIp + " route del " + GlobalConfig->currentProfile->getGateway() + "/32 via " << GlobalConfig->OldDefaultGw << " dev " << GlobalConfig->OldDefaultDev << "\n";

					}

					if (GlobalConfig->NewDefaultGw != "0.0.0.0")
					{
						QString sshdev = "";
// 						if ( !PppDevice.isEmpty() )
// 							sshev = PppDevice;
// 						else
						if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
							sshdev = "tun0";
						else
							sshdev ="tap0";

						if ( GlobalConfig->KvpncDebugLevel > 3 )
							GlobalConfig->appendLogEntry ( i18n ( "Removing extra route: %1 over %2 gw %3" ).arg ( "0.0.0.0" ).arg( GlobalConfig->NewDefaultGw ).arg( sshdev ), GlobalConfig->debug );
						downstream << GlobalConfig->pathToIp + " route del 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << sshdev << "\n";
					}
					
					downfile.close();

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

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

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

						if ( 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 restored the old /etc/resolv.conf." ), GlobalConfig->debug );
						}
						else
						{
							if ( GlobalConfig->KvpncDebugLevel > 1 )
								GlobalConfig->appendLogEntry ( i18n ( "/etc/resolv.conf was restored." ), GlobalConfig->debug );
						}
					}

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

				}


				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->getReplaceDefaultRoute() )
				{
					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 `echo $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 )
		{
			// 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 ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
					{
						if ( L2tpdProcess != 0L)
						{
							L2tpWaitForPppUpTimer.stop();
							disconnect (this, SIGNAL(L2tpdStdoutRecieved()), this, SLOT( processStdout_l2tpd()));
							disconnect (this, SIGNAL(L2tpdStderrRecieved()), this, SLOT( processStderr_l2tpd()));

							if( L2tpdProcess->isRunning() )
							{
								L2tpdProcess->kill();
								if ( L2tpdProcess != 0L && L2tpdProcess->isRunning())
									L2tpdProcess->tryTerminate();
								sleep(1);
								if (L2tpdProcess != NULL  && L2tpdProcess->isRunning())
									L2tpdProcess->kill();
							}
						}
					}
					if ( OpenL2tpProcess != 0L)
					{
						if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
						{
							if ( OpenL2tpProcess != 0L && OpenL2tpProcess->isRunning() )
							{

								disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_openl2tp() ) );
								disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_openl2tp() ) );

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

								if (QFile("/var/run/openl2tpd.pid").exists())
									QFile("/var/run/openl2tpd.pid").remove();

							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "slhc", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "slhc" ).arg ( "/etc/modprobe.conf" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "slhc" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "ppp_generic", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppox", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "pppox" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppox" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppol2tp", parent ,true))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}

							startStopOpenl2tp(true);
							sleep(2);
							startStopOpenl2tp();
							}
						}
					}
				}
			}

			timer.stop();
			IpsecWhackStatusTimer.stop();

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

			putenv ( ( char* ) ( "LC_ALL=C" ) );
			IpsecWhackDeleteProcess = new QProcess ( this );
			IpsecWhackDeleteProcess->addArgument ( GlobalConfig->pathToIpsec );
			IpsecWhackDeleteProcess->addArgument ( "whack" );
			IpsecWhackDeleteProcess->addArgument ( "--name" );
			IpsecWhackDeleteProcess->addArgument ( GlobalConfig->currentProfile->getName() );
			IpsecWhackDeleteProcess->addArgument ( "--delete" );

			connect ( IpsecWhackDeleteProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhackdelete() ) );
			connect ( IpsecWhackDeleteProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhackdelete() ) );

			if ( !IpsecWhackDeleteProcess->start(env) )
			{
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --delete" ) );
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --delete" ) , GlobalConfig->error );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --delete" ), GlobalConfig->debug);

				int tryCounter=0;
				while (IpsecWhackDeleteProcess !=0 && IpsecWhackDeleteProcess->isRunning())
				{
					tryCounter++;
     					if (tryCounter ==20)
					{
						tryCounter=0;
						if ( GlobalConfig->KvpncDebugLevel > 8 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg  ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --delete" ), GlobalConfig->debug);
					}
					usleep(500);
				}
			}
			
			DisconnectProcess = new QProcess ( this );
			DisconnectProcess->addArgument ( GlobalConfig->pathToIpsec );
			if (!IpsecType.contains( "strongSwan" ) )
			{
				DisconnectProcess->addArgument ( "setup" );
				DisconnectProcess->addArgument ( "stop" );
			}
			if ( ! IpsecType.contains ( "free" ) && ( (IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4))
			{
				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) )
			{
				if (!IpsecType.contains( "strongSwan" ) )
				{
					KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ipsec setup stop" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ipsec setup stop" ) , GlobalConfig->error );
				}
				if ( ! IpsecType.contains ( "free" ) && ( (IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4))
				{
					KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ipsec stop" ) );
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ipsec stop" ) , GlobalConfig->error );
				}
			}
			else
			{
				int tryCounter=0;
				while (DisconnectProcess !=0 && DisconnectProcess->isRunning())
				{
					tryCounter++;
					if (tryCounter ==20)
					{
						tryCounter=0;
						if ( GlobalConfig->KvpncDebugLevel > 8 )
						{
							if (!IpsecType.contains( "strongSwan" ) )
								GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "ipsec setup stop" ), GlobalConfig->debug );
							if (IpsecType.contains( "strongSwan" ) &&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 ) )
								GlobalConfig->appendLogEntry (i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "ipsec stop" ), GlobalConfig->debug );
						}
					}
					usleep(500);
				}
			}
// 			delRouteIpsec();
			removeIptablesFreeswan();
			setGuiStatus ( disconnected );

			GlobalConfig->currentConnectRetry=0;

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

			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan)
			{
				if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
				{
					// 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 );
					}
				}	
			}

			// start ipsec with restored config again
// 			startStopIpsec(true);
			startStopIpsec(false,false);

		}
		else if (  GlobalConfig->currentProfile->getConnectionType() == 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 (RacoonctlProcess !=0 && RacoonctlProcess->isRunning())
// 			{
// 				disconnect( RacoonctlProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoonctl() ) );
// 				disconnect( RacoonctlProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoonctl() ) );
// 
// 				RacoonctlProcess->kill();
// 			}
			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 ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
							{
								if ( L2tpdProcess != 0L && L2tpdProcess->isRunning() )
								{

									L2tpWaitForPppUpTimer.stop();
									disconnect (this, SIGNAL(L2tpdStdoutRecieved()), this, SLOT( processStdout_l2tpd()));
									disconnect (this, SIGNAL(L2tpdStderrRecieved()), this, SLOT( processStderr_l2tpd()));

									L2tpdProcess->kill();
									if (L2tpdProcess->isRunning())
										L2tpdProcess->tryTerminate();
									sleep(1);
									if (L2tpdProcess != 0L  && L2tpdProcess->isRunning())
										L2tpdProcess->kill();
								}
							}
							if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
							{
								if ( OpenL2tpProcess != 0L)
								{
									if ( OpenL2tpProcess->isRunning() )
									{
										disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_openl2tp() ) );
										disconnect ( OpenL2tpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_openl2tp() ) );
										OpenL2tpProcess->tryTerminate();
										sleep(1);
										if (OpenL2tpProcess->isRunning())
											OpenL2tpProcess->tryTerminate();
										sleep(1);
										if (OpenL2tpProcess != 0L  && OpenL2tpProcess->isRunning())
											OpenL2tpProcess->kill();
	
										if (QFile("/var/run/openl2tpd.pid").exists())
											QFile("/var/run/openl2tpd.pid").remove();
									}
								}
							}

							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "slhc", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "slhc" ).arg ( "/etc/modprobe.conf" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "slhc" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "ppp_generic", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "ppp_generic" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppox", parent ))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed." ).arg ( "pppox" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
								GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppox" ), GlobalConfig->debug );
							}
							if (!Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppol2tp", parent ,true))
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}
							else
							{
								if (GlobalConfig->KvpncDebugLevel > 3)
									GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeded" ).arg ( "pppol2tp" ), GlobalConfig->debug );
							}
							startStopOpenl2tp(true);
							sleep(2);
							startStopOpenl2tp();
		
						//}
					//}
				//}
			
			}

			if ( RacoonTailProcess != 0 && RacoonTailProcess->isRunning() )
			{
				disconnect ( RacoonTailProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_tail_racoon() ) );
				disconnect ( RacoonTailProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_tail_racoon() ) );
				// 					terminateConnection( RacoonTailProcess );
				RacoonTailProcess->kill();
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "Killing \"%1\"..." ).arg ( "racoon tail" ) , GlobalConfig->debug );
			}

			if ( GlobalConfig->KvpncDebugLevel > 3 )
				GlobalConfig->appendLogEntry ( i18n ( "%1 tunnel state: %2"  ).arg("racoon").arg ( QString().setNum(racoon_tunnel_state) ) , GlobalConfig->debug );
				

			if (racoon_tunnel_state==1)
				stopRacoon();
			else
			{
				if (RacoonctlProcess != 0L)
				{
					if (RacoonctlProcess->isRunning())
						RacoonctlProcess->kill();
				}
			}

			if ( RacoonProcess != 0 && RacoonProcess->isRunning() )
			{
				disconnect ( RacoonProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_racoon() ) );
				disconnect ( RacoonProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_racoon() ) );

				// 					terminateConnection( RacoonProcess );
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "Killing \"%1\"..." ).arg ( "racoon" ) , GlobalConfig->debug );
				RacoonProcess->kill();
			}

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

			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon && ( GlobalConfig->currentProfile->getL2tpDaemon() == "l2tpd" ||  GlobalConfig->currentProfile->getL2tpDaemon() == "l2tpd") )
			{
				if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
				{
					// 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 );
					}
				}
			}
		}
		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(GlobalConfig->pathToPptp);
				
				if(!pptpdKillProcess->start(env))
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( QString(GlobalConfig->pathToKillall+" -TERM "+GlobalConfig->pathToPptp ) ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( QString(GlobalConfig->pathToKillall+" -TERM "+GlobalConfig->pathToPptp ) ) , GlobalConfig->debug );
				}
				sleep(5);


				pptpdKillProcess->kill();
				pptpdKillProcess->clearArguments();
				pptpdKillProcess->addArgument(GlobalConfig->pathToKillall);
				pptpdKillProcess->addArgument("-KILL");
				pptpdKillProcess->addArgument(GlobalConfig->pathToPptp);
				
				if(!pptpdKillProcess->start(env))
				{
					KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( QString(GlobalConfig->pathToKillall+" -KILL "+GlobalConfig->pathToPptp ) ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 1 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( QString(GlobalConfig->pathToKillall+" -KILL "+GlobalConfig->pathToPptp ) ) , GlobalConfig->debug );
				}

				int killcounter=0;
				while (PptpProcess != 0 && PptpProcess->isRunning() && killcounter < 5)
				{
					sleep(1);
					killcounter++;
					if ( GlobalConfig->KvpncDebugLevel > 8 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "pptp" ) , GlobalConfig->debug );
					GlobalConfig->appPointer->processEvents();
				}
				
				if (killcounter >= 5)
				{
					pptpdKillProcess->kill();
					pptpdKillProcess->clearArguments();
					pptpdKillProcess->addArgument(GlobalConfig->pathToKillall);
					pptpdKillProcess->addArgument("-9");
					pptpdKillProcess->addArgument(GlobalConfig->pathToPptp);
					
					if(!pptpdKillProcess->start(env))
					{
						KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( QString(GlobalConfig->pathToKillall+" -SIGKILL "+GlobalConfig->pathToPptp ) ) );
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( QString(GlobalConfig->pathToKillall+" -SIGKILL "+GlobalConfig->pathToPptp ) ) , GlobalConfig->debug );
					}

					while (PptpProcess != 0 && PptpProcess->isRunning())
					{
						sleep(1);
						if ( GlobalConfig->KvpncDebugLevel > 8 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." ).arg ( "pptp" ) , 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";
					downstream << "if [ -x /sbin/resolvconf ] ; then\n";
					downstream << "	dev=$1\n";
					downstream << "	if [ -z $dev ] ; then\n";
					downstream << "		dev=\"ppp0\"\n";
					downstream << "	fi\n";
					downstream << "	/sbin/resolvconf -d $dev\n";
					downstream << "else" << "\n";
					downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
					downstream << "fi" << "\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 restored the old /etc/resolv.conf." ), GlobalConfig->debug );
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 1 )
							GlobalConfig->appendLogEntry ( i18n ( "/etc/resolv.conf was restored." ), GlobalConfig->debug );
					}
				}


				if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
				{
					// 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 (managementhandler != 0)
				managementhandler->greetingtimer.stop();

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

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

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

			// 				terminateConnection( SshProcess );
			// 				SshProcess = new QProcess ();
			// 				SshProcess->addArgument( GlobalConfig->pathToKillall );
			// 				SshProcess->addArgument( "openvpn" );
			//
			// 				connect( SshProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_disconnect() ) );
			// 				connect( SshProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_disconnect() ) );
			//
			// 				if ( !DisconnectProcess->start(env) ) {
			// 					KMessageBox::sorry( this, i18n( "\"%1\" start failed!" ).arg( "killall ssh" ) );
			// 				}
			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;
	}
	
	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( i18n ( "Disconnected." ), GlobalConfig->debug );
}

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 );
*/
// 		NetworkInterface iface(GlobalConfig,parent);
// 		QString gatewayofdefaultinterface = "GW IP of default interface: " + iface.getGatewayOfDefaultInterface();
// 		mw->DebugOutput->append( gatewayofdefaultinterface );
// 		QString NetmaskOfInterface = "netmask IP of  interface: " + iface.getNetmaskOfInterface("wlan0");
// 		mw->DebugOutput->append( NetmaskOfInterface );
/*
		if (iface.inSameNetwork("192.168.10.253","255.255.255.0","192.168.10.222","255.255.255.0"))
			mw->DebugOutput->append("192.168.10.253 in same network as 192.168.10.222: yes");
		else
			mw->DebugOutput->append("192.168.10.253 in same network as 192.168.10.222: no");

		if (iface.inSameNetwork("192.168.10.253","255.255.255.0","192.168.1.2","255.255.255.0"))
			mw->DebugOutput->append("192.168.10.253 in same network as 192.168.1.2: yes");
		else
			mw->DebugOutput->append("192.168.10.253 in same network as 192.168.1.2: no");
*/
/*
		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();

// 	 Utils::IpsecAlgos algos = Utils(GlobalConfig).getIpsecAlgos();

	Utils::PppdCapabilities pppdcap = Utils ( GlobalConfig ).checkPppdCapabilities();

		if (pppdcap.pppdHasMppeRequiredSupport==true)
			mw->DebugOutput->append( "pppdHasMppeRequiredSupport: yes");
		else
			mw->DebugOutput->append( "pppdHasMppeRequiredSupport: no");
		if (pppdcap.pppdHasRequireMppeSupport==true)
			mw->DebugOutput->append( "pppdHasRequireMppeSupport: yes");
		else
			mw->DebugOutput->append( "pppdHasRequireMppeSupport: no");
		if (pppdcap.pppdHasReplacedefaultrouteSupport==true)
			mw->DebugOutput->append( "pppdHasReplacedefaultrouteSupport: yes");
		else
			mw->DebugOutput->append( "pppdHasReplacedefaultrouteSupport: no");
		if (pppdcap.pppdHasMppeSupport==true)
			mw->DebugOutput->append( "pppdHasMppeSupport: yes");
		else
			mw->DebugOutput->append( "pppdHasMppeSupport: no");
		if (pppdcap.oldPppdStyle==true)
			mw->DebugOutput->append( "oldPppdStyle: yes");
		else
			mw->DebugOutput->append( "oldPppdStyle: no");
		if (pppdcap.pppdOk==true)
			mw->DebugOutput->append( "pppdOk: yes");
		else
			mw->DebugOutput->append( "pppdOk: no");
// 
// 
// 	if (pppdcap.pppdHasMppeSupport)
// 		mw->DebugOutput->append( "pppdHasMppeSupport: true");
// 	else
// 		mw->DebugOutput->append( "pppdHasMppeSupport: false");
// 
// 	if (pppdcap.oldPppdStyle)
// 		mw->DebugOutput->append( "oldPppdStyle: true");
// 	else
// 		mw->DebugOutput->append( "oldPppdStyle: false");

// 	Utils::IpsecAlgos KernelCrypto = Utils ( GlobalConfig ).getKernelCrypto();
// 
//  	// phase 2 encr algos from kernel
// 	QString EncrAlgos="";
// 	for ( QStringList::Iterator it = KernelCrypto.IpsecEspEncryptionAlgorithms.begin(); it != KernelCrypto.IpsecEspEncryptionAlgorithms.end(); ++it )
// 	{
// 		  EncrAlgos+= QString(", "+*it );
// 	}
// 	mw->DebugOutput->append( "Kernel encryption algos:\n");
// 	mw->DebugOutput->append( EncrAlgos+"\n");
// 
// 	// phase 2 auth algos from kernel
// 	QString AuthAlgos="";
// 	for ( QStringList::Iterator it = KernelCrypto.IpsecEspAuthenticationAlgorithms.begin(); it != KernelCrypto.IpsecEspAuthenticationAlgorithms.end(); ++it )
// 	{
// 		AuthAlgos+= QString(", "+*it );
// 	}
// 	mw->DebugOutput->append( "Kernel auth algos:\n");
// 	mw->DebugOutput->append( AuthAlgos+"\n");
		
}

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

void KVpnc::vpnTypesInfoClicked()
{
	VpnTypesInfoDialog infodlg ( GlobalConfig );
	VpnTypesInfoAction->setChecked ( true );
	infodlg.exec();
	VpnTypesInfoAction->setChecked ( false );
}

void KVpnc::donateClicked()
{
	this->slotStatusMsg ( i18n ( "Calling KVpnc website..." ), ID_FLASH_MSG );
	QString donateurl = "http://home.gna.org/kvpnc/en/donate.html";
	QString browser = QString ( KConfigGroup ( KGlobal::config(), "General" ).readEntry ( "BrowserApplication" ) ).remove ( "!", "" );

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

		KRun * run = new KRun( KURL( donateurl ),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 ( "browser" ) ), GlobalConfig->debug );
		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( i18n ( "URL \"%1\" with browser  \"%2\" called." ).arg ( donateurl ).arg ( browser ), GlobalConfig->debug );
// 	}
	this->slotStatusMsg ( i18n ( "Ready." ), ID_STATUS_MSG );
}

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 ( ProcessMsg_connect.find ( "Connect Banner", 0, FALSE ) > -1 )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[vpnc] " + i18n ( "Connect banner recieved" ), GlobalConfig->debug );
			GlobalConfig->appendLogEntry ( ProcessMsg_connect , GlobalConfig->info );
		}



		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->KvpncDebugLevel > 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()
{
	bool abort = false;
// 	QString ProcessMsg_connect_raw = QString ( RacoonProcess->readStdout() );
// 	if (ProcessMsg_connect_raw.length() ==0)
// 		return;
// 
// 	QStringList ProcessMsg_connect_raw_list = QStringList::split( '\n', ProcessMsg_connect_raw);
// 	for ( QStringList::Iterator it = ProcessMsg_connect_raw_list.begin(); it != ProcessMsg_connect_raw_list.end(); ++it )

	while ( RacoonProcess->canReadLineStdout() )
	{
		ProcessMsg_connect = RacoonProcess->readLineStdout();
// 		ProcessMsg_connect = *it;

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

		// 	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 (ProcessMsg_connect.find ( "ERROR: ", 0 , FALSE ) > -1 && ProcessMsg_connect.find ( "algorithm mismatched", 0 , FALSE ) > -1 )
// 		{
// 			KMessageBox::error( this, i18n( "Algorithm mismatched, please select another one." ) );
// 			GlobalConfig->appendLogEntry ( i18n ( "[racoon err]: algorithm mismatched, please select another one." ) , GlobalConfig->error );
// 			abort = true;
// 		}

		if ( ProcessMsg_connect.find ( "ISAKMP-SA established", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "STATE: upscript finished", 0 , FALSE ) > -1 ||  ProcessMsg_connect.find ( "STATE: phase1 up", 0 , FALSE ) > -1)
		{
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon  )
				{
					GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "IPSec phase 1 established." ), GlobalConfig->info );
				}
				else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
					GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "Low level IPsec phase 1 established." ), GlobalConfig->info );
				}
				racoon_tunnel_state=1;
		}
		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();
					}
				}

			}
		}

		// 	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::readFromStderr_racoon()
{

	bool abort = false;
// 	QString ProcessMsg_connect = QString ( RacoonProcess->readStderr() );
// 	if (ProcessMsg_connect.length() ==0)
// 		return;
	while ( RacoonProcess->canReadLineStderr() )
	{
		ProcessMsg_connect = RacoonProcess->readLineStderr();
	
		GlobalConfig->appendLogEntry ( "[racoon err raw] " + ProcessMsg_connect, GlobalConfig->error );


		// binding to port failed
		if ( ProcessMsg_connect.find ( "ERROR: failed to bind to address", 0 , FALSE ) > -1  ||   ProcessMsg_connect.find ( "ERROR: no address could be bound.", 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" )
				{

					//RacoonProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
// 					disconnect ( RacoonProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_racoon() ) );
// 					disconnect ( RacoonProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_racoon() ) );

					if ( GlobalConfig->doKillRacoonIfStillRunning && abort == false )
					{
						if ( GlobalConfig->KvpncDebugLevel > 3 )
							GlobalConfig->appendLogEntry ( i18n ( "%1 could not bind too port, tring to kill it...." ).arg ( "racoon" ) , GlobalConfig->error );
			
						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->error );
							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 ( "-v" );
							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 );


					 		//RacoonProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
// 							connect ( RacoonProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_racoon() ) );
// 							connect ( RacoonProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_racoon() ) );

							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
								{
									doTailRacoonLog();
									racoonStarted();
									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: fatal BAD-PROPOSAL-SYNTAX", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Bad proposal from peer reported." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Bad proposal from peer reported, aborting." ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: fatal BAD-PROPOSAL-SYNTAX", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Bad proposal from peer reported." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Bad proposal from peer reported, aborting." ) , 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: delete phase1 handle.", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: none message must be encrypted", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) , 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 ( "ignore information because ISAKMP-SAhas not been established yet.", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "ignore information because ISAKMP-SA has not been established yet.", 0 , FALSE ) > -1)
		{
			//KMessageBox::error( this, i18n( "ERROR: fatal parse failure" ) );
			KMessageBox::error ( this, i18n ( "Phase 2 negotiation of IPSec connection has been failed. Please check encryption and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Phase 2 negotiation of IPSec connection has been failed. Please check encryption and hash algorithm." ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "has weak file permission", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Wrong file permission. Aborting." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Wrong file permission. Aborting." ) , 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 ( 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 ( "ERROR: ", 0 , FALSE ) > -1 && ProcessMsg_connect.find ( "algorithm mismatched", 0 , FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "Algorithm mismatched, please select another one." ) );
			GlobalConfig->appendLogEntry ( i18n ( "[racoon err]: algorithm mismatched, please select another one." ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Error: Peer not responding", 0 , FALSE ) > -1 )
		{
			//KMessageBox::error ( this, i18n ( "racoonctl: Peer not responding" )  );
			GlobalConfig->appendLogEntry ( i18n ( "racoonctl: Peer not responding" )  , GlobalConfig->error );
			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() );
		if ( GlobalConfig->KvpncDebugLevel > 3 )
			GlobalConfig->appendLogEntry ( "[racoon helper] " + ProcessMsg_connect, GlobalConfig->debug );
	}
}

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

		bool wrong_algo=false;

		if ( ProcessMsg_connect.find ( "libipsec: syntax error while parsing", 0, FALSE ) > -1 && !wrong_algo )
		{
			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 ( ProcessMsg_connect.find ( "algorithm mismatched") > -1)
// 		{
// 			KMessageBox::error ( this, i18n ( "Algorithms mismatched. Please select other values for authentication and encryption." ).arg ( "setkey" ) );
// 			GlobalConfig->appendLogEntry ( i18n ( "Algorithms mismatched. Please select other values for authentication and encryption." ) , GlobalConfig->error );
// 			wrong_algo = true;
// 			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;
			}
	
			else if ( ProcessMsg_connect.find ( "apparently already active", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "ipsec_setup: Openswan IPsec apparently already active, start aborted", 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 ( "Openswan seems still running, restart it." ) , GlobalConfig->info );
	// 			abort = true;
				startStopIpsec(true);
				sleep(5);
				startStopIpsec();
				ipsecStarted();
			}

			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 ( "ipsec" ) , 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 version 2.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 ( ProcessMsg_connect.find ( "unable to start strongSwan -- fatal errors in config", 0, FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ("Unable to start strongSwan -- fatal errors in config. Please contact the KVpnc author." ));
			GlobalConfig->appendLogEntry ( "[ipsec err] " + i18n ( "Unable to start strongSwan -- fatal errors in config. Please contact the KVpnc author." ), GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Starting strongSwan", 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[ipsec] " + ProcessMsg_connect, GlobalConfig->info );
		}
		else if ( ProcessMsg_connect.find ( "apparently already active", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "Openswan IPsec apparently already active, start aborted", 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 ( "Openswan seems still running, restart it." ) , GlobalConfig->error );
// 			abort = true;
			startStopIpsec(true);
			sleep(5);
			startStopIpsec();
			ipsecStarted();
		}
		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 )
		{
			GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "l2tpd" ) , GlobalConfig->error );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );
			return ;
		}
	}
}

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

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

		if ( ProcessMsg_connect.find ( "encountered fatal error in state STATE_XAUTH", 0 , FALSE ) > -1 )
		{
			// xauth failed openswan
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Authentication failed (%1)!" ).arg ( i18n ( "XAUTH" ) ) );
			GlobalConfig->appendLogEntry ( i18n ( "Authentication failed (%1)!" ).arg ( i18n ( "XAUTH" ) ) , GlobalConfig->error );
			AuthRetry = true;
			disconnectClicked();
			connectClicked();
		}
		else if ( ProcessMsg_connect.find ( "extended authentication failed", 0 , FALSE ) > -1 || (GlobalConfig->WaitingForXauth==true && ProcessMsg_connect.find ( "expected ISAKMP_CFG_SET, got ISAKMP_CFG_REQUEST", 0 , FALSE ) > -1))
		{
			// xauth failed strongswan
			KMessageBox::error ( this, i18n ( "Authentication failed (%1)!" ).arg ( i18n ( "XAUTH" ) ) );
			GlobalConfig->appendLogEntry ( i18n ( "Authentication failed (%1)!" ).arg ( i18n ( "XAUTH" ) ) , GlobalConfig->error );
			AuthRetry = true;
			disconnectClicked();
			connectClicked();
		}
		else if ( ProcessMsg_connect.find ( "Can't authenticate: no preshared key found", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			abort=true;
			KMessageBox::error ( this, i18n ( "Preshared key not found for connection." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Preshared key not found for connection." ) , GlobalConfig->error );
		}
		else if ( ProcessMsg_connect.find ( "prompt for Username:", 0 , FALSE ) > -1 )
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry ( i18n ( "XAUTH username requested, send it..." ) , GlobalConfig->debug );

			if (GlobalConfig->KvpncDebugLevel > 5)
				GlobalConfig->appendLogEntry ( i18n ( "XAUTH username: %1" ).arg(GlobalConfig->TmpUsername) , GlobalConfig->debug );

			IpsecWhackProcess->writeToStdin( GlobalConfig->TmpUsername+"\n" );
		}
		else if ( ProcessMsg_connect.find ( "prompt for Password:", 0 , FALSE ) > -1 )
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry ( i18n ( "XAUTH password requested, send it..." ) , GlobalConfig->debug );
			if (GlobalConfig->KvpncDebugLevel > 5)
				GlobalConfig->appendLogEntry ( i18n ( "XAUTH password: %1" ).arg(GlobalConfig->TmpPassword) , GlobalConfig->debug );

			IpsecWhackProcess->writeToStdin( GlobalConfig->TmpPassword+"\n" );
		}
		else if ( ProcessMsg_connect.find ( "listening for IKE messages", 0 , FALSE ) > -1 )
		{
			// strongswan after ipsec whack --listen
/*			disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
			disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
			delete(IpsecWhackProcess);*/
			putenv ( ( char* ) ( "LC_ALL=C" ) );
			IpsecWhackProcess = new QProcess ( this );
			IpsecWhackProcess->addArgument ( GlobalConfig->pathToIpsec );
			IpsecWhackProcess->addArgument ( "whack" );
			IpsecWhackProcess->addArgument ( "--name" );
			IpsecWhackProcess->addArgument ( GlobalConfig->currentProfile->getName() );
			IpsecWhackProcess->addArgument ( "--initiate" );

			connect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
			connect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
			connect ( IpsecWhackProcess, SIGNAL ( exited() ), this, SLOT ( ipsecwhack_exited() ) );

			if ( !IpsecWhackProcess->start(env) )
			{
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) );
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) , GlobalConfig->error );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --initiate" ), GlobalConfig->debug);
			}
		}
		else if ( ProcessMsg_connect.find ( "added connection", 0 , FALSE ) > -1 )
		{
// 			XAUTH
			if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
			{
				ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( "ipsec" ) ;
   				 if (IpsecToolInfo->Version.contains ( "Openswan" , false))
				{
					sleep(3);
					//openswan
					putenv ( ( char* ) ( "LC_ALL=C" ) );
					IpsecWhackProcess = new QProcess ( this );
					IpsecWhackProcess->addArgument ( GlobalConfig->pathToIpsec );
					IpsecWhackProcess->addArgument ( "whack" );
					IpsecWhackProcess->addArgument ( "--name" );
					IpsecWhackProcess->addArgument ( GlobalConfig->currentProfile->getName() );
					IpsecWhackProcess->addArgument ( "--initiate" );

					connect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
					connect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
					connect ( IpsecWhackProcess, SIGNAL ( exited() ), this, SLOT ( ipsecwhack_exited() ) );

					QString LogPassword="";
					if (GlobalConfig->KvpncDebugLevel > 5)
						LogPassword=GlobalConfig->TmpPassword;
					else
						LogPassword="*****";
					if ( !IpsecWhackProcess->start(env) )
					{
						KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) );
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) , GlobalConfig->error );
						disconnectClicked();
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --initiate" ), GlobalConfig->debug);
					}
				}
			}

		}
		else if ( ProcessMsg_connect.find ( "XAUTH: Successfully Authenticated", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( i18n ( "Authentication succeded." ) , GlobalConfig->info );
		}
		else if ( ProcessMsg_connect.find ( "parsing XAUTH status", 0 , FALSE ) > -1 )
		{
			GlobalConfig->WaitingForXauth=true;
		}
		else if ( ProcessMsg_connect.find ( "added connection", 0 , FALSE ) > -1 )
		{
// 			XAUTH
			if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
			{
				ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( "ipsec" ) ;
  				if (IpsecToolInfo->Version.contains ( "Openswan" , false))
				{
					sleep(3);
					//openswan
					putenv ( ( char* ) ( "LC_ALL=C" ) );
					IpsecWhackProcess = new QProcess ( this );
					IpsecWhackProcess->addArgument ( GlobalConfig->pathToIpsec );
					IpsecWhackProcess->addArgument ( "whack" );
					IpsecWhackProcess->addArgument ( "--name" );
					IpsecWhackProcess->addArgument ( GlobalConfig->currentProfile->getName() );
					IpsecWhackProcess->addArgument ( "--initiate" );

					connect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
					connect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
					connect ( IpsecWhackProcess, SIGNAL ( exited() ), this, SLOT ( ipsecwhack_exited() ) );

					QString LogPassword="";
					if (GlobalConfig->KvpncDebugLevel > 5)
						LogPassword=GlobalConfig->TmpPassword;
					else
						LogPassword="*****";
					if ( !IpsecWhackProcess->start(env) )
					{
						KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) );
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) , GlobalConfig->error );
						disconnectClicked();
					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 0 )
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --initiate" ), GlobalConfig->debug);
					}
				}
			}

		}
// 		else if ( ProcessMsg_connect.find ( "ISAKMP SA established", 0 , FALSE ) > -1 )
// 		{
// 
// 			if (IpsecPhase2Up)
// 				return;
// 
// 			if (IpsecPhase1Up)
// 				return;
// 			else
// 				IpsecPhase1Up=true;
// 			timer.stop();
// 			IpsecWhackStatusTimer.stop();
// 			abort = false;
// 			if (GlobalConfig->KvpncDebugLevel > 1)
// 			{
// 				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
// 				{
// 					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "IPSec phase 1 established." ), GlobalConfig->info );
// 				}
// 				else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
// 				{
// 					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec phase 1 established." ), GlobalConfig->info );
// 				}
// 			}
// 
// 		}
		else if ( ProcessMsg_connect.find ( "IPsec SA established", 0 , FALSE ) > -1 )
		{
			ipsecPhase2Established();
		}
		else if ( ProcessMsg_connect.find ( "XAUTH: Successfully Authenticated", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( i18n ( "Authentication succeded." ) , GlobalConfig->info );
		}
		else if ( ProcessMsg_connect.find ( "apparently already active", 0 , FALSE ) > -1 )
		{
// 			KMessageBox::error ( this, i18n ( "Openswan seems still running, restart it." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Openswan seems still running, restart it." ) , GlobalConfig->info );
// 			abort = true;
			startStopIpsec(true);
			sleep(5);
			startStopIpsec();
			ipsecStarted();
		}
		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)
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Wrong connection parameters used. Please verify in IPSec settings." ) );
				GlobalConfig->appendLogEntry ( i18n ( "Peer reported that we use wrong connection parameters." ) , GlobalConfig->error );
				abort = true;
				stopContinue = true;
			}
		}
 		else if ( ProcessMsg_connect.find ( "INVALID_ID_INFORMATION", 0 , FALSE ) > -1 )
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings." ) );
				GlobalConfig->appendLogEntry ( i18n ( "Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings." ) , 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 )
		{
			QString PeerID = ProcessMsg_connect.section ( '\'', 3, 3 );
			QString OurID = ProcessMsg_connect.section ( '\'', 1, 1 );
			KMessageBox::error ( this, i18n ( "Wrong ID \"%1\" from peer got, we expect \"%2\"." ).arg ( PeerID ).arg ( OurID ) );
			GlobalConfig->appendLogEntry ( i18n ( "Wrong ID \"%1\" from peer got, we expect \"%2\"." ).arg ( PeerID ).arg ( OurID ) , GlobalConfig->error );
			int result = KMessageBox::questionYesNo ( this, i18n( "Do you want to use  \"%1\" instead of \"%2\" as remote ID and reconnect?" ).arg(  PeerID ).arg(OurID ), i18n( "Fix remote ID?" ) );
			if ( result == 3) // Yes
			{
				disconnectClicked();
				GlobalConfig->currentProfile->setUseSpecialRemoteID(true);
				GlobalConfig->currentProfile->setSpecialRemoteID(PeerID);
				GlobalConfig->currentProfile->setRemoteIDType("user");
				saveSessionClicked();
				connectClicked();
			}
			else
			{
				if ( !stopContinue )
				{

					abort = true;
					stopContinue = true;
				}
			}
		}

		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[ipsec whack] " + ProcessMsg_connect, GlobalConfig->debug );
			// 		if (GlobalConfig->KvpncDebugLevel > 0)
			// 			GlobalConfig->appendLogEntry( "out: " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[ipsec whack 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 ( "ipsec whack --listen" ) , GlobalConfig->debug );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );
			return ;
		}

	}

}

void KVpnc::readFromStderr_ipsecwhack()
{
	while ( IpsecWhackProcess->canReadLineStderr() )
	{
		bool NormalMsg = true;
		bool ErrorMsg = false;
		bool abort = false;

		ProcessMsg_connect = IpsecWhackProcess->readLineStderr();
		// 	QString ProcessMsg_connect = QString( IpsecWhackProcess->readStderr() );


		GlobalConfig->appendLogEntry ( "[ipsec whack err] " + ProcessMsg_connect, GlobalConfig->error );

// 		// 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 ( "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)
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Wrong connection parameters used. Please verify in IPSec settings." ) );
				GlobalConfig->appendLogEntry ( i18n ( "Peer reported that we use wrong connection parameters." ) , GlobalConfig->error );
				abort = true;
				stopContinue = true;
			}
		}
 		else if ( ProcessMsg_connect.find ( "INVALID_ID_INFORMATION", 0 , FALSE ) > -1 )
		{
			if ( !stopContinue )
			{
				KMessageBox::error ( this, i18n ( "Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings." ) );
				GlobalConfig->appendLogEntry ( i18n ( "Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings." ) , 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 )
		{
			QString PeerID = ProcessMsg_connect.section ( '\'', 3, 3 );
			QString OurID = ProcessMsg_connect.section ( '\'', 1, 1 );
			KMessageBox::error ( this, i18n ( "Wrong ID \"%1\" from peer got, we expect \"%2\"." ).arg ( PeerID ).arg ( OurID ) );
			GlobalConfig->appendLogEntry ( i18n ( "Wrong ID \"%1\" from peer got, we expect \"%2\"." ).arg ( PeerID ).arg ( OurID ) , GlobalConfig->error );
			int result = KMessageBox::questionYesNo ( this, i18n( "Do you want to use  \"%1\" instead of \"%2\" as remote ID and reconnect?" ).arg(  PeerID ).arg(OurID ), i18n( "Fix remote ID?" ) );
			if ( result == 3) // Yes
			{
				disconnectClicked();
				GlobalConfig->currentProfile->setUseSpecialRemoteID(true);
				GlobalConfig->currentProfile->setSpecialRemoteID(PeerID);
				GlobalConfig->currentProfile->setRemoteIDType("user");
				saveSessionClicked();
				connectClicked();
			}
			else
			{
				if ( !stopContinue )
				{

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

void KVpnc::readFromStdout_ipsecwhacklisten()
{
	if( IpsecWhackListenProcess == 0)
		return; 
	while ( IpsecWhackListenProcess->canReadLineStdout() )
	{
		ProcessMsg_connect = IpsecWhackListenProcess->readLineStdout();
		// 	QString ProcessMsg_connect = QString( IpsecWhackListenProcess->readStdout() );

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

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( "[ipsec whack listen] " + ProcessMsg_connect, GlobalConfig->debug );

		if ( ProcessMsg_connect.find ( "listening for IKE messages", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->KvpncDebugLevel > 3)
				GlobalConfig->appendLogEntry ( "[ipsec whack listen] " + i18n("Listen was successful."), GlobalConfig->debug );
			start_ipsec_initiate();
		}
		else if ( ProcessMsg_connect.find ( "ISAKMP SA established", 0 , FALSE ) > -1 )
		{

			timer.stop();
			IpsecWhackStatusTimer.stop();

			if (IpsecPhase1Up)
				return;
			else
				IpsecPhase1Up=true;
			timer.stop();
			IpsecWhackStatusTimer.stop();
			abort = false;
			if (GlobalConfig->KvpncDebugLevel > 1)
			{
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
				{
					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "IPSec phase 1 established." ), GlobalConfig->info );
				}
				else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec phase 1 established." ), GlobalConfig->info );
				}
			}

		}
		else if ( ProcessMsg_connect.find ( "IPsec SA established", 0 , FALSE ) > -1 )
		{
			timer.stop();
			IpsecWhackStatusTimer.stop();

			if (IpsecPhase2Up)
				return;
			else
				IpsecPhase2Up=true;
			abort = false;
			
			if (GlobalConfig->KvpncDebugLevel > 1)
			{
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
				{
					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "IPSec phase 2 established." ), GlobalConfig->info );
				}
				else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec phase 2 established." ), GlobalConfig->info );
				}
			}

			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 whack listen] " + ProcessMsg_connect, GlobalConfig->debug );
// 			// 		if (GlobalConfig->KvpncDebugLevel > 0)
// 			// 			GlobalConfig->appendLogEntry( "out: " + ProcessMsg_connect, GlobalConfig->debug );
// 		}
// 		else if ( ErrorMsg )
// 		{
// 			GlobalConfig->appendLogEntry ( "[ipsec whack listen 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 ( "ipsec whack --listen" ) , GlobalConfig->debug );
// 			disconnectClicked();
// 			GlobalConfig->status = GlobalConfig->disconnected;
// 			setGuiStatus ( disconnected );
// 			return ;
// 		}
	}
}

void KVpnc::readFromStderr_ipsecwhacklisten()
{
	bool abort = false;
	if (IpsecWhackListenProcess ==0)
		return;
	while ( IpsecWhackListenProcess->canReadLineStderr() )
	{
		ProcessMsg_connect = IpsecWhackListenProcess->readLineStderr();
		// 	QString ProcessMsg_connect = QString( IpsecWhackListenProcess->readStderr() );

// 		GlobalConfig->appendLogEntry ( "[ipsec whack listen err] " + ProcessMsg_connect, GlobalConfig->error );
		

		if ( ProcessMsg_connect.find ( "Pluto is not running", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[ipsec whack listen " + i18n("Waiting for pluto"), GlobalConfig->debug );
			if (connectCounter > 25)
			{
				GlobalConfig->appendLogEntry ( "[ipsec whack listen " + i18n("Waiting for pluto needs too long"), GlobalConfig->debug );
				abort=true;
			}
			else
			{
				// we have to give some time to sleep and try again...
				connect ( IpsecWhackListenProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhacklisten() ) );
				connect ( IpsecWhackListenProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhacklisten() ) );
				IpsecWhackListenProcess->tryTerminate();
				sleep(2);
				if (IpsecWhackListenProcess->isRunning())
				{
					IpsecWhackListenProcess->kill();
					sleep(1);
				}
				connectCounter++;
				ipsecStarted();
			}
			return;
		}
		if ( ProcessMsg_connect.find ( "listening for IKE messages", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->KvpncDebugLevel > 3)
				GlobalConfig->appendLogEntry ( "[ipsec whack listen] " + i18n("Listen was successful."), GlobalConfig->debug );
			start_ipsec_initiate();
		}
		else
		{
			GlobalConfig->appendLogEntry ( "[ipsec whack listen 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 ( "ipsec whack --listen" ) , GlobalConfig->debug );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );
			return ;
		}
	}
}

void KVpnc::readFromStdout_ipsecwhackstatus()
{
	if (IpsecWhackStatusProcess ==0)
		return;
// 	QString ProcessMsg_connect_full = QString( IpsecWhackStatusProcess->readStdout() );
// 	QStringList ProcessMsg_connect_list = QStringList::split('\n', ProcessMsg_connect_full);
	while ( IpsecWhackStatusProcess !=0 && IpsecWhackStatusProcess->canReadLineStdout() )
// 	for ( QStringList::Iterator it = ProcessMsg_connect_list.begin(); it != ProcessMsg_connect_list.end(); ++it )
	{
// 		QString ProcessMsg_connect = *it;
		QString ProcessMsg_connect = IpsecWhackStatusProcess->readLineStdout();
		// 	QString ProcessMsg_connect = QString( IpsecWhackStatusProcess->readStdout() );

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

		if (GlobalConfig->KvpncDebugLevel > 4)
			GlobalConfig->appendLogEntry ( "[ipsec whack status] " + ProcessMsg_connect, GlobalConfig->debug );

		if ( ProcessMsg_connect.find (QString(GlobalConfig->currentProfile->getName()), 0, FALSE ) > -1)
		{
			
			if ( ProcessMsg_connect.find ( "ISAKMP SA established", 0 , FALSE ) > -1 )
			{

				timer.stop();
				IpsecWhackStatusTimer.stop();

				if (IpsecPhase2Up)
					return;

				if (IpsecPhase1Up)
					return;
				else
					IpsecPhase1Up=true;

				

				if (GlobalConfig->KvpncDebugLevel > 1)
				{
					if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
					{
						GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "IPSec phase 1 established." ), GlobalConfig->info );
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
					{
						GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec phase 1 established." ), GlobalConfig->info );
					}
				}
				return;
			}

			else if ( ProcessMsg_connect.find ( "IPsec SA established", 0 , FALSE ) > -1 )
			{
				ipsecPhase2Established();
			}
		}

// 		// normal
// 		if ( GlobalConfig->KvpncDebugLevel > 3 )
// 		{
// 			if ( NormalMsg )
// 			{
// 					GlobalConfig->appendLogEntry ( "[ipsec whack status] " + ProcessMsg_connect, GlobalConfig->debug );
// 				// 		if (GlobalConfig->KvpncDebugLevel > 0)
// 				// 			GlobalConfig->appendLogEntry( "out: " + ProcessMsg_connect, GlobalConfig->debug );
// 			}
// 		}
// 		else if ( ErrorMsg )
// 		{
// 			GlobalConfig->appendLogEntry ( "[ipsec whack status 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 ( "ipsec whack status" ) , GlobalConfig->debug );
// 			disconnectClicked();
// 			GlobalConfig->status = GlobalConfig->disconnected;
// 			setGuiStatus ( disconnected );
// 			return ;
// 		}
	}
}

void KVpnc::readFromStderr_ipsecwhackstatus()
{
	if (IpsecWhackStatusProcess ==0)
		return;
// 	bool abort = false;
	while ( IpsecWhackStatusProcess !=0 && IpsecWhackStatusProcess->canReadLineStderr() )
	{
		ProcessMsg_connect = IpsecWhackStatusProcess->readLineStderr();
		// 	QString ProcessMsg_connect = QString( IpsecWhackStatusProcess->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 )
// 		{
// 
// 		}


		if (IpsecStatusCheck==true)
		{

			if (GlobalConfig->KvpncDebugLevel > 6 )
				GlobalConfig->appendLogEntry ( "[ipsec whack status err] " + ProcessMsg_connect, GlobalConfig->error );


			if ( ProcessMsg_connect.find ( "Pluto is not running", 0, FALSE ) > -1)
			{
				GlobalConfig->appendLogEntry ( i18n("ipsec daemon is not running, restarting it..."), GlobalConfig->info );
				startStopIpsec(true);
				sleep(1);
				startStopIpsec(false);
			}



		}
		else
		{
			GlobalConfig->appendLogEntry ( "[ipsec whack status err] " + ProcessMsg_connect, GlobalConfig->error );

			if ( ProcessMsg_connect.find ( "Pluto is not running", 0, FALSE ) > -1)
			{
				if (!IpsecStartingInProgress)
				{
					GlobalConfig->appendLogEntry ( i18n("ipsec daemon is not running, restarting it..."), GlobalConfig->info );
					startStopIpsec(true);
					sleep(1);
					startStopIpsec(false);
				}
			}
		}

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

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

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

		if ( ProcessMsg_connect.find ( "listening for IKE messages", 0 , FALSE ) > -1 )
		{
			// strongswan after ipsec whack --listen
/*			disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
			disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
			delete(IpsecWhackProcess);*/
			putenv ( ( char* ) ( "LC_ALL=C" ) );
			IpsecWhackProcess = new QProcess ( this );
			IpsecWhackProcess->addArgument ( GlobalConfig->pathToIpsec );
			IpsecWhackProcess->addArgument ( "whack" );
			IpsecWhackProcess->addArgument ( "--name" );
			IpsecWhackProcess->addArgument ( GlobalConfig->currentProfile->getName() );
			IpsecWhackProcess->addArgument ( "--initiate" );

			connect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
			connect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
			connect ( IpsecWhackProcess, SIGNAL ( exited() ), this, SLOT ( ipsecwhack_exited() ) );

			if ( !IpsecWhackProcess->start(env) )
			{
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) );
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) , GlobalConfig->error );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --initiate" ), GlobalConfig->debug);
			}
		}

		// normal
		if ( NormalMsg )
		{
			if ( GlobalConfig->KvpncDebugLevel > 1 )
				GlobalConfig->appendLogEntry ( "[ipsec whack listen] " + ProcessMsg_connect, GlobalConfig->debug );
			// 		if (GlobalConfig->KvpncDebugLevel > 0)
			// 			GlobalConfig->appendLogEntry( "out: " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else if ( ErrorMsg )
		{
			GlobalConfig->appendLogEntry ( "[ipsec whack delete 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 ( "ipsec whack --delete" ) , GlobalConfig->debug );

			return ;
		}
	}
}

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


		GlobalConfig->appendLogEntry ( "[ipsec whack delete 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 ( "ipsec whack --delete" ) , GlobalConfig->debug );

			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;

		if ( ProcessMsg_connect.find ( "ERROR", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[racoon err] " + ProcessMsg_connect, GlobalConfig->error );
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 3 )
			{
				if ( ProcessMsg_connect.find ( "ERROR", 0 , FALSE ) == -1 )
					GlobalConfig->appendLogEntry ( "[racoon tail] " + ProcessMsg_connect, GlobalConfig->debug );
			}
		}

// 		// binding to port failed
// 		if ( ProcessMsg_connect.find ( "ERROR: failed to bind to address", 0 , FALSE ) > -1  ||   ProcessMsg_connect.find ( "ERROR: no address could be bound.", 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" )
// 				{
// 
// 					//RacoonProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
// // 					disconnect ( RacoonProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_racoon() ) );
// // 					disconnect ( RacoonProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_racoon() ) );
// 
// 					if ( GlobalConfig->doKillRacoonIfStillRunning && abort == false )
// 					{
// 						if ( GlobalConfig->KvpncDebugLevel > 3 )
// 							GlobalConfig->appendLogEntry ( i18n ( "%1 could not bind too port, tring to kill it...." ).arg ( "racoon" ) , GlobalConfig->error );
// 			
// 						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->error );
// 							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 ( "-v" );
// 							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 );
// 
// 
// 					 		//RacoonProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
// // 							connect ( RacoonProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_racoon() ) );
// // 							connect ( RacoonProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_racoon() ) );
// 
// 							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
// 								{
// 									doTailRacoonLog();
// 									racoonStarted();
// 									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;
// 			}
// 
// 		}

		if ( ProcessMsg_connect.find ( "ERROR: failed to bind to address", 0 , FALSE ) > -1  ||   ProcessMsg_connect.find ( "ERROR: no address could be bound.", 0 , FALSE ) > -1)
		{
   			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: delete phase1 handle.", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) , 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 ( "ERROR: no configuration found for", 0 , FALSE ) > -1 )
		{
			// 			KMessageBox::error( this, i18n( "ERROR: no configuration found" ) );
			GlobalConfig->appendLogEntry ( i18n ( "ERROR: no configuration found" ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: no peer's CERT payload found.", 0 , FALSE ) > -1 )
		{
			// 			KMessageBox::error( this, i18n( "ERROR: no peer's CERT payload found." ) );
			GlobalConfig->appendLogEntry ( i18n ( "ERROR: no peer's CERT payload found." ) , GlobalConfig->error );

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

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ERROR: such a cert type isn't supported:", 0 , FALSE ) > -1 )
		{
 			////KMessageBox::error( this, i18n( "ERROR: such a cert type isn't supported:" ) );
 			//GlobalConfig->appendLogEntry ( i18n ( "ERROR: such a cert type isn't supported:" ) , GlobalConfig->error );
 			//
 			//abort = true;
		}
		else if ( ProcessMsg_connect.find ( "ignore information because ISAKMP-SAhas not been established yet.", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "ignore information because ISAKMP-SA has not been established yet.", 0 , FALSE ) > -1)
		{
			//KMessageBox::error( this, i18n( "ERROR: fatal parse failure" ) );
			KMessageBox::error ( this, i18n ( "Phase 2 negotiation of IPSec connection has been failed. Please check encryption and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Phase 2 negotiation of IPSec connection has been failed. Please check encryption and hash algorithm." ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "has weak file permission", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Wrong file permission. Aborting." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Wrong file permission. Aborting." ) , GlobalConfig->error );

			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "STATE: phase1 up", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( i18n ( "Phase1 is now up." ) , GlobalConfig->error );
		}
		else if ( ProcessMsg_connect.find ( "IPsec-SA established", 0 , FALSE ) > -1 || ProcessMsg_connect.find ( "STATE: upscript finished", 0 , FALSE ) > -1)
		{
			racoon_tunnel_state++;
			if (racoon_tunnel_state  == 1 )
			{
				if ( GlobalConfig->KvpncDebugLevel > 1 )
					GlobalConfig->appendLogEntry ( "[racoon tail] " + i18n ( "First tunnel is now up, waiting for second one..." ), GlobalConfig->debug );

				if (GlobalConfig->currentProfile->getUseModeConfig())
				{
					QFile ModeCfgFile (QString(tmpPath + "/racoon-" + GlobalConfig->currentProfile->getName() + ".modecfg"));
					if (ModeCfgFile.exists())
					{
						QString TmpDns1="";
						QString TmpDns2="";
						QString internal_addr4="";
						QString internal_netmask4="";
						QString internal_cidr4="";
						QString internal_dns4="";
						QString internal_dns4_list="";
						QString internal_wins4="";
						QString internal_wins4_list="";
						QString split_include="";
						QString split_local="";
						QString default_domain="";
						QString resolvtemp="";
						if (ModeCfgFile.open ( IO_ReadOnly ) )
						{
							QTextStream stream ( &ModeCfgFile );
							QString line="";
							while ( !stream.atEnd() )
							{
								line = stream.readLine(); // line of text excluding '\n'
								if (GlobalConfig->KvpncDebugLevel > 5)
									GlobalConfig->appendLogEntry("[ModeCfg] "+line, GlobalConfig->debug);

								QString ModeCfgVar=line.section('=',0,0);
								QString ModeCfgVal=line.section('=',1,-1);
								if (ModeCfgVal=="INTERNAL_ADDR4")
									internal_addr4 = ModeCfgVal;
								else if (ModeCfgVal=="INTERNAL_NETMASK4")
									internal_netmask4=ModeCfgVal;
								else if (ModeCfgVal=="INTERNAL_CIDR4")
									internal_cidr4=ModeCfgVal;
								else if (ModeCfgVal=="INTERNAL_DNS4")
									internal_dns4=ModeCfgVal;
								else if (ModeCfgVal=="INTERNAL_DNS4_LIST")
									internal_dns4_list=ModeCfgVal;
								else if (ModeCfgVal=="INTERNAL_WINS4")
									internal_wins4=ModeCfgVal;
								else if (ModeCfgVal=="INTERNAL_WINS4_LIST")
									internal_wins4_list=ModeCfgVal;
								else if (ModeCfgVal=="SPLIT_INCLUDE")
									split_include=ModeCfgVal;
								else if (ModeCfgVal=="SPLIT_LOCAL")
									split_local=ModeCfgVal;
								else if (ModeCfgVal=="DEFAULT_DOMAIN")
									default_domain=ModeCfgVal;
							}
							ModeCfgFile.close();
						}

						// tmp
						TmpDns1 = internal_dns4;

						
						QFile racoonupfile ( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".up" );
						QTextStream racoonupstream ( &racoonupfile );
						if ( racoonupfile.open ( IO_WriteOnly ) )
						{
							QString DefaultDevice = NetworkInterface (GlobalConfig,parent).getDefaultInterface();
							racoonupstream << "if [ -x /sbin/resolvconf ] ; then\n";
							racoonupstream << "	dev=$1\n";
							racoonupstream << "	if [ -z $dev ] ; then\n";
							racoonupstream << "		dev=\""+DefaultDevice+"\"\n";
							racoonupstream << "fi\n";
							if ( !TmpDns1.isEmpty() || !TmpDns2.isEmpty() )
							{
								bool no_nameserver=false;
								racoonupstream << "if [ -x /sbin/resolvconf ] ; then\n";
								if(TmpDns2.isEmpty())
								{
									resolvtemp += "	nameserver " + TmpDns1+ "\n";
									racoonupstream << "echo \"nameserver " << TmpDns1 << "\"" << " " << "$dev\" > "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
								}
								else
								{
									resolvtemp += "	nameserver " + TmpDns1 + "\nnameserver " + TmpDns2+"\n";
									racoonupstream << "echo \"nameserver " << TmpDns1 << "\"\nnameserver " << TmpDns2 << " " << "$dev\" > "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
								}
								
								racoonupstream << "else" << "\n";
								racoonupstream << "echo >> /etc/resolv.conf\n";
								racoonupstream << "echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
								racoonupstream << "echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";
								racoonupstream << "echo \"nameserver " << TmpDns1 << "\" >> /etc/resolv.conf" << "\n";
								if ( !TmpDns2.isEmpty() )
								{
									racoonupstream << "echo \"nameserver " << TmpDns2 << "\" >> /etc/resolv.conf" << "\n";

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

										Utils ( GlobalConfig, this ).doChmod ( racoonupfile.name(), "u+x" );
									}
								}
							}
						}

					}
				}

			}
			else if ( racoon_tunnel_state == 2 )
			{


				doIptablesRacoon();
				addRouteRacoon();

				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
				{
					GlobalConfig->appendLogEntry ( "[racoon tail] " + 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();
					}
				}
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
				{
					GlobalConfig->appendLogEntry ( "[racoon tail] " + i18n ( "Low level IPsec connection established." ), GlobalConfig->success );
					start_l2tpd();
				}

			}
		}
		else if ( ProcessMsg_connect.find ( "Reading configuration from", 0 , FALSE ) > -1 )
		{
// 			GlobalConfig->appendLogEntry ( i18n ( "Reading configuration from got" ) , GlobalConfig->debug );
// 			sleep(3);
//    			racoonStarted();
		}
		else if ( ProcessMsg_connect.find ( "ERROR: none message must be encrypted", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Phase 1 negotiation of IPSec connection has been failed. Please check encryption of phase 1 and hash algorithm." ) , 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::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 tail err] " + ProcessMsg_connect, GlobalConfig->error );
		}
	}
}

void KVpnc::readFromStdout_racoonctl()
{
	//	QString ProcessMsg_connect = QString( RacoonctlProcess->readStdout() );
	while ( RacoonctlProcess->canReadLineStdout() )
	{
		bool abort = false;

		QString ProcessMsg_connect = RacoonctlProcess->readLineStdout() + "\n";
		//QString ProcessMsg_connect = RacoonctlProcess->readStdout();
// 		if ( GlobalConfig->KvpncDebugLevel > 3 )
		{
			GlobalConfig->appendLogEntry ( "[racoonctl] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		if ( ProcessMsg_connect.find ( "ERROR", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( "[racoonctl err] " + ProcessMsg_connect, GlobalConfig->error );
		}
		if ( ProcessMsg_connect.find ( "send: Bad file descriptor", 0 , FALSE ) > -1 )
		{

// 			KMessageBox::error ( this, i18n ( "Racoon seem not running!" )  );
			GlobalConfig->appendLogEntry ( i18n ( "Racoon seem not running!" )  , GlobalConfig->error );

// 			if (GlobalConfig->KvpncDebugLevel > 3)
// 				GlobalConfig->appendLogEntry ( i18n ( "Racoon seem not running!" )  , GlobalConfig->debug );

// 			if (RacoonctlConnectCounter > 25)
// 			{
// 				GlobalConfig->appendLogEntry ( "[racoonctl] " + i18n("Waiting for racoon needs too long"), GlobalConfig->debug );
// 				abort=true;
// 			}
// 			else
// 			{
// 
// 				if (GlobalConfig->KvpncDebugLevel > 3)
// 					GlobalConfig->appendLogEntry ( i18n ( "Racoon seem not running, waiting" )  , GlobalConfig->debug );
// 
// 				// we have to give some time to sleep and try again...
// 				RacoonctlProcess->tryTerminate();
// 				sleep(2);
// 				if (RacoonctlProcess->isRunning())
// 				{
// 					disconnect( RacoonctlProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoonctl() ) );
// 					disconnect( RacoonctlProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoonctl() ) );
// 					disconnect ( RacoonctlProcess, SIGNAL ( processExited () ), this, SLOT ( racoonctlExited() ) );
// 					RacoonctlProcess->kill();
// 					sleep(1);
// 					racoonStarted();
// 				}
// 				RacoonctlConnectCounter++;
// 			}

// 			abort =true;
		}
		else if ( ProcessMsg_connect.find ( "racoonctl: Cannot send combuf", 0 , FALSE ) > -1 )
		{
			//KMessageBox::error ( this, i18n ( "racoonctl: Cannot send combuf" )  );
			GlobalConfig->appendLogEntry ( i18n ( "racoonctl: Cannot send combuf" )  , GlobalConfig->error );
			abort =true;
		}
		else if ( ProcessMsg_connect.find ( "Error: Peer not responding", 0 , FALSE ) > -1 )
		{
			//KMessageBox::error ( this, i18n ( "racoonctl: Peer not responding" )  );
			GlobalConfig->appendLogEntry ( i18n ( "racoonctl: Peer not responding" )  , GlobalConfig->error );
			abort =true;
		}
		if ( ProcessMsg_connect.find ( "Password:", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->VpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[racoonctl] " + 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->KvpncDebugLevel > 3 )
				GlobalConfig->appendLogEntry ( "[racoonctl] " + i18n ( "User password: %1\n" ).arg(UserPassStr), GlobalConfig->debug );


			RacoonctlProcess->writeToStdin ( UserPassStr );
			RacoonctlProcess->writeToStdin ( "\n" );
		}
		else if ( ProcessMsg_connect.find ( "VPN connexion terminated", 0 , FALSE ) > -1 )
		{
			//KMessageBox::error ( this, i18n ( "VPN connexion terminated" )  );
			GlobalConfig->appendLogEntry ( i18n ( "VPN connexion terminated" )  , GlobalConfig->debug );
			abort =false;
		}
		else if ( ProcessMsg_connect.find ( "VPN connexion established", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
			{
				GlobalConfig->appendLogEntry( "[racoon] " + i18n( "Low level connection established." ), GlobalConfig->success );
				racoon_tunnel_state=1;
				start_l2tpd();
			}
			else
			{
				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();
				}
			}
		}
		if ( abort )
		{
			GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "racoon" ) , GlobalConfig->error );
			disconnectClicked();
		}
	}
}

void KVpnc::readFromStderr_racoonctl()
{
	//	QString ProcessMsg_connect = QString( RacoonctlProcess->readStderr() );
	while ( RacoonctlProcess->canReadLineStderr() )
	{
		bool abort = false;
		QString ProcessMsg_connect = RacoonctlProcess->readLineStderr() + "\n";
		//QString ProcessMsg_connect = RacoonctlProcess->readStderr();
		//		if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( "[racoonctl err] " + ProcessMsg_connect, GlobalConfig->error );

		if ( ProcessMsg_connect.find ( "send: Bad file descriptor", 0 , FALSE ) > -1 )
		{
// 			KMessageBox::error ( this, i18n ( "Racoon seem not running!" )  );
			GlobalConfig->appendLogEntry ( i18n ( "Racoon seem not running!" )  , GlobalConfig->error );
// 			abort =true;
		}
		else if ( ProcessMsg_connect.find ( "racoonctl: Cannot send combuf", 0 , FALSE ) > -1 )
		{
// 			KMessageBox::error ( this, i18n ( "racoonctl: Cannot send combuf" )  );
			GlobalConfig->appendLogEntry ( i18n ( "racoonctl: Cannot send combuf" )  , GlobalConfig->error );
// 			abort =true;
		}
		if ( ProcessMsg_connect.find ( "Password:", 0 , FALSE ) > -1 )
		{
			if ( GlobalConfig->VpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[racoonctl err] " + 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->KvpncDebugLevel > 3 )
				GlobalConfig->appendLogEntry ( "[racoonctl err] " + i18n ( "User password: %1\n" ).arg(UserPassStr), GlobalConfig->debug );


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


		if ( abort )
		{
			GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "racoon" ) , 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 )
		{
			timer.stop();
			connectCounter=0;
// 			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			KMessageBox::error ( this, i18n ( "Authentication has been failed." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Authentication has been failed." ) , GlobalConfig->error );
			//abort = true;
			AuthRetry = true;
			connectClicked();
		}
		else if ( ProcessMsg_connect.find ( "peer refused to authenticate", 0 , FALSE ) > -1 )
		{
			timer.stop();
			connectCounter=0;
// 			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
			KMessageBox::error ( this, i18n ( "The peer refused to authenticate." ) );
			GlobalConfig->appendLogEntry ( i18n ( "The peer refused to authenticate." ) , GlobalConfig->error );
			abort = true;
			//abort = true;
			AuthRetry = true;
			connectClicked();
		}
		else if ( ProcessMsg_connect.find ( "EAP: peer reports authentication failure", 0 , FALSE ) > -1 )
		{
			KMessageBox::error ( this, i18n ( "The peer refused to authenticate (it wants EAP). Please check username, password and EAP settings." ) );
			GlobalConfig->appendLogEntry ( i18n ( "The peer refused to authenticate (it wants EAP). Please check username, password and EAP settings." ) , 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 ( "Loopback detected", 0 , FALSE ) > -1 )
		{
// 			KMessageBox::error ( this, i18n ( "Loopback detected. Reconnecting." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Loopback detected. Reconnecting." ) , GlobalConfig->error );
			abort = true;
			connectClicked();
		}
		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" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
// 			{
// 				// 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";
				pppdupstream << "if [ -x /sbin/resolvconf ] ; then\n";
				pppdupstream << "	echo > /dev/null" << "\n";
				pppdupstream << "else" << "\n";
				pppdupstream << "	echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
				pppdupstream << "fi\n";

				QString resolvtemp="";
				bool no_nameserver=true;
				if (!GlobalConfig->currentProfile->getUseDnsServer() )
				{
					pppdupstream << "if [ -x /sbin/resolvconf ] ; then\n";
					pppdupstream << "	dev=$1\n";
					pppdupstream << "	if [ -z $dev ] ; then\n";
					pppdupstream << "		dev=\"ppp0\"\n";
					pppdupstream << "fi\n";
					if ( !TmpDns1.isEmpty() || !TmpDns2.isEmpty() )
					{
						no_nameserver=false;
						pppdupstream << "if [ -x /sbin/resolvconf ] ; then\n";
						if(TmpDns2.isEmpty())
						{
							resolvtemp += "	nameserver " + TmpDns1+ "\n";
							pppdupstream << "echo \"nameserver " << TmpDns1 << "\"" << " " << "$dev\" > "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
						}
						else
						{
							resolvtemp += "	nameserver " + TmpDns1 + "\nnameserver " + TmpDns2+"\n";
							pppdupstream << "echo \"nameserver " << TmpDns1 << "\"\nnameserver " << TmpDns2 << " " << "$dev\" > "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
						}
						
						pppdupstream << "else" << "\n";
						pppdupstream << "echo >> /etc/resolv.conf\n";
						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 << "fi" << "\n";

					pppdupstream << "# " << "\n";
				}
				if ((GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty()) || (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf()  && ! !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty()))
				{
					pppdupstream << "if [  -x /sbin/resolvconf ] ; then\n";
					pppdupstream << "	dev=$1\n";
					pppdupstream << "	if [ -z $dev ] ; then\n";
					pppdupstream << "		dev=\"ppp0\"\n";
					pppdupstream << "	fi\n";
					
					if ( GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty() )
						resolvtemp+= "nameserver "+GlobalConfig->currentProfile->getDnsServer()+"\n";
					if ( GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
						resolvtemp+= "search "+GlobalConfig->currentProfile->getSearchDomainInResolvConf()+"\n";
					pppdupstream << "else\n";
					if ( GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty() )
					{
						pppdupstream << "echo \"nameserver " << GlobalConfig->currentProfile->getDnsServer() + "\" >> /etc/resolv.conf\n";
						no_nameserver=false;
					}
					if ( GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
						pppdupstream << "echo \"search " << GlobalConfig->currentProfile->getSearchDomainInResolvConf() + "\" >> /etc/resolv.conf\n";
					pppdupstream << "fi\n";
				}


				pppdupstream << "if [ -x /sbin/resolvconf ] ; then\n";
				pppdupstream << "	echo \""+resolvtemp+"\" > "+tmpPath + "/pppd.resolvconf.tmp" << "\n";
				pppdupstream << "	cat "+tmpPath + "/pppd.resolvconf.tmp > "+tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName()+"\n";
				pppdupstream << "	cat   "+tmpPath + "/pppd.resolvconf.tmp | /sbin/resolvconf -a $dev\n";
				pppdupstream << "	cat   "+tmpPath + "/pppd.resolvconf.tmp | /sbin/resolvconf -u\n";

				pppdupstream << "	rm -f   "+tmpPath + "/pppd.resolvconf.tmp\n";
				
				if (no_nameserver==true)
				{
					pppdupstream << "else\n";
					pppdupstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() + " | grep nameserver >> /etc/resolv.conf\n";
				}

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

				if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
				{
					if ( GlobalConfig->KvpncDebugLevel > 3 )
						GlobalConfig->appendLogEntry ( i18n ( "replacing default route: %1" ).arg ( i18n("yes")), GlobalConfig->debug );

					if ( ! pppdHasReplacedefaultrouteSupport )
					{
// 						pppdupstream << GlobalConfig->pathToIp + " route replace default dev " + pppdev + "\n";
						pppdupstream << GlobalConfig->pathToRoute << " del default " << "\n";
						pppdupstream << GlobalConfig->pathToRoute << " add default " << pppdev << "\n";
					}

					if ( GlobalConfig->KvpncDebugLevel > 3 )
						GlobalConfig->appendLogEntry ( i18n ( "Setting extra route: %1 over %2 gw %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg(GlobalConfig->OldDefaultDev).arg( GlobalConfig->OldDefaultGw), GlobalConfig->debug );

					pppdupstream << GlobalConfig->pathToIp + " route add " + GlobalConfig->currentProfile->getGateway() + "/32 via " << GlobalConfig->OldDefaultGw << " dev " << GlobalConfig->OldDefaultDev << "\n";

					NetworkInterface iface ( GlobalConfig , parent );
					int defaultroutecount = iface.getDefaultRouteCount();
					if (defaultroutecount <1)
					{
// 						pppdupstream << GlobalConfig->pathToIp + " route add 0.0.0.0 via " << GlobalConfig->OldDefaultGw << " dev " << pppdev << "\n";
						pppdupstream << GlobalConfig->pathToRoute << " add default " << pppdev << "\n";

						if ( GlobalConfig->KvpncDebugLevel > 4 )
							GlobalConfig->appendLogEntry ( i18n ( "default route count: %1" ).arg ( QString().setNum(defaultroutecount)), GlobalConfig->debug );

						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "No default route found but replace it was requested, adding one over device %1 with gateway %2..." ).arg(pppdev).arg ( GlobalConfig->NewDefaultGw), GlobalConfig->debug );

					}
					if (defaultroutecount > 1)
					{
						pppdupstream << "newdefaultgw=$("<< GlobalConfig->pathToIp <<" route show default | grep default | grep -v "+ GlobalConfig->OldDefaultGw+")" << "\n";
						pppdupstream << "if [ -z $newdefaultgw ]; then" << "\n";
						pppdupstream << "	newdefaultgw=\"" << GlobalConfig->OldDefaultGw << "\"" << "\n";
						pppdupstream << "fi" << "\n";
						for (int i=0;i<defaultroutecount;i++)
						{
							pppdupstream << GlobalConfig->pathToRoute << " del default" << "\n";
						}
// 						pppdupstream << GlobalConfig->pathToIp + " route add 0.0.0.0 via " << GlobalConfig->OldDefaultGw << " dev " << pppdev << "\n";
						pppdupstream << GlobalConfig->pathToRoute << " add default " << pppdev << "\n";
						
						if ( GlobalConfig->KvpncDebugLevel > 4 )
							GlobalConfig->appendLogEntry ( i18n ( "default route count: %1" ).arg ( QString().setNum(defaultroutecount)), GlobalConfig->debug );

						if ( GlobalConfig->KvpncDebugLevel > 2 )
							GlobalConfig->appendLogEntry ( i18n ( "More than one default route found, deleting all and adding one over device %1 with gateway %2..." ).arg(pppdev).arg ( GlobalConfig->NewDefaultGw), GlobalConfig->debug );

					}
					else
					{
						if ( GlobalConfig->KvpncDebugLevel > 4 )
							GlobalConfig->appendLogEntry ( i18n ( "default route count : %1" ).arg ( "1"), GlobalConfig->debug );
					}



// 				NetworkInterface iface(GlobalConfig,GlobalConfig->appPointer, this);
// 				GlobalConfig->NewDefaultGw = iface.getGatewayOfDefaultInterface();
// 
// 				if (GlobalConfig->NewDefaultGw != "0.0.0.0")
// 				{
// 					if ( GlobalConfig->KvpncDebugLevel > 3 )
// 						GlobalConfig->appendLogEntry ( i18n ( "Setting extra route: %1 over %2 gw %3" ).arg ( "0.0.0.0" ).arg( pppdev ).arg( GlobalConfig->NewDefaultGw), GlobalConfig->debug );
// 					pppdupstream << GlobalConfig->pathToIp + " route add 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << pppdev << "\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 );
			}

			QString iplocal=getenv("IPLOCAL");
			QString ipremote=getenv("IPREMOTE");
			QString ifname=getenv("IFNAME");
			QString speed=getenv("SPEED");

			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "Local IP address: %1, remote IP address: %2, device: %3, speed: %4" ).arg ( TunnelInterfaceIP ).arg(ipremote).arg(ifname).arg(speed), GlobalConfig->debug );
			
			setFirewallAfterConnect();
			if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect() )
				executeCommandAfterConnect();
				
			
// 			if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
// 			{
// 				if (! 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 );
// 					}
// 
// 				}
// 				{
// 					if ( GlobalConfig->KvpncDebugLevel > 1 )
// 						GlobalConfig->appendLogEntry ( i18n ( "pppd supports replacedefaultroute and replace the route it" )  , config->debug );
// 				}
// 			}
			// 	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;
		bool error_found=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;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "MPPE required but not available", 0 , FALSE ) > -1 )
		{
			if (error_found==false)
				KMessageBox::error ( this, i18n ( "MPPE required but not available" ) );
			GlobalConfig->appendLogEntry ( i18n ( "MPPE required but not available" ) , GlobalConfig->error );
			abort = true;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "peer refused to authenticate", 0 , FALSE ) > -1 )
		{
			if (error_found==false)
				KMessageBox::error ( this, i18n ( "The peer refused to authenticate." ) );
			GlobalConfig->appendLogEntry ( i18n ( "The peer refused to authenticate." ) , GlobalConfig->error );
			abort = true;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "could not find module", 0 , FALSE ) > -1 )
		{
			if (error_found==false)
				KMessageBox::error ( this, i18n ( "Module not found." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Module not found." ), GlobalConfig->error );
			abort = true;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "Connection terminated.", 0 , FALSE ) > -1 )
		{
			//if (error_found==false)
				//   KMessageBox::error( this, i18n( "Connection has been terminated." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Connection has been terminated." ), GlobalConfig->info );
			abort = true;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "tcflush failed: Bad file descriptor", 0 , FALSE ) > -1 )
		{
			if (error_found==false)
				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;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "MPPE required, but kernel has no support", 0 , FALSE ) > -1 )
		{
			if (error_found==false)
				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;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "unrecognized option 'mppe'", 0 , FALSE ) > -1 )
		{
			if (error_found==false)
				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;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "Input/output error", 0 , FALSE ) > -1 )
		{
			//if (error_found==false)
				//KMessageBox::error( this, i18n( "Input/output error" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Input/output error" ) , GlobalConfig->error );
			abort = true;
			error_found=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;
			error_found=true;
		}
		else if ( ProcessMsg_connect.find ( "No auth is possible sent", 0 , FALSE ) > -1 )
		{
			if (error_found==false)
				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;
			error_found=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->setUseAuthenticationAlgorithm(true);
			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 ( "Options error: Parameter", 0 , FALSE ) > -1 )
		{
			KMessageBox::error( this, i18n( "OpenVPN configuration error. Wrong parameter in config file. Please contact the KVpnc author." ) );
			GlobalConfig->appendLogEntry( i18n( "OpenVPN configuration error. Wrong parameter in config file. Please contact the KVpnc author." ), 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 ( "TUN/TAP device", 0, FALSE ) > -1 )
		{
			// TUN/TAP device tun0 opened
			NetworkDevice = ProcessMsg.section ( ' ', -2, -2 ); // tun0
			OpenvpnDevice = ProcessMsg.section ( ' ', -2, -2 ); // 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()
{
	L2tpdBufferStdoutString += QString (L2tpdProcess->readStdout());
	emit L2tpdStdoutRecieved();
	return;

}

void KVpnc::readFromStderr_l2tpd()
{
	L2tpdBufferStderrString += QString (L2tpdProcess->readStderr());
	emit L2tpdStderrRecieved();
	return;

}

void KVpnc::processStdout_l2tpd()
{

	QString ProcessMsg_connect_raw = L2tpdBufferStdoutString;
	QStringList ProcessMsg_connect_list = QStringList::split('\n',ProcessMsg_connect_raw);
	L2tpdBufferStdoutString ="";
	for ( QStringList::Iterator it = ProcessMsg_connect_list.begin(); it != ProcessMsg_connect_list.end(); ++it )
	{
		bool NormalMsg = true;
		bool ErrorMsg = false;
		QString ProcessMsg_connect = *it;

		if (GlobalConfig->KvpncDebugLevel > 7)
			GlobalConfig->appendLogEntry ( QString( "[l2tpd raw] " + ProcessMsg_connect ) , GlobalConfig->debug );


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

			}
		}
		else if ( ProcessMsg_connect.find ( "Connection closed to", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Connection was closed." ) ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "pppd exited for call", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "pppd exited for call" ) ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "unrecognized option", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "unknown option in generated config file, please report to maintainer." ) ) , GlobalConfig->error );
			abort = true;
		}


		// 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 secrets file
			if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
			{
				// 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 );
				}
			}

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

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

void KVpnc::processStderr_l2tpd()
{
	QString ProcessMsg_connect_raw = L2tpdBufferStderrString;
	QStringList ProcessMsg_connect_list = QStringList::split('\n',ProcessMsg_connect_raw);
	L2tpdBufferStderrString ="";

	for ( QStringList::Iterator it = ProcessMsg_connect_list.begin(); it != ProcessMsg_connect_list.end(); ++it )
	{

		bool NormalMsg = true;
		bool ErrorMsg = false;
		QString ProcessMsg_connect = *it;
		bool abort = false;
		bool connectSuccess = false;



		if (GlobalConfig->KvpncDebugLevel > 7)
			GlobalConfig->appendLogEntry ( QString( "[l2tpd err raw] " + ProcessMsg_connect ) , GlobalConfig->debug );
		//
// 		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->error );
				abort = true;
			}
			else if ( ProcessMsg_connect.find ( "Connection closed to", 0 , FALSE ) > -1 )
			{
				ErrorMsg=true;
				GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Connection was closed." ) ) , GlobalConfig->error );
				abort = true;
			}
			else if ( ProcessMsg_connect.find ( "pppd exited for call", 0 , FALSE ) > -1 )
			{
				ErrorMsg=true;
				GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "pppd exited for call" ) ) , GlobalConfig->error );
				abort = true;
			}
			else if ( ProcessMsg_connect.find ( "Unable to load config file", 0 , FALSE ) > -1 )
			{
				ErrorMsg=true;
				KMessageBox::error ( this, i18n ( "Syntax error in config detected. Please report that to the KVpnc maintainer." ) );
				GlobalConfig->appendLogEntry ( QString ( "[l2tpd err] " + i18n ( "Error in generated config file for l2tpd, please report to maintainer." ) ) , GlobalConfig->error );
				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 ( "Low level connection to %1 established." ).arg ( GlobalConfig->currentProfile->getGateway() ) ) , GlobalConfig->info );
				abort = false;
				if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
				{
					GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "Low level connection %1 established." ).arg ( GlobalConfig->currentProfile->getGateway() ) ) , GlobalConfig->info );

					abort = false;
				}

				disconnect ( &L2tpWaitForPppUpTimer, SIGNAL ( timeout() ), this, SLOT ( checkL2tpPppUp() ) );
				connect ( &L2tpWaitForPppUpTimer, SIGNAL ( timeout() ), this, SLOT ( checkL2tpPppUp() ) );
				L2tpWaitForPppUpTimer.start ( 1000, FALSE );

			}
			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 ( "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;
				}
			}
			else if ( ProcessMsg_connect.find ( "Connecting to host", 0 , FALSE ) > -1 )
			{
				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;
			}

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

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

				if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
				{
					// 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 ;
			}
		}
// 		if (GlobalConfig->appPointer->hasPendingEvents ())
// 			GlobalConfig->appPointer->processEvents();
	}
}

void KVpnc::readFromStdout_openl2tp()
{
	while ( OpenL2tpProcess != 0 && OpenL2tpProcess->canReadLineStdout() )
	{
		bool abort=false;
		bool connectSuccess=false;
		ProcessMsg_connect = OpenL2tpProcess->readLineStdout();

		if (GlobalConfig->enableDebugOpenl2tp)
		{
			GlobalConfig->appendLogEntry ( "[openl2tp] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else
		{
			if (ProcessMsg_connect.find ( "FUNC:", 0 , FALSE ) < 0  && ProcessMsg_connect.find ("FSM:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("AVP:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("PROTO:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("XPRT:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("DATA:", 0 , FALSE ) < 0)
				GlobalConfig->appendLogEntry ( "[openl2tp] " + ProcessMsg_connect, GlobalConfig->debug );
		}

		if ( ProcessMsg_connect.find ( "address", 0 , FALSE ) > -1  )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Got IP address" ), GlobalConfig->debug );
			
			if (ProcessMsg_connect.find ( "local", 0 , FALSE ) > -1  )
			{
				TunnelInterfaceIP = ProcessMsg_connect.section(' ',4,4);
				if ( !TunnelInterfaceIP.isEmpty() )
					GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
				
				connectSuccess=true;
			}
		}
		else if ( ProcessMsg_connect.find ( "event ICRP_ACCEPT in state WAITREPLY", 0 , FALSE ) > -1  )
		{
			// short before low level connection up
		}
		else if ( ProcessMsg_connect.find ( "starting UNIX pppd", 0 , FALSE ) > -1  )
		{
			// low level connection sure up
		}
		else if ( ProcessMsg_connect.find ( "state change: WAITCTLREPLY --> ESTABLISHED", 0 , FALSE ) > -1  )
		{
			// low level connection up
		}
		else if ( ProcessMsg_connect.find ( "Using interface", 0 , FALSE ) > -1  )
		{

				QString L2tpPppDevice = ProcessMsg_connect.section(' ',2,2);
				if (GlobalConfig->KvpncDebugLevel >  2)
					GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( L2tpPppDevice ), GlobalConfig->debug );
		}
		else if ( ProcessMsg_connect.find ( "authentication succeeded:", 0 , FALSE ) > -1  )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Authentication succeeded." ), GlobalConfig->debug );
			abort = false;
// 			connectSuccess=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;
		}



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

			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 ( "openl2tpd" ) , GlobalConfig->debug );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );

			return ;
		}

	}
}

void KVpnc::readFromStderr_openl2tp()
{
	while ( OpenL2tpProcess != 0 && OpenL2tpProcess->canReadLineStderr() )
	{
		bool abort=false;
		ProcessMsg_connect = OpenL2tpProcess->readLineStderr();
		GlobalConfig->appendLogEntry ( "[openl2tp err] " + ProcessMsg_connect, GlobalConfig->error );


		if ( ProcessMsg_connect.find ( "parse error", 0 , FALSE ) > -1  )
		{
			KMessageBox::error ( this, i18n ( "Error in generated configuration file for \"%1\", please contact KVpnc team." ).arg ( "openl2tpd" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Error in generated configuration file for \"%1\", please contact KVpnc team." ).arg ( "openl2tpd" ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "File /var/run/openl2tpd.pid already exists", 0 , FALSE ) > -1  )
		{
			KMessageBox::error ( this, i18n ( "Lock file of %1 still exists. Please remove it if %2 is not running." ).arg ( "openl2tpd" ).arg ( "openl2tpd" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Lock file of %1 still exists." ).arg ( "openl2tpd" ) , GlobalConfig->error );
			abort = true;
		}


		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_startstopOpenl2tp()
{
	while ( StartStopOpenl2tpProcess != 0 && StartStopOpenl2tpProcess->canReadLineStdout() )
	{
		bool abort=false;
		bool connectSuccess=false;
		ProcessMsg_connect = StartStopOpenl2tpProcess->readLineStdout();

		if (GlobalConfig->enableDebugOpenl2tp)
		{
			GlobalConfig->appendLogEntry ( "[openl2tp] " + ProcessMsg_connect, GlobalConfig->debug );
		}
		else
		{
			if (ProcessMsg_connect.find ( "FUNC:", 0 , FALSE ) < 0  && ProcessMsg_connect.find ("FSM:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("AVP:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("PROTO:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("XPRT:", 0 , FALSE ) < 0 && ProcessMsg_connect.find ("DATA:", 0 , FALSE ) < 0)
				GlobalConfig->appendLogEntry ( "[openl2tp] " + ProcessMsg_connect, GlobalConfig->debug );
		}


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

			return ;
		}

	}
}

void KVpnc::readFromStderr_startstopOpenl2tp()
{
	while ( StartStopOpenl2tpProcess != 0 && StartStopOpenl2tpProcess->canReadLineStderr() )
	{
		bool abort=false;
		ProcessMsg_connect = StartStopOpenl2tpProcess->readLineStderr();
		GlobalConfig->appendLogEntry ( "[openl2tp 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 ( "openl2tp" ) , GlobalConfig->debug );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );

			return ;
		}
	}
}

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_ssh(KProcess *, char *buffer, int buflen)
{
// 	while ( SshProcess->canReadLineStdout() )
// 	{
// 		ProcessMsg_connect = SshProcess->readLineStdout();
		// 	QString ProcessMsg_connect = QString( SshProcess->readStdout() );

// 		QString ProcessMsg_connect = QString::fromLatin1(buffer, buflen);
		QString ProcessMsg_connect_raw = QString::fromLatin1(buffer, buflen);
		QStringList ProcessMsg_connect_raw_list = QStringList::split(  "debug1:",ProcessMsg_connect_raw);

	 for ( QStringList::Iterator it = ProcessMsg_connect_raw_list.begin(); it != ProcessMsg_connect_raw_list.end(); ++it ) 
	{
		ProcessMsg_connect = *it;

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

		if ( ProcessMsg_connect.find ( "ssh_is_up", 0 , FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( i18n ( "SSH tunnel is now up" ) , GlobalConfig->info );
			connectSuccess=true;
		}

		if ( ProcessMsg_connect.find ( "REMOTE HOST IDENTIFICATION HAS CHANGED!", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Remote host identification has changed!" ) ) ;
			GlobalConfig->appendLogEntry ( i18n ( "Remote host identification has changed!" )  , GlobalConfig->error );
			abort=false;
		}
		else if ( ProcessMsg_connect.find ( "Host key verification failed", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Host key verification failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Host key verification failed" ) , GlobalConfig->error );
			abort=true;
		}
		else if ( ProcessMsg_connect.find ( "has changed and you have requested strict checking", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Hostkey for %1 has changed and you have requested strict checking" ).arg ( GlobalConfig->TmpGatewayIP ) );
			GlobalConfig->appendLogEntry ( i18n ( "Hostkey for %1 has changed and you have requested strict checking" ).arg ( GlobalConfig->TmpGatewayIP ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( ": No route to host", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "No route to host %1" ).arg ( GlobalConfig->TmpGatewayIP ) );
			GlobalConfig->appendLogEntry ( i18n ( "No route to host %1" ).arg ( GlobalConfig->TmpGatewayIP ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Authentication succeeded", 0 , FALSE ) > -1 )
		{
			ErrorMsg=false;
// 			KMessageBox::error ( this, i18n ( "Authentication succeeded" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Authentication succeeded" ) , GlobalConfig->info );
// 			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Remote: Failed to open the tunnel device.", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Remote: Failed to open the tunnel device." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Remote: Failed to open the tunnel device." ), GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "open failed: administratively prohibited: open failed", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Action administratively prohibited" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Action administratively prohibited" ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Connection established.", 0 , FALSE ) > -1 )
		{
// 			KMessageBox::error ( this, i18n ( "Low level connection to host %1 established." ).arg ( GlobalConfig->TmpGatewayIP ) );
			GlobalConfig->appendLogEntry ( i18n ( "Low level connection to host %1 established." ).arg ( GlobalConfig->TmpGatewayIP ) , GlobalConfig->info );
		}

		else if ( ProcessMsg_connect.find ( "No more authentication methods to try.", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "No more authentication methods to try." ) );
			GlobalConfig->appendLogEntry ( i18n ( "No more authentication methods to try." ) , GlobalConfig->error );
			abort = true;
		}
		if ( abort )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "ssh" ) , GlobalConfig->debug );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );
			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 );

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

			QString sshdev = "";
			if ( !PppdDevice.isEmpty() )
				sshdev = PppdDevice;
			else
			{
					if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
						sshdev="tun0";
					else
						sshdev= "tap0";
			}

			// write ssh.<profile>.up
			QFile sshupfile ( tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".up" );
			QTextStream sshupstream ( &sshupfile );
			if ( sshupfile.open ( IO_WriteOnly ) )
			{
				sshupstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
				sshupstream << "# generated by kvpnc. Do not edit it." << "\n";
				sshupstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
				sshupstream << "cat /etc/resolv.conf > " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << "\n";
				sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
				sshupstream << "	echo > /dev/null" << "\n";
				sshupstream << "else" << "\n";
				sshupstream << "	echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
				sshupstream << "fi\n";

				sshupstream << "\n";
				if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
					sshupstream << GlobalConfig->pathToIfconfig << " "+sshdev+" " + GlobalConfig->currentProfile->getLocalVirtualIP() + " pointopoint " << GlobalConfig->currentProfile->getRemoteVirtualIP() << " up" <<"\n";
				if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tap" )
					sshupstream << GlobalConfig->pathToIfconfig << " "+sshdev+" " + GlobalConfig->currentProfile->getLocalVirtualIP()  << " up" <<"\n";

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

				QString resolvtemp="";
				bool no_nameserver=true;
				if (!GlobalConfig->currentProfile->getUseDnsServer() )
				{
					sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
					sshupstream << "	dev=$1\n";
					sshupstream << "	if [ -z $dev ] ; then\n";
					if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
						sshupstream << "		dev=\"tun0\"\n";
					else
						sshupstream << "		dev=\"tap0\"\n";
					sshupstream << "fi\n";
					if ( !TmpDns1.isEmpty() || !TmpDns2.isEmpty() )
					{
						no_nameserver=false;
						sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
						if(TmpDns2.isEmpty())
						{
							resolvtemp += "	nameserver " + TmpDns1+ "\n";
							sshupstream << "echo \"nameserver " << TmpDns1 << "\"" << " " << "$dev\" > "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
						}
						else
						{
							resolvtemp += "	nameserver " + TmpDns1 + "\nnameserver " + TmpDns2+"\n";
							sshupstream << "echo \"nameserver " << TmpDns1 << "\"\nnameserver " << TmpDns2 << " " << "$dev\" > "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
						}
						
						sshupstream << "else" << "\n";
						sshupstream << "echo >> /etc/resolv.conf\n";
						sshupstream << "echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
						sshupstream << "echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";
						sshupstream << "echo \"nameserver " << TmpDns1 << "\" >> /etc/resolv.conf" << "\n";
						if ( !TmpDns2.isEmpty() )
							sshupstream << "echo \"nameserver " << TmpDns2 << "\" >> /etc/resolv.conf" << "\n";
						
					}

					sshupstream << "fi" << "\n";

					sshupstream << "# " << "\n";
				}
				if ((GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty()) || (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf()  && ! !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty()))
				{
					sshupstream << "if [  -x /sbin/resolvconf ] ; then\n";
					sshupstream << "	dev=$1\n";
					sshupstream << "	if [ -z $dev ] ; then\n";
					if ( GlobalConfig->currentProfile->getTunnelDeviceType() == "tun" )
						sshupstream << "		dev=\"tun0\"\n";
					else
						sshupstream << "		dev=\"tap0\"\n";
					sshupstream << "	fi\n";
					
					if ( GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty() )
						resolvtemp+= "nameserver "+GlobalConfig->currentProfile->getDnsServer()+"\n";
					if ( GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
						resolvtemp+= "search "+GlobalConfig->currentProfile->getSearchDomainInResolvConf()+"\n";
					sshupstream << "else\n";
					if ( GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty() )
					{
						sshupstream << "echo \"nameserver " << GlobalConfig->currentProfile->getDnsServer() + "\" >> /etc/resolv.conf\n";
						no_nameserver=false;
					}
					if ( GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
						sshupstream << "echo \"search " << GlobalConfig->currentProfile->getSearchDomainInResolvConf() + "\" >> /etc/resolv.conf\n";
					sshupstream << "fi\n";
				}


				sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
				sshupstream << "	echo \""+resolvtemp+"\" > "+tmpPath + "/pppd.resolvconf.tmp" << "\n";
				sshupstream << "	cat "+tmpPath + "/pppd.resolvconf.tmp > "+tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName()+"\n";
				sshupstream << "	cat   "+tmpPath + "/pppd.resolvconf.tmp | /sbin/resolvconf -a $dev\n";
				sshupstream << "	cat   "+tmpPath + "/pppd.resolvconf.tmp | /sbin/resolvconf -u\n";

				sshupstream << "	rm -f   "+tmpPath + "/pppd.resolvconf.tmp\n";
				
				if (no_nameserver==true)
				{
					sshupstream << "else\n";
					sshupstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() + " | grep nameserver >> /etc/resolv.conf\n";
				}

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

				sshupstream << GlobalConfig->pathToIp << " route show | grep default > " << OldDefaultroute << "\n";

				if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
				{
					sshupstream << GlobalConfig->pathToIp + " route replace default dev " + sshdev + "\n";

					if ( GlobalConfig->KvpncDebugLevel > 3 )
						GlobalConfig->appendLogEntry ( i18n ( "Setting extra route: %1 over %2 gw %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg(GlobalConfig->OldDefaultDev).arg( GlobalConfig->OldDefaultGw), GlobalConfig->debug );

					sshupstream << GlobalConfig->pathToIp + " route add " + GlobalConfig->currentProfile->getGateway() + "/32 via " << GlobalConfig->OldDefaultGw << " dev " << GlobalConfig->OldDefaultDev << "\n";

				}

				GlobalConfig->NewDefaultGw = iface.getGatewayOfDefaultInterface();

				if (GlobalConfig->NewDefaultGw != "0.0.0.0")
				{
					if ( GlobalConfig->KvpncDebugLevel > 3 )
						GlobalConfig->appendLogEntry ( i18n ( "Setting extra route: %1 over %2 gw %3" ).arg ( "0.0.0.0" ).arg( sshdev ).arg( GlobalConfig->NewDefaultGw), GlobalConfig->debug );
					sshupstream << GlobalConfig->pathToIp + " route add 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << sshdev << "\n";
				}
				sshupfile.close();
			}
			

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

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

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) finished." ).arg ( "SshUpScript" ).arg(tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".up") , GlobalConfig->debug );
			}
			
			setFirewallAfterConnect();
			if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect() )
				executeCommandAfterConnect();
			
			if ( GlobalConfig->currentProfile->getReplaceDefaultRoute())
			{
				tmpPath = locateLocal ( "data", "kvpnc/" );
				QString SshReplaceDefaultRouteScript = tmpPath + "ssh_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh";

				QFile file ( SshReplaceDefaultRouteScript );
				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 ( SshReplaceDefaultRouteScript );
					if ( !ReplaceDefaultRouteProcess->start(env) )
					{
						KMessageBox::sorry ( this, i18n ( "\"%1\" %2 start failed!" ).arg ( i18n ( "ssh 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 ( "ssh replace route process" )).arg( tmpPath + "ssh_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh") , GlobalConfig->debug );
					}
				}
				else
				{
					GlobalConfig->appendLogEntry ( i18n ( "Could not write: \"%1\" (%2)!" ).arg ( i18n ( "ssh replace route script" )).arg(SshReplaceDefaultRouteScript), 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();
				}
			}
		}

		if (ErrorMsg)
			GlobalConfig->appendLogEntry ( "[ssh error] " + ProcessMsg_connect, GlobalConfig->error );
		else
			GlobalConfig->appendLogEntry ( "[ssh] " + ProcessMsg_connect, GlobalConfig->info );

	}
}

void KVpnc::readFromStderr_ssh(KProcess *, char *buffer, int buflen)
{
// 	while ( SshProcess->canReadLineStderr() )
// 	{
// 		ProcessMsg_connect = SshProcess->readLineStderr();
		// 	QString ProcessMsg_connect = QString( SshProcess->readStderr() );
// 		QString ProcessMsg_connect = QString::fromLatin1(buffer, buflen);

		QString ProcessMsg_connect_raw = QString::fromLatin1(buffer, buflen);
		QStringList ProcessMsg_connect_raw_list = QStringList::split(  "debug1:",ProcessMsg_connect_raw);

	 for ( QStringList::Iterator it = ProcessMsg_connect_raw_list.begin(); it != ProcessMsg_connect_raw_list.end(); ++it ) 
	{
		ProcessMsg_connect = *it;

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

		if ( ProcessMsg_connect.find ( "REMOTE HOST IDENTIFICATION HAS CHANGED!", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Remote host identification has changed!" ) ) ;
			GlobalConfig->appendLogEntry ( i18n ( "Remote host identification has changed!" )  , GlobalConfig->error );
			abort=false;
		}
		else if ( ProcessMsg_connect.find ( "Host key verification failed", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Host key verification failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Host key verification failed" ) , GlobalConfig->error );
			abort=true;
		}
		else if ( ProcessMsg_connect.find ( "has changed and you have requested strict checking", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Hostkey for %1 has changed and you have requested strict checking" ).arg ( GlobalConfig->TmpGatewayIP ) );
			GlobalConfig->appendLogEntry ( i18n ( "Hostkey for %1 has changed and you have requested strict checking" ).arg ( GlobalConfig->TmpGatewayIP ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( ": No route to host", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "No route to host %1" ).arg ( GlobalConfig->TmpGatewayIP ) );
			GlobalConfig->appendLogEntry ( i18n ( "No route to host %1" ).arg ( GlobalConfig->TmpGatewayIP ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Authentication succeeded", 0 , FALSE ) > -1 )
		{
			ErrorMsg=false;
// 			KMessageBox::error ( this, i18n ( "Authentication succeeded" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Authentication succeeded" ) , GlobalConfig->info );
// 			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Remote: Failed to open the tunnel device.", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Remote: Failed to open the tunnel device." ) );
			GlobalConfig->appendLogEntry ( i18n ( "Remote: Failed to open the tunnel device." ), GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "open failed: administratively prohibited: open failed", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "Action administratively prohibited" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Action administratively prohibited" ) , GlobalConfig->error );
			abort = true;
		}
		else if ( ProcessMsg_connect.find ( "Connection established.", 0 , FALSE ) > -1 )
		{
// 			KMessageBox::error ( this, i18n ( "Low level connection to host %1 established." ).arg ( GlobalConfig->TmpGatewayIP ) );
			GlobalConfig->appendLogEntry ( i18n ( "Low level connection to host %1 established." ).arg ( GlobalConfig->TmpGatewayIP ) , GlobalConfig->info );
		}
		else if ( ProcessMsg_connect.find ( "No more authentication methods to try.", 0 , FALSE ) > -1 )
		{
			ErrorMsg=true;
			KMessageBox::error ( this, i18n ( "No more authentication methods to try." ) );
			GlobalConfig->appendLogEntry ( i18n ( "No more authentication methods to try." ) , GlobalConfig->error );
			abort = true;
		}
		if (ErrorMsg)
			GlobalConfig->appendLogEntry ( "[ssh error] " + ProcessMsg_connect, GlobalConfig->error );
		else
			GlobalConfig->appendLogEntry ( "[ssh] " + ProcessMsg_connect, GlobalConfig->info );
		if ( abort )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process." ).arg ( "ssh" ) , GlobalConfig->debug );
			disconnectClicked();
			GlobalConfig->status = GlobalConfig->disconnected;
			setGuiStatus ( disconnected );
			return ;
		}
	}
}

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::readFromStdout_executeCommandBeforeConnect()
{
	while ( CmdBeforeConnectProcess->canReadLineStdout() )
	{
		ProcessMsg_connect = CmdBeforeConnectProcess->readLineStdout();
		//ProcessMsg_connect = QString( CmdBeforeConnectProcess->readStdout() );

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( "[CmdBeforeConnect] " + ProcessMsg_connect, GlobalConfig->debug );
	}
}

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

		GlobalConfig->appendLogEntry ( "[CmdBeforeConnect err] " + ProcessMsg_connect, GlobalConfig->error );
	}
}

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

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( "[CmdAfterConnect] " + ProcessMsg_connect, GlobalConfig->debug );
	}
}

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

		GlobalConfig->appendLogEntry ( "[CmdAfterConnect err] " + ProcessMsg_connect, GlobalConfig->error );
	}
}

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

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( "[CmdBeforeDisconnect] " + ProcessMsg_connect, GlobalConfig->debug );
	}
}

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

		GlobalConfig->appendLogEntry ( "[CmdBeforeDisconnect err] " + ProcessMsg_connect, GlobalConfig->error );
	}
}

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

		if ( GlobalConfig->KvpncDebugLevel > 1 )
			GlobalConfig->appendLogEntry ( "[CmdAfterDisconnect] " + ProcessMsg_connect, GlobalConfig->debug );
	}
}

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

		GlobalConfig->appendLogEntry ( "[CmdAfterDisconnect err] " + ProcessMsg_connect, GlobalConfig->error );
	}
}

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 ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco ||GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig )
	{
		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 );
		}
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan ||  GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan)
	{
		timer.stop();
		GlobalConfig->appendLogEntry ( i18n ( "Timeout while connecting to %1. %2 connect process will be killed.!" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( "ipsec" ), GlobalConfig->error );

		disconnectClicked();

	}
}

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

		VpnAccountData * it;
		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() );

	}
	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();
	
	ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( "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)";
	}
	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)";
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
		TypeString = "Vtun";


	if ( !Name.isEmpty() )
	{

		int result = KMessageBox::questionYesNo ( this, i18n ( "Really delete profile \"%1\" (type: %2, Server: %3)?" ).arg ( GlobalConfig->currentProfile->getName() ).arg(TypeString).arg(GlobalConfig->currentProfile->getGateway()), 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::renameSessionClicked ()
{

	VpnAccountData * it;
	bool nameOk = false;
	bool ok = true;
	QString newName="";
	QString Oldname = GlobalConfig->currentProfile->getName();
	newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( GlobalConfig->currentProfile->getName()  ), &ok );
	while ( nameOk == false )
	{
		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			if ( (it != GlobalConfig->currentProfile ) && (it->getName() == GlobalConfig->currentProfile->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" ) );

				newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( GlobalConfig->currentProfile->getName() + "_2" ), &ok );
				if ( ok == false )
				{
					KMessageBox::information ( 0, i18n ( "Rename was canceled." ) );
					GlobalConfig->appendLogEntry ( i18n ( "Rename was canceled." ), GlobalConfig->info );
					slotStatusMsg ( i18n ( "Rename was canceled." ), ID_FLASH_MSG );
					return ;
				}
			}
			nameOk = true;
		}
		nameOk = true;
	}

	if (nameOk)
	{
		for ( it = GlobalConfig->AccountList->first(); it; it = GlobalConfig->AccountList->next() )
		{
			if ( it == GlobalConfig->currentProfile )
			{
				it = GlobalConfig->AccountList->first();
				GlobalConfig->currentProfile->setName(newName);
				nameOk = 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() );
				}
				mw->SessionCombo->setCurrentText ( GlobalConfig->currentProfile->getName() );
				GlobalConfig->removeEntry( Oldname );

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

				this->ConnectAction->setEnabled ( true );
				sessionToggled ( GlobalConfig->currentProfile->getName() );

				KMessageBox::information ( 0, i18n ( "Rename of \"%1\" to \"%2\" was successful." ).arg ( Oldname ).arg(GlobalConfig->currentProfile->getName()) );
				GlobalConfig->appendLogEntry ( i18n ( "Rename of \"%1\" to \"%2\" was successful." ).arg ( Oldname ).arg(GlobalConfig->currentProfile->getName()), GlobalConfig->info );
				slotStatusMsg ( i18n ( "Rename of \"%1\" to \"%2\" was successful." ).arg ( Oldname ).arg(GlobalConfig->currentProfile->getName()), ID_FLASH_MSG );

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

}

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)";
						if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
							bin = "racoon, l2tpd | xl2tpd";
						if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
							bin = "racoon, openl2tpd";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
					{
						type = "l2tpd (ipsec)";
						if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
							bin = "ipsec, l2tpd | xl2tpd";
						if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
							bin = "ipsec, openl2tpd";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun )
					{
						type = "vtun";
						bin = "vtund";
					}
					else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
					{
						type = "ssh";
						bin = "ssh, ksshaskpass | gnome-ssh-askpass";
					}
					else
					{
						type = "other";
						bin = "";
					}

					if ( GlobalConfig->KvpncDebugLevel > 2 )
					{
						GlobalConfig->appendLogEntry ( i18n ( "Selected connection type: %1." ).arg ( type ), GlobalConfig->debug );
						int Authtype = it->getAuthType();
						QString AuthTypeText="";
						if (Authtype == VpnAccountData::cert)
							AuthTypeText="cert";
						else if (VpnAccountData::psk)
							AuthTypeText="psk";
						else if (VpnAccountData::hybrid)
							AuthTypeText="hybrid";
						else
							AuthTypeText="unknown auth";
						GlobalConfig->appendLogEntry ( i18n ( "Selected auth type: %1." ).arg ( AuthTypeText ), 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 ( "pkcs11-tool" );
							if ( Pkcs11ToolInfo->found )
								UseSmartcardOk=true;
							else
								UseSmartcardOk=false;
						}

						if ( type != "pptp" && type != "l2tpd (racoon)" && type != "l2tpd (ipsec)" && type != "ssh" )
						{
							if (Utils ( GlobalConfig ).getToolInfo ( bin ) != 0 && Utils ( GlobalConfig ).getToolInfo ( 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;
								bool racoon_and_openl2tp_available=false;
								if (Utils ( GlobalConfig ).getToolInfo ( "racoon" )->found)
								{
									if (Utils ( GlobalConfig ).getToolInfo ( "l2tpd" )->found)
										racoon_and_l2tpd_available = true;
									if (Utils ( GlobalConfig ).getToolInfo ( "xl2tpd" )->found)
										racoon_and_xl2tpd_available = true;
									if (Utils ( GlobalConfig ).getToolInfo ( "openl2tpd" )->found)
										racoon_and_openl2tp_available = true;
								}
								if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
								{
									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 );
									}
									else 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 );
									}
									else 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 (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
								{
									if ( racoon_and_openl2tp_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 ( "openl2tp" ), KVpncConfig::info );

										this->ConnectAction->setEnabled ( TRUE );
										mw->buttonConnect->setEnabled ( TRUE );
									}
								}
							}
							if ( type == "l2tpd (ipsec)" )
							{
								bool ipsec_and_l2tpd_available = false;
								bool ipsec_and_xl2tpd_available = false;
								bool ipsec_and_openl2tp_available=false;
								if (Utils ( GlobalConfig ).getToolInfo ( "ipsec" )->found)
								{
									if (Utils ( GlobalConfig ).getToolInfo ( "l2tpd" )->found)
										ipsec_and_l2tpd_available = true;
									if (Utils ( GlobalConfig ).getToolInfo ( "xl2tpd" )->found)
										ipsec_and_xl2tpd_available = true;
									if (Utils ( GlobalConfig ).getToolInfo ( "openl2tpd" )->found)
										ipsec_and_openl2tp_available = true;
								}

								QString deamon="";
								if (ipsec_and_l2tpd_available)
									deamon="l2tpd";
								if (ipsec_and_xl2tpd_available)
									deamon="xl2tpd";
								if (ipsec_and_openl2tp_available)
									deamon="openl2tp";
								if ( ipsec_and_l2tpd_available || ipsec_and_xl2tpd_available || ipsec_and_openl2tp_available )
								{
									if ( !GlobalConfig->currentProfile->getUseSmartcard() )
									{
										
										if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
										{
											if ( ipsec_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 ( "ipsec" ).arg ( "l2tpd" ), KVpncConfig::info );

												this->ConnectAction->setEnabled ( TRUE );
												mw->buttonConnect->setEnabled ( TRUE );
											}
											else if ( ipsec_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 ( "ipsec" ).arg ( "xl2tpd" ), KVpncConfig::info );

												this->ConnectAction->setEnabled ( TRUE );
												mw->buttonConnect->setEnabled ( TRUE );
											}
											else if ( ipsec_and_l2tpd_available==false &&  ipsec_and_xl2tpd_available==false )
											{
												GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) are not available, connect will be disabled." ).arg ( "ipsec" ).arg ( "l2tpd/xl2tpd" ), KVpncConfig::error );
											}
										}
										if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
										{
											if ( ipsec_and_openl2tp_available )
											{
												// 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 ( "openl2tp" ), KVpncConfig::info );

												this->ConnectAction->setEnabled ( TRUE );
												mw->buttonConnect->setEnabled ( TRUE );
											}
											else if ( ipsec_and_openl2tp_available==false )
											{
												GlobalConfig->appendLogEntry ( i18n ( "The required daemons (%1 and %2) are not available, connect will be disabled." ).arg ( "ipsec" ).arg ( "openl2tp" ), KVpncConfig::error );
											}
										}
									}
									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 ( "pppd" )->found)
								{
									if (Utils ( GlobalConfig ).getToolInfo ( "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 );
								}
							}
							if ( type == "ssh" )
							{
								bool ssh_and_kaskpass_available = false;
								bool ssh_and_gnomeaskpass_available = false;
								if (Utils ( GlobalConfig ).getToolInfo ( "ssh" )->found)
								{
									if (Utils ( GlobalConfig ).getToolInfo ( "ksshaskpass" )->found)
										ssh_and_kaskpass_available = true;
									if (Utils ( GlobalConfig ).getToolInfo ( "gnome-ssh-askpass" )->found)
										ssh_and_gnomeaskpass_available = true;
								}
								if ( ssh_and_kaskpass_available )
								{
									// programs are installed
									if ( GlobalConfig->KvpncDebugLevel > 2 )
										GlobalConfig->appendLogEntry ( i18n ( "The required programs (%1 and %2) are available, connect will be enabled." ).arg ( "ssh" ).arg ( "ksshaskpass" ), KVpncConfig::info );

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

								}
								else if ( ssh_and_gnomeaskpass_available )
								{
									// programs are installed
									if ( GlobalConfig->KvpncDebugLevel > 2 )
										GlobalConfig->appendLogEntry ( i18n ( "The required programs (%1 and %2) are available, connect will be enabled." ).arg ( "ssh" ).arg ( "gnome-ssh-askpass" ), KVpncConfig::info );

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

								}
								else
								{
									GlobalConfig->appendLogEntry ( i18n ( "The required programs (%1 and %2) are not available, connect will be disabled." ).arg ( "pppd" ).arg ( i18n("%1 or %2").arg("ksshaskpass").arg("gnome-ssh-askpass") ), 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 );
			}
			if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
			{
				NetworkInterface iface ( GlobalConfig, parent );

				// FIXME make it dynamiclly
				if (GlobalConfig->currentProfile->getConnectionType() == "tun")
					TunnelInterfaceIP = iface.getInterfaceIP ( "tun0" );
				else
					TunnelInterfaceIP = iface.getInterfaceIP ( "tap0" );
			}
			// 		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->TmpUsername.isEmpty())
		Username = GlobalConfig->TmpUsername;
	else
		Username = GlobalConfig->currentProfile->getUserName();

	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: %1@%2 [%3], %4" ).arg ( Username ).arg ( GlobalConfig->currentProfile->getGateway() ).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 && ! (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) )
		{
			TypeString =  i18n("*S/WAN");
			StatusMsg = i18n ( "Connected: %1 [%2], %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( TypeString ).arg ( durationString );
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
		{
			TypeString =  i18n("racoon");
			StatusMsg = i18n ( "Connected: %1 [%2], %3" ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( TypeString ).arg ( durationString );
		}
		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 || (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()))
		{
			TypeString = IpsecType;
			StatusMsg = i18n ( "Connected: %1@%2 [%3], %4" ).arg ( Username ).arg ( GlobalConfig->currentProfile->getGateway() ).arg ( TypeString ).arg ( durationString );
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn )
		{
			TypeString =  i18n("OpenVPN");
			StatusMsg = i18n ( "Connected: %1@%2 [%3], %4" ).arg ( Username  ).arg ( GlobalConfig->currentProfile->getGateway()).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 );
	}
	else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
	{
		TypeString =  i18n("SSH");
		StatusMsg = i18n ( "Connected: %1@%2 [%3], %4" ).arg ( Username  ).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->currentProfile->getConnectionType() == VpnAccountData::ssh) && 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->currentProfile->getConnectionType() == VpnAccountData::cisco  || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn ||
	 GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh)
	{
		ToolTipMsg += i18n ( "Tunnel device type: %1\n" ).arg ( GlobalConfig->currentProfile->getTunnelDeviceType() );
	}

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

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

		mw->SessionCombo->setEnabled ( false );
		ImportCertAction->setEnabled ( false );
		DeleteSessionAction->setEnabled ( false );
		RenameSessionAction->setEnabled ( false );
		ImportSessionAction->setEnabled ( false );
		NewProfileWizardAction->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 ( Username ).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 ( Username ).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 && ! (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) )
			{
				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)");
				DeamonString = "racoon, "+GlobalConfig->currentProfile->getL2tpDaemon();

				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, "+GlobalConfig->currentProfile->getL2tpDaemon();
				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 );
			}
			else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
			{
				TypeString = IpsecType;
				DeamonString = "ipsec";
				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 + "]";
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh )
		{
			TypeString =  i18n("SSH");
			DeamonString = "ssh";
			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 );
		RenameSessionAction->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 );
		RenameSessionAction->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 openProfileManager=false;
		QString RetName="";
		bool ret = GlobalConfig->importKvpncConfig(filename,RetName,openProfileManager);
		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 );
			mw->SessionCombo->setCurrentText ( RetName );
			sessionToggled ( RetName );

// 			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 );
			if (openProfileManager==true)
				showProfileManagerClicked();
		}

	}
}

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;
	bool openProfileManager=true;
	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;
					}
				}
			}
			if (openProfileManager==true)
				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;
	bool openProfileManager=true;
	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;
				}
			}
		}

		if (openProfileManager)
			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 openProfileManager=false;
		QString RetName="";
		bool ret = GlobalConfig->importIpsecConfig (filename,RetName,openProfileManager);
		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 );

			mw->SessionCombo->setCurrentText ( RetName );
			sessionToggled ( RetName );

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

		}
		if (openProfileManager==true)
			showProfileManagerClicked();

	}

}

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" ) );
	ChmodProcess = new QProcess(this);
	ChmodProcess->addArgument ( "chmod" );
	ChmodProcess->addArgument ( "go-rwx" );
	ChmodProcess->addArgument ( tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key" );

	if ( !ChmodProcess->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::doRacoon()
{
	disconnect( ConnectProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoon_helper() ) );
	disconnect( ConnectProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoon_helper() ) );
	if ( ConnectProcess )
		disconnect ( ConnectProcess, SIGNAL ( processExited () ), this, SLOT ( doRacoon() ) );


	
	if ( ConnectProcess->normalExit () )
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[racoon]: " + i18n("%1 finished.").arg("setkey"), GlobalConfig->debug );

		/*
		/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 = 0;
		RacoonProcess = new QProcess ( this );
		RacoonProcess->addArgument ( GlobalConfig->pathToRacoon );
		RacoonProcess->addArgument ( "-F" ); // foreground we want :)
// 		RacoonProcess->addArgument ( "-v" );
// 		RacoonProcess->addArgument ( "-dd" );
		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 );

// 		RacoonProcess->setCommunication ( QProcess::Stdin | QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr );
// 		RacoonProcess->closeStdin();
		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;

			if ( GlobalConfig->RacoonDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n("%1 started. ").arg("racoon"), GlobalConfig->info );

			doTailRacoonLog();
			sleep(3);

			racoonStarted();

			//			sec = hour = min = 0;

			//    GlobalConfig->status = GlobalConfig->disconnected;
			// 			timer.stop();
			//			connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
			//			durationTimer.start( 1000, FALSE );
		}
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( "[racoon]: " + i18n("%1 finished with error.").arg("setkey"), GlobalConfig->debug );

	}
}

void KVpnc::stopRacoon()
{
	if ( GlobalConfig->KvpncDebugLevel > 2 )
		GlobalConfig->appendLogEntry ( i18n("Stopping %1.").arg("racoon"), GlobalConfig->debug );

	putenv ( ( char* ) ( "LC_ALL=C" ) );
	RacoonctlProcess = new QProcess ( this );
	QString PathToRacoonctl = "";
	ToolInfo* Tool = Utils ( GlobalConfig ).getToolInfo ( "racoonctl" );
	PathToRacoonctl = Tool->PathToExec;

	RacoonctlProcess->addArgument ( PathToRacoonctl );
	RacoonctlProcess->addArgument( "vd" );

	RacoonctlProcess->addArgument( GlobalConfig->TmpGatewayIP );

	connect( RacoonctlProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoonctl() ) );
	connect( RacoonctlProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoonctl() ) );
	connect ( RacoonctlProcess, SIGNAL ( processExited () ), this, SLOT ( racoonctlExited() ) );
	

	if ( !RacoonctlProcess->start(env) )
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( QString("racoonctl dc "+GlobalConfig->TmpGatewayIP) ) );
	else
	{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n("%1 started. ").arg(QString("racoonctl dc "+GlobalConfig->TmpGatewayIP)), GlobalConfig->info );

				while ( RacoonctlProcess->isRunning() )
				{
					usleep ( 500 );
					// parent->QApplication::processEvents();
				}
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished." ).arg ( QString("racoonctl dc "+GlobalConfig->TmpGatewayIP) ), GlobalConfig->debug );
	}
}

void KVpnc::doTailRacoonLog()
{
	putenv ( ( char* ) ( "LC_ALL=C" ) );
	RacoonTailProcess = new QProcess ( this );
	RacoonTailProcess->addArgument ( GlobalConfig->pathToTail );
	RacoonTailProcess->addArgument ( "-n" );
	RacoonTailProcess->addArgument ( "1000" );
	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 ( GlobalConfig->pathToTail+" -f " + tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" ) );
		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToTail+" -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 ( GlobalConfig->pathToTail+" -f " + tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" ), GlobalConfig->debug );


	}
}

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 + "default-route." + 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 + "default-route." + 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()
{

	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( i18n ( "Policy was successful activated and daemon (%1) is running, starting up tunnel..." ).arg ( "racoon" ), GlobalConfig->debug );

	bool AdminSockExist=false;
	int tryCounter=0;
	while (!AdminSockExist && tryCounter < 20)
	{
  		AdminSockExist=QFile("/var/run/racoon/racoon.sock").exists();
		tryCounter++;
		if (tryCounter ==20)
			break;
		else
		{
			tryCounter=0;
			if ( GlobalConfig->KvpncDebugLevel > 8 )
			{
				GlobalConfig->appendLogEntry ( i18n ( "Waiting admin sock of %1..." ).arg ( "racoon" ), GlobalConfig->debug );
			}
		}
		usleep(500);
		GlobalConfig->appPointer->processEvents();
	}

	if (tryCounter==20)
	{
		GlobalConfig->appendLogEntry ( i18n ( "Waiting admin sock of %1 needs too long. Stop." ).arg ( "racoon" ), GlobalConfig->debug );
		disconnectClicked();
		return;
	}

	putenv ( ( char* ) ( "LC_ALL=C" ) );
	RacoonctlProcess = new QProcess ( this );
	QString PathToRacoonctl = "";
	ToolInfo* Tool = Utils ( GlobalConfig ).getToolInfo ( "racoonctl" );
	PathToRacoonctl = Tool->PathToExec;

	RacoonctlProcess->addArgument ( PathToRacoonctl );
	RacoonctlProcess->addArgument( "vc" );

	if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
	{
		RacoonctlProcess->addArgument ( "-u" );
		RacoonctlProcess->addArgument ( GlobalConfig->TmpUsername );
	}

	RacoonctlProcess->addArgument( GlobalConfig->TmpGatewayIP );

	connect( RacoonctlProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoonctl() ) );
	connect( RacoonctlProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoonctl() ) );
	connect( RacoonctlProcess, SIGNAL ( processExited () ), this, SLOT ( racoonctlExited() ) );
	

	if ( !RacoonctlProcess->start(env) )
		if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( QString("racoonctl vc -u "+GlobalConfig->TmpUsername+" "+GlobalConfig->TmpGatewayIP) ) );
		else
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( QString("racoonctl vc "+GlobalConfig->TmpGatewayIP) ) );
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
		{
			if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( QString("racoonctl vc -u "+GlobalConfig->TmpUsername+" "+GlobalConfig->TmpGatewayIP) ), GlobalConfig->debug );
			else
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( QString("racoonctl vc "+GlobalConfig->TmpGatewayIP) ), GlobalConfig->debug );
		}

		if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
		{
// 			for (int waitforconnect=0;waitforconnect< 25;waitforconnect++)
// 				usleep(500);

// 			sleep(10);
			if ( GlobalConfig->VpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[racoonctl] " + 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->KvpncDebugLevel > 8 )
				GlobalConfig->appendLogEntry ( "[racoonctl] " + i18n ( "User password: %1\n" ).arg(UserPassStr), GlobalConfig->debug );
	
	
			RacoonctlProcess->writeToStdin ( UserPassStr );
			RacoonctlProcess->writeToStdin ( "\n" );
		}
		
	}

	// 		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::ipsecStarted()
{
	disconnect ( IpsecProcess, SIGNAL ( processExited () ), this, SLOT ( ipsecStarted() ) );

// 	ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( "ipsec" ) ;

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

	IpsecStatusCheck=true;
	checkIpsecWhackStatus();
	IpsecStatusCheck=false;

	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Starting \"%1\"..." ).arg ( GlobalConfig->pathToIpsec+" whack' --listen" ) , GlobalConfig->debug );


	connectCounter=0;
	sleep(1);
	putenv ( ( char* ) ( "LC_ALL=C" ) );
	IpsecWhackListenProcess = new QProcess ( this );
	IpsecWhackListenProcess->addArgument ( GlobalConfig->pathToIpsec );
	IpsecWhackListenProcess->addArgument ( "whack" );
	IpsecWhackListenProcess->addArgument ( "--listen" );

	connect ( IpsecWhackListenProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhacklisten() ) );
	connect ( IpsecWhackListenProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhacklisten() ) );

	if ( !IpsecWhackListenProcess->start(env) )
	{
		KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --listen" ) );
		GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --listen" ) , GlobalConfig->error );
		disconnectClicked();
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 0 )
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack  --listen" ), GlobalConfig->debug);
	}
}

void KVpnc::checkIpsecWhackStatus()
{

	putenv ( ( char* ) ( "LC_ALL=C" ) );
	IpsecWhackStatusProcess = new QProcess ( this );
	IpsecWhackStatusProcess->addArgument ( GlobalConfig->pathToIpsec );
	IpsecWhackStatusProcess->addArgument ( "whack" );
	IpsecWhackStatusProcess->addArgument ( "--status" );
	disconnect ( IpsecWhackStatusProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhackstatus() ) );
	disconnect ( IpsecWhackStatusProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhackstatus() ) );
	connect ( IpsecWhackStatusProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhackstatus() ) );
	connect ( IpsecWhackStatusProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhackstatus() ) );

	connect ( IpsecWhackStatusProcess, SIGNAL ( processExited() ), this, SLOT ( IpsecWhackStatusProcessExited() ) );

	if ( !IpsecWhackStatusProcess->start(env) )
	{
		if (IpsecStatusCheck == false && IpsecPhase2Up==false)
		{
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --status" ) );
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --status" ) , GlobalConfig->error );
			disconnectClicked();
		}
	}
	else
	{
		if ( GlobalConfig->KvpncDebugLevel > 5 )
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack  --status" ), GlobalConfig->debug);
		if (IpsecStatusCheck == true && IpsecPhase2Up==false)
		{
			if (!timer.isActive())
			{
				disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
				connect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
				// FIXME make connect timeout value in GUI available
				timer.start ( 2000 * 1000, FALSE );
			}
			if (!IpsecWhackStatusTimer.isActive())
			{
				disconnect ( &IpsecWhackStatusTimer, SIGNAL ( timeout() ), this, SLOT ( checkIpsecWhackStatus() ) );
				connect ( &IpsecWhackStatusTimer, SIGNAL ( timeout() ), this, SLOT ( checkIpsecWhackStatus() ) );
				IpsecWhackStatusTimer.start(5 * 1000, FALSE);
			}
		}
	}
}

void KVpnc::startStopIpsec(bool stop, bool silent)
{

	ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( "ipsec" ) ;

	ConnectProcess = new QProcess ( this );
	ConnectProcess->addArgument ( GlobalConfig->pathToIpsec );

	 if (IpsecToolInfo->Version.contains ( "Openswan" , false))
		ConnectProcess->addArgument ( "setup" );

	if (stop==false)
	{
		if (silent==false || GlobalConfig->KvpncDebugLevel > 5)
		{
			if (IpsecToolInfo->Version.contains ( "strongSwan", false ) /*&&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 )*/ )
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[" + IpsecType + "] " + i18n ( "Starting %1..." ).arg("openswan"), GlobalConfig->debug );
			}

			if (IpsecToolInfo->Version.contains ( "Openswan" , false))
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( "[" + IpsecType + "] " + i18n ( "Starting %1..." ).arg("strongSwan"), GlobalConfig->debug );
			}
		}

		GlobalConfig->currentConnectRetry++;
		ConnectProcess->addArgument ( "start" );
	}
	else
	{
		if (silent==false || GlobalConfig->KvpncDebugLevel > 5)
		{
			if (IpsecToolInfo->Version.contains ( "strongSwan", false ) /*&&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 )*/ )
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( "[" + IpsecType + "] " + i18n ( "Stopping %1..." ).arg("openswan"), GlobalConfig->debug );
			}

			if (IpsecToolInfo->Version.contains ( "Openswan" , false))
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( "[" + IpsecType + "] " + i18n ( "Stopping %1..." ).arg("strongSwan"), GlobalConfig->debug );
			}
		}
		ConnectProcess->addArgument ( "stop" );
	}

	if (silent==false|| GlobalConfig->KvpncDebugLevel > 8)
	{
		connect ( ConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsec() ) );
		connect ( ConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsec() ) );
	}

	IpsecStartingInProgress=true;
	if ( !ConnectProcess->start(env) )
	{
		if (silent==false)
		{
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ipsec" ) );
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ipsec" ) , GlobalConfig->error );
		}
		// 		disconnectClicked();
		ConnectProcess->tryTerminate();
		usleep(500);
		if (ConnectProcess->isRunning())
			ConnectProcess->kill();
		IpsecStartingInProgress=false;
	}
	else
	{	
		if (silent==false)
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "ipsec" ) , GlobalConfig->debug );
		}
		int currentConnectCounter=0;
		while (currentConnectCounter < GlobalConfig->currentProfile->getMaxConnectTries()*1000 && ConnectProcess->isRunning())
		{
			if (silent==false)
			{
				if ( GlobalConfig->KvpncDebugLevel > 8 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running, waiting" ).arg ( "ipsec" ) , GlobalConfig->debug );
			}
			currentConnectCounter++;
			usleep(200);
			if (GlobalConfig->appPointer->hasPendingEvents ())
				GlobalConfig->appPointer->processEvents();

			if (currentConnectCounter > GlobalConfig->currentProfile->getMaxConnectTries()*1000)
			{
				if (silent==false)
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running but needs too long, stopping" ).arg ( "ipsec" ) , GlobalConfig->debug );
					disconnectClicked();
					IpsecStartingInProgress=false;
					return;
				}
				
			}
		}
		IpsecStartingInProgress=false;
	}
}

void KVpnc::addIpsecConnection()
{


}

void KVpnc::start_ipsec_initiate()
{
			// strongswan after ipsec whack --listen
/*			disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
			disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
			delete(IpsecWhackProcess);*/


			sleep(4);

			putenv ( ( char* ) ( "LC_ALL=C" ) );
			IpsecWhackProcess = new QProcess ( this );
			IpsecWhackProcess->addArgument ( GlobalConfig->pathToIpsec );
			IpsecWhackProcess->addArgument ( "whack" );
			IpsecWhackProcess->addArgument ( "--name" );
			IpsecWhackProcess->addArgument ( GlobalConfig->currentProfile->getName() );
			IpsecWhackProcess->addArgument ( "--initiate" );

			connect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
			connect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
			connect ( IpsecWhackProcess, SIGNAL ( exited() ), this, SLOT ( ipsecwhack_exited() ) );

			if ( !IpsecWhackProcess->start(env) )
			{
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) );
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( GlobalConfig->pathToIpsec+" whack' --name "+GlobalConfig->currentProfile->getName()+" --initiate" ) , GlobalConfig->error );
				disconnectClicked();
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( GlobalConfig->pathToIpsec+" whack --name "+GlobalConfig->currentProfile->getName()+" --initiate" ), GlobalConfig->debug);

				checkIpsecWhackStatus();
			}
	

}

void KVpnc::ipsecPhase2Established()
{
	if (IpsecPhase2Up)
		return;
	else
	{
		timer.stop();
		IpsecWhackStatusTimer.stop();

		// hack: if from status phase2 is first
		if (IpsecPhase1Up== false)
		{

			if (IpsecPhase1Up)
				return;
			else
				IpsecPhase1Up=true;

			if (IpsecPhase2Up)
				return;

			if (GlobalConfig->KvpncDebugLevel > 1)
			{
				if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
				{
					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "IPSec phase 1 established." ), GlobalConfig->info );
				}
				else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
				{
					GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec phase 1 established." ), GlobalConfig->info );
				}
			}

		}
		IpsecPhase2Up=true;
	}

	if (GlobalConfig->KvpncDebugLevel > 1)
	{
		if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan )
		{
			GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "IPSec phase 2 established." ), GlobalConfig->info );
		}
		else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan )
		{
			GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec phase 2 established." ), GlobalConfig->info );
		}
	}

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

}

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

}

void KVpnc::startStopOpenl2tp(bool stop, bool silent)
{

	if ( GlobalConfig->KvpncDebugLevel > 0 )
		GlobalConfig->appendLogEntry ( "[openl2tp] " + i18n ( "Starting %1..." ).arg ( "/etc/init.d/openl2tpd" ) , GlobalConfig->debug );
	StartStopOpenl2tpProcess = new QProcess ( this );
	StartStopOpenl2tpProcess->addArgument ( "/etc/init.d/openl2tp" );

	if (stop==false)
	{
		if (silent==false || GlobalConfig->KvpncDebugLevel > 5)
		{

				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "Starting %1..." ).arg("openl2tpd"), GlobalConfig->debug );
		}
		StartStopOpenl2tpProcess->addArgument ( "start" );
		GlobalConfig->currentConnectRetry++;
	}
	else
	{
		if (silent==false || GlobalConfig->KvpncDebugLevel > 5)
		{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry (  i18n ( "Stopping %1..." ).arg("openl2tp"), GlobalConfig->debug );
		}
		StartStopOpenl2tpProcess->addArgument ( "stop" );
	}

	if (silent==false|| GlobalConfig->KvpncDebugLevel > 8)
	{
		connect ( StartStopOpenl2tpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_startstopOpenl2tp() ) );
		connect ( StartStopOpenl2tpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( rreadFromStderr_startstopOpenl2tp() ) );
	}

	IpsecStartingInProgress=true;
	if ( !StartStopOpenl2tpProcess->start(env) )
	{
		if (silent==false)
		{
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( "ipsec" ) );
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "ipsec" ) , GlobalConfig->error );
		}
		// 		disconnectClicked();
		StartStopOpenl2tpProcess->tryTerminate();
		usleep(500);
		if (StartStopOpenl2tpProcess->isRunning())
			StartStopOpenl2tpProcess->kill();
		IpsecStartingInProgress=false;
	}
	else
	{	
		if (silent==false)
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
			{
				if (stop==false)
				{
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "/etc/init.d/openl2tp start" ) , GlobalConfig->debug );
				}
				else
				{
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "/etc/init.d/openl2tp stop" ) , GlobalConfig->debug );
				}
			}
		}
		int currentConnectCounter=0;
		while (currentConnectCounter < GlobalConfig->currentProfile->getMaxConnectTries()*1000 && StartStopOpenl2tpProcess->isRunning())
		{
			if (silent==false)
			{
				if ( GlobalConfig->KvpncDebugLevel > 8 )
				{
					if (stop==false)
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running, waiting" ).arg ( "/etc/init.d/openl2tp start" ) , GlobalConfig->debug );
					else
						GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running, waiting" ).arg ( "/etc/init.d/openl2tp stop" ) , GlobalConfig->debug );
				}
			}
			currentConnectCounter++;
			usleep(200);
			if (GlobalConfig->appPointer->hasPendingEvents ())
				GlobalConfig->appPointer->processEvents();

			if (currentConnectCounter > GlobalConfig->currentProfile->getMaxConnectTries()*1000)
			{
				if (silent==false)
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
					{
						if (stop==false)
						{
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running but needs too long, stopping" ).arg ( "/etc/init.d/openl2tp start" ) , GlobalConfig->debug );
						}
						else
						{
							GlobalConfig->appendLogEntry ( i18n ( "\"%1\" still running but needs too long, stopping" ).arg ( "/etc/init.d/openl2tp stop" ) , GlobalConfig->debug );
						}
					}
					disconnectClicked();
					return;
				}
				
			}
		}
	}
}

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() )
	{
		QStringList cmds = QStringList::split('\n',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 ) )
		{
			for ( QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it )
				stream << *it << " ; ";
			file.close();

			CmdBeforeConnectProcess = new QProcess ( this );
			CmdBeforeConnectProcess->addArgument ( GlobalConfig->InterpreterShell );
			CmdBeforeConnectProcess->addArgument ( CmdBeforeConnectScript );

			connect ( CmdBeforeConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandBeforeConnect() ) );
			connect ( CmdBeforeConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandBeforeConnect() ) );

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Executing command before connect:\n%1" ).arg ( cmds.join (";") ), 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();
				
				disconnect ( CmdBeforeConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandBeforeConnect() ) );
				disconnect ( CmdBeforeConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandBeforeConnect() ) );
				
				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() )
	{
		QStringList cmds = QStringList::split('\n',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 ) )
		{
			for ( QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it )
				stream << *it << " ; ";

			file.close();

			CmdAfterConnectProcess = new QProcess ( this );
			CmdAfterConnectProcess->addArgument ( GlobalConfig->InterpreterShell );
			CmdAfterConnectProcess->addArgument ( CmdAfterConnectScript );

			connect ( CmdAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandAfterConnect() ) );
			connect ( CmdAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandAfterConnect() ) );
			
			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 ( cmds.join (";") ), 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();

				disconnect ( CmdAfterConnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandAfterConnect() ) );
				disconnect ( CmdAfterConnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandAfterConnect() ) );

				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() )
	{
		QStringList cmds = QStringList::split('\n',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 ) )
		{
			for ( QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it )
				stream << *it << " ; ";
			file.close();
		
			CmdBeforeDisconnectProcess = new QProcess ( this );
			CmdBeforeDisconnectProcess->addArgument ( GlobalConfig->InterpreterShell );
			CmdBeforeDisconnectProcess->addArgument ( CmdBeforeDisconnectScript );

			connect ( CmdBeforeDisconnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandBeforeDisconnect() ) );
			connect ( CmdBeforeDisconnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandBeforeDisconnect() ) );

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

				disconnect ( CmdBeforeDisconnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandBeforeDisconnect() ) );
				disconnect ( CmdBeforeDisconnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandBeforeDisconnect() ) );

				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 ( cmds.join (";") ), GlobalConfig->debug );
		}
		else
		{
			// file could not written
		}
	}
}

void KVpnc::executeCommandAfterDisconnect()
{
	if ( GlobalConfig->currentProfile->getExecuteCmdAfterDisconnect() && !GlobalConfig->currentProfile->getCommandAfterDisconnect().isEmpty() )
	{
		QStringList cmds = QStringList::split('\n',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 ) )
		{
			for ( QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it )
				stream << *it << " ; ";
			file.close();

			CmdAfterDisconnectProcess = new QProcess ( this );
			CmdAfterDisconnectProcess->addArgument ( GlobalConfig->InterpreterShell );
			CmdAfterDisconnectProcess->addArgument ( CmdAfterDisconnectScript );

			connect ( CmdAfterDisconnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandAfterDisconnect() ) );
			connect ( CmdAfterDisconnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandAfterDisconnect() ) );

			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Executing command after disconnect:\n%1" ).arg ( cmds.join (";") ), 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();
				}

				disconnect ( CmdAfterDisconnectProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_executeCommandAfterDisconnect() ) );
				disconnect ( CmdAfterDisconnectProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_executeCommandAfterDisconnect() ) );

				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 ( "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 ( "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 Route="";
		QStringList RoutesList;
		QTextStream stream ( &file );
		if ( file.open ( IO_WriteOnly ) )
		{
			stream << "#!"<< GlobalConfig->InterpreterShell << "\n";
			for ( QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end();++it )
			{
				Route += "\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;
				Route += net;
				if ( !Gateway.isEmpty() && Gateway != "-" )
				{
					GatewayString += "gateway ";
					GatewayString += Gateway;
					Route +=  " " + i18n ( "over gateway" ) + " " + Gateway + "\n";
					extended = true;
				}
				if ( !Interface.isEmpty() && Interface != "-" )
				{
					InterfaceString += Interface;
					if ( Interface != "default" )
						dev = Interface;
					Route += " " + i18n ( "over interface" ) + " " + dev + "\n";
					extended = true;
				}
				else
				{
					dev="";
				}
				if ( extended == false )
					Route += net;
				RoutesList.append(Route);
				Route="";

				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 );
					for ( QStringList::Iterator it = RoutesList.begin(); it != RoutesList.end(); ++it )
						GlobalConfig->appendLogEntry ( *it , 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 Route="";
		QStringList RoutesList;
		QTextStream stream ( &file );
		if ( file.open ( IO_WriteOnly ) )
		{
			stream << "#!"<< GlobalConfig->InterpreterShell << "\n";
			for ( QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end();++it )
			{
				Route += "\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;
				Route += net;
				if ( !Gateway.isEmpty() && Gateway != "-" )
				{
					GatewayString += "gw ";
					GatewayString += Gateway;
					Route += " " + i18n ( "over gateway" ) + " " + Gateway + "\n";
					extended = true;
				}
				if ( !Interface.isEmpty() && Interface != "-" )
				{
					InterfaceString += Interface;
					if ( Interface != "default" )
						dev = Interface;
					Route += " " + i18n ( "over interface" ) + " " + dev + "\n";
					extended = true;
				}
				else
				{
					dev="";
				}
				if ( extended == false )
					Route += net;

				RoutesList.append(Route);
				Route="";

				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 );
					for ( QStringList::Iterator it = RoutesList.begin(); it != RoutesList.end(); ++it )
						GlobalConfig->appendLogEntry ( *it , 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 );

        if (itemtext != GlobalConfig->currentProfile->getName())
        {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Switching to %1"  , QString( itemtext )), GlobalConfig->debug );
                bool profileInList = false;
                for ( uint i = 0; i < GlobalConfig->AccountList->count();i++ )
                {
                        if ( GlobalConfig->AccountList->at ( i ) ->getName() == itemtext )
                        {
                                profileInList = true;

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

        }
        else
        {
                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 ( "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::backupIpsecSystemConfig()
{
		// 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();
		}
		else
		{
			GlobalConfig->appendLogEntry(i18n("%1 could not opened. Stop.").arg(IpsecPrefix + "/ipsec.conf.before.kvpnc"),GlobalConfig->error);
			setGuiStatus(disconnected);
			return;
		}

		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();
		}
		else
		{
			GlobalConfig->appendLogEntry(i18n("%1 could not opened. Stop.").arg(IpsecPrefix + "/ipsec.secrets.before.kvpnc"),GlobalConfig->error);
			setGuiStatus(disconnected);
			return;
		}
		stream.unsetDevice();
}

void KVpnc::backupDefaultRoute()
{
	OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
	QString OldDefaultrouteFilePath = tmpPath + "backup_default-route." + GlobalConfig->currentProfile->getName()+".sh"; // default-route.<id>
	QFile BackupDefaultRouteFile ( OldDefaultrouteFilePath ); // warning: static
	QTextStream stream2 ( &BackupDefaultRouteFile );
	if ( BackupDefaultRouteFile.open ( IO_WriteOnly ) )
	{
		stream2 << " #!" << GlobalConfig->InterpreterShell << "\n";
		stream2 << GlobalConfig->pathToIp << " route show | grep default > " << OldDefaultroute << "\n";
		BackupDefaultRouteFile.close();

		QProcess BackupDefaultRouteProcess(this);
		BackupDefaultRouteProcess.addArgument(GlobalConfig->InterpreterShell);
		BackupDefaultRouteProcess.addArgument(OldDefaultrouteFilePath);

		if (!BackupDefaultRouteProcess.start())
		{
			KMessageBox::sorry ( this, i18n ( "\"%1\" start failed!" ).arg ( "backup default route process" ) );
			GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( "backup default route process" ), GlobalConfig->error );
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "backup default route process" ), GlobalConfig->debug );

			while(BackupDefaultRouteProcess.isRunning())
			{
				sleep(1);
			}
		}

	}
	else
	{
		//KMessageBox::error ( this, i18n ( "Default route could not backuped!" ) );
		GlobalConfig->appendLogEntry ( i18n ( "Default route could not backuped!" ), GlobalConfig->error );
	}
}

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::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::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 << "# userdefined packet size" << "\n";
					openvpn_stream << "mssfix " << GlobalConfig->currentProfile->getMssfix() << "\n\n";
				}

				if ( GlobalConfig->currentProfile->getUseFragment() )
				{
					openvpn_stream << "\n";
					openvpn_stream << "# userdefined 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() << "\n";
			if ( GlobalConfig->currentProfile->getUseRemotePort() )
			{
				openvpn_stream << "\n" << "# port" << "\n" << 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::sshExited()
{

}

void KVpnc::ipsecwhack_exited()
{
	disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
	disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
	delete(IpsecWhackProcess);
}

void KVpnc::IpsecWhackStatusProcessExited()
{
// 	disconnect ( IpsecWhackStatusProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_ipsecwhackstatus() ) );
// 	disconnect ( IpsecWhackStatusProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_ipsecwhackstatus() ) );
// 	disconnect ( IpsecWhackStatusProcess, SIGNAL ( processExited() ), this, SLOT ( IpsecWhackStatusProcessExited() ) );
// 	delete(IpsecWhackStatusProcess);
// 	IpsecWhackStatusProcess=0;
}

void KVpnc::racoonctlExited()
{
	disconnect( RacoonctlProcess, SIGNAL( readyReadStdout() ), this, SLOT( readFromStdout_racoonctl() ) );
	disconnect( RacoonctlProcess, SIGNAL( readyReadStderr() ), this, SLOT( readFromStderr_racoonctl() ) );
	disconnect ( RacoonctlProcess, SIGNAL ( processExited () ), this, SLOT ( racoonctlExited() ) );
}

void KVpnc::prepareL2tpd()
{

	if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
	{
		// bug in openswan: only 80 chars in line allowed!!!
		int pppdoptionsfilepathlen = QString("pppoptfile = "+tmpPath + "options." + GlobalConfig->currentProfile->getName() + ".l2tpd").length();
		if ( pppdoptionsfilepathlen > 80)
		{
			KMessageBox::error ( this, i18n ( "The line length for pppoptfile is too longer than 80 chars: %1. Openswan has an bug and cant handle that. Please rename profile to a shorter name." ).arg ( QString().setNum(pppdoptionsfilepathlen) ) );
			GlobalConfig->appendLogEntry ( i18n ( "The line length for pppoptfile is too longer than 80 chars: %1. Openswan has an bug and cant handle that. Please rename profile to a shorter name." ).arg ( QString().setNum(pppdoptionsfilepathlen) ), GlobalConfig->error );
			stopContinue = true;
			return;
		}

			NetworkInterface iface ( GlobalConfig, parent );
			if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" || GlobalConfig->currentProfile->getNetworkDevice() == "" )
			{
				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() );
			}

		// 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";
	// 		else
	// 			stream << "listen-addr = 127.0.0.1" <<"\n";
	// 		stream << "listen-addr = 0.0.0.0" <<"\n";

			stream << "port = 1701" << "\n";


			if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
			{
				if ( GlobalConfig->enableDebugXl2tpdNetwork )
					stream << "debug network = yes" << "\n";
				if ( GlobalConfig->enableDebugXl2tpdpacket )
					stream << "debug packet = yes" << "\n";
				if ( GlobalConfig->enableDebugXl2tpdstate )
					stream << "debug state = yes" << "\n";
				if ( GlobalConfig->enableDebugXl2tpdtunnel )
					stream << "debug tunnel = yes" << "\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";

			// dont need to let authenticate the peer
			stream << "require authentication = no" << "\n";
			
			if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
			{
				stream << "require chap = yes" << "\n";
				stream << "refuse pap = yes" << "\n";
			}
			if (GlobalConfig->currentProfile->getAuthMethod() == "pap" )
			{
				stream << "refuse chap = yes" << "\n";
				stream << "require pap = yes" << "\n";
			}

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

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



			stream << "name = " << UsernameStr << "\n";
			stream << "pppoptfile = " << tmpPath + "options." + GlobalConfig->currentProfile->getName() + ".l2tpd" << "\n";
			stream << "ppp debug = yes" << "\n";
			stream << "autodial = yes" << "\n";
			L2tpdConfigFile.close();

			L2tpdProcess = 0L;
		}
		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 180" << "\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";

			stream << "linkname kvpnc." << GlobalConfig->currentProfile->getName() << "\n";
			// FIXME how i can get safe the right interface name otherway?
			

			if (GlobalConfig->PppdDebugLevel)
				stream << "debug" << "\n";
	// // 		stream << "kdebug 1" << "\n";

			Utils::PppdCapabilities pppdcap = Utils ( GlobalConfig ).checkPppdCapabilities();
			pppdHasReplacedefaultrouteSupport = pppdcap.pppdHasReplacedefaultrouteSupport;


			if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
			{
				stream << "# use chap" << "\n";
				stream << pppdcap.RequireAuthChapOption << "\n";
			}

			if (GlobalConfig->currentProfile->getAuthMethod() == "mschap")
			{
				stream << "# use mschap" << "\n";
				stream << pppdcap.RequireAuthMschapOption << "\n";
			}

			if (GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
			{
				stream << "# use mschap-v2" << "\n";
				stream << pppdcap.RequireAuthMschapv2Option << "\n";
			}

			if (GlobalConfig->currentProfile->getAuthMethod() == "pap" )
			{
				stream << "# use pap" << "\n";
				stream << pppdcap.RequireAuthPapOption << "\n";
			}

			QString deamon="";
			if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
			{
				if ( GlobalConfig->enableDebugPppd )	
					stream << "debug" << "\n";
			}
			else
			{
				if ( GlobalConfig->enableDebugPppd )	
					stream << "debug" << "\n";
			}

			if ( !GlobalConfig->currentProfile->getReplaceDefaultRoute() )
			{
				stream << "# dont set defaultroute\n";
				stream << "nodefaultroute";
				stream << "\n";
			}
			else
			{
				if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
				{
					stream << "# set defaultroute\n";
					stream << "defaultroute\n";
					if ( pppdcap.pppdHasReplacedefaultrouteSupport )
						stream << "replacedefaultroute\n";
				}
				stream << "\n";
			}

			if ( GlobalConfig->currentProfile->getUseMtu() )
			{
				stream << "mtu " << GlobalConfig->currentProfile->getMtu() << "\n";
			}
			if ( GlobalConfig->currentProfile->getUseMru() )
			{

				stream << "mru " << GlobalConfig->currentProfile->getMru() << "\n";
			}

			stream << "connect-delay 5000" << "\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;
// 
// 			if (GlobalConfig->TmpUsername.isEmpty() && !GlobalConfig->currentProfile->getUserName().isEmpty() )
// 				GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
// 
// 
// 			if (GlobalConfig->KvpncDebugLevel > 1)
// 				GlobalConfig->appendLogEntry ( i18n ( "Username: %1" ).arg ( GlobalConfig->TmpUsername.isEmpty() ), 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 ( "l2tpd secrets file" ), GlobalConfig->error );
// 			stopContinue = true;
// 		}

		if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
		{

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

			// 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 );
			QFile ChapSecretsFile(ChapSecrets);
			stream.setDevice ( &ChapSecretsFile );
			if ( ChapSecretsFile.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() )
				{
					// line: "<domainname>\\<username>"<tab><remote host><tab>"<password>"<tab><ip address>
					stream << "\"" << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << "\"\t" << "*" << "\t" << " \"" << GlobalConfig->TmpPassword << "\"\t*\n";
				}
				else
				{
					// line: "<username>"<tab><remote host><tab>"<password>"<tab><ip address>
					stream << "\"" << UsernameStr << "\"\t" << "*" << "\t" << " \"" << GlobalConfig->TmpPassword << "\"\t*\n";

				}
				stream << "# --- generated by kvpnc. Do not edit it." << "\n";
				ChapSecretsFile.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 );


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

			// 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 );
			QFile papSecretsFile(papSecrets);
			papSecretsFile.setName ( 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";

				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() )
				{
					// line: "<domainname>\\<username>"<tab><remote host><tab>"<password>"<tab><ip address>
					stream << "\"" << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << "\"\t" << "*" << "\t" << GlobalConfig->TmpPassword << "\t*\n";
				}
				else
				{
					// line: "<username>"<tab><remote host><tab>"<password>"<tab><ip address>
					stream << UsernameStr << "\t" << "*" << "\t" << "\"" << GlobalConfig->TmpPassword << "\""<< "\t*\n";
				}
				stream << "# --- generated by kvpnc. Do not edit it." << "\n";
				papSecretsFile.close();


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

	}
	if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
	{
		// write openl2tp.<profilename>.conf
		QString tmpPath = locateLocal ( "data", "kvpnc/" );
		QString OpenL2tpContName = tmpPath + "openl2tp." + GlobalConfig->currentProfile->getName() + ".conf";
		QFile OpenL2tpConfigFile (OpenL2tpContName );
		QTextStream stream ( &OpenL2tpConfigFile );
		if ( OpenL2tpConfigFile.open ( IO_WriteOnly ) )
		{
			stream << "# generated by kvpnc. Do not edit it." << "\n";
			stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
			stream << "" << "\n";
			stream << "ppp profile modify profile_name=default ";
			if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
				stream << "auth_eap=no auth_pap=no auth_mschapv1=no auth_mschapv2=no";

			if (GlobalConfig->currentProfile->getAuthMethod() == "mschap")
				stream << "auth_eap=no auth_pap=no auth_mschapv1=yes auth_mschapv2=yes";

			if (GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2" )
				stream << "auth_eap=no auth_pap=no auth_mschapv1=no auth_mschapv2=yes";

			if (GlobalConfig->currentProfile->getAuthMethod() == "pap" )
				stream << "auth_eap=no auth_pap=yes auth_mschapv1=no auth_mschapv2=no";
			
			stream << "\n";
			stream << "tunnel create tunnel_name=" << GlobalConfig->currentProfile->getName()<< " dest_ipaddr="  << GlobalConfig->TmpGatewayIP << " persist=yes" << "\n";


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

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


			stream << "session create tunnel_name=" << GlobalConfig->currentProfile->getName() << " session_name=" << GlobalConfig->currentProfile->getName() << " user_name=" << UsernameStr << " user_password=" << GlobalConfig->TmpPassword << "\n";

			OpenL2tpConfigFile.close();


 			if (!Utils ( GlobalConfig, parent ).loadKernelModule ( "slhc", parent ))
			{
				if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" failed" ).arg ( "slhc" ).arg ( "/etc/modprobe.conf" ), GlobalConfig->debug );
				else
					if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" succeded" ).arg ( "slhc" ), GlobalConfig->debug );
			}
 			if (!Utils ( GlobalConfig, parent ).loadKernelModule ( "ppp_generic", parent ))
			{
				if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" failed." ).arg ( "ppp_generic" ), GlobalConfig->debug );
				else
					if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" succeded" ).arg ( "ppp_generic" ), GlobalConfig->debug );
			}
  			if (!Utils ( GlobalConfig, parent ).loadKernelModule ( "pppox", parent ))
			{
				if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" failed." ).arg ( "pppox" ), GlobalConfig->debug );
				else
					if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" succeded" ).arg ( "pppox" ), GlobalConfig->debug );
			}
  			if (!Utils ( GlobalConfig, parent ).loadKernelModule ( "pppol2tp", parent ))
			{
				if (GlobalConfig->KvpncDebugLevel > 3)
					GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" failed" ).arg ( "pppol2tp" ), GlobalConfig->debug );
				else
					if (GlobalConfig->KvpncDebugLevel > 3)
						GlobalConfig->appendLogEntry ( i18n ( "Loading module \"%1\" succeded" ).arg ( "pppol2tp" ), GlobalConfig->debug );
			}

		}
		else
		{
			GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed!" ).arg ( "openl2tp config file" ), GlobalConfig->error );
			stopContinue = true;
		}
	}
}

void KVpnc::start_l2tpd()
{
	QString daemon="";
	if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)
	{
		if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Using %1.").arg("xl2tpd"),GlobalConfig->debug);
			daemon="xl2tpd";
		}
		else
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Using %1.").arg("l2tpd"),GlobalConfig->debug);
			daemon="l2tpd";
		}

		bool control_interface_success=true;

		QString L2tpdPid="";
		if (daemon == "xl2tpd")
			L2tpdPid="/var/run/xl2tpd.pid";
		else
			L2tpdPid="/var/run/l2tpd.pid";


		QString L2tpdControl="";
		if (daemon == "xl2tpd")
			L2tpdControl="/var/run/l2tp-control";
		else
			L2tpdControl="/var/run/l2tp-control";


	
// 		if (QFile(L2tpdPid).exists())
// 		{
// 			if (GlobalConfig->KvpncDebugLevel > 1)
// 				GlobalConfig->appendLogEntry(i18n("Using control interface for starting l2tp connection"),GlobalConfig->debug);
// 
// 			QString L2tpdControl="";
// 			if (daemon == "xl2tpd")
// 				L2tpdControl="/var/run/xl2tpd/l2tp-control";
// 			else
// 				L2tpdControl="/var/run/l2tp-control";
// 
// 			QFile L2tpdControlFile ( L2tpdControl );
// 			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 );
			//
			if (daemon == "xl2tpd")
			{
				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" );

			if (daemon == "xl2tpd")
			{
				L2tpdProcess->addArgument ( "-C" );
				L2tpdProcess->addArgument ( L2tpdControl  );
			}
			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 ( "\""+daemon+"\" cmd line: " + cmdline , GlobalConfig->debug );
			}
		
			connect ( L2tpdProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_l2tpd() ) );
			connect ( L2tpdProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_l2tpd() ) );

			connect (this, SIGNAL(L2tpdStdoutRecieved()), this, SLOT( processStdout_l2tpd()));
			connect (this, SIGNAL(L2tpdStderrRecieved()), this, SLOT( processStderr_l2tpd()));
		
			if ( !L2tpdProcess->start(env) )
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( daemon ), GlobalConfig->error );
				KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( daemon ) );
				setGuiStatus ( disconnected );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 0 )
					GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "l2tpd" ), GlobalConfig->debug );


// 				if (GlobalConfig->KvpncDebugLevel > 1)
// 					GlobalConfig->appendLogEntry(i18n("Using control interface for starting l2tp connection"),GlobalConfig->debug);
// 
// 				QString L2tpdControl="";
// 				if (daemon == "xl2tpd")
// 					L2tpdControl="/var/run/xl2tpd/l2tp-control";
// 				else
// 					L2tpdControl="/var/run/l2tp-control";
// 
// 				QFile L2tpdControlFile ( L2tpdControl );
// 				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 ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp)
	{
		{
			if (GlobalConfig->KvpncDebugLevel > 1)
				GlobalConfig->appendLogEntry(i18n("Using %1.").arg("openl2tp"),GlobalConfig->debug);
			daemon="openl2tp";
		}

// 		bool control_interface_success=true;

// 		QString L2tpdPid="";
// 		if (daemon == "xl2tpd")
// 			L2tpdPid="/var/run/xl2tpd.pid";
// 		else
// 			L2tpdPid="/var/run/l2tpd.pid";

		startStopOpenl2tp(true);
		sleep(2);
		startStopOpenl2tp();

		if (GlobalConfig->KvpncDebugLevel > 1)
			GlobalConfig->appendLogEntry(i18n("Starting openl2tpd manually"),GlobalConfig->debug);
// 		sleep ( 2 );
		
		// start openl2tpd
		OpenL2tpProcess = new QProcess ( this );
		//
		if (GlobalConfig->KvpncDebugLevel > 1)
			GlobalConfig->appendLogEntry(i18n("Using %1.").arg("openl2tpd"),GlobalConfig->debug);
		OpenL2tpProcess->addArgument ( GlobalConfig->pathToOpenl2tp );

// 		 if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon)
// 		{
// 			// use ipsec tools extensions
// 			OpenL2tpProcess->addArgument ( "-p" );
// 			OpenL2tpProcess->addArgument ( "ipsec.so" );
// 		}
		OpenL2tpProcess->addArgument ( "-f" ); // foreground
		OpenL2tpProcess->addArgument ( "-c" );

		QString tmpPath = locateLocal ( "data", "kvpnc/" );
		QString OpenL2tpContName = tmpPath + "openl2tp." + GlobalConfig->currentProfile->getName() + ".conf";

		OpenL2tpProcess->addArgument (OpenL2tpContName );

		OpenL2tpProcess->addArgument ( "-D" ); // debug

		if ( GlobalConfig->KvpncDebugLevel > 2 )
		{
			QString cmdline = "";
			QStringList cmdarguments = OpenL2tpProcess->arguments();
			for ( QStringList::Iterator it = cmdarguments.begin(); it != cmdarguments.end(); ++it )
			{
				cmdline += " " + QString ( *it );
			}
			GlobalConfig->appendLogEntry ( "\""+daemon+"\" cmd line: " + cmdline , GlobalConfig->debug );
		}

		connect ( OpenL2tpProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_openl2tp() ) );
		connect ( OpenL2tpProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_openl2tp() ) );

		if ( !OpenL2tpProcess->start(env) )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!" ).arg ( daemon ), GlobalConfig->error );
			KMessageBox::error ( this, i18n ( "\"%1\" start failed!" ).arg ( daemon ) );
			setGuiStatus ( disconnected );
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started." ).arg ( "openl2tp" ), GlobalConfig->debug );


		}


	}
}

void KVpnc::checkL2tpPppUp()
{

	GlobalConfig->appendLogEntry ( i18n ( "Check ppp device..." ), GlobalConfig->debug );
	QString tmpPath = locateLocal ( "data", "kvpnc/" );
	QFile L2tpPppPidFile ("/var/run/ppp-kvpnc." +GlobalConfig->currentProfile->getName()+".pid");
	
	if (L2tpPppPidFile.exists())
	{
		if (L2tpPppPidFile.open(IO_ReadOnly))
		{
			QString L2tpPppDevice="";
			QTextStream stream ( &L2tpPppPidFile );
			QString line = "";
			while ( !stream.atEnd() )
			{
				line = stream.readLine();
				if ( line.contains ( "ppp" ) )
				{
					L2tpPppDevice= line.stripWhiteSpace();
					break;
				}
			}

			L2tpPppPidFile.close();
			if (L2tpPppDevice.length() > 1)
			{
				
				// ok, we got the device

				if (GlobalConfig->KvpncDebugLevel >  2)
					GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n" ).arg ( L2tpPppDevice ), GlobalConfig->debug );

    				L2tpWaitForPppUpTimer.stop();
				bool connectSuccess=false;

				NetworkInterface iface ( GlobalConfig, parent );
				if ( iface.interfaceExist ( L2tpPppDevice ) )
				{
					TunnelInterfaceIP = iface.getInterfaceIP ( L2tpPppDevice );
					if ( !TunnelInterfaceIP.isEmpty() )
						GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
				}


				if (TunnelInterfaceIP.isEmpty())
				{
					sleep(10);
					if ( iface.interfaceExist ( L2tpPppDevice ) )
					{
						TunnelInterfaceIP = iface.getInterfaceIP ( L2tpPppDevice );
						if ( !TunnelInterfaceIP.isEmpty() )
							GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1\n" ).arg ( TunnelInterfaceIP ), GlobalConfig->debug );
						if (!TunnelInterfaceIP.isEmpty())
						{
							connectSuccess=true;
						}
					}
				}
				else
				{
					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();

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

				}
			}

		}
// 		else
// 		{
// 
// 		}
	}

}

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

// --- 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 ( uint i = 0; i < GlobalConfig->AccountList->count();i++ )
	{
		if ( GlobalConfig->AccountList->at ( i ) ->getName() == profilename )
		{
			sessionToggled ( profilename );
			mw->SessionCombo->setCurrentText (profilename );
			GlobalConfig->currentProfile = GlobalConfig->AccountList->at ( i );
			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->pathToIpsec.isEmpty() )
			{
				tool->addSearchPath ( GlobalConfig->pathToIpsec.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;
}

