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

//BEGIN INCLUDES
#include "kvpncconfig.h"
#include "utils.h"
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <iostream>
#include <kstandarddirs.h>
//END INCLUDES

KVpncConfig::KVpncConfig(QWidget *parent,KStatusBar *statusbar)
{
	this->parent = parent;
	this->statusbar = statusbar;

	pathToVpnc = "";
	pathToCiscoVpnc = "";
	pathToRacoon = "";
	pathToSetkey = "";
	pathToFreeswan = "";
	pathToPppd="";
	pathToPptp="";
	pathToL2tpd="";
	pathToXl2tpd="";
	pathToKill="";
	pathToKillall="";
	pathToPing="";
	pathToOpenvpn="";
	pathToIp="/sbin/ip";
	pathToIfconfig="/sbin/ifconfig";
	pathToRoute="/sbin/route";
	pathToNetstat="/bin/netstat";
	pathToL2tpd="/usr/sbin/l2tpd";
	pathToPkcs11Tool="/usr/bin/pkcs11-tool";
	AutoConnectProfile="";
	Vpnc_pid_file = "";
	Pppd_pid_file = "";
	lastProfile = "";
	logfileName = "";

	TmpPassword="";
	TmpGroupPassword="";
	TmpUsername="";
	TmpPrivKeyPassStr="";
	TmpGatewayIP="";
	TmpXauthInterPasscode="";
	TmpPrivateKeyPass="";
	TmpHttpProxyPassword="";

	connectSleepDelay = 15;
	connectSleepRetry = 0;
	tryConnectTimeout = 10;
	runningCheckCounter = 0;
	runningCheckTimeout = 60;
	mainwindow_pos_x=0;
	mainwindow_pos_y=0;
	mainwindow_height=200;
	mainwindow_width=400;

	OpenvpnManagementPort=2222;

	minimizeAfterConnect = true;
	//showDebugConsole = false;
	useDefaultPaths = false;
	writeLogFile = true;
	useSilentQuit = false;
	holdGeneratedScripts = true;
	enableDebugPppd=false;
	enableDebugPptpd=false;
	enableDebugL2tpd=false;
	enableDebugXl2tpd=false;
	enableDebugOpenvpn=false;
	useColorizedLogOutput=true;
	showInterfaceIPinTooltip=true;
	dontQuitOnCloseEvent=true;
	PppdDebugLevel = false;
	doAutoConnectAtStartup=false;
	useKwallet=true;
	showStatusBar=true;
	showToolBar=true;
	firstUseOfKwallet=true;
	shutdownIsCalled=false;
	skipKwalletStoring = false;
	hideOnCloseInfo = false;
	enableFreeswanVerbose=false;
	doKillL2tpdIfStillRunning=true;
	doKillRacoonIfStillRunning=true;
	hideMainWindow=false;
	showInterfaceIPinTooltip = true;
	showConnectionTimeInTooltip = true;

	VpncDebugLevel = 0;
	RacoonDebugLevel = "info";
	KvpncDebugLevel = 0;
	OpenvpnDebugLevel =0;
	LogViewerFontSize=0; // can be from -3 up to +3

	DebugBackgroundcolor=black;

	ToolList = new QPtrList<ToolInfo>();
	ToolList->setAutoDelete( TRUE );

	AccountList = new QPtrList<VpnAccountData>();
	AccountList->setAutoDelete( TRUE ); // the list owns the objects

	InfoLogColor=Qt::black;
	ErrorLogColor=Qt::red;
	SuccessLogColor=Qt::darkGreen;
	DebugLogColor=Qt::yellow;

	KStandardDirs *dirs = KGlobal::dirs();
	logfileName = QString(dirs->saveLocation( "data" ));
	QString logfilePath = QString(logfileName + "/kvpnc/kvpnc.log");
	logfile.setName( logfilePath );
	logFileStream.setDevice( &logfile );

	currentProfile=0L;
}

KVpncConfig::~KVpncConfig()
{
	delete AccountList;
	delete ToolList;
}

void KVpncConfig::setLogOutput(QTextEdit *LogOutput)
{
	this->LogOutput = LogOutput;
}

void KVpncConfig::appendLogEntry( QString msg, LogType type )
{

	// write to logfile
	if ( writeLogFile )
	{
		if ( !logfile.isOpen() )
		{
			KStandardDirs * dirs = KGlobal::dirs();
			QString logfileName = dirs->saveLocation( "data" );
			logfileName += "/kvpnc/kvpnc.log"; // /root.kde/share/apps/kvpnc.log
			//    KMessageBox::information( this, logfileName, "info" );
			logfile.setName( logfileName );
			if ( !logfile.open( IO_WriteOnly | IO_Append ) )
				KMessageBox::error( 0, i18n( "Log file can not be opened!" ) );
			else
			{
				//				QTextStream s( &logfile );
				logFileStream << i18n( "Log session started at: " );
				logFileStream << QDateTime::currentDateTime().toString( Qt::TextDate );
				logFileStream << "\n";
				logfile.flush();
			}
		}
		else
		{
			QString date = QDate().currentDate().toString(Qt::ISODate)+ " ";
			QString time = QTime().currentTime().toString(Qt::ISODate)+ " ";
			QString prefix="";
			switch ( type )
			{
					case info:
					prefix=i18n("info")+": ";
					break;
					case remote:
					prefix=i18n("remote")+": ";
					break;
					case error:
					prefix=i18n("error")+": ";
					break;
					case success:
					prefix=i18n("success")+": ";
					break;
					case debug:
					prefix=i18n("debug")+": ";
					break;
			}
// 			appPointer->processEvents();
			logFileStream << date << time << prefix << msg << "\n";
			logfile.flush();
// 			appPointer->processEvents();
		}


		// write into debug console
		QString prefix="";
		QString postfix="";

		// font size
		prefix+="<font size=\""+QString().setNum(LogViewerFontSize)+"\">";
		postfix+="<\\font>";

		if (useColorizedLogOutput)
			prefix+="<font color=\"";

		switch ( type )
		{
				case info:
				if (useColorizedLogOutput)
				{
					prefix+=InfoLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("info")+": ";
				break;
				case remote:
				if (useColorizedLogOutput)
				{
					prefix+=RemoteLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("remote")+": ";

				break;
				case error:
				if (useColorizedLogOutput)
				{
					prefix+=ErrorLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("error")+": ";

				break;
				case success:
				if (useColorizedLogOutput)
				{
					prefix+=SuccessLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("success")+": ";
				break;
				case debug:
				if (useColorizedLogOutput)
				{
					prefix+=DebugLogColor.name();
					prefix+="\">";
				}
				prefix+=i18n("debug")+": ";
				break;
		}

		if (useColorizedLogOutput)
			postfix+="</font>";

		LogOutput->append( prefix+msg+postfix );
// 		appPointer->processEvents();
	}
}

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

}

void KVpncConfig::saveOptions()
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString filePath = dirs->findResource ( "config", "kvpncrc" );
	QFile::remove
		( filePath );
	config->setGroup( "General Options" );

	config->writeEntry( "Minimize after connect", minimizeAfterConnect );
	config->writeEntry("Hide on startup", hideMainWindow );
	config->writeEntry( "Use silent quit", useSilentQuit );
	config->writeEntry( "Dont quit on CloseEvent", dontQuitOnCloseEvent );
	config->writeEntry( "Enable pppd debug", enableDebugPppd );
	config->writeEntry( "Enable pptpd debug", enableDebugPptpd );
	config->writeEntry( "Enable l2tpd debug", enableDebugL2tpd );
	config->writeEntry( "Enable xl2tpd debug", enableDebugXl2tpd );
	config->writeEntry( "Enable FreeSWAN verbose", enableFreeswanVerbose );
	config->writeEntry( "Show debugconsole", showDebugConsole );
	config->writeEntry( "Pid file for vpnc ", Vpnc_pid_file );
	config->writeEntry( "Vpnc debuglevel", VpncDebugLevel );
	config->writeEntry( "Racoon debuglevel", RacoonDebugLevel );
	config->writeEntry( "Kvpnc debuglevel", KvpncDebugLevel );
	config->writeEntry( "Pppd debuglevel", PppdDebugLevel );
	config->writeEntry( "Openvpn debuglevel", OpenvpnDebugLevel );
	config->writeEntry( "Pptp debuglevel", PptpLogLevel );
	config->writeEntry( "Path to vpnc-bin", pathToVpnc );
	config->writeEntry( "Path to vpnclient", pathToCiscoVpnc );
	config->writeEntry( "Path to racoon", pathToRacoon );
	config->writeEntry( "Path to setkey", pathToSetkey );
	config->writeEntry( "Path to iptables", pathToIptables );
	config->writeEntry( "Path to openssl", pathToOpenssl );
	config->writeEntry( "Path to freeswan", pathToFreeswan );
	config->writeEntry( "Path to pppd", pathToPppd );
	config->writeEntry( "Path to pptp", pathToPptp );
	config->writeEntry( "Path to l2tpd", pathToL2tpd );
	config->writeEntry( "Path to xl2tpd", pathToXl2tpd );
	config->writeEntry( "Path to kill", pathToKill );
	config->writeEntry( "Path to kill-all", pathToKillall );
	config->writeEntry( "Path to ping", pathToPing );
	config->writeEntry( "Path to openvpn", pathToOpenvpn );
	config->writeEntry( "Path to iputility", pathToIp );
	config->writeEntry( "Path to ifconfig", pathToIfconfig );
	config->writeEntry( "Path to route", pathToRoute );
	config->writeEntry( "Path to netstat", pathToNetstat );
	config->writeEntry( "Path to pkcs11-tool", pathToPkcs11Tool );
	config->writeEntry( "Show Statusbar", showStatusBar );
	config->writeEntry( "Try connect timeout", tryConnectTimeout );
	config->writeEntry( "Last Profile", lastProfile );
	config->writeEntry( "Write log file", writeLogFile );
	config->writeEntry( "Hold generated scripts", holdGeneratedScripts );
	config->writeEntry( "Programs in path", programsInPath );
	config->writeEntry( "Info logwindow color", InfoLogColor );
	config->writeEntry( "Remote logwindow color", RemoteLogColor );
	config->writeEntry( "Error logwindow color", ErrorLogColor );
	config->writeEntry( "Success  logwindow color", SuccessLogColor );
	config->writeEntry( "Debug logwindow color", DebugLogColor );
	config->writeEntry("Debug background color", DebugBackgroundcolor );
	config->writeEntry( "Use colorized log output", useColorizedLogOutput );
	config->writeEntry( "Show interface IP in tooltip", showInterfaceIPinTooltip );
	config->writeEntry( "Auto connect profile", AutoConnectProfile );
	config->writeEntry( "Do auto connect at startup", doAutoConnectAtStartup );
	config->writeEntry( "Log viewer font size", LogViewerFontSize );
	config->writeEntry( "Mainwindow width", parent->width() );
	config->writeEntry( "Mainwindow height", parent->height() );
	config->writeEntry( "Mainwindow position x", parent->x() );
	config->writeEntry( "Mainwindow position y", parent->y() );
	config->writeEntry("Openvpn management port", OpenvpnManagementPort );
	config->writeEntry( "hideOnCloseInfo" ,hideOnCloseInfo);
//   config->writeEntry( "ToolBar Settings" ,parent->toolBar( "mainToolBar" ));
	config->writeEntry("Use KWallet",useKwallet);
	config->writeEntry("FeedbackMailSent",feedbackMailSent);
	config->writeEntry("Do kill l2tpd if still running",doKillL2tpdIfStillRunning);
	config->writeEntry("Do kill racoon if still running",doKillRacoonIfStillRunning);
// 	appPointer->processEvents();

	if (useKwallet && KWallet::Wallet::isEnabled())
		config->writeEntry( "First use of Kwallet", false );
	/* = user data = */
	VpnAccountData *it;
	if ( !AccountList->isEmpty() )
	{
		for ( it = AccountList->first(); it; it = AccountList->next() )
		{
// 			appPointer->processEvents();
			std::cout << "Save profile: " << it->getName().ascii() << std::endl;
			if ( !it->getName().isEmpty() )
			{
				QString name = it->getName();
				QString ProfileName = "Profile_";
				ProfileName += name;
				config->setGroup( ProfileName );

				config->writeEntry("Description",it->getDescription());

				/* passwords with kwallet */
				if ( useKwallet && KWallet::Wallet::isEnabled())
				{
					if (!skipKwalletStoring )
					{
						if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Wallet enabled and available, writing to wallet." ),debug);
						// Open local wallet
						wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet());
// 						appPointer->processEvents();
						if (wallet != 0)
						{
							QString walletname="kvpnc";
							// Check if folder exists, otherwise create it
							bool walletOK=true;
							if (!wallet->hasFolder(walletname))
							{
								walletOK = wallet->createFolder(walletname);
// 								wallet->sync();
// 								appPointer->processEvents();
							}
							if (walletOK)
							{
								wallet->setFolder(walletname);
// 								appPointer->processEvents();
								//std::cout << "[set] account: " << ProfileName << ", loginname: " << loginname << ", password: " << pwd << std::endl;
								bool UserPasswordOK=true;
								if ( it->getSaveUserPassword() )
									UserPasswordOK = (wallet->writePassword (QString(name+"__user_pw"), it->getUserPassword()) == 0);
								else
									UserPasswordOK = (wallet->writePassword (QString(name+"__user_pw"), "") == 0);
// 								wallet->sync();
// 								appPointer->processEvents();

								bool PskOK=true;
								if ( it->getSavePsk() )
									PskOK = (wallet->writePassword (QString(name+"__psk"), it->getPreSharedKey()) == 0);
								else
									PskOK = (wallet->writePassword (QString(name+"__psk"), "") == 0);
// 								wallet->sync();

// 								appPointer->processEvents();

								bool PskKeyPassOK = (wallet->writePassword (QString(name+"__priv_key_pwd"), it->getPrivateKeyPass()) == 0);
								wallet->sync();

// 								appPointer->processEvents();

								if (KvpncDebugLevel > 2)
								{
									if (UserPasswordOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was ok." ).arg(i18n("user password")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("user password")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("user password")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "User password", it->getUserPassword() );
										// 									}

										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("user password")), error);
									}

									if (PskOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was successful." ).arg(i18n("preshared key")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("pre shared key")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("pre shared key")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "Pre shared key", it->getPreSharedKey() );
										// 									}
										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("preshared key")),error);
									}

									if (PskOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was successful." ).arg(i18n("preshared key")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("preshared key password")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("reshared key password")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "Pre shared key", it->getPreSharedKey() );
										// 									}
										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("preshared key")),error);
									}
									if (PskKeyPassOK)
										if (KvpncDebugLevel > 2)
											appendLogEntry(i18n( "write of %1 was successful." ).arg(i18n("preshared key password")), debug);
									else
									{
										// 									if ( KMessageBox::warningContinueCancel( 0,
										// 									        i18n( "KVpnc is unable to save %1 password securely in your wallet.<br>"
										// 									              "Do you want to save the password in the <b>unsafe</b> configuration file instead?" ).arg(i18n("preshared key password")),
										// 									        i18n( "Unable to store secure %1" ).arg(i18n("reshared key password")),
										// 									        KGuiItem( i18n( "Store &Unsafe" ), QString::fromLatin1( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
										// 									{
										// 										config->writeEntry( "Pre shared key", it->getPreSharedKey() );
										// 									}
										appendLogEntry(i18n( "write of %1 has failed." ).arg(i18n("preshared key password")),error);
									}
									//std::cout << "success: " << pwdOK << std::endl;
								}
// 								appPointer->processEvents();
								wallet->sync();
							}
							else
							{
								KMessageBox::error( 0, i18n( "Unable to create wallet folder for kvpnc!" ) );
								appendLogEntry(i18n( "Unable to create wallet folder for kvpnc!" ), error);
							}
						}
					}
					else //sessionSaving neither writing to wallet nor to config-file
					{
					if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Writing into Wallet is not possible at shutdown, skipping." ),debug);
					}
				}
				else//Wallet not available
				{
					//if (!useKwallet)
					{
						if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Wallet disabled or not available, writing to config file." ),debug);
						// write passwords to config file :|
						if ( it->getSaveUserPassword() )
						{
							config->writeEntry( "User password", it->getUserPassword() );
						}
						if ( it->getSavePsk() )
						{
							config->writeEntry( "Pre shared key", it->getPreSharedKey() );
						}
						config->writeEntry( "PrivateKey password", it->getPrivateKeyPass() );
					}
				}

// 				appPointer->processEvents();

// 				KMessageBox::information(0,"connection type changed: "+QString().setNum(it->getConnectionType())+QString(" ")+it->getName(),QString("type set"));

				// normal config
				if ( it->getConnectionType() == VpnAccountData::cisco )
					config->writeEntry( "Connection type", "cisco" );
				else if ( it->getConnectionType() == VpnAccountData::ciscoorig )
					config->writeEntry( "Connection type", "ciscoorig" );
				else if ( it->getConnectionType() == VpnAccountData::racoon )
					config->writeEntry( "Connection type", "racoon" );
				else if ( it->getConnectionType() == VpnAccountData::l2tpd_racoon )
					config->writeEntry( "Connection type", "l2tpd (racoon)" );
				else if ( it->getConnectionType() == VpnAccountData::freeswan )
					config->writeEntry( "Connection type", "freeswan" );
				else if ( it->getConnectionType() == VpnAccountData::l2tpd_freeswan )
					config->writeEntry( "Connection type", "l2tpd (openswan)" );
				else if ( it->getConnectionType() == VpnAccountData::pptp )
					config->writeEntry( "Connection type", "pptp" );
				else if ( it->getConnectionType() == VpnAccountData::openvpn )
					config->writeEntry( "Connection type", "openvpn" );
				else
					config->writeEntry( "Connection type", "other" );
				config->writeEntry( "VPN Gateway", it->getGateway() );
				config->writeEntry( "VPN ID", it->getID() );
				config->writeEntry( "Username", it->getUserName() );

				config->writeEntry( "Save user password", it->getSaveUserPassword() );
				config->writeEntry( "Save PSK", it->getSavePsk() );
				config->writeEntry( "Save private key password", it->getSavePrivateKeyPassword() );
				config->writeEntry( "Private key", it->getPrivateKey() );
				config->writeEntry( "Use advanced settings", it->getUseAdvancedSettings() );
				config->writeEntry( "Application version", it->getApplicationVersion() );
				config->writeEntry( "Local port", it->getLocalPort() );
				config->writeEntry( "Remote port", it->getRemotePort() );
				config->writeEntry( "NT domain name", it->getNtDomainName() );
				config->writeEntry( "Perfect forward secrety", it->getPerfectForwardSecrety() );
				config->writeEntry( "IKE group", it->getIkeGroup() );
				
				config->writeEntry( "Use application version", it->getUseApplicationVersion() );
				config->writeEntry( "Use global IPSec secret", it->getUseGlobalIpsecSecret() );
				config->writeEntry( "Use IKE group", it->getUseIkeGroup() );
				config->writeEntry( "Use local port", it->getUseLocalPort() );
				config->writeEntry( "Use remote port", it->getUseRemotePort() );
				config->writeEntry( "Use NT domain name", it->getUseNtDomainName() );
				config->writeEntry( "Use single DES", it->getUseSingleDes() );
				config->writeEntry( "Use perfect Forward Secrety", it->getUsePerfectForwardSecrety() );
				config->writeEntry( "Remote net address", it->getRemoteNetAddr() );
				config->writeEntry( "Remote net mask", it->getRemoteNetMask() );

				config->writeEntry( "x509 certificate", it->getX509Certificate() );
				config->writeEntry( "Ca certificate", it->getCaCertificate() );
				config->writeEntry( "Network device", it->getNetworkDevice() );
				config->writeEntry( "Cert path", it->getCertPath() );
				if ( it->getAuthType() == VpnAccountData::cert )
					config->writeEntry( "Auth type", "cert" );
				else
					config->writeEntry( "Auth type", "psk" );
				config->writeEntry( "do ping ip", it->getDoPingIP() );
				config->writeEntry( "Ping host IP", it->getPingHostIP() );

// 				appPointer->processEvents();

				config->writeEntry( "Use special remote ID", it->getUseSpecialRemoteID() );
				config->writeEntry( "Special server certificate", it->getSpecialServerCertificate() );
				config->writeEntry( "Use special server certificate", it->getUseSpecialServerCertificate() );
				config->writeEntry( "Special remote ID", it->getSpecialRemoteID() );
				config->writeEntry( "Use UDP-protocol", it->getUseUdp() );
				config->writeEntry( "Use UDP-port", it->getUseUdpPort() );
				config->writeEntry( "local UDP port", it->getUdpPort() );
				config->writeEntry( "use DNS-server", it->getUseDnsServer() );
				config->writeEntry( "DNS server", it->getDnsServer() );
				config->writeEntry( "get dns server from peer", it->getUseGetDnsFromPeer() );
				config->writeEntry( "refuse 40 bit encryption", it->getRefuse40BitEncryption() );
				config->writeEntry( "refuse 128 bit encryption", it->getRefuse128BitEncryption() );
				config->writeEntry( "require stateless encryption", it->getAllowStatefulMode() );
				config->writeEntry( "require mppe", it->getRequireMppe() );
				config->writeEntry( "refuse EAP", it->getRefuseEap() );
				config->writeEntry( "Disable MPPE compression", it->getDisableMPPEComp() );
				config->writeEntry( "Local virtual IP", it->getLocalVirtualIP() );
				config->writeEntry( "Remote virtual IP", it->getRemoteVirtualIP() );
				config->writeEntry( "Pre shared key file", it->getPreSharedKeyFile() );
				config->writeEntry( "Execute command before connect", it->getExecuteCmdBeforeConnect() );
				config->writeEntry( "Execute command after connect", it->getExecuteCmdAfterConnect() );
				config->writeEntry( "Execute command before disconnect", it->getExecuteCmdBeforeDisconnect() );
				config->writeEntry( "Execute command after disconnect", it->getExecuteCmdAfterDisconnect() );
				config->writeEntry( "Command before connect", it->getCommandBeforeConnect() );
				config->writeEntry( "Command after connect", it->getCommandAfterConnect() );
				config->writeEntry( "Command before disconnect", it->getCommandBeforeDisconnect() );
				config->writeEntry( "Command after disconnect", it->getCommandAfterDisconnect() );
				config->writeEntry( "Use no BSD compression", it->getUseNoBsdComp() );
				config->writeEntry( "Do not use no IP by default", it->getUseNoIpDefault());
				config->writeEntry( "Use no deflate", it->getUseNoDeflate() );
				config->writeEntry( "Set default route", it->getSetDefaultRoute() );
				config->writeEntry( "Replace default route", it->getReplaceDefaultRoute() );
				config->writeEntry( "Use own MTU", it->getUseMtu() );
				config->writeEntry( "Use own MRU", it->getUseMru() );
				config->writeEntry( "MTU for pppd", it->getMtu() );
				config->writeEntry( "MRU for pppd", it->getMru() );
				config->writeEntry( "Use Virtual IP", it->getUseVirtualIP() );
				config->writeEntry( "Virtual IP", it->getVirtualIP() );
				config->writeEntry( "PSK is in file", it->getPskIsInFile() );
				config->writeEntry( "Use additional network routes", it->getUseAdditionalNetworkRoutes() );
				config->writeEntry( "Hash algorithm", it->getHashAlgo() );
				config->writeEntry( "Encryption algorithm", it->getEncryptionAlgorithm() );
				config->writeEntry( "Authentication algorithm", it->getAuthenticationAlgorithm() );
				config->writeEntry( "Tunnel device type", it->getTunnelDeviceType() );
				config->writeEntry( "Use userdefined port", it->getUseUserdefinedPort() );
				config->writeEntry( "Userdefined port", it->getUserdefinedPort() );
				config->writeEntry( "Keep default route", it->getKeepDefaultRoute() );
				config->writeEntry( "NS cert type", it->getNsCertType() );
				config->writeEntry( "Use NS cert type", it->getUseNsCertType() );
				config->writeEntry( "Use connection status check", it->getUseConnectionStatusCheck() );
				config->writeEntry( "Connection check success count", it->getConnectionStatusCheckSuccessCount() );
				config->writeEntry( "Connection check status interval", it->getConnectionStatusInterval() );
				config->writeEntry( "Do reconnect after connection lost", it->getDoReconnectAfterConnectionLost());
				config->writeEntry( "Disable LZO compression", it->getDisableLzoCompression());
				config->writeEntry( "AuthWithUsernameAndPassword", it->getAuthWithUsernameAndPassword() );
				config->writeEntry( "AllowEmptyGroupPassword", it->getAllowEmptyGroupPassword() );
				config->writeEntry( "Use userdefinied cipher", it->getUseUserdefiniedCipher() );
				config->writeEntry( "Userdefinied cipher", it->getUserdefiniedCipher() );
				config->writeEntry( "Use redirect gateway", it->getUseRedirectGateway() );
// 				appPointer->processEvents();
				config->writeEntry( "Use TLS auth", it->getUseTlsAuth() );
				config->writeEntry( "TLS auth file", it->getTlsAuthFile() );
				config->writeEntry( "Use HTTP proxy", it->getUseHttpProxy() );
				config->writeEntry( "HTTP proxy host", it->getHttpProxy() );
				config->writeEntry( "HTTP proxy port", it->getHttpProxyPort() );
				config->writeEntry( "HTTP proxy timeout", it->getHttpProxyTimeout() );
				config->writeEntry( "Dont save username", it->getDontSaveUsername() );
				config->writeEntry( "Use mode config", it->getUseModeConfig() );
				config->writeEntry( "Exchange mode", it->getExchangeMode() );
				config->writeEntry( "Use delay at reconnect", it->getUseReconnectDelay() );
				config->writeEntry( "Reconnect delay", it->getReconnectDelay() );
				config->writeEntry( "Use TLS host", it->getUseTlsRemoteHost() );
				config->writeEntry( "TLS remote host", it->getTlsRemoteHost() );
				config->writeEntry( "Disable opportunistic encryption", it->getDisableOpportunisticEncryption() );
				config->writeEntry( "Right next hop", it->getRightNextHop() );
				config->writeEntry( "Left next hop", it->getLeftNextHop() );
				config->writeEntry( "Use mssfix", it->getUseMssfix() );
				config->writeEntry( "Use userdefinied packet size for fragmentation", it->getUseFragment() );
				config->writeEntry( "Use userdef packet size", it->getMssfix() );
				config->writeEntry( "Fragment", it->getFragment() );
				config->writeEntry( "PeerTimeout", it->getPeerTimeout() );
				config->writeEntry("Disable CCP", it->getDisableCcp() );
				config->writeEntry("Use smartcard", it->getUseSmartcard() );
				config->writeEntry("Use Xauth interactive", it->getUseXauthInteractive() );
				config->writeEntry("Use HTTP Proxy Authentication", it->getUseHttpProxyAuth() );
				config->writeEntry("Use HTTP Proxy Authtype", it->getHttpProxyAuthType() );
				config->writeEntry("Use HTTP Proxy Auth user", it->getHttpProxyUser() );
				config->writeEntry("Use HTTP Proxy Auth pass", it->getHttpProxyPass() );
				config->writeEntry("Use only CA cert and user auth", it->getUseOnlyCaCertAndUserAuth() );
				config->writeEntry("Use mail address as identifier", it->getUseMailAddressAsIdentifier() );
				config->writeEntry("Use right next hop", it->getUseRightNextHop() );
				config->writeEntry("Use left next hop", it->getUseLeftNextHop() );
				config->writeEntry("Pkcs11 providers", it->getPkcs11Providers() );
				config->writeEntry("Pkcs11 slot type", it->getPkcs11SlotType() );
				config->writeEntry("Pkcs11 slot", it->getPkcs11Slot() );
				config->writeEntry("Pkcs11 id type", it->getPkcs11IdType() );
				config->writeEntry("Pkcs11 id", it->getPkcs11Id() );
				config->writeEntry("Pkcs11 sign mode", it->getPkcs11SignMode() );
				config->writeEntry("Use Pkcs11 providers", it->getUsePkcs11Providers() );
				config->writeEntry("Allow empty private key password", it->getAllowEmptyPrivateKeyPassword());
				config->writeEntry("Allow ip address change of peer", it->getAllowIpAddressChangeOfPeer());
				config->writeEntry("Auth method", it->getAuthMethod());
				config->writeEntry("Command after connect delay time", it->getCommandAfterConnectDelayTime());
				config->writeEntry("Use search domain in resolv conf",it->getUseSearchDomainInResolvConf());
				config->writeEntry("Search domain in resolv conf",it->getSearchDomainInResolvConf());
				config->writeEntry("Authentication direction",it->getAuthenticationDirection());

// 				appPointer->processEvents();

				QString AdditionalNetworkRoutesString;
				QStringList AdditionalNetworkRoutes = it->getAdditionalNetworkRoutes();

				// Networks delimited by a ','
				for ( QStringList::Iterator it2 = AdditionalNetworkRoutes.begin(); it2 != 	AdditionalNetworkRoutes.end(); ++it2 )
				{
					AdditionalNetworkRoutesString+=*it2;
					AdditionalNetworkRoutesString+=",";
				}
				AdditionalNetworkRoutesString=AdditionalNetworkRoutesString.left(AdditionalNetworkRoutesString.length()-1);
				config->writeEntry( "Additional network routes", AdditionalNetworkRoutesString );


				/* give info */
// 				slotStatusMsg ( i18n( "Profile \"%1\" saved." ).arg( ProfileName.remove("Profile_") ), ID_FLASH_MSG );

				appendLogEntry ( i18n( "Profile \"%1\" saved." ).arg( ProfileName.remove("Profile_") ) , info);
// 				appPointer->processEvents();
			}
			appPointer->processEvents();
		}
	}
	config->sync();
	doBackupConfig();

	slotStatusMsg ( i18n( "Profiles saved." ) , ID_FLASH_MSG );
	appPointer->processEvents();
}

void KVpncConfig::loadOptions()
{
	config->setGroup( "Notification Messages" );
	hideOnCloseInfo = config->readBoolEntry( "hideOnCloseInfo" ,false);

	config->setGroup( "General Options" );
	minimizeAfterConnect = config->readBoolEntry( "Minimize after connect", true );
	hideMainWindow = config->readBoolEntry("Hide on startup", false );
	useSilentQuit = config->readBoolEntry( "Use silent quit", false );
	dontQuitOnCloseEvent = config->readBoolEntry( "Dont quit on CloseEvent", true );
	showDebugConsole = config->readBoolEntry( "Show debugconsole", true );
	enableDebugPppd = config->readBoolEntry( "Enable pppd debug", false );
	enableDebugPptpd = config->readBoolEntry( "Enable pptpd debug", false );
	enableFreeswanVerbose = config->readBoolEntry( "Enable FreeSWAN verbose", false );
	Vpnc_pid_file = config->readEntry( "Pid file for vpnc ", "/var/run/vpnc/pid" );
	RacoonDebugLevel = config->readEntry( "Racoon debuglevel", "info" );
	// we need to correct old int value
	if (RacoonDebugLevel == "0")
		RacoonDebugLevel="info";

	VpncDebugLevel = config->readNumEntry( "Vpnc debuglevel", 0 );
	KvpncDebugLevel = config->readNumEntry( "Kvpnc debuglevel", 0 );
	PppdDebugLevel = config->readBoolEntry( "Pppd debuglevel", false );
	OpenvpnDebugLevel = config->readNumEntry( "Openvpn debuglevel", 0 );
	PptpLogLevel = config->readNumEntry( "Pptp debuglevel", 1 );
	enableDebugL2tpd = config->readBoolEntry( "enable l2tpd debug", false );
	enableDebugXl2tpd = config->readBoolEntry( "Enable xl2tpd debug", false );
	pathToVpnc = config->readEntry( "Path to vpnc-bin", "/usr/sbin/vpnc" );
	pathToCiscoVpnc = config->readEntry( "Path to vpnclient", "/usr/local/bin/vpnclient" );
	pathToSetkey = config->readEntry( "Path to setkey", "/usr/sbin/setkey" );
	pathToRacoon = config->readEntry( "Path to racoon", "/usr/sbin/racoon" );
	pathToIptables = config->readEntry( "Path to iptables", "/sbin/iptables" );
	pathToOpenssl = config->readEntry( "Path to openssl", "/usr/bin/openssl" );
	pathToFreeswan = config->readEntry( "Path to freeswan", "/usr/sbin/ipsec" );
	pathToIp = config->readEntry( "Path to iputility", "/sbin/ip" );
	pathToIfconfig = config->readEntry( "Path to ifconfig", "/sbin/ifconfig" );
	pathToRoute = config->readEntry( "Path to route", "/sbin/route" );
	pathToNetstat = config->readEntry( "Path to netstat", "/bin/netstat" );
	pathToPppd = config->readEntry ("Path to pppd","/usr/sbin/pppd");
	pathToPptp = config->readEntry ("Path to pptp","/usr/sbin/pptp");
	pathToL2tpd = config->readEntry ("Path to l2tpd","/usr/sbin/l2tpd");
	pathToXl2tpd = config->readEntry ("Path to xl2tpd","/usr/sbin/xl2tpd");
	pathToKill = config->readEntry ("Path to kill","/bin/kill");
	pathToKillall = config->readEntry ("Path to kill-all","/usr/bin/killall");
	pathToPing = config->readEntry ("Path to ping","/bin/ping");
	pathToOpenvpn = config->readEntry ("Path to openvpn","/usr/sbin/openvpn");
	pathToPkcs11Tool = config->readEntry( "Path to pkcs11-tool", "/usr/bin/pkcs11-tool" );

	tryConnectTimeout = QString( config->readEntry( "Try connect timeout", "10" ) ).toInt();
	lastProfile = config->readEntry( "Last Profile", "" );
	writeLogFile = config->readBoolEntry( "Write log file", true );
	holdGeneratedScripts = config->readBoolEntry( "Hold generated scripts", true );
	showStatusBar = config->readBoolEntry( "Show Statusbar", true );
	programsInPath = config->readBoolEntry( "Programs in path", true );

	if (programsInPath)
		useDefaultPaths=true;

	InfoLogColor = config->readColorEntry ( "Info logwindow color", new QColor(Qt::black) );
	RemoteLogColor = config->readColorEntry ( "Remote logwindow color", new QColor(Qt::blue) );
	ErrorLogColor = config->readColorEntry( "Error logwindow color", new QColor(Qt::red ));
	SuccessLogColor = config->readColorEntry( "Success  logwindow color", new QColor(Qt::darkGreen) );
	DebugLogColor = config->readColorEntry( "Debug logwindow color", new QColor(255,175,0 ));
	DebugBackgroundcolor = config->readColorEntry("Debug background color", new QColor (Qt::white) );
	useColorizedLogOutput = config->readBoolEntry("Use colorized log output", true);
	showInterfaceIPinTooltip = config->readBoolEntry( "Show interface IP in tooltip", true );
	AutoConnectProfile= config->readEntry( "Auto connect profile", "" );
	doAutoConnectAtStartup = config->readBoolEntry( "Do auto connect at startup", false );
	LogViewerFontSize = config->readNumEntry( "Log viewer font size", 2 );

	WindowSize = QSize( config->readNumEntry( "Mainwindow width", 50 ), this->config->readNumEntry( "Mainwindow height", 50 ) );
	WindowPos = QPoint ( config->readNumEntry( "Mainwindow position x", 10 ), this->config->readNumEntry( "Mainwindow position y", 50 ) );

	OpenvpnManagementPort = config->readNumEntry("Openvpn management port", 2222 );

	appPointer->processEvents();

	if ( writeLogFile )
		if ( !logfile.isOpen() )
		{
			KStandardDirs *dirs = KGlobal::dirs();

			QDir AppFolder (QString(dirs->saveLocation( "data" )+"/kvpnc"));
			if (!AppFolder.exists())
			{
				// 		KMessageBox::error( this, i18n( "creating dir: %1" ).arg(dirs->saveLocation( "data" )+"/kvpnc" ));
				QDir AppFolder2(dirs->saveLocation( "data" ));
				if(!AppFolder2.mkdir("kvpnc",true))
				{
					KMessageBox::error( 0, i18n( "The appdir for kvpnc could not be created. Be sure that you have write permission of \"%1\"." ).arg(dirs->saveLocation( "data" )) );
					appendLogEntry( i18n( "The appdir for kvpnc could not be created. Be sure that you have write permission of \"%1\"." ).arg(dirs->saveLocation( "data" )),error);
				}
			}

			logfileName = dirs->saveLocation( "data" );
			logfileName += "/kvpnc/kvpnc.log";
			//KMessageBox::information( this, logfileName, "info" );
			logfile.setName( logfileName );
			if ( !logfile.open( IO_WriteOnly | IO_Append ) )
			{
				KMessageBox::error( 0, i18n( "Log file cant be opened!" ) );
				appendLogEntry(i18n( "Unable to find \"%1\"!" ).arg("pppd"),error);
			}
			else
			{
				QTextStream s( &logfile );
				s << i18n( "Log session started at: " ) << QDateTime::currentDateTime().toString( Qt::TextDate ) << endl;
			}
		}

	useKwallet = config->readBoolEntry("Use KWallet", true);
	firstUseOfKwallet = config->readBoolEntry( "First use of Kwallet", true );
	feedbackMailSent = config->readBoolEntry("FeedbackMailSent",false);
	doKillL2tpdIfStillRunning = config->readBoolEntry("Do kill l2tpd if still running",true);
	doKillXl2tpdIfStillRunning = config->readBoolEntry("Do kill xl2tpd if still running",true);
	doKillRacoonIfStillRunning = config->readBoolEntry("Do kill racoon if still running",true);


	if ( KvpncDebugLevel > 2 )
		appendLogEntry( i18n( "Global configuration loaded." ) ,info);


	/* = user data = */
	/* old style: one profile: will be removed in future */
	/*
	config->setGroup( "Client Options" );
	this->mw->gatewayLineEdit->setText( config->readEntry( "VPN Gateway", "" ) );
	this->mw->IDLineEdit->setText( config->readEntry( "VPN ID", "" ) );
	this->mw->PSKLineEdit->setText( config->readEntry( "Group password", "" ) );
	this->mw->UsernameLineEdit->setText( config->readEntry( "Username", "" ) );
	this->mw->PasswordEdit->setText( config->readEntry( "Password", "" ) );

	this->mw->CheckUserPass->setChecked( config->readBoolEntry( "Save user password", false ) );
	this->mw->CheckGroupPass->setChecked( config->readBoolEntry( "Save group password", false ) );
	*/

	/* profiles are stored in a group which is named to the following scheme:
	 Profile_XXXXX
	 XXXXX is the account name (important: unique!)
	*/
	QStringList configGroups = config->groupList();
	bool oldConfigurationFound = false;

	bool sessionFound = false;

	for ( QStringList::Iterator it = configGroups.begin(); it != configGroups.end(); ++it )
	{
		QString name = *it;
		name.stripWhiteSpace();
		if ( name.left( 7 ) == "Profile" && name.length() > 8 )
		{
			// Profile found

			sessionFound = true;

			if ( KvpncDebugLevel > 2 )
			{
				QString tmp = i18n( "Profile found: " );
				tmp += name.right( ( name.length() ) - 8 );
				appendLogEntry ( tmp, debug );
			}
			config->setGroup( name );
			QString UserPassword="";
			QString PrivateKeyPass="";
			QString PreSharedKey ="";

			/* passwords with kwallet */
			if (useKwallet && KWallet::Wallet::isEnabled() && !firstUseOfKwallet)
			{
				if (KvpncDebugLevel > 2)
					appendLogEntry(i18n( "Wallet enabled and available, reading passwords from wallet." ),debug);
				// Open local wallet
				wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet());
				if (wallet != 0)
				{
					QString walletname="kvpnc";

					if (!wallet->hasFolder(walletname))
					{
						wallet->createFolder(walletname);
						wallet->sync();
					}

					if (wallet->setFolder(walletname))
					{
						if (KvpncDebugLevel > 2)
							appendLogEntry(i18n( "Folder for kvpnc has been set." ),debug);

						QString profilename = name.right( ( name.length() ) - 8 );

						if (wallet->readPassword(QString(profilename+"__user_pw"), UserPassword) != 0)
							appendLogEntry(i18n( "read of %1 has failed." ).arg(i18n("user password")),error);
						else
							if (KvpncDebugLevel > 2)
								appendLogEntry(i18n( "read of %1 was successful." ).arg(i18n("user password")),debug);

						if (wallet->readPassword(QString(profilename+"__psk"), PreSharedKey) != 0)
							appendLogEntry(i18n( "read of %1 has failed." ).arg(i18n("preshared key")),error);
						else
							if (KvpncDebugLevel > 2)
								appendLogEntry(i18n( "read of %1 was successful." ).arg(i18n("preshared key")),debug);

						if (wallet->readPassword(QString(profilename+"__priv_key_pwd"), PrivateKeyPass) != 0)
							appendLogEntry(i18n( "read of %1 has failed." ).arg(i18n("preshared key password")),error);
						else
							if (KvpncDebugLevel > 2)
								appendLogEntry(i18n( "read of %1 was successful." ).arg(i18n("preshared key password")),debug);
					}
					else
					{
						KMessageBox::error( 0, i18n( "Unable to set wallet folder for kvpnc!" ) );
						appendLogEntry(i18n( "Unable to set wallet folder for kvpnc!" ), error);
					}
					appPointer->processEvents();
				}
				else
				{
					KMessageBox::error( 0, i18n( "Unable to open wallet folder for kvpnc!" ) );
					appendLogEntry(i18n( "Unable to open wallet folder for kvpnc!" ), error);
				}


			}
			else
			{
				if (KvpncDebugLevel > 2)
				{
					if (useKwallet && KWallet::Wallet::isEnabled() && firstUseOfKwallet)
						appendLogEntry(i18n( "Wallet enabled, available but first time, reading passwords from config file." ),debug);
					else
						appendLogEntry(i18n( "Wallet disabled or not available, reading passwords from config file." ),debug);
				}
				// read from config file
				UserPassword = config->readEntry( "User password", "" );
				PrivateKeyPass = config->readEntry( "PrivateKey password", "" );
				PreSharedKey = config->readEntry( "Pre shared key", "" );
			}

			VpnAccountData::ConnectionType ConnType = VpnAccountData::ConnectionType( VpnAccountData::cisco );
			QString type_string = config->readEntry( "Connection type", "cisco" );

			if ( type_string == "cisco" )
				ConnType = VpnAccountData::cisco;
			else if ( type_string == "ciscoorig" )
				ConnType = VpnAccountData::ciscoorig;
			else if ( type_string == "racoon" )
				ConnType = VpnAccountData::racoon;
			else if ( type_string == "l2tpd (racoon)" )
				ConnType = VpnAccountData::l2tpd_racoon;
			else if ( type_string == "freeswan" )
				ConnType = VpnAccountData::freeswan;
			else if ( type_string == "l2tpd (openswan)" )
				ConnType = VpnAccountData::l2tpd_freeswan;
			else if ( type_string == "pptp" )
				ConnType = VpnAccountData::pptp;
			else if ( type_string == "openvpn" )
				ConnType = VpnAccountData::openvpn;
			else
				ConnType = VpnAccountData::other;

			QString Name = name.right( name.length() - 8 );
			VpnAccountData *data = new VpnAccountData( ConnType, Name );
			data->setGateway( config->readEntry( "VPN Gateway", "" ));
			data->setID( config->readEntry( "VPN ID", "" ) );
			data->setDescription( config->readEntry("Description",""));
			data->setUserName( config->readEntry( "Username", "" ));
			data->setSaveUserPassword( config->readBoolEntry( "Save user password", false ));
			data->setSavePsk( config->readBoolEntry( "Save PSK", false ));
			data->setSavePrivateKeyPassword( config->readBoolEntry( "Save private key password", true ) );
			data->setUseAdvancedSettings( config->readBoolEntry( "Use advanced settings", false ));
			data->setApplicationVersion( config->readEntry( "Application version", "Cisco Systems VPN Client 0.3-rm+zomb.1:Linux" ));
			data->setLocalPort( config->readNumEntry( "Local port", 500 ));
			data->setRemotePort( config->readNumEntry( "Remote port", 500 ));
			data->setNtDomainName( config->readEntry( "NT domain name", "" ));
			data->setPerfectForwardSecrety( config->readEntry( "Perfect forward secrety", "server" ));
			data->setIkeGroup( config->readEntry( "IKE group", "dh1" ));
			data->setUseApplicationVersion( config->readBoolEntry( "Use application version", false ));
			data->setUseGlobalIpsecSecret( config->readBoolEntry( "Use global IPSec secret", false ));
			data->setUseIkeGroup( config->readBoolEntry( "Use IKE group", false ));
			data->setUseLocalPort( config->readBoolEntry( "Use local port", false ));
			data->setUseRemotePort( config->readBoolEntry( "Use remote port", false ));
			data->setUseNtDomainName( config->readBoolEntry( "Use NT domain name", false ));
			data->setUseSingleDes( config->readBoolEntry( "Use single DES", false ));
			data->setUsePerfectForwardSecrety( config->readBoolEntry( "Use perfect Forward Secrety", false ));
			data->setX509Certificate( config->readEntry( "x509 certificate", "" ));
			data->setCaCertificate( config->readEntry( "Ca certificate", "" ));
			data->setNetworkDevice( config->readEntry( "Network device", "default" ));
			data->setCertPath( config->readEntry( "Cert path", "/etc/racoon/certs" ));
			data->setPrivateKey( config->readEntry( "Private key", "" ));
			VpnAccountData::AuthenticationType authtype;
			if ( config->readEntry( "Auth type", "cert" ) == "cert" )
				authtype = VpnAccountData::cert;
			else
				authtype = VpnAccountData::psk;
			data->setAuthType(authtype);

			appPointer->processEvents();

			data->setDoPingIP( config->readBoolEntry( "do ping ip", false ));
			data->setPingHostIP( config->readEntry( "Ping host IP", "" ));
			data->setUseSpecialRemoteID( config->readBoolEntry( "Use special remote ID", false ));
			data->setSpecialRemoteID( config->readEntry( "Special remote ID", "" ));
			data->setUseSpecialServerCertificate( config->readBoolEntry( "Use special server certificate", false ));
			data->setSpecialServerCertificate( config->readEntry( "Special server certificate", "" ));
			data->setUseUdp( config->readBoolEntry( "Use UDP-protocol", false ));
			data->setUseUdpPort( config->readBoolEntry( "Use UDP-port", false ));
			data->setUdpPort( config->readNumEntry( "local UDP port", 4500 ));
			data->setUseDnsServer( config->readBoolEntry( "use DNS-server", false));
			data->setDnsServer( config->readEntry( "DNS server", "" ));
			data->setUseGetDnsFromPeer( config->readBoolEntry( "get dns server from peer", true ));
			data->setRefuse40BitEncryption( config->readBoolEntry( "refuse 40 bit encryption", true ));
			data->setRefuse128BitEncryption( config->readBoolEntry( "refuse 128 bit encryption", false ));
			data->setAllowStatefulMode( config->readBoolEntry( "require stateless encryption",false ));
			data->setRequireMppe( config->readBoolEntry( "require mppe", true ));
			data->setRefuseEap( config->readBoolEntry( "refuse EAP", false ));
			data->setUseNoBsdComp( config->readBoolEntry( "Use no BSD compression", true ));
			data->setUseNoIpDefault(config->readBoolEntry( "Do not use no IP by default", false));
			data->setUseNoDeflate( config->readBoolEntry( "Use no deflate", true ));
			data->setDisableMPPEComp( config->readBoolEntry( "Disable MPPE compression", false ));
			data->setLocalVirtualIP( config->readEntry( "Local virtual IP", "" ));
			data->setRemoteVirtualIP( config->readEntry( "Remote virtual IP", "" ));
			data->setPreSharedKeyFile( config->readEntry( "Pre shared key file", "" ));
			data->setExecuteCmdBeforeConnect( config->readBoolEntry( "Execute command before connect",false));
			data->setExecuteCmdAfterConnect( config->readBoolEntry( "Execute command after connect",false));
			data->setExecuteCmdBeforeDisconnect( config->readBoolEntry( "Execute command before disconnect", false));
			data->setExecuteCmdAfterDisconnect( config->readBoolEntry( "Execute command after disconnect", false));
			data->setCommandBeforeConnect( config->readEntry( "Command before connect", "" ));
			data->setCommandAfterConnect( config->readEntry( "Command after connect", "" ));
			data->setCommandBeforeDisconnect( config->readEntry( "Command before disconnect", "" ));
			data->setCommandAfterDisconnect( config->readEntry( "Command after disconnect", "" ));
			data->setSetDefaultRoute( config->readBoolEntry( "Set default route", true ));
			data->setReplaceDefaultRoute( config->readBoolEntry( "Replace default route", false ));
			data->setUseMtu( config->readBoolEntry( "Use own MTU", false ));
			data->setUseMru( config->readBoolEntry( "Use own MRU", false ));
			data->setMtu( config->readNumEntry( "MTU for pppd", 1492 ));
			data->setMru( config->readNumEntry( "MRU for pppd", 1492 ));
			data->setUseVirtualIP( config->readBoolEntry( "Use Virtual IP", false ));
			data->setVirtualIP( config->readEntry( "Virtual IP", "" ));
			data->setPskIsInFile( config->readBoolEntry( "PSK is in file", false ));
			data->setUseAdditionalNetworkRoutes(	config->readBoolEntry( "Use additional network routes", false ));
			appPointer->processEvents();
			QString AdditionalNetworkRoutesString = config->readEntry( "Additional network routes", "" );
			// Networks delimited by a ','
			QStringList AdditionalNetworkRoutes(QStringList::split( ",", AdditionalNetworkRoutesString ));
			data->setAdditionalNetworkRoutes(AdditionalNetworkRoutes);
			data->setHashAlgo( config->readEntry( "Hash algorithm", "md5" ));
			data->setEncryptionAlgorithm( config->readEntry( "Encryption algorithm", "3des" ));
			data->setAuthenticationAlgorithm( config->readEntry( "Authentication algorithm", "hmac_sha1" ));
			data->setTunnelDeviceType( config->readEntry( "Tunnel device type", "tun" ));
			data->setUseUserdefinedPort( config->readBoolEntry( "Use userdefined port", false ));
			data->setUserdefinedPort( config->readNumEntry( "Userdefined port", 1194 ));
			data->setKeepDefaultRoute( config->readBoolEntry ("Keep default route", false ));
			data->setNsCertType( config->readEntry( "NS cert type", "client" ));
			data->setUseNsCertType( config->readBoolEntry( "Use NS cert type", false ));
			data->setUseConnectionStatusCheck ( config->readBoolEntry( "Use connection status check", true ));
			data->setConnectionStatusCheckSuccessCount ( config->readNumEntry( "Connection check success count", 4 ));
			data->setConnectionStatusInterval ( config->readNumEntry( "Connection check status interval", 1 ));
			data->setDoReconnectAfterConnectionLost(config->readBoolEntry("Do reconnect after connection lost", false));
			data->setDisableLzoCompression(config->readBoolEntry("Disable LZO compression", false));
			data->setUserPassword( UserPassword );
			data->setRemoteNetAddr( config->readEntry("Remote net address","") );
			data->setRemoteNetMask( QString().setNum(config->readNumEntry("Remote net mask",24 )));
			data->setPreSharedKey( PreSharedKey );
			data->setPrivateKeyPass( PrivateKeyPass );
			data->setAuthWithUsernameAndPassword( config->readBoolEntry( "AuthWithUsernameAndPassword",false ) );
			data->setAllowEmptyGroupPassword( config->readBoolEntry( "AllowEmptyGroupPassword", false ) );
			data->setUseUserdefiniedCipher( config->readBoolEntry( "Use userdefinied cipher", false ) );
			data->setUserdefiniedCipher( config->readEntry( "Userdefinied cipher", "" ) );
			appPointer->processEvents();
			data->setUseRedirectGateway( config->readBoolEntry( "Use redirect gateway", false ) );
			data->setUseTlsAuth( config->readBoolEntry( "Use TLS auth", false ) );
			data->setTlsAuthFile( config->readEntry( "TLS auth file", "" ) );
			data->setUseHttpProxy( config->readBoolEntry( "Use HTTP proxy", false ) );
			data->setHttpProxy( config->readEntry( "HTTP proxy host", "" ) );
			data->setHttpProxyPort( config->readNumEntry( "HTTP proxy port", 8080 ) );
			data->setHttpProxyTimeout( config->readNumEntry( "HTTP proxy timeout", 5 ) );
			data->setDontSaveUsername( config->readBoolEntry( "Dont save username", false ) );
			data->setUseModeConfig( config->readBoolEntry( "Use mode config", false ) );
			data->setExchangeMode( config->readEntry( "Exchange mode", "main" ) );
			data->setUseReconnectDelay( config->readBoolEntry( "Use delay at reconnect", false ) );
			data->setReconnectDelay( config->readNumEntry( "Reconnect delay", 5 ) );
			data->setUseTlsRemoteHost( config->readBoolEntry( "Use TLS host", false) );
			data->setTlsRemoteHost( config->readEntry( "TLS remote host", "") );
			data->setDisableOpportunisticEncryption( config->readBoolEntry( "Disable opportunistic encryption", false  ) );
			data->setRightNextHop( config->readEntry( "Right next hop", "" ) );
			data->setLeftNextHop( config->readEntry( "Left next hop", "" ) );
			data->setUseMssfix(config->readBoolEntry( "Use userdef packet size", false) );
			data->setUseFragment(config->readBoolEntry( "Use userdefinied packet size for fragmentation" , false) );
			data->setMssfix(config->readNumEntry( "Mssfix", 1300) );
			data->setFragment( config->readNumEntry( "Fragment", 1300) );
			data->setPeerTimeout( config->readNumEntry( "PeerTimeout",0) );
			data->setDisableCcp( config->readBoolEntry("Disable CCP",false) );
			data->setUseSmartcard( config->readBoolEntry("Use smartcard", false) );
			data->setUseXauthInteractive(config->readBoolEntry("Use Xauth interactive", false) );
			data->setUseHttpProxyAuth( config->readBoolEntry("Use HTTP Proxy Authentication", false ) );
			data->setHttpProxyAuthType( config->readEntry("Use HTTP Proxy Authtype", "basic") );
			data->setHttpProxyUser( config->readEntry("Use HTTP Proxy Auth user", "") );
			data->setHttpProxyPass( config->readEntry("Use HTTP Proxy Auth pass", "") );
			data->setUseOnlyCaCertAndUserAuth(config->readBoolEntry("Use only CA cert and user auth", false) );
			data->setUseMailAddressAsIdentifier(config->readBoolEntry("Use mail address as identifier", false) );
			data->setUseRightNextHop(config->readBoolEntry("Use right next hop", false) );
			data->setUseLeftNextHop(config->readBoolEntry("Use left next hop", false) );
			data->setPkcs11Providers(config->readEntry("Pkcs11 providers", "/usr/local/lib/libetpkcs11.so" ) );
			data->setPkcs11SlotType(config->readEntry("Pkcs11 slot type", "id") );
			data->setPkcs11Slot(config->readEntry("Pkcs11 slot", "0") );
			data->setPkcs11IdType(config->readEntry("Pkcs11 id type", "id") );
			data->setPkcs11Id(config->readEntry("Pkcs11 id","" ) );
			data->setPkcs11SignMode(config->readEntry("Pkcs11 sign mode", "auto") );
			data->setUsePkcs11Providers(config->readBoolEntry("Use Pkcs11 providers", false) );
			data->setAllowEmptyPrivateKeyPassword( config->readBoolEntry("Allow empty private key password", false ));
			data->setAllowIpAddressChangeOfPeer(config->readBoolEntry("Allow ip address change of peer", false));
			data->setAuthMethod(config->readEntry("Auth method", "chap"));
			data->setCommandAfterConnectDelayTime(config->readNumEntry("Command after connect delay time", 5));
			data->setUseSearchDomainInResolvConf(config->readBoolEntry("Use search domain in resolv conf",false));
			data->setSearchDomainInResolvConf(config->readEntry("Search domain in resolv conf",""));
			data->setAuthenticationDirection(config->readEntry("Authentication direction","none"));

			appPointer->processEvents();
			AccountList->append( data );
		}

		if ( name == "Client Options" )
		{
			// old style configuration found
			config->setGroup( "Client Options" );
			QString Name = "Default";
			VpnAccountData::ConnectionType ConnType = VpnAccountData::cisco;
			QString Gateway = config->readEntry( "VPN Gateway", "" );
			QString ID = config->readEntry( "VPN ID", "" );
			QString Psk = config->readEntry( "Group password", "" );
			QString Username = config->readEntry( "Username", "" );
			QString UserPassword = config->readEntry( "Password", "" );
			bool saveUserPassword = config->readBoolEntry( "Save user password", false );
			bool savePsk = config->readBoolEntry( "Save group password", false );

			VpnAccountData *AccData = new VpnAccountData( ConnType, Name);
			AccData->setGateway ( Gateway );
			AccData->setID( ID );
			AccData->setPreSharedKey( Psk);
			AccData->setUserName( Username );
			AccData->setUserPassword( UserPassword );
			AccData->setSaveUserPassword( saveUserPassword );
			AccData->setSavePsk( savePsk );
			AccData->setLocalPort( 500 );
			AccData->setPerfectForwardSecrety ( "server" );
			AccData->setIkeGroup( "dh1" );
			AccountList->append( AccData );

			lastProfile = "Default";

			// now mark for deleting old configuration
			oldConfigurationFound = true;
			if ( KvpncDebugLevel > 2 )
				appendLogEntry ( i18n( "Old configuration found, converted." ),info );

			if ( KvpncDebugLevel > 2 )
				appendLogEntry( i18n( "Configuration for profile \"%1\" loaded." ).arg( Name ),info );

			appPointer->processEvents();
		}


	}
	if ( oldConfigurationFound )
	{
		// delete configuration file
		KStandardDirs * dirs = KGlobal::dirs();
		QString filePath = dirs->findResource ( "config", "kvpncrc" );
		QFile::remove
			( filePath );
		if ( KvpncDebugLevel > 2 )
			appendLogEntry ( i18n( "Old configuration deleted." ), debug );
	}
}

void KVpncConfig::doBackupConfig()
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString  config = QString(dirs->saveLocation( "config" )+"/kvpncrc");
	QFile OriginalConfFile( config );
	QFile backupOriginalConfFile( config+".backup" );
	QTextStream writestream( &backupOriginalConfFile );
	QTextStream readstream( &OriginalConfFile );
	if ( OriginalConfFile.open( IO_ReadOnly ) )
	{
		if (backupOriginalConfFile.open(IO_WriteOnly))
		{
			QString OriginalConfFileContent = QString( OriginalConfFile.readAll() )	;
			writestream << OriginalConfFileContent;
			OriginalConfFile.close();
			backupOriginalConfFile.close();
		}
	}
}

void KVpncConfig::restoreBackupConfig()
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString  config = QString(dirs->saveLocation( "config" )+"/kvpncrc");
	QFile OriginalConfFile( config+".backup" );
	QFile backupOriginalConfFile( config );
	QTextStream writestream( &backupOriginalConfFile );
	QTextStream readstream( &OriginalConfFile );
	if ( OriginalConfFile.open( IO_ReadOnly ) )
	{
		if (backupOriginalConfFile.open(IO_WriteOnly))
		{
			QString OriginalConfFileContent = QString( OriginalConfFile.readAll() )	;
			writestream << OriginalConfFileContent;
			OriginalConfFile.close();
			backupOriginalConfFile.close();
		}
	}
}

void KVpncConfig::getToolsInfo()
{
	ToolInfo *it;
	//std::cout << "Tool (bin): " << bin << std::endl;
	if (!ToolList->isEmpty())
	{
		for ( it = ToolList->first(); it; it = ToolList->next() )
		{

				

				if(programsInPath)
				{
					it->addSearchPath("/sbin");
					it->addSearchPath("/usr/local/sbin");
					it->addSearchPath("/usr/sbin");
					it->addSearchPath("/bin");
					it->addSearchPath("/usr/local/bin");
					it->addSearchPath("/usr/bin");
				}
				it->collectToolInfo();
		}
	}
}

void KVpncConfig::removeEntry(QString Name)
{
	KStandardDirs * dirs = KGlobal::dirs();
	QString filePath = dirs->findResource ( "config", "kvpncrc" );

	appPointer->processEvents();

	if (useKwallet && KWallet::Wallet::isEnabled())
		config->deleteEntry( "First use of Kwallet", false );
	/* = user data = */
	VpnAccountData *it;
	if ( !AccountList->isEmpty() )
	{
		for ( it = AccountList->first(); it; it = AccountList->next() )
		{
			if ( !it->getName().isEmpty() )
			{
				QString name = it->getName();
				if (it->getName() == Name)
				{
					//std::cout << "Remove profile: " << it->getName() << std::endl;
					QString ProfileName = "Profile_";
					ProfileName += name;
					config->setGroup( ProfileName );

					/* passwords with kwallet */
					if ( useKwallet && KWallet::Wallet::isEnabled())
					{
	// 					if (KvpncDebugLevel > 0)
	// 						appendLogEntry(i18n( "Wallet enabled and available, writing to wallet." ),debug);
	// 					// Open local wallet
						wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet());
						if (wallet != 0)
						{
							QString walletname="kvpnc";
							// Check if folder exists, otherwise create it
							bool walletOK=true;
							if (!wallet->hasFolder(walletname))
							{
								walletOK = wallet->createFolder(walletname);
								wallet->sync();
							}
							if (walletOK)
							{
								wallet->setFolder(walletname);
								//std::cout << "[set] account: " << ProfileName << ", loginname: " << loginname << ", password: " << pwd << std::endl;
								bool UserPasswordOK = (wallet->removeEntry (QString(name+"__user_pw")) == 0);
								bool PskOK= (wallet->removeEntry (QString(name+"__psk")) == 0);
								bool PskKeyPassOK = (wallet->removeEntry (QString(name+"__priv_key_pwd")) == 0);
// 								wallet->sync();

								if (KvpncDebugLevel > 2)
								{
									if (UserPasswordOK)
										appendLogEntry(i18n( "delete of %1 was ok." ).arg(i18n("user password")), debug);
									else
										appendLogEntry(i18n( "delete of %1 has failed." ).arg(i18n("user password")), debug);
	//
									if (PskOK)
										appendLogEntry(i18n( "delete of %1 was successful." ).arg(i18n("preshared key")), debug);
									else
										appendLogEntry(i18n( "delete of %1 has failed." ).arg(i18n("preshared key")),debug);

									if (PskKeyPassOK)
										appendLogEntry(i18n( "delete of %1 was successful." ).arg(i18n("private key password")), debug);
									else
										appendLogEntry(i18n( "delete of %1 has failed." ).arg(i18n("private key password")),debug);


	// 								//std::cout << "success: " << pwdOK << std::endl;
								}
							}
							else
							{
								KMessageBox::error( 0, i18n( "Unable to create wallet folder for kvpnc!" ) );
								appendLogEntry(i18n( "Unable to create wallet folder for kvpnc!" ), error);
						}
					}
				}
					if (KvpncDebugLevel > 0)
						appendLogEntry(i18n( "Wallet disabled or not available, writing to config file." ),debug);
					// write passwords to config file :|
					config->deleteEntry( "User password" );
					config->deleteEntry( "Pre shared key" );
					config->deleteEntry( "PrivateKey password" );
					// 			}

					config->deleteEntry( "Connection type" );
					config->deleteEntry( "VPN Gateway" );
					config->deleteEntry( "VPN ID" );
					config->deleteEntry( "Username" );
					config->deleteEntry( "Save user password" );
					config->deleteEntry( "Save PSK" );
					config->deleteEntry( "Private key" );
					config->deleteEntry( "Use advanced settings" );
					config->deleteEntry( "Application version" );
					config->deleteEntry( "Local port" );
					config->deleteEntry( "NT domain name" );
					config->deleteEntry( "Perfect forward secrety" );
					config->deleteEntry( "IKE group" );
					config->deleteEntry( "Use application version" );
					config->deleteEntry( "Use global IPSec secret" );
					config->deleteEntry( "Use IKE group" );
					config->deleteEntry( "Use local port" );
					config->deleteEntry( "Use NT domain name" );
					config->deleteEntry( "Use single DES" );
					config->deleteEntry( "Use perfect Forward Secrety" );
					config->deleteEntry( "Remote net address" );
					config->deleteEntry( "Remote net mask" );
					config->deleteEntry( "x509 certificate" );
					config->deleteEntry( "Ca certificate" );
					config->deleteEntry( "Network device" );
					config->deleteEntry( "Cert path" );
					config->deleteEntry( "Auth type");
					config->deleteEntry( "do ping ip" );
					config->deleteEntry( "Ping host IP" );
					config->deleteEntry( "Use special remote ID" );
					config->deleteEntry( "Special server certificate" );
					config->deleteEntry( "Use special server certificate" );
					config->deleteEntry( "Special remote ID" );
					config->deleteEntry( "Use UDP-protocol" );
					config->deleteEntry( "Use UDP-port" );
					config->deleteEntry( "local UDP port" );
					config->deleteEntry( "use DNS-server" );
					config->deleteEntry( "DNS server" );
					config->deleteEntry( "get dns server from peer" );
					config->deleteEntry( "refuse 40 bit encryption" );

					appPointer->processEvents();

					config->deleteEntry( "refuse 128 bit encryption" );
					config->deleteEntry( "require stateless encryption" );
					config->deleteEntry( "require mppe" );
					config->deleteEntry( "refuse EAP" );
					config->deleteEntry( "Disable MPPE compression" );
					config->deleteEntry( "Local virtual IP" );
					config->deleteEntry( "Remote virtual IP" );
					config->deleteEntry( "Pre shared key file" );
					config->deleteEntry( "Execute command before connect" );
					config->deleteEntry( "Execute command after connect" );
					config->deleteEntry( "Execute command before disconnect" );
					config->deleteEntry( "Execute command after disconnect" );
					config->deleteEntry( "Command before connect" );
					config->deleteEntry( "Command after connect" );
					config->deleteEntry( "Command before disconnect" );
					config->deleteEntry( "Command after disconnect" );
					config->deleteEntry( "Use no BSD compression" );
					config->deleteEntry( "Use no deflate" );
					config->deleteEntry( "Set default route" );
					config->deleteEntry( "Replace default route" );
					config->deleteEntry( "Use own MTU" );
					config->deleteEntry( "Use own MRU" );
					config->deleteEntry( "MTU for pppd" );
					config->deleteEntry( "MRU for pppd" );
					config->deleteEntry( "Use Virtual IP" );
					config->deleteEntry( "Virtual IP" );
					config->deleteEntry( "PSK is in file" );
					config->deleteEntry( "Use additional network routes" );
					config->deleteEntry( "Hash algorithm" );
					config->deleteEntry( "Tunnel device type" );
					config->deleteEntry( "Use userdefined port" );
					config->deleteEntry( "Userdefined port" );
					config->deleteEntry( "Keep default route" );
					config->deleteEntry( "Additional network routes" );
					config->deleteEntry("AuthWithUsernameAndPassword" );
					config->deleteEntry("AllowEmptyGroupPassword" );
					config->deleteEntry("Encryption algorithm");
					config->deleteEntry("Authentication algorithm");

					config->deleteGroup( ProfileName );

					/* give info */
					//slotStatusMsg ( i18n( "Profile \"%1\" removed." ).arg( Name ), ID_FLASH_MSG );
					appendLogEntry ( i18n( "Profile \"%1\" removed." ).arg( Name ) , info);
					AccountList->remove(it);
					break;
				}
			}
		}
		appPointer->processEvents();
	}
	config->sync();
	appPointer->processEvents();
}


#include "kvpncconfig.moc"
